From b176e929b9037344c6831bc5ac36255cb9d8cc60 Mon Sep 17 00:00:00 2001 From: H3CoF6 <1707889225@qq.com> Date: Thu, 14 May 2026 04:09:55 +0800 Subject: [PATCH 01/48] feat: implement upload group avatar --- .../core/src/bridge/actions/group-admin.ts | 29 +++++++++++++++++++ packages/core/src/bridge/bridge.ts | 2 ++ packages/core/src/bridge/proto/highway.ts | 10 +++++++ .../core/src/onebot/actions/group-admin.ts | 8 +++-- packages/core/src/onebot/api-handler.ts | 1 + packages/core/src/onebot/instance-context.ts | 1 + 6 files changed, 49 insertions(+), 2 deletions(-) diff --git a/packages/core/src/bridge/actions/group-admin.ts b/packages/core/src/bridge/actions/group-admin.ts index fcc27fdc..ec2927ac 100644 --- a/packages/core/src/bridge/actions/group-admin.ts +++ b/packages/core/src/bridge/actions/group-admin.ts @@ -151,3 +151,32 @@ export async function getGroupAtAllRemain( }; } +// ─────────────── group avatar ─────────────── + +export async function setGroupAvatar( + bridge: Bridge, + groupId: number, + source: string, +): Promise { + const { loadBinarySource, computeHashes } = await import('../highway/utils'); + const { fetchHighwaySession, uploadHighwayHttp } = await import('../highway/highway-client'); + const { protoEncode } = await import('../../protobuf/decode'); + const { GroupAvatarUploadExtSchema } = await import('../proto/highway'); + + const loaded = await loadBinarySource(source, 'group avatar'); + if (!loaded.bytes.length) throw new Error('group avatar file is empty'); + + const extend = protoEncode({ + field1: 101, + groupId: BigInt(groupId), + field3: new Uint8Array([0x08, 0x01, 0x12, 0x00]), + field5: 3, + field6: 0, + }, GroupAvatarUploadExtSchema); + + const hashes = computeHashes(loaded.bytes); + const session = await fetchHighwaySession(bridge); + + await uploadHighwayHttp(bridge, session, 3000, loaded.bytes, hashes.md5, extend); +} + diff --git a/packages/core/src/bridge/bridge.ts b/packages/core/src/bridge/bridge.ts index 67e22ca0..0cd1692f 100644 --- a/packages/core/src/bridge/bridge.ts +++ b/packages/core/src/bridge/bridge.ts @@ -43,6 +43,7 @@ import { setGroupSpecialTitle as setGroupSpecialTitle_, setGroupRemark as setGroupRemark_, getGroupAtAllRemain as getGroupAtAllRemain_, + setGroupAvatar as setGroupAvatar_, } from './actions/group-admin'; import { uploadGroupFile as uploadGroupFile_, @@ -631,6 +632,7 @@ export class Bridge { async markPrivateMsgAsRead(userId: number, sequence: number): Promise { return markPrivateMsgAsRead_(this, userId, sequence); } async setFriendRemark(userId: number, remark: string): Promise { return setFriendRemark_(this, userId, remark); } async setGroupRemark(groupId: number, remark: string): Promise { return setGroupRemark_(this, groupId, remark); } + async setGroupAvatar(groupId: number, source: string): Promise { return setGroupAvatar_(this, groupId, source); } async getGroupHonorInfo(groupId: number, type: WebHonorType | string): Promise { return getGroupHonorInfo_(this, groupId, type); } diff --git a/packages/core/src/bridge/proto/highway.ts b/packages/core/src/bridge/proto/highway.ts index 2346dc81..f61f30bf 100644 --- a/packages/core/src/bridge/proto/highway.ts +++ b/packages/core/src/bridge/proto/highway.ts @@ -334,3 +334,13 @@ export const NTV2UploadRichMediaRespSchema = { respHead: { field: 1, type: 'message' as const, schema: NTV2UploadRespHeadSchema }, upload: { field: 2, type: 'message' as const, schema: NTV2UploadRespBodySchema }, } satisfies ProtoSchema; + +// --- Group Avatar Upload Extend --- + +export const GroupAvatarUploadExtSchema = { + field1: { field: 1, type: 'uint32' as const }, + groupId: { field: 2, type: 'uint64' as const }, + field3: { field: 3, type: 'bytes' as const }, + field5: { field: 5, type: 'uint32' as const }, + field6: { field: 6, type: 'uint32' as const }, +} satisfies ProtoSchema; diff --git a/packages/core/src/onebot/actions/group-admin.ts b/packages/core/src/onebot/actions/group-admin.ts index 2feebbc4..871e7753 100644 --- a/packages/core/src/onebot/actions/group-admin.ts +++ b/packages/core/src/onebot/actions/group-admin.ts @@ -103,7 +103,11 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { return okResponse(); }); - h.registerAction('set_group_portrait', async () => { - return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented'); + h.registerAction('set_group_portrait', async (params) => { + const groupId = asNumber(params.group_id); + const file = asString(params.file); + if (!groupId || !file) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and file are required'); + await ctx.setGroupAvatar(groupId, file); + return okResponse(); }); } diff --git a/packages/core/src/onebot/api-handler.ts b/packages/core/src/onebot/api-handler.ts index f2815912..f9762d41 100644 --- a/packages/core/src/onebot/api-handler.ts +++ b/packages/core/src/onebot/api-handler.ts @@ -106,6 +106,7 @@ export interface ApiActionContext { // Extended NapCat-compatible setFriendRemark: (userId: number, remark: string) => Promise; setGroupRemark: (groupId: number, remark: string) => Promise; + setGroupAvatar: (groupId: number, source: string) => Promise; getGroupFileCount: (groupId: number) => Promise<{ fileCount: number; maxCount: number }>; setMsgEmojiLike: (messageId: number, emojiId: string, set: boolean) => Promise; markGroupMsgAsRead: (groupId: number, sequence: number) => Promise; diff --git a/packages/core/src/onebot/instance-context.ts b/packages/core/src/onebot/instance-context.ts index 3131a020..059fd985 100644 --- a/packages/core/src/onebot/instance-context.ts +++ b/packages/core/src/onebot/instance-context.ts @@ -171,6 +171,7 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext { forceFetchClientKey: () => bridge.forceFetchClientKey(), setFriendRemark: (userId, remark) => bridge.setFriendRemark(userId, remark), setGroupRemark: (groupId, remark) => bridge.setGroupRemark(groupId, remark), + setGroupAvatar: (groupId, source) => bridge.setGroupAvatar(groupId, source), getGroupFileCount: (groupId) => bridge.fetchGroupFileCount(groupId), setMsgEmojiLike: async (messageId, emojiId, set) => { const meta = messageStore.findMeta(messageId); From 0401ac4afb6fa8f23c489eb898a7f2eac2a1a105 Mon Sep 17 00:00:00 2001 From: H3CoF6 <1707889225@qq.com> Date: Sat, 16 May 2026 12:17:23 +0800 Subject: [PATCH 02/48] feat: implement some group album actions --- .../core/src/bridge/actions/group-album.ts | 76 ++++++ packages/core/src/bridge/bridge.ts | 15 ++ packages/core/src/bridge/proto/oidb-action.ts | 80 +++++- .../src/bridge/web-actions/group-album.ts | 29 ++ packages/core/src/bridge/web-actions/index.ts | 5 + packages/core/src/bridge/web/group-album.ts | 250 ++++++++++++++++++ .../core/src/onebot/actions/group-album.ts | 54 ++++ packages/core/src/onebot/api-handler.ts | 5 + packages/core/src/onebot/instance-context.ts | 3 + 9 files changed, 516 insertions(+), 1 deletion(-) create mode 100644 packages/core/src/bridge/actions/group-album.ts create mode 100644 packages/core/src/bridge/web-actions/group-album.ts create mode 100644 packages/core/src/bridge/web/group-album.ts create mode 100644 packages/core/src/onebot/actions/group-album.ts diff --git a/packages/core/src/bridge/actions/group-album.ts b/packages/core/src/bridge/actions/group-album.ts new file mode 100644 index 00000000..a8bfe139 --- /dev/null +++ b/packages/core/src/bridge/actions/group-album.ts @@ -0,0 +1,76 @@ +// Group album actions via TRPC protocol + +import type { Bridge } from '../bridge'; +import { protoEncode, protoDecode } from '@/protobuf/decode'; +import { GetMediaListRequestSchema, GetMediaListResponseSchema } from '../proto/oidb-action'; + +export interface GroupAlbumMediaResult { + mediaList: any[]; + nextAttachInfo: string; + raw: any; +} + +function convertBigIntToString(obj: any): any { + if (obj === null || obj === undefined) return obj; + if (typeof obj === 'bigint') return obj.toString(); + if (Array.isArray(obj)) return obj.map(convertBigIntToString); + if (typeof obj === 'object') { + const result: any = {}; + for (const key in obj) { + result[key] = convertBigIntToString(obj[key]); + } + return result; + } + return obj; +} + +export async function getGroupAlbumMediaList( + bridge: Bridge, + groupId: number, + albumId: string, + attachInfo: string = '' +): Promise { + const traceId = `_${Date.now()}_${Math.floor(Math.random() * 100000)}`; + + const body = protoEncode({ + field1: 0, + field2: new Uint8Array(0), + field3: new Uint8Array(0), + reqInfo: { + groupId: groupId.toString(), + albumId: albumId, + field3: 0, + attachInfo: attachInfo, // 填入翻页游标 + field5: '', + }, + traceId: traceId, + extMap: [{ key: 'fc-appid', value: '100' }], + }, GetMediaListRequestSchema); + + const result = await bridge.sendRawPacket( + 'QunAlbum.trpc.qzone.webapp_qun_media.QunMedia.GetMediaList', + body, + 15000 + ); + + if (!result.success || !result.gotResponse || !result.responseData) { + throw new Error(result.errorMessage || 'failed to get album media list'); + } + + const resp = protoDecode(result.responseData, GetMediaListResponseSchema); + + // 校验外层 TRPC 状态码 + if (!resp || (resp as any).field1 !== 0) { + throw new Error(`fetch album media list error: retCode ${(resp as any)?.field1 || 'unknown'}`); + } + + const data = (resp as any).data || {}; + const mediaList = data.mediaList || []; + const nextAttachInfo = data.nextAttachInfo || ''; + + return convertBigIntToString({ + mediaList, + nextAttachInfo, + raw: resp + }); +} diff --git a/packages/core/src/bridge/bridge.ts b/packages/core/src/bridge/bridge.ts index 0cd1692f..4f1a17bb 100644 --- a/packages/core/src/bridge/bridge.ts +++ b/packages/core/src/bridge/bridge.ts @@ -111,7 +111,10 @@ import { getCookiesStr as getCookiesStr_, getCsrfToken as getCsrfToken_, getCredentials as getCredentials_, + getGroupAlbumListWeb as getGroupAlbumListWeb_, + uploadImageToGroupAlbumWeb as uploadImageToGroupAlbumWeb_, } from './web-actions'; +import { getGroupAlbumMediaList as getGroupAlbumMediaList_ } from './actions/group-album'; import type { GroupFilesResult } from './actions/group-file'; import type { MediaIndexNode } from './actions/shared'; import { BridgeEventBus } from './event-bus'; @@ -645,6 +648,18 @@ export class Bridge { return getGroupEssenceAll_(this, groupId); } + async getGroupAlbumList(groupId: number): Promise { + return getGroupAlbumListWeb_(this, groupId); + } + + async uploadImageToGroupAlbum(groupId: number, albumId: string, albumName: string, filePath: string): Promise { + return uploadImageToGroupAlbumWeb_(this, groupId, albumId, albumName, filePath); + } + + async getGroupAlbumMediaList(groupId: number, albumId: string): Promise { + return getGroupAlbumMediaList_(this, groupId, albumId); + } + async sendGroupNotice(groupId: number, content: string, options?: any) { return sendGroupNotice_(this, groupId, content, options); } diff --git a/packages/core/src/bridge/proto/oidb-action.ts b/packages/core/src/bridge/proto/oidb-action.ts index 59012e4b..90c55574 100644 --- a/packages/core/src/bridge/proto/oidb-action.ts +++ b/packages/core/src/bridge/proto/oidb-action.ts @@ -1120,4 +1120,82 @@ export const Oidb0xf16ReqSchema = { field12: { field: 12, type: 'uint32' as const }, } satisfies ProtoSchema; -export const Oidb0xf16RespSchema = {} satisfies ProtoSchema; \ No newline at end of file +export const Oidb0xf16RespSchema = {} satisfies ProtoSchema; + +///////// --- group album +// --- Request Schemas --- + +export const ExtMapEntrySchema = { + key: { field: 1, type: 'string' as const }, + value: { field: 2, type: 'string' as const }, +} satisfies ProtoSchema; + +export const ReqInfoSchema = { + groupId: { field: 1, type: 'string' as const }, + albumId: { field: 2, type: 'string' as const }, + field3: { field: 3, type: 'int32' as const }, + attachInfo: { field: 4, type: 'string' as const }, + field5: { field: 5, type: 'string' as const }, +} satisfies ProtoSchema; + +export const GetMediaListRequestSchema = { + field1: { field: 1, type: 'int32' as const }, + field2: { field: 2, type: 'bytes' as const }, + field3: { field: 3, type: 'bytes' as const }, + reqInfo: { field: 4, type: 'message' as const, schema: ReqInfoSchema }, + traceId: { field: 5, type: 'string' as const }, + extMap: { field: 10, type: 'repeated_message' as const, schema: ExtMapEntrySchema }, +} satisfies ProtoSchema; + +// --- Response Schemas --- + +export const UrlInfoSchema = { + url: { field: 1, type: 'string' as const }, + width: { field: 2, type: 'uint32' as const }, + height: { field: 3, type: 'uint32' as const }, +} satisfies ProtoSchema; + +export const PhotoUrlSchema = { + spec: { field: 1, type: 'uint32' as const }, + url: { field: 2, type: 'message' as const, schema: UrlInfoSchema } +} satisfies ProtoSchema; + +export const ImageInfoSchema = { + name: { field: 1, type: 'string' as const }, + sloc: { field: 2, type: 'string' as const }, + lloc: { field: 3, type: 'string' as const }, + photoUrls: { field: 4, type: 'repeated_message' as const, schema: PhotoUrlSchema }, + defaultUrl: { field: 5, type: 'message' as const, schema: UrlInfoSchema }, + isGif: { field: 6, type: 'bool' as const }, + hasRaw: { field: 7, type: 'bool' as const }, +} satisfies ProtoSchema; + +export const MediaInfoSchema = { + type: { field: 1, type: 'uint32' as const }, + image: { field: 2, type: 'message' as const, schema: ImageInfoSchema }, + uploader: { field: 6, type: 'string' as const }, + batchId: { field: 7, type: 'uint64' as const }, + uploadTime: { field: 8, type: 'uint64' as const }, +} satisfies ProtoSchema; + +export const GetMediaListRspDataSchema = { + albumInfo: { + field: 1, + type: 'message' as const, + schema: { + albumId: { field: 1, type: 'string' as const }, + owner: { field: 2, type: 'string' as const }, + name: { field: 3, type: 'string' as const }, + } satisfies ProtoSchema + }, + mediaList: { field: 3, type: 'repeated_message' as const, schema: MediaInfoSchema }, + prevAttachInfo: { field: 4, type: 'string' as const }, + nextAttachInfo: { field: 5, type: 'string' as const }, // 用于翻页拉取的 token +} satisfies ProtoSchema; + +export const GetMediaListResponseSchema = { + field1: { field: 1, type: 'int32' as const }, + field2: { field: 2, type: 'bytes' as const }, + field3: { field: 3, type: 'bytes' as const }, + data: { field: 4, type: 'message' as const, schema: GetMediaListRspDataSchema }, // 将原本的 bytes 修正为 message 解析 +} satisfies ProtoSchema; \ No newline at end of file diff --git a/packages/core/src/bridge/web-actions/group-album.ts b/packages/core/src/bridge/web-actions/group-album.ts new file mode 100644 index 00000000..205611c8 --- /dev/null +++ b/packages/core/src/bridge/web-actions/group-album.ts @@ -0,0 +1,29 @@ +// Group album actions via web API + +import type { Bridge } from '../bridge'; +import { getGroupAlbumList, uploadImageToGroupAlbum } from '../web/group-album'; +import { getCookies } from './cookies'; + +export async function getGroupAlbumListWeb(bridge: Bridge, groupId: number) { + const groupCode = groupId.toString(); + const uin = bridge.qqInfo.uin; + const cookieObject = await getCookies(bridge, 'qzone.qq.com'); + + const albumData = await getGroupAlbumList(cookieObject, groupCode, uin); + + return albumData?.album || []; +} + +export async function uploadImageToGroupAlbumWeb( + bridge: Bridge, + groupId: number, + albumId: string, + albumName: string, + filePath: string +): Promise { + const groupCode = groupId.toString(); + const uin = bridge.qqInfo.uin; + const cookieObject = await getCookies(bridge, 'qzone.qq.com'); + + await uploadImageToGroupAlbum(cookieObject, groupCode, albumId, albumName, filePath, uin); +} diff --git a/packages/core/src/bridge/web-actions/index.ts b/packages/core/src/bridge/web-actions/index.ts index 8cf8375b..c7f834f8 100644 --- a/packages/core/src/bridge/web-actions/index.ts +++ b/packages/core/src/bridge/web-actions/index.ts @@ -25,3 +25,8 @@ export { getGroupNotice, deleteGroupNoticeByFid, } from './group-notice'; + +export { + getGroupAlbumListWeb, + uploadImageToGroupAlbumWeb, +} from './group-album'; diff --git a/packages/core/src/bridge/web/group-album.ts b/packages/core/src/bridge/web/group-album.ts new file mode 100644 index 00000000..f6c33d03 --- /dev/null +++ b/packages/core/src/bridge/web/group-album.ts @@ -0,0 +1,250 @@ +import { RequestUtil, cookieToString, getBknFromCookie } from './request-util'; +import { createHash } from 'crypto'; +import { readFileSync, statSync, createReadStream, writeFileSync, unlinkSync } from 'fs'; +import { basename, join } from 'path'; +import { tmpdir } from 'os'; + +// 群相册信息 +export interface GroupAlbumInfo { + id: string; + name: string; + picNum: number; + createTime: number; + [key: string]: any; +} + +// 获取群相册列表返回 +export interface GroupAlbumListRet { + album: GroupAlbumInfo[]; + [key: string]: any; +} + +// 相册媒体信息 +export interface AlbumMediaInfo { + photoId: string; + url: string; + uploadTime: number; + [key: string]: any; +} + +/** + * 获取群相册列表 + */ +export async function getGroupAlbumList( + cookieObject: Record, + groupId: string, + uin: string +): Promise { + if (!cookieObject || typeof cookieObject !== 'object') { + throw new Error('cookieObject is required'); + } + + const bkn = getBknFromCookie(cookieObject); + + const url = `https://h5.qzone.qq.com/proxy/domain/u.photo.qzone.qq.com/cgi-bin/upp/qun_list_album_v2?${new URLSearchParams({ + random: '7570', + g_tk: bkn, + format: 'json', + inCharset: 'utf-8', + outCharset: 'utf-8', + qua: 'V1_IPH_SQ_6.2.0_0_HDBM_T', + cmd: 'qunGetAlbumList', + qunId: groupId, + qunid: groupId, + start: '0', + num: '1000', + uin, + getMemberRole: '0', + }).toString()}`; + + const ret = await RequestUtil.HttpGetJson<{ data: GroupAlbumListRet }>( + url, + 'GET', + '', + { Cookie: cookieToString(cookieObject) } + ); + + if (!ret || typeof ret !== 'object') { + throw new Error('invalid response from qzone api'); + } + + return ret.data; +} + +/** + * 创建群相册上传会话 + */ +async function createAlbumUploadSession( + groupId: string, + albumId: string, + albumName: string, + filePath: string, + skey: string, + pskey: string, + imgMd5: string, + uin: string +): Promise { + const imgSize = statSync(filePath).size; + const imgName = basename(filePath); + const bkn = getBknFromCookie({ skey }); + const timestamp = Math.floor(Date.now() / 1000); + + const body = { + control_req: [{ + uin, + token: { type: 4, data: pskey, appid: 5 }, + appid: 'qun', + checksum: imgMd5, + check_type: 0, + file_len: imgSize, + env: { refer: 'qzone', deviceInfo: 'h5' }, + model: 0, + biz_req: { + sPicTitle: imgName, + sPicDesc: '', + sAlbumName: albumName, + sAlbumID: albumId, + iAlbumTypeID: 0, + iBitmap: 0, + iUploadType: 0, + iUpPicType: 0, + iBatchID: timestamp, + sPicPath: '', + iPicWidth: 0, + iPicHight: 0, + iWaterType: 0, + iDistinctUse: 0, + iNeedFeeds: 1, + iUploadTime: timestamp, + mapExt: { appid: 'qun', userid: groupId }, + stExtendInfo: { mapParams: { photo_num: '1', video_num: '0', batch_num: '1' } }, + }, + session: '', + asy_upload: 0, + cmd: 'FileUpload', + }], + }; + + const api = `https://h5.qzone.qq.com/webapp/json/sliceUpload/FileBatchControl/${imgMd5}?g_tk=${bkn}`; + const cookie = `p_uin=o${uin}; p_skey=${pskey}; skey=${skey}; uin=o${uin}`; + + const response = await RequestUtil.HttpGetJson<{ data: { session: string }, ret: number, msg: string }>( + api, + 'POST', + JSON.stringify(body), + { Cookie: cookie, 'Content-Type': 'application/json' } + ); + + if (response.ret !== 0 || !response.data?.session) { + throw new Error(`创建上传会话失败: ${response.msg}`); + } + + return response.data.session; +} + + +/** + * 修复后的上传图片分片方法 + */ +async function uploadAlbumSlice( + session: string, + filePath: string, + // 移除 offset 和 chunkSize 参数,改为在内部控制 + imgMd5: string, + skey: string, + pskey: string, + uin: string +): Promise { + const img_size = statSync(filePath).size; + const slice_size = 16384; // 严格使用 16KB + const bkn = getBknFromCookie({ skey }); + const cookie = `p_uin=o${uin}; p_skey=${pskey}; skey=${skey}; uin=o${uin}`; + + const stream = createReadStream(filePath, { highWaterMark: slice_size }); + let seq = 0; + let offset = 0; + + for await (const chunk of stream) { + const end = Math.min(offset + chunk.length, img_size); + + // 使用原生的 FormData 构建安全的 multipart 请求 + const form = new FormData(); + form.append('uin', uin); + form.append('appid', 'qun'); + form.append('session', session); + form.append('offset', offset.toString()); + form.append('data', new Blob([chunk as Buffer], { type: 'application/octet-stream' }), 'blob'); + form.append('checksum', ''); + form.append('check_type', '0'); + form.append('retry', '0'); + form.append('seq', seq.toString()); + form.append('end', end.toString()); + form.append('cmd', 'FileUpload'); + form.append('slice_size', slice_size.toString()); + form.append('biz_req.iUploadType', '0'); + + const api = `https://h5.qzone.qq.com/webapp/json/sliceUpload/FileUpload?seq=${seq}&retry=0&offset=${offset}&end=${end}&total=${img_size}&type=form&g_tk=${bkn}`; + + // 放弃使用 HttpGetJson,改用原生 fetch,它能完美处理 FormData 和边界 + const response = await fetch(api, { + method: 'POST', + headers: { + Cookie: cookie, + // 注意:不要手动设置 Content-Type,fetch 会自动加上带有正确 boundary 的 multipart/form-data + }, + body: form, + }); + + if (!response.ok) { + throw new Error(`HTTP error! status: ${response.status}`); + } + + const post = await response.json() as { ret: number, msg: string }; + if (post.ret !== 0) { + throw new Error(`分片 ${seq} 上传失败: ${post.msg}`); + } + + offset += chunk.length; + seq++; + } +} + +/** + * 上传图片到群相册 + */ +export async function uploadImageToGroupAlbum( + cookieObject: Record, + groupId: string, + albumId: string, + albumName: string, + filePath: string, + uin: string +): Promise { + const { loadBinarySource } = await import('../highway/utils'); + const loaded = await loadBinarySource(filePath, 'album image'); + + let tempFile: string | null = null; + let actualPath = filePath; + + if (/^(https?:\/\/|base64:\/\/)/i.test(filePath)) { + tempFile = join(tmpdir(), `album_${Date.now()}_${Math.random().toString(36).slice(2)}.tmp`); + writeFileSync(tempFile, loaded.bytes); + actualPath = tempFile; + } + + try { + const imgMd5 = createHash('md5').update(loaded.bytes).digest('hex'); + // const imgSize = loaded.bytes.length; + const skey = cookieObject.skey || ''; + const pskey = cookieObject.p_skey || ''; + + const session = await createAlbumUploadSession(groupId, albumId, albumName, actualPath, skey, pskey, imgMd5, uin); + + await uploadAlbumSlice(session, actualPath, imgMd5, skey, pskey, uin); + + } finally { + if (tempFile) { + try { unlinkSync(tempFile); } catch { /* ignore */ } + } + } +} diff --git a/packages/core/src/onebot/actions/group-album.ts b/packages/core/src/onebot/actions/group-album.ts new file mode 100644 index 00000000..322ec249 --- /dev/null +++ b/packages/core/src/onebot/actions/group-album.ts @@ -0,0 +1,54 @@ +import type { ApiHandler, ApiActionContext } from '../api-handler'; +import { asNumber, asString } from '../api-handler'; +import { RETCODE, failedResponse, okResponse } from '../types'; + +export function register(h: ApiHandler, ctx: ApiActionContext): void { + h.registerAction('get_group_album_list', async (params) => { + const groupId = asNumber(params.group_id); + if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required'); + + try { + const albumList = await ctx.getGroupAlbumList(groupId); + return okResponse(albumList); + } catch (error) { + const message = error instanceof Error ? error.message : 'failed to get group album list'; + return failedResponse(RETCODE.INTERNAL_ERROR, message); + } + }); + + h.registerAction('upload_image_to_qun_album', async (params) => { + const groupId = asNumber(params.group_id); + const albumId = asString(params.album_id); + const albumName = asString(params.album_name); + const file = asString(params.file); + + if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required'); + if (!albumId) return failedResponse(RETCODE.BAD_REQUEST, 'album_id is required'); + if (!albumName) return failedResponse(RETCODE.BAD_REQUEST, 'album_name is required'); + if (!file) return failedResponse(RETCODE.BAD_REQUEST, 'file is required'); + + try { + await ctx.uploadImageToGroupAlbum(groupId, albumId, albumName, file); + return okResponse(null); + } catch (error) { + const message = error instanceof Error ? error.message : 'failed to upload image to group album'; + return failedResponse(RETCODE.INTERNAL_ERROR, message); + } + }); + + h.registerAction('get_group_album_media_list', async (params) => { + const groupId = asNumber(params.group_id); + const albumId = asString(params.album_id); + + if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required'); + if (!albumId) return failedResponse(RETCODE.BAD_REQUEST, 'album_id is required'); + + try { + const mediaList = await ctx.getGroupAlbumMediaList(groupId, albumId); + return okResponse(mediaList); + } catch (error) { + const message = error instanceof Error ? error.message : 'failed to get group album media list'; + return failedResponse(RETCODE.INTERNAL_ERROR, message); + } + }); +} diff --git a/packages/core/src/onebot/api-handler.ts b/packages/core/src/onebot/api-handler.ts index f9762d41..2a5b9107 100644 --- a/packages/core/src/onebot/api-handler.ts +++ b/packages/core/src/onebot/api-handler.ts @@ -10,6 +10,7 @@ import { register as registerGroupAdmin } from './actions/group-admin'; import { register as registerGroupFile } from './actions/group-file'; import { register as registerRequest } from './actions/request'; import { register as registerExtended } from './actions/extended'; +import { register as registerGroupAlbum } from './actions/group-album'; import { WebHonorType } from '@/bridge/web/group-honor'; // import {ClientKeyInfo} from "@/bridge/bridge"; @@ -118,6 +119,9 @@ export interface ApiActionContext { getGroupHonorInfo: (groupId: number, type: WebHonorType | string) => Promise; getGroupEssence: (groupId: number, pageStart?: number, pageLimit?: number) => Promise; getGroupEssenceAll: (groupId: number) => Promise; + getGroupAlbumList: (groupId: number) => Promise; + uploadImageToGroupAlbum: (groupId: number, albumId: string, albumName: string, filePath: string) => Promise; + getGroupAlbumMediaList: (groupId: number, albumId: string) => Promise; sendGroupNotice: (groupId: number, content: string, options?: any) => Promise; getGroupNotice: (groupId: number) => Promise; deleteGroupNotice: (groupId: number, fid: string) => Promise; @@ -145,6 +149,7 @@ export class ApiHandler { registerGroupFile(this, context); registerRequest(this, context); registerExtended(this, context); + registerGroupAlbum(this, context); } registerAction(action: string, handler: ActionHandler): void { diff --git a/packages/core/src/onebot/instance-context.ts b/packages/core/src/onebot/instance-context.ts index 059fd985..910d24f0 100644 --- a/packages/core/src/onebot/instance-context.ts +++ b/packages/core/src/onebot/instance-context.ts @@ -187,6 +187,9 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext { getGroupHonorInfo: (groupId: number, type: WebHonorType | string) => bridge.getGroupHonorInfo(groupId, type), getGroupEssence: (groupId, pageStart = 0, pageLimit = 50) => bridge.getGroupEssence(groupId, pageStart, pageLimit), getGroupEssenceAll: (groupId) => bridge.getGroupEssenceAll(groupId), + getGroupAlbumList: (groupId) => bridge.getGroupAlbumList(groupId), + uploadImageToGroupAlbum: (groupId, albumId, albumName, filePath) => bridge.uploadImageToGroupAlbum(groupId, albumId, albumName, filePath), + getGroupAlbumMediaList: (groupId, albumId) => bridge.getGroupAlbumMediaList(groupId, albumId), sendGroupNotice: (groupId, content, options) => bridge.sendGroupNotice(groupId, content, options), getGroupNotice: (groupId) => bridge.getGroupNotice(groupId), deleteGroupNotice: (groupId, fid) => bridge.deleteGroupNotice(groupId, fid), From c58f4d4085cf3075d1de172589766dd06158da96 Mon Sep 17 00:00:00 2001 From: H3CoF6 <1707889225@qq.com> Date: Sat, 16 May 2026 13:34:02 +0800 Subject: [PATCH 03/48] fix: fix group album upload error --- packages/core/src/bridge/web/group-album.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/packages/core/src/bridge/web/group-album.ts b/packages/core/src/bridge/web/group-album.ts index f6c33d03..a15c1d9b 100644 --- a/packages/core/src/bridge/web/group-album.ts +++ b/packages/core/src/bridge/web/group-album.ts @@ -3,6 +3,7 @@ import { createHash } from 'crypto'; import { readFileSync, statSync, createReadStream, writeFileSync, unlinkSync } from 'fs'; import { basename, join } from 'path'; import { tmpdir } from 'os'; +import * as console from "node:console"; // 群相册信息 export interface GroupAlbumInfo { @@ -127,11 +128,15 @@ async function createAlbumUploadSession( const api = `https://h5.qzone.qq.com/webapp/json/sliceUpload/FileBatchControl/${imgMd5}?g_tk=${bkn}`; const cookie = `p_uin=o${uin}; p_skey=${pskey}; skey=${skey}; uin=o${uin}`; + // + // console.log(api); + // console.log(cookie); + // console.log(JSON.stringify(body)); const response = await RequestUtil.HttpGetJson<{ data: { session: string }, ret: number, msg: string }>( api, 'POST', - JSON.stringify(body), + body, { Cookie: cookie, 'Content-Type': 'application/json' } ); From e2ee528939446865793e99978b5c42020a183f4d Mon Sep 17 00:00:00 2001 From: H3CoF6 <1707889225@qq.com> Date: Sat, 16 May 2026 14:33:42 +0800 Subject: [PATCH 04/48] fix: address P0 and P1 issues from code review - P0-1: restore customExt field in SetStatusReqSchema - P0-2: remove duplicate setGroupAvatar implementation - P1-3: add attach_info pagination support for get_group_album_media_list - P1-5: clean up commented console.log statements - P1-6: remove raw field from GroupAlbumMediaResult --- .../core/src/bridge/actions/group-admin.ts | 29 ------------------- .../core/src/bridge/actions/group-album.ts | 5 +--- packages/core/src/bridge/bridge-interface.ts | 2 +- packages/core/src/bridge/bridge.ts | 4 +-- packages/core/src/bridge/proto/oidb-action.ts | 1 + packages/core/src/bridge/web/group-album.ts | 4 --- .../core/src/onebot/actions/group-album.ts | 3 +- packages/core/src/onebot/api-handler.ts | 2 +- packages/core/src/onebot/instance-context.ts | 2 +- 9 files changed, 9 insertions(+), 43 deletions(-) diff --git a/packages/core/src/bridge/actions/group-admin.ts b/packages/core/src/bridge/actions/group-admin.ts index 3c4ffe9c..ef59e9a1 100644 --- a/packages/core/src/bridge/actions/group-admin.ts +++ b/packages/core/src/bridge/actions/group-admin.ts @@ -214,32 +214,3 @@ export async function getGroupAtAllRemain( }; } -// ─────────────── group avatar ─────────────── - -export async function setGroupAvatar( - bridge: Bridge, - groupId: number, - source: string, -): Promise { - const { loadBinarySource, computeHashes } = await import('../highway/utils'); - const { fetchHighwaySession, uploadHighwayHttp } = await import('../highway/highway-client'); - const { protoEncode } = await import('../../protobuf/decode'); - const { GroupAvatarUploadExtSchema } = await import('../proto/highway'); - - const loaded = await loadBinarySource(source, 'group avatar'); - if (!loaded.bytes.length) throw new Error('group avatar file is empty'); - - const extend = protoEncode({ - field1: 101, - groupId: BigInt(groupId), - field3: new Uint8Array([0x08, 0x01, 0x12, 0x00]), - field5: 3, - field6: 0, - }, GroupAvatarUploadExtSchema); - - const hashes = computeHashes(loaded.bytes); - const session = await fetchHighwaySession(bridge); - - await uploadHighwayHttp(bridge, session, 3000, loaded.bytes, hashes.md5, extend); -} - diff --git a/packages/core/src/bridge/actions/group-album.ts b/packages/core/src/bridge/actions/group-album.ts index a8bfe139..cd30fe6a 100644 --- a/packages/core/src/bridge/actions/group-album.ts +++ b/packages/core/src/bridge/actions/group-album.ts @@ -7,7 +7,6 @@ import { GetMediaListRequestSchema, GetMediaListResponseSchema } from '../proto/ export interface GroupAlbumMediaResult { mediaList: any[]; nextAttachInfo: string; - raw: any; } function convertBigIntToString(obj: any): any { @@ -40,7 +39,7 @@ export async function getGroupAlbumMediaList( groupId: groupId.toString(), albumId: albumId, field3: 0, - attachInfo: attachInfo, // 填入翻页游标 + attachInfo: attachInfo, field5: '', }, traceId: traceId, @@ -59,7 +58,6 @@ export async function getGroupAlbumMediaList( const resp = protoDecode(result.responseData, GetMediaListResponseSchema); - // 校验外层 TRPC 状态码 if (!resp || (resp as any).field1 !== 0) { throw new Error(`fetch album media list error: retCode ${(resp as any)?.field1 || 'unknown'}`); } @@ -71,6 +69,5 @@ export async function getGroupAlbumMediaList( return convertBigIntToString({ mediaList, nextAttachInfo, - raw: resp }); } diff --git a/packages/core/src/bridge/bridge-interface.ts b/packages/core/src/bridge/bridge-interface.ts index fbdd0d15..24440d0f 100644 --- a/packages/core/src/bridge/bridge-interface.ts +++ b/packages/core/src/bridge/bridge-interface.ts @@ -94,7 +94,7 @@ export interface BridgeInterface { // ─── Group Album ─── getGroupAlbumList(groupId: number): Promise; uploadImageToGroupAlbum(groupId: number, albumId: string, albumName: string, filePath: string): Promise; - getGroupAlbumMediaList(groupId: number, albumId: string): Promise; + getGroupAlbumMediaList(groupId: number, albumId: string, attachInfo?: string): Promise; // ─── Forward ─── uploadForwardNodes(nodes: ForwardNodePayload[], groupId?: number): Promise; diff --git a/packages/core/src/bridge/bridge.ts b/packages/core/src/bridge/bridge.ts index 001db52f..ee048910 100644 --- a/packages/core/src/bridge/bridge.ts +++ b/packages/core/src/bridge/bridge.ts @@ -495,8 +495,8 @@ export class Bridge implements BridgeInterface { return uploadImageToGroupAlbumWeb_(this, groupId, albumId, albumName, filePath); } - async getGroupAlbumMediaList(groupId: number, albumId: string): Promise { - return getGroupAlbumMediaList_(this, groupId, albumId); + async getGroupAlbumMediaList(groupId: number, albumId: string, attachInfo?: string): Promise { + return getGroupAlbumMediaList_(this, groupId, albumId, attachInfo); } async sendGroupNotice(groupId: number, content: string, options?: any) { diff --git a/packages/core/src/bridge/proto/oidb-action.ts b/packages/core/src/bridge/proto/oidb-action.ts index 54e28d41..82cc8dae 100644 --- a/packages/core/src/bridge/proto/oidb-action.ts +++ b/packages/core/src/bridge/proto/oidb-action.ts @@ -879,6 +879,7 @@ export const SetStatusReqSchema = { status: { field: 1, type: 'int32' as const }, extStatus: { field: 2, type: 'int32' as const }, batteryStatus: { field: 3, type: 'int32' as const }, + customExt: { field: 4, type: 'message' as const, schema: SetStatusCustomExtSchema }, } satisfies ProtoSchema; export const SetStatusRespSchema = { diff --git a/packages/core/src/bridge/web/group-album.ts b/packages/core/src/bridge/web/group-album.ts index a15c1d9b..3ea71e19 100644 --- a/packages/core/src/bridge/web/group-album.ts +++ b/packages/core/src/bridge/web/group-album.ts @@ -128,10 +128,6 @@ async function createAlbumUploadSession( const api = `https://h5.qzone.qq.com/webapp/json/sliceUpload/FileBatchControl/${imgMd5}?g_tk=${bkn}`; const cookie = `p_uin=o${uin}; p_skey=${pskey}; skey=${skey}; uin=o${uin}`; - // - // console.log(api); - // console.log(cookie); - // console.log(JSON.stringify(body)); const response = await RequestUtil.HttpGetJson<{ data: { session: string }, ret: number, msg: string }>( api, diff --git a/packages/core/src/onebot/actions/group-album.ts b/packages/core/src/onebot/actions/group-album.ts index 322ec249..43034bdf 100644 --- a/packages/core/src/onebot/actions/group-album.ts +++ b/packages/core/src/onebot/actions/group-album.ts @@ -39,12 +39,13 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { h.registerAction('get_group_album_media_list', async (params) => { const groupId = asNumber(params.group_id); const albumId = asString(params.album_id); + const attachInfo = asString(params.attach_info) || ''; if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required'); if (!albumId) return failedResponse(RETCODE.BAD_REQUEST, 'album_id is required'); try { - const mediaList = await ctx.getGroupAlbumMediaList(groupId, albumId); + const mediaList = await ctx.getGroupAlbumMediaList(groupId, albumId, attachInfo); return okResponse(mediaList); } catch (error) { const message = error instanceof Error ? error.message : 'failed to get group album media list'; diff --git a/packages/core/src/onebot/api-handler.ts b/packages/core/src/onebot/api-handler.ts index ca2b622b..0afcc20c 100644 --- a/packages/core/src/onebot/api-handler.ts +++ b/packages/core/src/onebot/api-handler.ts @@ -111,7 +111,7 @@ export interface ApiActionContext { getGroupEssenceAll: (groupId: number) => Promise; getGroupAlbumList: (groupId: number) => Promise; uploadImageToGroupAlbum: (groupId: number, albumId: string, albumName: string, filePath: string) => Promise; - getGroupAlbumMediaList: (groupId: number, albumId: string) => Promise; + getGroupAlbumMediaList: (groupId: number, albumId: string, attachInfo?: string) => Promise; sendGroupNotice: (groupId: number, content: string, options?: any) => Promise; getGroupNotice: (groupId: number) => Promise; deleteGroupNotice: (groupId: number, fid: string) => Promise; diff --git a/packages/core/src/onebot/instance-context.ts b/packages/core/src/onebot/instance-context.ts index 8653217a..db6333d0 100644 --- a/packages/core/src/onebot/instance-context.ts +++ b/packages/core/src/onebot/instance-context.ts @@ -188,7 +188,7 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext { getGroupEssenceAll: (groupId) => bridge.getGroupEssenceAll(groupId), getGroupAlbumList: (groupId) => bridge.getGroupAlbumList(groupId), uploadImageToGroupAlbum: (groupId, albumId, albumName, filePath) => bridge.uploadImageToGroupAlbum(groupId, albumId, albumName, filePath), - getGroupAlbumMediaList: (groupId, albumId) => bridge.getGroupAlbumMediaList(groupId, albumId), + getGroupAlbumMediaList: (groupId, albumId, attachInfo) => bridge.getGroupAlbumMediaList(groupId, albumId, attachInfo), sendGroupNotice: (groupId, content, options) => bridge.sendGroupNotice(groupId, content, options), getGroupNotice: (groupId) => bridge.getGroupNotice(groupId), deleteGroupNotice: (groupId, fid) => bridge.deleteGroupNotice(groupId, fid), From b441647df4fcc5fbaeee018078c4a74f2fc2044b Mon Sep 17 00:00:00 2001 From: airline233 Date: Sun, 17 May 2026 15:27:43 +0800 Subject: [PATCH 05/48] feat(http-server): support parse content-type of urlencoded --- .../src/onebot/network/http-server-adapter.ts | 66 ++++++-- .../tests/http-server-content-type.test.ts | 149 ++++++++++++++++++ 2 files changed, 203 insertions(+), 12 deletions(-) create mode 100644 packages/core/tests/http-server-content-type.test.ts diff --git a/packages/core/src/onebot/network/http-server-adapter.ts b/packages/core/src/onebot/network/http-server-adapter.ts index 778ae4b2..4c36e68a 100644 --- a/packages/core/src/onebot/network/http-server-adapter.ts +++ b/packages/core/src/onebot/network/http-server-adapter.ts @@ -136,19 +136,61 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter } else if (req.method === 'POST') { const bodyContent = await readRequestBody(req); if (bodyContent.trim()) { - try { - const parsedBody = JSON.parse(bodyContent); - if (typeof parsedBody === 'object' && parsedBody !== null && !Array.isArray(parsedBody)) { - if (parsedBody.action && !action) action = String(parsedBody.action); - if (parsedBody.params && typeof parsedBody.params === 'object' && !Array.isArray(parsedBody.params)) { - params = parsedBody.params as Record; - } else { - params = parsedBody as Record; + const contentType = req.headers['content-type'] ?? ''; + if (contentType.includes('application/x-www-form-urlencoded')) { + const parsed = new URLSearchParams(bodyContent); + parsed.forEach((value, key) => { + try { + params[key] = JSON.parse(value); + } catch { + params[key] = value; } - echo = parsedBody.echo; + }); + if (params.action && !action) { + action = String(params.action); + delete params.action; } - } catch { - writeJson(res, 400, { status: 'failed', retcode: 1400, data: null, wording: 'bad request: invalid json' }); + if (params.echo !== undefined) { + echo = params.echo; + delete params.echo; + } + } else if (contentType.includes('application/json') || !contentType) { + try { + const parsedBody = JSON.parse(bodyContent); + if (typeof parsedBody === 'object' && parsedBody !== null && !Array.isArray(parsedBody)) { + if (parsedBody.action && !action) action = String(parsedBody.action); + if (parsedBody.params && typeof parsedBody.params === 'object' && !Array.isArray(parsedBody.params)) { + params = parsedBody.params as Record; + } else { + params = parsedBody as Record; + } + echo = parsedBody.echo; + } + } catch { + if (contentType.includes('application/json')) { + writeJson(res, 400, { status: 'failed', retcode: 1400, data: null, wording: 'bad request: invalid json' }); + return; + } + // 无 content-type,JSON 失败则 fallback 到 urlencoded + const parsed = new URLSearchParams(bodyContent); + parsed.forEach((value, key) => { + try { + params[key] = JSON.parse(value); + } catch { + params[key] = value; + } + }); + if (params.action && !action) { + action = String(params.action); + delete params.action; + } + if (params.echo !== undefined) { + echo = params.echo; + delete params.echo; + } + } + } else { + writeJson(res, 400, { status: 'failed', retcode: 1400, data: null, wording: `bad request: unsupported content-type: ${contentType}` }); return; } } @@ -200,4 +242,4 @@ function writeJson(res: ServerResponse, statusCode: number, data: unknown): void res.statusCode = statusCode; res.setHeader('Content-Type', 'application/json; charset=utf-8'); res.end(JSON.stringify(data)); -} +} \ No newline at end of file diff --git a/packages/core/tests/http-server-content-type.test.ts b/packages/core/tests/http-server-content-type.test.ts new file mode 100644 index 00000000..71d7ea26 --- /dev/null +++ b/packages/core/tests/http-server-content-type.test.ts @@ -0,0 +1,149 @@ +// Tests for HTTP server adapter content-type parsing (POST body). +// Covers: application/x-www-form-urlencoded, application/json, +// no content-type fallback, and unsupported content-type rejection. + +import { describe, expect, it, vi, beforeAll, afterAll } from 'vitest'; +import http from 'http'; +import { HttpServerAdapter } from '../src/onebot/network/http-server-adapter'; +import type { NetworkAdapterContext } from '../src/onebot/network/adapter'; +import type { HttpServerNetwork } from '../src/onebot/types'; + +// ─── Helpers ─── + +function fakeCtx(handleFn: (action: string, params: Record) => unknown): NetworkAdapterContext { + return { + uin: '10001', + api: { + handle: vi.fn(async (action: string, params: Record) => { + const data = handleFn(action, params); + return { status: 'ok', retcode: 0, data }; + }), + } as any, + buildLifecycleEvent: vi.fn(() => ({})), + buildHeartbeatEvent: vi.fn(() => ({})), + }; +} + +function post(port: number, path: string, body: string, headers: Record = {}): Promise<{ status: number; body: any }> { + return new Promise((resolve, reject) => { + const req = http.request({ hostname: '127.0.0.1', port, path, method: 'POST', headers }, (res) => { + const chunks: Buffer[] = []; + res.on('data', (c) => chunks.push(c)); + res.on('end', () => { + const raw = Buffer.concat(chunks).toString('utf8'); + try { + resolve({ status: res.statusCode!, body: JSON.parse(raw) }); + } catch { + resolve({ status: res.statusCode!, body: raw }); + } + }); + }); + req.on('error', reject); + req.end(body); + }); +} + +// ─── Tests ─── + +describe('HttpServerAdapter content-type parsing', () => { + let adapter: HttpServerAdapter; + let handleFn: ReturnType) => unknown>>; + const PORT = 19876; + + beforeAll(async () => { + handleFn = vi.fn((_action: string, params: Record) => params); + const ctx = fakeCtx(handleFn); + const config: HttpServerNetwork = { name: 'test-http', port: PORT, enabled: true, messageFormat: 'array', reportSelfMessage: false }; + adapter = new HttpServerAdapter('test-http', config, ctx); + adapter.open(); + // Wait for server to be listening + await new Promise((resolve) => setTimeout(resolve, 100)); + }); + + afterAll(() => { + adapter.close(); + }); + + it('should parse application/json body', async () => { + const res = await post(PORT, '/send_message', JSON.stringify({ params: { group_id: 123, message: 'hi' } }), { + 'content-type': 'application/json', + }); + expect(res.status).toBe(200); + expect(res.body.status).toBe('ok'); + expect(handleFn).toHaveBeenCalledWith('send_message', { group_id: 123, message: 'hi' }); + }); + + it('should parse application/x-www-form-urlencoded body', async () => { + handleFn.mockClear(); + const body = 'group_id=456&message=hello'; + const res = await post(PORT, '/send_message', body, { + 'content-type': 'application/x-www-form-urlencoded', + }); + expect(res.status).toBe(200); + expect(res.body.status).toBe('ok'); + expect(handleFn).toHaveBeenCalledWith('send_message', { group_id: 456, message: 'hello' }); + }); + + it('should JSON-parse values in urlencoded body', async () => { + handleFn.mockClear(); + const body = 'user_id=789&data={"nested":true}'; + const res = await post(PORT, '/get_info', body, { + 'content-type': 'application/x-www-form-urlencoded', + }); + expect(res.status).toBe(200); + expect(handleFn).toHaveBeenCalledWith('get_info', { user_id: 789, data: { nested: true } }); + }); + + it('should extract action from urlencoded body when path has no action', async () => { + handleFn.mockClear(); + const body = 'action=get_status&key=value'; + const res = await post(PORT, '/', body, { + 'content-type': 'application/x-www-form-urlencoded', + }); + expect(res.status).toBe(200); + expect(handleFn).toHaveBeenCalledWith('get_status', { key: 'value' }); + }); + + it('should extract echo from urlencoded body', async () => { + handleFn.mockClear(); + const body = 'action=test_action&echo=12345&foo=bar'; + const res = await post(PORT, '/', body, { + 'content-type': 'application/x-www-form-urlencoded', + }); + expect(res.status).toBe(200); + expect(res.body.echo).toBe(12345); + expect(handleFn).toHaveBeenCalledWith('test_action', { foo: 'bar' }); + }); + + it('should reject unsupported content-type with 400', async () => { + const res = await post(PORT, '/send_message', '', { + 'content-type': 'application/xml', + }); + expect(res.status).toBe(400); + expect(res.body.wording).toContain('unsupported content-type'); + }); + + it('should reject invalid JSON with explicit application/json content-type', async () => { + const res = await post(PORT, '/send_message', 'not-json{{{', { + 'content-type': 'application/json', + }); + expect(res.status).toBe(400); + expect(res.body.wording).toContain('invalid json'); + }); + + it('should fallback to urlencoded when no content-type and body is not valid JSON', async () => { + handleFn.mockClear(); + const body = 'action=fallback_action¶m1=value1'; + const res = await post(PORT, '/', body, {}); + expect(res.status).toBe(200); + expect(handleFn).toHaveBeenCalledWith('fallback_action', { param1: 'value1' }); + }); + + it('should parse JSON when no content-type and body is valid JSON', async () => { + handleFn.mockClear(); + const body = JSON.stringify({ action: 'json_action', params: { x: 1 } }); + const res = await post(PORT, '/', body, {}); + expect(res.status).toBe(200); + expect(handleFn).toHaveBeenCalledWith('json_action', { x: 1 }); + }); +}); From b99f5c0bf17cb0f7093e31471cebe22b1f867180 Mon Sep 17 00:00:00 2001 From: stla <130404897+Stlara-F@users.noreply.github.com> Date: Mon, 18 May 2026 07:03:45 +0000 Subject: [PATCH 06/48] fix(request-actions): match group add/invite flags by UID and add regression tests --- .../src/onebot/modules/request-actions.ts | 11 ++- .../core/tests/onebot/request-actions.test.ts | 67 +++++++++++++++++++ 2 files changed, 77 insertions(+), 1 deletion(-) create mode 100644 packages/core/tests/onebot/request-actions.test.ts diff --git a/packages/core/src/onebot/modules/request-actions.ts b/packages/core/src/onebot/modules/request-actions.ts index e2bf9784..9dcdb8b9 100644 --- a/packages/core/src/onebot/modules/request-actions.ts +++ b/packages/core/src/onebot/modules/request-actions.ts @@ -9,11 +9,20 @@ export async function handleGroupAddRequest( // flag format: "add:groupId:uid" or "invite:groupId:uid" (from event-converter) const parts = flag.split(':'); if (parts.length < 3) throw new Error('invalid group request flag'); + const requestType = parts[0]; const groupId = parseInt(parts[1], 10); + const targetUid = parts.slice(2).join(':'); if (!groupId) throw new Error('invalid group_id in flag'); + if (!targetUid) throw new Error('invalid request target in flag'); const requests = await bridge.fetchGroupRequests(); - const matching = requests.find(r => r.groupId === groupId); + const matching = requests.find((r) => { + if (r.groupId !== groupId) return false; + if (requestType === 'add') return r.targetUid === targetUid; + if (requestType === 'invite') return r.invitorUid === targetUid; + return false; + }) || requests.find(r => r.groupId === groupId); + if (!matching) { throw new Error('matching group request not found'); } diff --git a/packages/core/tests/onebot/request-actions.test.ts b/packages/core/tests/onebot/request-actions.test.ts new file mode 100644 index 00000000..6e51dcf5 --- /dev/null +++ b/packages/core/tests/onebot/request-actions.test.ts @@ -0,0 +1,67 @@ +import { describe, expect, it, vi } from 'vitest'; +import { handleGroupAddRequest } from '../../src/onebot/modules/request-actions'; +import type { BridgeInterface } from '../../src/bridge/bridge-interface'; +import type { GroupRequestInfo } from '../../src/bridge/qq-info'; + +function fakeBridge(overrides: Partial = {}): BridgeInterface { + return new Proxy(overrides as BridgeInterface, { + get(target, prop) { + if (prop in target) return (target as any)[prop]; + throw new Error(`fakeBridge: '${String(prop)}' was not stubbed`); + }, + }); +} + +function fakeRequest(overrides: Partial = {}): GroupRequestInfo { + return { + groupId: 999, + groupName: 'g', + targetUid: 'u_t', + targetUin: 5555, + targetName: 'target', + invitorUid: 'u_i', + invitorUin: 7777, + invitorName: 'inviter', + operatorUid: 'u_o', + operatorUin: 8888, + operatorName: 'op', + sequence: 42, + state: 1, + eventType: 7, + comment: 'pls', + filtered: false, + ...overrides, + }; +} + +describe('onebot/modules/request-actions / handleGroupAddRequest', () => { + it('matches add requests by groupId and targetUid', async () => { + const setGroupAddRequest = vi.fn(async () => {}); + const bridge = fakeBridge({ + fetchGroupRequests: vi.fn(async () => [ + fakeRequest({ groupId: 999, targetUid: 'u_t', sequence: 42, eventType: 7, filtered: false }), + ]), + setGroupAddRequest: setGroupAddRequest as any, + }); + + await handleGroupAddRequest(bridge, 'add:999:u_t', true, 'ok'); + + expect(setGroupAddRequest).toHaveBeenCalledOnce(); + expect(setGroupAddRequest).toHaveBeenCalledWith(999, 42, 7, true, 'ok', false); + }); + + it('matches invite requests by groupId and invitorUid', async () => { + const setGroupAddRequest = vi.fn(async () => {}); + const bridge = fakeBridge({ + fetchGroupRequests: vi.fn(async () => [ + fakeRequest({ groupId: 999, invitorUid: 'u_i', sequence: 97, eventType: 8, filtered: false }), + ]), + setGroupAddRequest: setGroupAddRequest as any, + }); + + await handleGroupAddRequest(bridge, 'invite:999:u_i', false, 'no'); + + expect(setGroupAddRequest).toHaveBeenCalledOnce(); + expect(setGroupAddRequest).toHaveBeenCalledWith(999, 97, 8, false, 'no', false); + }); +}); From 4d7302a13f537aadc34e0c68ba7c3389e0192a25 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Mon, 18 May 2026 18:01:57 +0800 Subject: [PATCH 07/48] chore(github): add issue templates for bug reports and feature requests Adds structured YAML issue forms (bug + feature) and a config that disables blank issues and links to the QQ group / Telegram channels already in README. --- .github/ISSUE_TEMPLATE/bug_report.yml | 119 +++++++++++++++++++++ .github/ISSUE_TEMPLATE/config.yml | 11 ++ .github/ISSUE_TEMPLATE/feature_request.yml | 76 +++++++++++++ 3 files changed, 206 insertions(+) create mode 100644 .github/ISSUE_TEMPLATE/bug_report.yml create mode 100644 .github/ISSUE_TEMPLATE/config.yml create mode 100644 .github/ISSUE_TEMPLATE/feature_request.yml diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml new file mode 100644 index 00000000..80b0d277 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -0,0 +1,119 @@ +name: Bug 反馈 +description: 报告一个可复现的问题 +title: "[Bug] " +labels: ["bug"] +body: + - type: markdown + attributes: + value: | + 感谢花时间反馈 Bug。请尽量填全以下信息,方便我们定位问题。 + 在提交前,请先在 [Issues](https://github.com/SnowLuma/SnowLuma/issues?q=is%3Aissue) 中搜索是否已有相同问题。 + + - type: checkboxes + id: preflight + attributes: + label: 提交前检查 + options: + - label: 我已搜索过 Issues,确认没有重复的反馈 + required: true + - label: 我使用的是 [最新 Release](https://github.com/SnowLuma/SnowLuma/releases) 或当前 `dev` 分支构建 + required: true + + - type: input + id: snowluma-version + attributes: + label: SnowLuma 版本 + description: 启动日志首行或 `package.json` 里的版本号 + placeholder: "例如 1.8.5" + validations: + required: true + + - type: dropdown + id: adapter + attributes: + label: 出问题的适配器 + description: 可多选 + multiple: true + options: + - WebSocket Server + - WebSocket Client + - HTTP Server + - HTTP Post + - WebUI + - Bridge / Core(协议层) + - 其他 / 不确定 + validations: + required: true + + - type: input + id: os + attributes: + label: 操作系统 + placeholder: "例如 Windows 11 23H2 / macOS 14.5 / Ubuntu 22.04" + validations: + required: true + + - type: input + id: node-version + attributes: + label: Node.js 版本 + description: '`node -v` 的输出。如果使用预构建包可填"预构建包"' + placeholder: "例如 v20.11.0 或 预构建包" + validations: + required: true + + - type: input + id: qq-version + attributes: + label: QQ 客户端版本 + description: QQ NT 客户端的版本号 + placeholder: "例如 9.9.15-29722" + + - type: textarea + id: description + attributes: + label: 问题描述 + description: 简要说明发生了什么 + validations: + required: true + + - type: textarea + id: reproduce + attributes: + label: 复现步骤 + description: 详细列出如何触发这个问题 + placeholder: | + 1. 启动 SnowLuma 并登录账号 ... + 2. 通过 HTTP Server 调用 `send_group_msg` ... + 3. 观察到 ... + validations: + required: true + + - type: textarea + id: expected + attributes: + label: 期望行为 + validations: + required: true + + - type: textarea + id: actual + attributes: + label: 实际行为 + validations: + required: true + + - type: textarea + id: logs + attributes: + label: 相关日志 / 错误堆栈 + description: | + 粘贴控制台日志、SSE 实时日志或错误堆栈。 + 请注意脱敏:移除 access token、账号密码、私聊内容等敏感信息。 + render: shell + + - type: textarea + id: extra + attributes: + label: 补充信息 + description: 配置片段(脱敏后)、截图、相关 Issue / PR 链接等 diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 00000000..cb45a4d5 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,11 @@ +blank_issues_enabled: false +contact_links: + - name: QQ 群 + url: https://qm.qq.com/q/g3UMLpWALe + about: 日常使用问题、快速交流可以先来 QQ 群 + - name: Telegram + url: https://t.me/napcatqq + about: 海外用户交流频道 + - name: Releases + url: https://github.com/SnowLuma/SnowLuma/releases + about: 在反馈 Bug 前,请先确认已使用最新发布版本 diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml new file mode 100644 index 00000000..6b4b027c --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.yml @@ -0,0 +1,76 @@ +name: 功能请求 +description: 提议一个新功能或对现有功能的增强 +title: "[Feature] " +labels: ["enhancement"] +body: + - type: markdown + attributes: + value: | + 感谢您的建议。在提交前,请先在 [Issues](https://github.com/SnowLuma/SnowLuma/issues?q=is%3Aissue) 中搜索是否已有类似提案。 + + - type: checkboxes + id: preflight + attributes: + label: 提交前检查 + options: + - label: 我已搜索过 Issues,确认没有重复的提案 + required: true + + - type: dropdown + id: scope + attributes: + label: 涉及范围 + multiple: true + options: + - OneBot 协议 / 消息段 + - WebSocket Server / Client 适配器 + - HTTP Server / Post 适配器 + - WebUI 管理面板 + - SDK (`@snowluma/sdk`) + - UI 组件 (`@snowluma/ui`) + - Bridge / Core(协议层) + - 构建 / 发布流程 + - 文档 + - 其他 + validations: + required: true + + - type: textarea + id: problem + attributes: + label: 需求场景 / 当前痛点 + description: 这个功能要解决什么问题?目前是如何变通处理的? + validations: + required: true + + - type: textarea + id: proposal + attributes: + label: 期望方案 + description: 您希望它如何工作?如果是 API 改动,建议给出示例输入 / 输出 + validations: + required: true + + - type: textarea + id: alternatives + attributes: + label: 已考虑的替代方案 + description: 还想过哪些其他实现路径,为什么放弃 + + - type: textarea + id: references + attributes: + label: 参考链接 + description: 例如 OneBot 规范条目、其他实现的对应特性、相关 Issue / PR + placeholder: | + - OneBot v11 规范: https://github.com/botuniverse/onebot-11/... + - 相关讨论: #xxx + + - type: checkboxes + id: willingness + attributes: + label: 您是否愿意提交 PR 来实现这个功能? + options: + - label: 愿意,且需要维护者讨论方案后再动手 + - label: 愿意,已有大致实现思路 + - label: 暂时只提建议 From 9f9db8d16feeeb032b0c4fb2d7fd32393146651b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=89=8B=E7=93=9C=E4=B8=80=E5=8D=81=E9=9B=AA?= Date: Mon, 18 May 2026 19:31:42 +0800 Subject: [PATCH 08/48] feat: Add @snowluma/protobuf package Introduce a new @snowluma/protobuf package (v0.0.4) that provides a lightweight protobuf-ts wrapper (NapProto/NapProtoMsg) with type helpers, ProtoField factory, and encode/decode utilities. Adds package.json, tsconfig.json, and the implementation at src/NapProto.ts. pnpm-lock.yaml was updated to include the @protobuf-ts/runtime dependency resolution. --- packages/protobuf/package.json | 14 +++ packages/protobuf/src/NapProto.ts | 202 ++++++++++++++++++++++++++++++ packages/protobuf/tsconfig.json | 5 + pnpm-lock.yaml | 11 ++ 4 files changed, 232 insertions(+) create mode 100644 packages/protobuf/package.json create mode 100644 packages/protobuf/src/NapProto.ts create mode 100644 packages/protobuf/tsconfig.json diff --git a/packages/protobuf/package.json b/packages/protobuf/package.json new file mode 100644 index 00000000..df67a597 --- /dev/null +++ b/packages/protobuf/package.json @@ -0,0 +1,14 @@ +{ + "name": "@snowluma/protobuf", + "type": "module", + "version": "0.0.4", + "description": "A lightweight, elegant, and efficient protobuf-ts solution.From NapNeko/NapCatQQ", + "main": "./src/NapProto.ts", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1", + "prepack": "tsc" + }, + "dependencies": { + "@protobuf-ts/runtime": "^2.9.4" + } +} diff --git a/packages/protobuf/src/NapProto.ts b/packages/protobuf/src/NapProto.ts new file mode 100644 index 00000000..09e47c3a --- /dev/null +++ b/packages/protobuf/src/NapProto.ts @@ -0,0 +1,202 @@ +// @ts-nocheck +import { MessageType, PartialMessage, RepeatType, ScalarType } from '@protobuf-ts/runtime'; +import { PartialFieldInfo } from '@protobuf-ts/runtime/build/types/reflection-info'; + +export type LowerCamelCase = CamelCaseHelper; + +export type CamelCaseHelper< + S extends string, + CapNext extends boolean, + IsFirstChar extends boolean +> = S extends `${infer F}${infer R}` + ? F extends '_' + ? CamelCaseHelper + : F extends `${number}` + ? `${F}${CamelCaseHelper}` + : CapNext extends true + ? `${Uppercase}${CamelCaseHelper}` + : IsFirstChar extends true + ? `${Lowercase}${CamelCaseHelper}` + : `${F}${CamelCaseHelper}` + : ''; + +export type ScalarTypeToTsType = T extends + | ScalarType.DOUBLE + | ScalarType.FLOAT + | ScalarType.INT32 + | ScalarType.FIXED32 + | ScalarType.UINT32 + | ScalarType.SFIXED32 + | ScalarType.SINT32 + ? number + : T extends ScalarType.INT64 | ScalarType.UINT64 | ScalarType.FIXED64 | ScalarType.SFIXED64 | ScalarType.SINT64 + ? bigint + : T extends ScalarType.BOOL + ? boolean + : T extends ScalarType.STRING + ? string + : T extends ScalarType.BYTES + ? Uint8Array + : never; + +export interface BaseProtoFieldType { + kind: 'scalar' | 'message'; + no: number; + type: T; + optional: O; + repeat: R; +} + +export interface ScalarProtoFieldType + extends BaseProtoFieldType { + kind: 'scalar'; +} + +export interface MessageProtoFieldType< + T extends () => ProtoMessageType, + O extends boolean, + R extends O extends true ? false : boolean +> extends BaseProtoFieldType { + kind: 'message'; +} + +export type ProtoFieldType = + | ScalarProtoFieldType + | MessageProtoFieldType<() => ProtoMessageType, boolean, boolean>; + +export type ProtoMessageType = { + [key: string]: ProtoFieldType; +}; + +export function ProtoField< + T extends ScalarType, + O extends boolean = false, + R extends O extends true ? false : boolean = false +> (no: number, type: T, optional?: O, repeat?: R): ScalarProtoFieldType; +export function ProtoField< + T extends () => ProtoMessageType, + O extends boolean = false, + R extends O extends true ? false : boolean = false +> (no: number, type: T, optional?: O, repeat?: R): MessageProtoFieldType; +export function ProtoField ( + no: number, + type: ScalarType | (() => ProtoMessageType), + optional?: boolean, + repeat?: boolean +): ProtoFieldType { + if (typeof type === 'function') { + return { kind: 'message', no, type, optional: optional ?? false, repeat: repeat ?? false }; + } else { + return { kind: 'scalar', no, type, optional: optional ?? false, repeat: repeat ?? false }; + } +} + +export type ProtoFieldReturnType = + NonNullable extends ScalarProtoFieldType + ? ScalarTypeToTsType + : T extends NonNullable> + ? NonNullable, E>> + : never; + +export type RequiredFieldsBaseType = { + [K in keyof T as T[K] extends { optional: true; } ? never : LowerCamelCase]: T[K] extends { + repeat: true; + } + ? ProtoFieldReturnType[] + : ProtoFieldReturnType; +}; + +export type OptionalFieldsBaseType = { + [K in keyof T as T[K] extends { optional: true; } ? LowerCamelCase : never]?: T[K] extends { + repeat: true; + } + ? ProtoFieldReturnType[] + : ProtoFieldReturnType; +}; + +export type RequiredFieldsType = E extends true + ? Partial> + : RequiredFieldsBaseType; + +export type OptionalFieldsType = E extends true + ? Partial> + : OptionalFieldsBaseType; + +export type NapProtoStructType = RequiredFieldsType & OptionalFieldsType; + +export type NapProtoEncodeStructType = NapProtoStructType; + +export type NapProtoDecodeStructType = NapProtoStructType; + +class NapProtoRealMsg { + private readonly _field: PartialFieldInfo[]; + private readonly _proto_msg: MessageType>; + private static cache = new WeakMap>(); + + private constructor (fields: T) { + this._field = Object.keys(fields).map((key) => { + const field = fields[key]; + if (field.kind === 'scalar') { + const repeatType = field.repeat + ? [ScalarType.STRING, ScalarType.BYTES].includes(field.type) + ? RepeatType.UNPACKED + : RepeatType.PACKED + : RepeatType.NO; + return { + no: field.no, + name: key, + kind: 'scalar', + T: field.type, + opt: field.optional, + repeat: repeatType, + }; + } else if (field.kind === 'message') { + return { + no: field.no, + name: key, + kind: 'message', + repeat: field.repeat ? RepeatType.PACKED : RepeatType.NO, + T: () => NapProtoRealMsg.getInstance(field.type())._proto_msg, + }; + } else { + throw new Error(`Unknown field kind: ${field.kind}`); + } + }) as PartialFieldInfo[]; + this._proto_msg = new MessageType>('nya', this._field); + } + + static getInstance (fields: T): NapProtoRealMsg { + let instance = this.cache.get(fields); + if (!instance) { + instance = new NapProtoRealMsg(fields); + this.cache.set(fields, instance); + } + return instance; + } + + encode (data: NapProtoEncodeStructType): Uint8Array { + return this._proto_msg.toBinary(this._proto_msg.create(data as PartialMessage>)); + } + + decode (data: Uint8Array): NapProtoDecodeStructType { + return this._proto_msg.fromBinary(data) as NapProtoDecodeStructType; + } +} + +export class NapProtoMsg { + private realMsg: NapProtoRealMsg; + + constructor (fields: T) { + this.realMsg = NapProtoRealMsg.getInstance(fields); + } + + encode (data: NapProtoEncodeStructType): Uint8Array { + return this.realMsg.encode(data); + } + + decode (data: Uint8Array): NapProtoDecodeStructType { + return this.realMsg.decode(data); + } +} + +export { ScalarType } from '@protobuf-ts/runtime'; diff --git a/packages/protobuf/tsconfig.json b/packages/protobuf/tsconfig.json new file mode 100644 index 00000000..cd0e5b46 --- /dev/null +++ b/packages/protobuf/tsconfig.json @@ -0,0 +1,5 @@ +{ + "extends": "../../tsconfig.base.json", + "include": ["src/**/*"], + "exclude": ["node_modules"] +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index be5db7cb..3d3a1829 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -64,6 +64,12 @@ importers: specifier: ^4.1.4 version: 4.1.4(@types/node@24.12.2)(vite@8.0.8(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)) + packages/protobuf: + dependencies: + '@protobuf-ts/runtime': + specifier: ^2.9.4 + version: 2.11.1 + packages/runtime: {} packages/sdk: @@ -680,6 +686,9 @@ packages: resolution: {integrity: sha512-tmmZ3lQxAe/k/+rNnXQRawJ4NjxO2hqiOLTHvWchtGZULp4RyFeh6aU4XdOYBFe2KE1oShQTv4AblOs2iOrNnQ==} engines: {node: '>= 10.0.0'} + '@protobuf-ts/runtime@2.11.1': + resolution: {integrity: sha512-KuDaT1IfHkugM2pyz+FwiY80ejWrkH1pAtOBOZFuR6SXEFTsnb/jiQWQ1rCIrcKx2BtyxnxW6BWwsVSA/Ie+WQ==} + '@radix-ui/number@1.1.1': resolution: {integrity: sha512-MkKCwxlXTgz6CFoJx3pCwn07GKp36+aZyu/u2Ln2VrA5DcdyCZkASEDBTd8x5whTQQL5CiYf4prXKLcgQdv29g==} @@ -3019,6 +3028,8 @@ snapshots: '@parcel/watcher-win32-x64': 2.5.6 optional: true + '@protobuf-ts/runtime@2.11.1': {} + '@radix-ui/number@1.1.1': {} '@radix-ui/primitive@1.1.3': {} From df691c4e8fb61adfb61297bfd8de28a48d65211e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=89=8B=E7=93=9C=E4=B8=80=E5=8D=81=E9=9B=AA?= Date: Mon, 18 May 2026 20:43:32 +0800 Subject: [PATCH 09/48] Revert "feat: Add @snowluma/protobuf package" This reverts commit 9f9db8d16feeeb032b0c4fb2d7fd32393146651b. --- packages/protobuf/package.json | 14 --- packages/protobuf/src/NapProto.ts | 202 ------------------------------ packages/protobuf/tsconfig.json | 5 - pnpm-lock.yaml | 11 -- 4 files changed, 232 deletions(-) delete mode 100644 packages/protobuf/package.json delete mode 100644 packages/protobuf/src/NapProto.ts delete mode 100644 packages/protobuf/tsconfig.json diff --git a/packages/protobuf/package.json b/packages/protobuf/package.json deleted file mode 100644 index df67a597..00000000 --- a/packages/protobuf/package.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "name": "@snowluma/protobuf", - "type": "module", - "version": "0.0.4", - "description": "A lightweight, elegant, and efficient protobuf-ts solution.From NapNeko/NapCatQQ", - "main": "./src/NapProto.ts", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1", - "prepack": "tsc" - }, - "dependencies": { - "@protobuf-ts/runtime": "^2.9.4" - } -} diff --git a/packages/protobuf/src/NapProto.ts b/packages/protobuf/src/NapProto.ts deleted file mode 100644 index 09e47c3a..00000000 --- a/packages/protobuf/src/NapProto.ts +++ /dev/null @@ -1,202 +0,0 @@ -// @ts-nocheck -import { MessageType, PartialMessage, RepeatType, ScalarType } from '@protobuf-ts/runtime'; -import { PartialFieldInfo } from '@protobuf-ts/runtime/build/types/reflection-info'; - -export type LowerCamelCase = CamelCaseHelper; - -export type CamelCaseHelper< - S extends string, - CapNext extends boolean, - IsFirstChar extends boolean -> = S extends `${infer F}${infer R}` - ? F extends '_' - ? CamelCaseHelper - : F extends `${number}` - ? `${F}${CamelCaseHelper}` - : CapNext extends true - ? `${Uppercase}${CamelCaseHelper}` - : IsFirstChar extends true - ? `${Lowercase}${CamelCaseHelper}` - : `${F}${CamelCaseHelper}` - : ''; - -export type ScalarTypeToTsType = T extends - | ScalarType.DOUBLE - | ScalarType.FLOAT - | ScalarType.INT32 - | ScalarType.FIXED32 - | ScalarType.UINT32 - | ScalarType.SFIXED32 - | ScalarType.SINT32 - ? number - : T extends ScalarType.INT64 | ScalarType.UINT64 | ScalarType.FIXED64 | ScalarType.SFIXED64 | ScalarType.SINT64 - ? bigint - : T extends ScalarType.BOOL - ? boolean - : T extends ScalarType.STRING - ? string - : T extends ScalarType.BYTES - ? Uint8Array - : never; - -export interface BaseProtoFieldType { - kind: 'scalar' | 'message'; - no: number; - type: T; - optional: O; - repeat: R; -} - -export interface ScalarProtoFieldType - extends BaseProtoFieldType { - kind: 'scalar'; -} - -export interface MessageProtoFieldType< - T extends () => ProtoMessageType, - O extends boolean, - R extends O extends true ? false : boolean -> extends BaseProtoFieldType { - kind: 'message'; -} - -export type ProtoFieldType = - | ScalarProtoFieldType - | MessageProtoFieldType<() => ProtoMessageType, boolean, boolean>; - -export type ProtoMessageType = { - [key: string]: ProtoFieldType; -}; - -export function ProtoField< - T extends ScalarType, - O extends boolean = false, - R extends O extends true ? false : boolean = false -> (no: number, type: T, optional?: O, repeat?: R): ScalarProtoFieldType; -export function ProtoField< - T extends () => ProtoMessageType, - O extends boolean = false, - R extends O extends true ? false : boolean = false -> (no: number, type: T, optional?: O, repeat?: R): MessageProtoFieldType; -export function ProtoField ( - no: number, - type: ScalarType | (() => ProtoMessageType), - optional?: boolean, - repeat?: boolean -): ProtoFieldType { - if (typeof type === 'function') { - return { kind: 'message', no, type, optional: optional ?? false, repeat: repeat ?? false }; - } else { - return { kind: 'scalar', no, type, optional: optional ?? false, repeat: repeat ?? false }; - } -} - -export type ProtoFieldReturnType = - NonNullable extends ScalarProtoFieldType - ? ScalarTypeToTsType - : T extends NonNullable> - ? NonNullable, E>> - : never; - -export type RequiredFieldsBaseType = { - [K in keyof T as T[K] extends { optional: true; } ? never : LowerCamelCase]: T[K] extends { - repeat: true; - } - ? ProtoFieldReturnType[] - : ProtoFieldReturnType; -}; - -export type OptionalFieldsBaseType = { - [K in keyof T as T[K] extends { optional: true; } ? LowerCamelCase : never]?: T[K] extends { - repeat: true; - } - ? ProtoFieldReturnType[] - : ProtoFieldReturnType; -}; - -export type RequiredFieldsType = E extends true - ? Partial> - : RequiredFieldsBaseType; - -export type OptionalFieldsType = E extends true - ? Partial> - : OptionalFieldsBaseType; - -export type NapProtoStructType = RequiredFieldsType & OptionalFieldsType; - -export type NapProtoEncodeStructType = NapProtoStructType; - -export type NapProtoDecodeStructType = NapProtoStructType; - -class NapProtoRealMsg { - private readonly _field: PartialFieldInfo[]; - private readonly _proto_msg: MessageType>; - private static cache = new WeakMap>(); - - private constructor (fields: T) { - this._field = Object.keys(fields).map((key) => { - const field = fields[key]; - if (field.kind === 'scalar') { - const repeatType = field.repeat - ? [ScalarType.STRING, ScalarType.BYTES].includes(field.type) - ? RepeatType.UNPACKED - : RepeatType.PACKED - : RepeatType.NO; - return { - no: field.no, - name: key, - kind: 'scalar', - T: field.type, - opt: field.optional, - repeat: repeatType, - }; - } else if (field.kind === 'message') { - return { - no: field.no, - name: key, - kind: 'message', - repeat: field.repeat ? RepeatType.PACKED : RepeatType.NO, - T: () => NapProtoRealMsg.getInstance(field.type())._proto_msg, - }; - } else { - throw new Error(`Unknown field kind: ${field.kind}`); - } - }) as PartialFieldInfo[]; - this._proto_msg = new MessageType>('nya', this._field); - } - - static getInstance (fields: T): NapProtoRealMsg { - let instance = this.cache.get(fields); - if (!instance) { - instance = new NapProtoRealMsg(fields); - this.cache.set(fields, instance); - } - return instance; - } - - encode (data: NapProtoEncodeStructType): Uint8Array { - return this._proto_msg.toBinary(this._proto_msg.create(data as PartialMessage>)); - } - - decode (data: Uint8Array): NapProtoDecodeStructType { - return this._proto_msg.fromBinary(data) as NapProtoDecodeStructType; - } -} - -export class NapProtoMsg { - private realMsg: NapProtoRealMsg; - - constructor (fields: T) { - this.realMsg = NapProtoRealMsg.getInstance(fields); - } - - encode (data: NapProtoEncodeStructType): Uint8Array { - return this.realMsg.encode(data); - } - - decode (data: Uint8Array): NapProtoDecodeStructType { - return this.realMsg.decode(data); - } -} - -export { ScalarType } from '@protobuf-ts/runtime'; diff --git a/packages/protobuf/tsconfig.json b/packages/protobuf/tsconfig.json deleted file mode 100644 index cd0e5b46..00000000 --- a/packages/protobuf/tsconfig.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "extends": "../../tsconfig.base.json", - "include": ["src/**/*"], - "exclude": ["node_modules"] -} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 3d3a1829..be5db7cb 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -64,12 +64,6 @@ importers: specifier: ^4.1.4 version: 4.1.4(@types/node@24.12.2)(vite@8.0.8(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)) - packages/protobuf: - dependencies: - '@protobuf-ts/runtime': - specifier: ^2.9.4 - version: 2.11.1 - packages/runtime: {} packages/sdk: @@ -686,9 +680,6 @@ packages: resolution: {integrity: sha512-tmmZ3lQxAe/k/+rNnXQRawJ4NjxO2hqiOLTHvWchtGZULp4RyFeh6aU4XdOYBFe2KE1oShQTv4AblOs2iOrNnQ==} engines: {node: '>= 10.0.0'} - '@protobuf-ts/runtime@2.11.1': - resolution: {integrity: sha512-KuDaT1IfHkugM2pyz+FwiY80ejWrkH1pAtOBOZFuR6SXEFTsnb/jiQWQ1rCIrcKx2BtyxnxW6BWwsVSA/Ie+WQ==} - '@radix-ui/number@1.1.1': resolution: {integrity: sha512-MkKCwxlXTgz6CFoJx3pCwn07GKp36+aZyu/u2Ln2VrA5DcdyCZkASEDBTd8x5whTQQL5CiYf4prXKLcgQdv29g==} @@ -3028,8 +3019,6 @@ snapshots: '@parcel/watcher-win32-x64': 2.5.6 optional: true - '@protobuf-ts/runtime@2.11.1': {} - '@radix-ui/number@1.1.1': {} '@radix-ui/primitive@1.1.3': {} From 64530cc2871664e3bb51a9c3d8f399f89cfb7c79 Mon Sep 17 00:00:00 2001 From: H3CoF6 <1707889225@qq.com> Date: Tue, 19 May 2026 02:37:11 +0800 Subject: [PATCH 10/48] Implement some actions: comment, send and cancel like, delete media for group album! --- .../core/src/bridge/actions/group-album.ts | 211 +++++++++++++++++- packages/core/src/bridge/bridge-interface.ts | 3 + packages/core/src/bridge/bridge.ts | 18 +- packages/core/src/bridge/proto/oidb-action.ts | 183 ++++++++++++++- .../core/src/onebot/actions/group-album.ts | 77 +++++++ packages/core/src/onebot/api-handler.ts | 3 + packages/core/src/onebot/instance-context.ts | 3 + 7 files changed, 495 insertions(+), 3 deletions(-) diff --git a/packages/core/src/bridge/actions/group-album.ts b/packages/core/src/bridge/actions/group-album.ts index cd30fe6a..2856905a 100644 --- a/packages/core/src/bridge/actions/group-album.ts +++ b/packages/core/src/bridge/actions/group-album.ts @@ -2,13 +2,29 @@ import type { Bridge } from '../bridge'; import { protoEncode, protoDecode } from '@/protobuf/decode'; -import { GetMediaListRequestSchema, GetMediaListResponseSchema } from '../proto/oidb-action'; +import { GetMediaListRequestSchema, + GetMediaListResponseSchema, + DoQunCommentRequestSchema, + DoQunCommentResponseSchema, + DoQunLikeRequestSchema, + DoQunLikeResponseSchema, + DeleteMediasRequestSchema, + DeleteMediasResponseSchema +} from '../proto/oidb-action'; export interface GroupAlbumMediaResult { mediaList: any[]; nextAttachInfo: string; } +export interface GroupAlbumCommentResult { + id: string; + user: { uin: string }; + content: Array<{ type: number; content: string }>; + time: string; + clientKey: string; +} + function convertBigIntToString(obj: any): any { if (obj === null || obj === undefined) return obj; if (typeof obj === 'bigint') return obj.toString(); @@ -71,3 +87,196 @@ export async function getGroupAlbumMediaList( nextAttachInfo, }); } + + + +export async function commentGroupAlbumMedia( + bridge: Bridge, + groupId: number, + albumId: string, + lloc: string, + content: string +): Promise { + const traceId = `_${Date.now()}_${Math.floor(Math.random() * 100000)}`; + const clientKey = Date.now().toString(); + const uin = bridge.identity.uin; + + const body = protoEncode({ + field1: 8527, + field2: new Uint8Array(0), + field3: new Uint8Array(0), + body: { + groupId: groupId.toString(), + field3: 2, + reqBody: { + field1: { field3: 0, field4: "" }, + field2: { + field1: { uin } + }, + field5: { + field1: { + field2: { + field1: 0, field2: "", + lloc, + field4: "", field6: "", field7: 0, field8: 0, field9: 0, field14: 0, field15: 0, field17: 0 + } + }, + albumId, + field5: 0 + }, + }, + field5: { + field2: { uin }, + field3: { + field1: 0, + field2: content, + field3: "", field4: "", field5: 0, field6: "" + }, + clientKey, + } + }, + traceId, + extMap: [{ key: 'fc-appid', value: '100' }], + }, DoQunCommentRequestSchema); + + const result = await bridge.sendRawPacket( + 'QunAlbum.trpc.qzone.webapp_qun_operation.FeedsWriter.DoQunComment', + body, + 15000 + ); + + if (!result.success || !result.gotResponse || !result.responseData) { + throw new Error(result.errorMessage || 'failed to comment on album media'); + } + + const resp = protoDecode(result.responseData, DoQunCommentResponseSchema); + + const resCode = (resp as any)?.field1; + if (!resp || (resCode !== 0 && resCode !== 8527 && !(resp as any).comment)) { + throw new Error(`comment album media error: retCode ${resCode || 'unknown'}`); + } + + const commentData = (resp as any).comment?.data || {}; + + return convertBigIntToString({ + id: commentData.id || '', + user: { uin: commentData.user?.uin || '' }, + content: commentData.content || [], + time: commentData.time || '0', + clientKey: commentData.clientKey || '', + }); +} + +export async function likeGroupAlbumMedia( + bridge: Bridge, + groupId: number, + albumId: string, + batchId: string, + lloc: string | undefined, + isLike: boolean +): Promise { + const uin = bridge.identity.uin; + const clientKey = `${uin}_${Date.now()}_${Math.floor(Math.random() * 100000)}`; + + const type = isLike ? 2 : 1; + const status = isLike ? 0 : 1; + + let id = ''; + if (lloc) { + id = `421_1_0_${groupId}|${albumId}|${batchId}^||^421_1_0_${groupId}|${albumId}|${lloc}^||^0`; + } else { + id = `421_1_0_${groupId}|${albumId}|${batchId}`; + } + + const body = protoEncode({ + field1: 5495, + field2: "h5_test", + field3: "h5_test", + body: { + type, + like: { id, status }, + publish: { + cellCommon: { + time: BigInt(Date.now()), + feedId: `422_0_${batchId}` + }, + cellUserInfo: { + user: { uin } + }, + cellMedia: { + albumId: albumId, + batchId: BigInt(batchId) + }, + cellQunInfo: { + qunId: groupId.toString() + } + }, + clientKey + }, + extMap: [{ key: 'fc-appid', value: '100' }], + }, DoQunLikeRequestSchema); + + const result = await bridge.sendRawPacket( + 'QunAlbum.trpc.qzone.webapp_qun_operation.FeedsWriter.DoQunLike', + body, + 15000 + ); + + if (!result.success || !result.gotResponse || !result.responseData) { + throw new Error(result.errorMessage || 'failed to like album media'); + } + + const resp = protoDecode(result.responseData, DoQunLikeResponseSchema); + const resCode = (resp as any)?.field1; + + if (!resp || resCode !== 5495) { + throw new Error(`like album media error: retCode ${resCode || 'unknown'}`); + } + + return (resp as any).body?.like || {}; +} + +export async function deleteGroupAlbumMedia( + bridge: Bridge, + groupId: number, + albumId: string, + lloc: string +): Promise { + const uin = bridge.identity.uin; + const clientKey = `${uin}_${Date.now()}_${Math.floor(Math.random() * 100000)}`; + + const body = protoEncode({ + field1: 8694, + field2: "h5_test", + field3: "h5_test", + body: { + groupId: groupId.toString(), + albumId: albumId, + lloc: lloc, + }, + traceId: clientKey, + extMap: [{ key: 'fc-appid', value: '100' }], + }, DeleteMediasRequestSchema); + + const result = await bridge.sendRawPacket( + 'QunAlbum.trpc.qzone.webapp_qun_media.QunMedia.DeleteMedias', + body, + 15000 + ); + + if (!result.success || !result.gotResponse || !result.responseData) { + throw new Error(result.errorMessage || 'failed to delete album media'); + } + + const resp = protoDecode(result.responseData, DeleteMediasResponseSchema); + const resCode = (resp as any)?.field1; + const errCode = (resp as any)?.field2; + const errMsg = (resp as any)?.field3; + + if (!resp || resCode !== 8694 || errCode) { + throw new Error(`delete album media error [${errCode || 'unknown'}]: ${errMsg || 'unknown'}`); + } + + return { success: true }; +} + diff --git a/packages/core/src/bridge/bridge-interface.ts b/packages/core/src/bridge/bridge-interface.ts index 24440d0f..e823567e 100644 --- a/packages/core/src/bridge/bridge-interface.ts +++ b/packages/core/src/bridge/bridge-interface.ts @@ -95,6 +95,9 @@ export interface BridgeInterface { getGroupAlbumList(groupId: number): Promise; uploadImageToGroupAlbum(groupId: number, albumId: string, albumName: string, filePath: string): Promise; getGroupAlbumMediaList(groupId: number, albumId: string, attachInfo?: string): Promise; + commentGroupAlbumMedia(groupId: number, albumId: string, lloc: string, content: string): Promise; + deleteGroupAlbumMedia(groupId: number, albumId: string, lloc: string): Promise; + likeGroupAlbumMedia(groupId: number, albumId: string, batchId: string, lloc: string | undefined, isLike: boolean): Promise; // ─── Forward ─── uploadForwardNodes(nodes: ForwardNodePayload[], groupId?: number): Promise; diff --git a/packages/core/src/bridge/bridge.ts b/packages/core/src/bridge/bridge.ts index ee048910..ee8acb60 100644 --- a/packages/core/src/bridge/bridge.ts +++ b/packages/core/src/bridge/bridge.ts @@ -129,7 +129,11 @@ import { getGroupAlbumListWeb as getGroupAlbumListWeb_, uploadImageToGroupAlbumWeb as uploadImageToGroupAlbumWeb_, } from './web-actions'; -import { getGroupAlbumMediaList as getGroupAlbumMediaList_ } from './actions/group-album'; +import { getGroupAlbumMediaList as getGroupAlbumMediaList_, + commentGroupAlbumMedia as commentGroupAlbumMedia_, + likeGroupAlbumMedia as likeGroupAlbumMedia_, + deleteGroupAlbumMedia as deleteGroupAlbumMedia_, +} from './actions/group-album'; import type { GroupFilesResult } from './actions/group-file'; import type { MediaIndexNode } from './actions/shared'; import { BridgeEventBus } from './event-bus'; @@ -499,6 +503,18 @@ export class Bridge implements BridgeInterface { return getGroupAlbumMediaList_(this, groupId, albumId, attachInfo); } + async commentGroupAlbumMedia(groupId: number, albumId: string, lloc: string, content: string): Promise { + return commentGroupAlbumMedia_(this, groupId, albumId, lloc, content); + } + + async likeGroupAlbumMedia(groupId: number, albumId: string, batchId: string, lloc: string | undefined, isLike: boolean): Promise { + return likeGroupAlbumMedia_(this, groupId, albumId, batchId, lloc, isLike); + } + + async deleteGroupAlbumMedia(groupId: number, albumId: string, lloc: string): Promise { + return deleteGroupAlbumMedia_(this, groupId, albumId, lloc); + } + async sendGroupNotice(groupId: number, content: string, options?: any) { return sendGroupNotice_(this, groupId, content, options); } diff --git a/packages/core/src/bridge/proto/oidb-action.ts b/packages/core/src/bridge/proto/oidb-action.ts index 82cc8dae..2037d6c0 100644 --- a/packages/core/src/bridge/proto/oidb-action.ts +++ b/packages/core/src/bridge/proto/oidb-action.ts @@ -1351,4 +1351,185 @@ export const GetMediaListResponseSchema = { field2: { field: 2, type: 'bytes' as const }, field3: { field: 3, type: 'bytes' as const }, data: { field: 4, type: 'message' as const, schema: GetMediaListRspDataSchema }, // 将原本的 bytes 修正为 message 解析 -} satisfies ProtoSchema; \ No newline at end of file +} satisfies ProtoSchema; + + +// --- DoQunComment: Comment on group album media --- + +// --- DoQunComment: 严格对齐底层字节的字段定义 --- + +export const CommentContentItemSchema = { + type: { field: 1, type: 'uint32' as const }, + content: { field: 2, type: 'string' as const }, +} satisfies ProtoSchema; + +export const CommentUserSchema = { + uin: { field: 13, type: 'string' as const }, +} satisfies ProtoSchema; + +// 评论具体内容结构 (原 CommentReqContentSchema) +export const CommentReqContentSchema = { + field2: { field: 2, type: 'message' as const, schema: CommentUserSchema }, + field3: { field: 3, type: 'message' as const, schema: { + field1: { field: 1, type: 'uint32' as const }, + field2: { field: 2, type: 'string' as const }, + field3: { field: 3, type: 'string' as const }, + field4: { field: 4, type: 'string' as const }, + field5: { field: 5, type: 'uint32' as const }, + field6: { field: 6, type: 'string' as const }, + } satisfies ProtoSchema }, + clientKey: { field: 7, type: 'string' as const }, // 对应你的 clientKey +} satisfies ProtoSchema; + +export const CommentReqPhotoInfoSchema = { + field1: { field: 1, type: 'message' as const, schema: { + field2: { field: 2, type: 'message' as const, schema: { + field1: { field: 1, type: 'uint32' as const }, + field2: { field: 2, type: 'string' as const }, + lloc: { field: 3, type: 'string' as const }, + field4: { field: 4, type: 'string' as const }, + field6: { field: 6, type: 'string' as const }, + field7: { field: 7, type: 'uint32' as const }, + field8: { field: 8, type: 'uint32' as const }, + field9: { field: 9, type: 'uint32' as const }, + field14: { field: 14, type: 'uint32' as const }, + field15: { field: 15, type: 'uint32' as const }, + field17: { field: 17, type: 'uint32' as const }, + } satisfies ProtoSchema }, + } satisfies ProtoSchema }, + albumId: { field: 3, type: 'string' as const }, + field5: { field: 5, type: 'uint32' as const }, +} satisfies ProtoSchema; + +export const CommentReqBodySchema = { + field1: { field: 1, type: 'message' as const, schema: { + field3: { field: 3, type: 'uint32' as const }, + field4: { field: 4, type: 'string' as const }, + } satisfies ProtoSchema }, + field2: { field: 2, type: 'message' as const, schema: { + field1: { field: 1, type: 'message' as const, schema: CommentUserSchema } + } satisfies ProtoSchema }, + field5: { field: 5, type: 'message' as const, schema: CommentReqPhotoInfoSchema }, // 注意:抓包证实照片在 field 5 +} satisfies ProtoSchema; + +export const DoQunCommentRequestSchema = { + field1: { field: 1, type: 'int32' as const }, + field2: { field: 2, type: 'bytes' as const }, + field3: { field: 3, type: 'bytes' as const }, + body: { field: 4, type: 'message' as const, schema: { + groupId: { field: 2, type: 'string' as const }, + field3: { field: 3, type: 'uint32' as const }, + reqBody: { field: 4, type: 'message' as const, schema: CommentReqBodySchema }, + field5: { field: 5, type: 'message' as const, schema: CommentReqContentSchema }, // 注意:评论文本实际在外层的 field 5 + } satisfies ProtoSchema }, + traceId: { field: 5, type: 'string' as const }, + extMap: { field: 10, type: 'repeated_message' as const, schema: ExtMapEntrySchema }, +} satisfies ProtoSchema; + +export const CommentRespUserSchema = { + uin: { field: 13, type: 'string' as const }, +} satisfies ProtoSchema; + +export const CommentRespContentSchema = { + type: { field: 1, type: 'uint32' as const }, + content: { field: 2, type: 'string' as const }, +} satisfies ProtoSchema; + +export const CommentRespDataSchema = { + id: { field: 1, type: 'string' as const }, + user: { field: 2, type: 'message' as const, schema: CommentRespUserSchema }, + content: { field: 3, type: 'repeated_message' as const, schema: CommentRespContentSchema }, + time: { field: 4, type: 'uint64' as const }, + clientKey: { field: 7, type: 'string' as const }, +} satisfies ProtoSchema; + +export const DoQunCommentResponseSchema = { + field1: { field: 1, type: 'int32' as const }, + comment: { field: 4, type: 'message' as const, schema: { + data: { field: 2, type: 'message' as const, schema: CommentRespDataSchema }, + } satisfies ProtoSchema }, +} satisfies ProtoSchema; + +// --- DoQunLike: Like group album media --- + +export const DoQunLikeReqLikeInfoSchema = { + id: { field: 1, type: 'string' as const }, + status: { field: 3, type: 'uint32' as const }, +} satisfies ProtoSchema; + +export const DoQunLikeReqCellCommonSchema = { + time: { field: 3, type: 'uint64' as const }, + feedId: { field: 4, type: 'string' as const }, +} satisfies ProtoSchema; + +export const DoQunLikeReqCellUserSchema = { + uin: { field: 13, type: 'string' as const }, // 修复:抓包证实 uin 是 field 13 +} satisfies ProtoSchema; + +export const DoQunLikeReqCellUserInfoSchema = { + user: { field: 1, type: 'message' as const, schema: DoQunLikeReqCellUserSchema }, +} satisfies ProtoSchema; + +export const DoQunLikeReqCellQunInfoSchema = { + qunId: { field: 1, type: 'string' as const }, +} satisfies ProtoSchema; + +export const DoQunLikeReqCellMediaSchema = { + albumId: { field: 3, type: 'string' as const }, + batchId: { field: 5, type: 'uint64' as const }, +} satisfies ProtoSchema; + +export const DoQunLikeReqFeedPublishSchema = { + cellCommon: { field: 1, type: 'message' as const, schema: DoQunLikeReqCellCommonSchema }, + cellUserInfo: { field: 2, type: 'message' as const, schema: DoQunLikeReqCellUserInfoSchema }, + cellMedia: { field: 5, type: 'message' as const, schema: DoQunLikeReqCellMediaSchema }, + cellQunInfo: { field: 12, type: 'message' as const, schema: DoQunLikeReqCellQunInfoSchema }, +} satisfies ProtoSchema; + +export const DoQunLikeReqBodySchema = { + type: { field: 2, type: 'uint32' as const }, + like: { field: 3, type: 'message' as const, schema: DoQunLikeReqLikeInfoSchema }, + publish: { field: 4, type: 'message' as const, schema: DoQunLikeReqFeedPublishSchema }, + clientKey: { field: 5, type: 'string' as const }, +} satisfies ProtoSchema; + +export const DoQunLikeRequestSchema = { + field1: { field: 1, type: 'int32' as const }, + field2: { field: 2, type: 'string' as const }, + field3: { field: 3, type: 'string' as const }, + body: { field: 4, type: 'message' as const, schema: DoQunLikeReqBodySchema }, + extMap: { field: 10, type: 'repeated_message' as const, schema: ExtMapEntrySchema }, +} satisfies ProtoSchema; + +export const DoQunLikeRespBodySchema = { + like: { field: 2, type: 'message' as const, schema: DoQunLikeReqLikeInfoSchema }, +} satisfies ProtoSchema; + +export const DoQunLikeResponseSchema = { + field1: { field: 1, type: 'int32' as const }, + body: { field: 4, type: 'message' as const, schema: DoQunLikeRespBodySchema }, +} satisfies ProtoSchema; + +// --- DeleteMedias: Delete group album media --- + +export const DeleteMediasReqBodySchema = { + groupId: { field: 1, type: 'string' as const }, + albumId: { field: 2, type: 'string' as const }, + lloc: { field: 3, type: 'string' as const }, +} satisfies ProtoSchema; + +export const DeleteMediasRequestSchema = { + field1: { field: 1, type: 'int32' as const }, + field2: { field: 2, type: 'string' as const }, + field3: { field: 3, type: 'string' as const }, + body: { field: 4, type: 'message' as const, schema: DeleteMediasReqBodySchema }, + traceId: { field: 5, type: 'string' as const }, // <-- 把它挪到外层了! + extMap: { field: 10, type: 'repeated_message' as const, schema: ExtMapEntrySchema }, +} satisfies ProtoSchema; + +export const DeleteMediasResponseSchema = { + field1: { field: 1, type: 'int32' as const }, // 8694 + field2: { field: 2, type: 'int32' as const }, // 错误码 (例如: 10023) + field3: { field: 3, type: 'string' as const }, // 错误信息 (例如: "no right delete...") +} satisfies ProtoSchema; + diff --git a/packages/core/src/onebot/actions/group-album.ts b/packages/core/src/onebot/actions/group-album.ts index 43034bdf..cd7f8b5d 100644 --- a/packages/core/src/onebot/actions/group-album.ts +++ b/packages/core/src/onebot/actions/group-album.ts @@ -52,4 +52,81 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { return failedResponse(RETCODE.INTERNAL_ERROR, message); } }); + + h.registerAction('do_group_album_comment', async (params) => { + const groupId = asNumber(params.group_id); + const albumId = asString(params.album_id); + const lloc = asString(params.lloc); + const content = asString(params.content); + + if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required'); + if (!albumId) return failedResponse(RETCODE.BAD_REQUEST, 'album_id is required'); + if (!lloc) return failedResponse(RETCODE.BAD_REQUEST, 'lloc is required'); + if (!content) return failedResponse(RETCODE.BAD_REQUEST, 'content is required'); + + try { + const comment = await ctx.commentGroupAlbumMedia(groupId, albumId, lloc, content); + return okResponse(comment); + } catch (error) { + const message = error instanceof Error ? error.message : 'failed to comment on album media'; + return failedResponse(RETCODE.INTERNAL_ERROR, message); + } + }); + + h.registerAction('set_group_album_media_like', async (params) => { + const groupId = asNumber(params.group_id); + const albumId = asString(params.album_id); + const batchId = asString(params.batch_id); + const lloc = params.lloc ? asString(params.lloc) : undefined; // 可选参数 + + if (!groupId || !albumId || !batchId) { + return failedResponse(RETCODE.BAD_REQUEST, 'group_id, album_id and batch_id are required'); + } + + try { + const res = await ctx.likeGroupAlbumMedia(groupId, albumId, batchId, lloc, true); + return okResponse(res); + } catch (error) { + const message = error instanceof Error ? error.message : 'failed to set like on album media'; + return failedResponse(RETCODE.INTERNAL_ERROR, message); + } + }); + + // 取消点赞群相册媒体 + h.registerAction('cancel_group_album_media_like', async (params) => { + const groupId = asNumber(params.group_id); + const albumId = asString(params.album_id); + const batchId = asString(params.batch_id); + const lloc = params.lloc ? asString(params.lloc) : undefined; // 可选参数 + + if (!groupId || !albumId || !batchId) { + return failedResponse(RETCODE.BAD_REQUEST, 'group_id, album_id and batch_id are required'); + } + + try { + const res = await ctx.likeGroupAlbumMedia(groupId, albumId, batchId, lloc, false); + return okResponse(res); + } catch (error) { + const message = error instanceof Error ? error.message : 'failed to cancel like on album media'; + return failedResponse(RETCODE.INTERNAL_ERROR, message); + } + }); + + h.registerAction('del_group_album_media', async (params) => { + const groupId = asNumber(params.group_id); + const albumId = asString(params.album_id); + const lloc = asString(params.lloc); + + if (!groupId || !albumId || !lloc) { + return failedResponse(RETCODE.BAD_REQUEST, 'group_id, album_id and lloc are required'); + } + + try { + const res = await ctx.deleteGroupAlbumMedia(groupId, albumId, lloc); + return okResponse(res); + } catch (error) { + const message = error instanceof Error ? error.message : 'failed to delete album media'; + return failedResponse(RETCODE.INTERNAL_ERROR, message); + } + }); } diff --git a/packages/core/src/onebot/api-handler.ts b/packages/core/src/onebot/api-handler.ts index 0afcc20c..6681c4a4 100644 --- a/packages/core/src/onebot/api-handler.ts +++ b/packages/core/src/onebot/api-handler.ts @@ -112,6 +112,9 @@ export interface ApiActionContext { getGroupAlbumList: (groupId: number) => Promise; uploadImageToGroupAlbum: (groupId: number, albumId: string, albumName: string, filePath: string) => Promise; getGroupAlbumMediaList: (groupId: number, albumId: string, attachInfo?: string) => Promise; + commentGroupAlbumMedia: (groupId: number, albumId: string, lloc: string, content: string) => Promise; + deleteGroupAlbumMedia: (groupId: number, albumId: string, lloc: string) => Promise; + likeGroupAlbumMedia: (groupId: number, albumId: string, batchId: string, lloc: string | undefined, isLike: boolean) => Promise; sendGroupNotice: (groupId: number, content: string, options?: any) => Promise; getGroupNotice: (groupId: number) => Promise; deleteGroupNotice: (groupId: number, fid: string) => Promise; diff --git a/packages/core/src/onebot/instance-context.ts b/packages/core/src/onebot/instance-context.ts index db6333d0..14d531f5 100644 --- a/packages/core/src/onebot/instance-context.ts +++ b/packages/core/src/onebot/instance-context.ts @@ -189,6 +189,9 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext { getGroupAlbumList: (groupId) => bridge.getGroupAlbumList(groupId), uploadImageToGroupAlbum: (groupId, albumId, albumName, filePath) => bridge.uploadImageToGroupAlbum(groupId, albumId, albumName, filePath), getGroupAlbumMediaList: (groupId, albumId, attachInfo) => bridge.getGroupAlbumMediaList(groupId, albumId, attachInfo), + commentGroupAlbumMedia: (groupId, albumId, lloc, content) => bridge.commentGroupAlbumMedia(groupId, albumId, lloc, content), + deleteGroupAlbumMedia: (groupId, albumId, lloc) => bridge.deleteGroupAlbumMedia(groupId, albumId, lloc), + likeGroupAlbumMedia: (groupId, albumId, batchId, lloc, isLike) => bridge.likeGroupAlbumMedia(groupId, albumId, batchId, lloc, isLike), sendGroupNotice: (groupId, content, options) => bridge.sendGroupNotice(groupId, content, options), getGroupNotice: (groupId) => bridge.getGroupNotice(groupId), deleteGroupNotice: (groupId, fid) => bridge.deleteGroupNotice(groupId, fid), From 194165f49df6611b722daf87662b81a46ae36644 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Mon, 18 May 2026 23:05:03 +0800 Subject: [PATCH 11/48] =?UTF-8?q?feat(proton):=20add=20@snowluma/proton=20?= =?UTF-8?q?=E2=80=94=20compile-time=20protobuf=20DSL?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Vendors SnowLuma/protobuf-dsl into the monorepo as @snowluma/proton, with edge-case fixes applied on top of the upstream source. Reference copy of the unmodified upstream is kept under dev/protobuf-dsl/. Edge cases fixed (each with a regression test): - Aliased pb / pb_repeated marker imports (`import { pb as P }`) — collector now resolves the marker name through the import resolver - Concrete interface with a generic-instantiated message field (`wrapped: pb<5, Wrapper>`) — field typeName now resolves to the mangled form, and the inner instantiation is queued for monomorphization - Generic template with a generic-instantiated field (`interface Outer { x: pb<5, Wrapper> }`) — the inner instantiation is now re-substituted and re-monomorphized at outer instantiation time - Wrapper-binding synthetic SourceFile was empty-text — getText() returned garbage, breaking mangled name computation downstream - Cross-file forwarded wrappers (chain → imported base) were not detected — parseFileForDefinitions now resolves imports recursively (value imports only, with cycle protection) - matchForwardedKnownWrapper did not propagate typePattern — chain treated as the encoded type instead of Wrapper - Synthetic-SF WeakMap was private to analyzer.ts — replacer could not see it. Moved to utils.ts so typeNodeToMangledName picks it up automatically. Defensive guard: any field whose typeName resolves to neither a primitive nor a known message now throws at analyze() time, instead of silently leaking the WireType.Varint placeholder into codegen. 95/95 tests pass; tsc --noEmit clean. --- packages/proton/package.json | 40 ++ packages/proton/protobuf.d.ts | 61 ++ packages/proton/src/ast/analyzer.ts | 267 +++++++ packages/proton/src/ast/callsite.ts | 119 ++++ packages/proton/src/ast/collector.ts | 157 +++++ packages/proton/src/ast/dependency-graph.ts | 32 + packages/proton/src/ast/import-resolver.ts | 659 ++++++++++++++++++ packages/proton/src/ast/monomorphizer.ts | 131 ++++ packages/proton/src/ast/types.ts | 72 ++ packages/proton/src/ast/utils.ts | 85 +++ packages/proton/src/codegen/decoder.ts | 154 ++++ packages/proton/src/codegen/encoder.ts | 590 ++++++++++++++++ packages/proton/src/codegen/generator.ts | 171 +++++ packages/proton/src/codegen/wire.ts | 52 ++ packages/proton/src/index.ts | 113 +++ packages/proton/src/runtime-map.ts | 71 ++ packages/proton/src/runtime.ts | 220 ++++++ packages/proton/src/transform/replacer.ts | 61 ++ .../proton/test/__tests__/analyzer.test.ts | 145 ++++ .../proton/test/__tests__/cross-file.test.ts | 342 +++++++++ .../proton/test/__tests__/generator.test.ts | 141 ++++ packages/proton/test/__tests__/plugin.test.ts | 307 ++++++++ .../proton/test/__tests__/replacer.test.ts | 94 +++ .../__tests__/runtime-map-fallback.test.ts | 98 +++ packages/proton/test/__tests__/wire.test.ts | 110 +++ .../proton/test/fixtures/aliased-pb-marker.ts | 21 + packages/proton/test/fixtures/bool-msg.ts | 3 + .../fixtures/cross-file/aliased-consumer.ts | 7 + .../test/fixtures/cross-file/consumer.ts | 6 + .../proton/test/fixtures/cross-file/deep.ts | 5 + .../fixtures/cross-file/generic-consumer.ts | 6 + .../test/fixtures/cross-file/generic-types.ts | 5 + .../proton/test/fixtures/cross-file/inner.ts | 5 + .../cross-file/local-wrapper-consumer.ts | 11 + .../proton/test/fixtures/cross-file/mid.ts | 7 + .../proton/test/fixtures/cross-file/outer.ts | 10 + .../test/fixtures/cross-file/protobuf.ts | 5 + .../proton/test/fixtures/cross-file/top.ts | 10 + .../proton/test/fixtures/cross-file/types.ts | 6 + .../cross-file/value-import-consumer.ts | 7 + .../test/fixtures/cross-file/wrapper-api.ts | 49 ++ .../cross-file/wrapper-complex-consumer.ts | 21 + .../fixtures/cross-file/wrapper-consumer.ts | 7 + .../cross-file/wrapper-edge-consumer.ts | 21 + .../cross-file/wrapper-type-source-base.ts | 6 + .../wrapper-type-source-consumer.ts | 15 + .../cross-file/wrapper-type-source.ts | 25 + .../proton/test/fixtures/generic-template.ts | 3 + .../proton/test/fixtures/generic-usage.ts | 8 + .../fixtures/generic-with-generic-field.ts | 24 + packages/proton/test/fixtures/multi-field.ts | 5 + .../test/fixtures/nested-generic-field.ts | 24 + packages/proton/test/fixtures/nested.ts | 7 + packages/proton/test/fixtures/no-pb.ts | 3 + packages/proton/test/fixtures/real.ts | 12 + packages/proton/test/fixtures/repeated.ts | 9 + packages/proton/test/fixtures/simple.ts | 3 + packages/proton/test/fixtures/string-msg.ts | 3 + packages/proton/test/helpers/index.ts | 21 + packages/proton/tsconfig.json | 19 + packages/proton/vitest.config.ts | 7 + pnpm-lock.yaml | 16 + 62 files changed, 4714 insertions(+) create mode 100644 packages/proton/package.json create mode 100644 packages/proton/protobuf.d.ts create mode 100644 packages/proton/src/ast/analyzer.ts create mode 100644 packages/proton/src/ast/callsite.ts create mode 100644 packages/proton/src/ast/collector.ts create mode 100644 packages/proton/src/ast/dependency-graph.ts create mode 100644 packages/proton/src/ast/import-resolver.ts create mode 100644 packages/proton/src/ast/monomorphizer.ts create mode 100644 packages/proton/src/ast/types.ts create mode 100644 packages/proton/src/ast/utils.ts create mode 100644 packages/proton/src/codegen/decoder.ts create mode 100644 packages/proton/src/codegen/encoder.ts create mode 100644 packages/proton/src/codegen/generator.ts create mode 100644 packages/proton/src/codegen/wire.ts create mode 100644 packages/proton/src/index.ts create mode 100644 packages/proton/src/runtime-map.ts create mode 100644 packages/proton/src/runtime.ts create mode 100644 packages/proton/src/transform/replacer.ts create mode 100644 packages/proton/test/__tests__/analyzer.test.ts create mode 100644 packages/proton/test/__tests__/cross-file.test.ts create mode 100644 packages/proton/test/__tests__/generator.test.ts create mode 100644 packages/proton/test/__tests__/plugin.test.ts create mode 100644 packages/proton/test/__tests__/replacer.test.ts create mode 100644 packages/proton/test/__tests__/runtime-map-fallback.test.ts create mode 100644 packages/proton/test/__tests__/wire.test.ts create mode 100644 packages/proton/test/fixtures/aliased-pb-marker.ts create mode 100644 packages/proton/test/fixtures/bool-msg.ts create mode 100644 packages/proton/test/fixtures/cross-file/aliased-consumer.ts create mode 100644 packages/proton/test/fixtures/cross-file/consumer.ts create mode 100644 packages/proton/test/fixtures/cross-file/deep.ts create mode 100644 packages/proton/test/fixtures/cross-file/generic-consumer.ts create mode 100644 packages/proton/test/fixtures/cross-file/generic-types.ts create mode 100644 packages/proton/test/fixtures/cross-file/inner.ts create mode 100644 packages/proton/test/fixtures/cross-file/local-wrapper-consumer.ts create mode 100644 packages/proton/test/fixtures/cross-file/mid.ts create mode 100644 packages/proton/test/fixtures/cross-file/outer.ts create mode 100644 packages/proton/test/fixtures/cross-file/protobuf.ts create mode 100644 packages/proton/test/fixtures/cross-file/top.ts create mode 100644 packages/proton/test/fixtures/cross-file/types.ts create mode 100644 packages/proton/test/fixtures/cross-file/value-import-consumer.ts create mode 100644 packages/proton/test/fixtures/cross-file/wrapper-api.ts create mode 100644 packages/proton/test/fixtures/cross-file/wrapper-complex-consumer.ts create mode 100644 packages/proton/test/fixtures/cross-file/wrapper-consumer.ts create mode 100644 packages/proton/test/fixtures/cross-file/wrapper-edge-consumer.ts create mode 100644 packages/proton/test/fixtures/cross-file/wrapper-type-source-base.ts create mode 100644 packages/proton/test/fixtures/cross-file/wrapper-type-source-consumer.ts create mode 100644 packages/proton/test/fixtures/cross-file/wrapper-type-source.ts create mode 100644 packages/proton/test/fixtures/generic-template.ts create mode 100644 packages/proton/test/fixtures/generic-usage.ts create mode 100644 packages/proton/test/fixtures/generic-with-generic-field.ts create mode 100644 packages/proton/test/fixtures/multi-field.ts create mode 100644 packages/proton/test/fixtures/nested-generic-field.ts create mode 100644 packages/proton/test/fixtures/nested.ts create mode 100644 packages/proton/test/fixtures/no-pb.ts create mode 100644 packages/proton/test/fixtures/real.ts create mode 100644 packages/proton/test/fixtures/repeated.ts create mode 100644 packages/proton/test/fixtures/simple.ts create mode 100644 packages/proton/test/fixtures/string-msg.ts create mode 100644 packages/proton/test/helpers/index.ts create mode 100644 packages/proton/tsconfig.json create mode 100644 packages/proton/vitest.config.ts diff --git a/packages/proton/package.json b/packages/proton/package.json new file mode 100644 index 00000000..d300cecb --- /dev/null +++ b/packages/proton/package.json @@ -0,0 +1,40 @@ +{ + "name": "@snowluma/proton", + "version": "1.8.5", + "private": true, + "type": "module", + "description": "Compile-time protobuf encoder/decoder generator for SnowLuma. TypeScript interfaces → fully-inlined, zero-runtime protobuf codec functions. Vendored from SnowLuma/protobuf-dsl (reference copy under dev/protobuf-dsl/) with edge-case fixes applied.", + "main": "./src/runtime.ts", + "types": "./protobuf.d.ts", + "exports": { + ".": { + "types": "./protobuf.d.ts", + "default": "./src/runtime.ts" + }, + "./vite": { + "types": "./src/index.ts", + "default": "./src/index.ts" + } + }, + "scripts": { + "test": "vitest run", + "test:watch": "vitest", + "typecheck": "tsc --noEmit" + }, + "dependencies": { + "typescript": "catalog:" + }, + "peerDependencies": { + "vite": "catalog:" + }, + "peerDependenciesMeta": { + "vite": { + "optional": true + } + }, + "devDependencies": { + "@types/node": "^24.12.2", + "vite": "catalog:", + "vitest": "^4.1.4" + } +} diff --git a/packages/proton/protobuf.d.ts b/packages/proton/protobuf.d.ts new file mode 100644 index 00000000..cc2f8deb --- /dev/null +++ b/packages/proton/protobuf.d.ts @@ -0,0 +1,61 @@ +// ── Protobuf field markers ──────────────────────────────────────────── +/** Marks a singular protobuf field: `name: pb` */ +export type pb<_ProtoNumber extends number, Type> = Type; +/** Marks a repeated protobuf field: `ids: pb_repeated` → Type[] */ +export type pb_repeated<_ProtoNumber extends number, Type> = Type[]; + +// ── Protobuf primitive types ────────────────────────────────────────── +export type uint_32 = number; +export type int_32 = number; +export type uint_64 = bigint; +export type int_64 = bigint; +export type sint_32 = number; +export type sint_64 = bigint; +export type bool = boolean; +export type float = number; +export type double = number; +export type fixed_32 = number; +export type fixed_64 = bigint; +export type sfixed_32 = number; +export type sfixed_64 = bigint; +export type bytes = Uint8Array; + +// ── Encode / decode (replaced at compile-time by the vite plugin) ──── +export function protobuf_encode(params: T): Uint8Array; +export function protobuf_decode(data: Uint8Array): T; + +// ── Optional runtime map fallback (disabled by default) ─────────────── +export interface ProtobufRuntimeField { + name: string; + fieldNumber: number; + typeName: string; + wireType: 0 | 1 | 2 | 5; + isMessage: boolean; + isOptional: boolean; + isRepeated: boolean; +} + +export interface ProtobufRuntimeMessage { + name: string; + fields: ProtobufRuntimeField[]; +} + +export interface ProtobufRuntimeCallSite { + file: string; + line: number; + column: number; + fnName: 'protobuf_encode' | 'protobuf_decode'; + typeName: string; +} + +export interface ProtobufRuntimeMap { + version: 1; + messages: ProtobufRuntimeMessage[]; + callSites: ProtobufRuntimeCallSite[]; +} + +/** Enables map-based runtime dynamic code generation fallback. */ +export function protobuf_enableRuntimeMapFallback(map: ProtobufRuntimeMap): void; + +/** Disables map-based runtime fallback and clears generated function cache. */ +export function protobuf_disableRuntimeMapFallback(): void; diff --git a/packages/proton/src/ast/analyzer.ts b/packages/proton/src/ast/analyzer.ts new file mode 100644 index 00000000..c7c1c61e --- /dev/null +++ b/packages/proton/src/ast/analyzer.ts @@ -0,0 +1,267 @@ +import ts from 'typescript'; +import { WireType, PRIMITIVE_TYPE_MAP, type ProtobufMessage, type MessageRegistry, type GenericProtobufTemplate } from './types.js'; +import { collectInterface, collectGenericInterface, collectConcreteFieldGenericTypeArgs } from './collector.js'; +import { monomorphizeTypeNode } from './monomorphizer.js'; +import { + createImportedTypeNameResolver, + typeNodeToMangledName, + registerSyntheticTypeSourceFile, + resolveSourceFileForTypeNode, +} from './utils.js'; +import type { ImportedDefinitions, WrapperBinding } from './import-resolver.js'; +import { + collectProtobufImportBindings, + matchProtobufCallSite, + type CanonicalProtobufFn, +} from './callsite.js'; +import { buildDependencyRegistry } from './dependency-graph.js'; + +export { typeNodeToMangledName } from './utils.js'; + +function getCallableName(expr: ts.Expression): string | null { + if (ts.isIdentifier(expr)) return expr.text; + if (ts.isPropertyAccessExpression(expr)) return expr.name.text; + return null; +} + +function instantiateWrapperTypePattern( + binding: WrapperBinding, + callerTypeArgs: ts.NodeArray, + sf: ts.SourceFile, +): ts.TypeNode | null { + if (!binding.typePattern || !binding.typeParamNames?.length) return callerTypeArgs[binding.typeArgIndex] ?? null; + + let text = binding.typePattern; + for (let i = 0; i < binding.typeParamNames.length; i++) { + const arg = callerTypeArgs[i]; + if (!arg) return null; + text = text.replace(new RegExp(`\\b${binding.typeParamNames[i]}\\b`, 'g'), arg.getText(sf)); + } + + // Parse the substituted type pattern into a fresh source file whose + // `fileName` is the binding's origin (so subsequent import resolution can + // find the right module) AND whose `text` contains the substituted source + // (so `getText()` on the resulting TypeNode returns the actual type, not + // garbage from an empty-text companion file). + const parsed = ts.createSourceFile( + binding.sourceFilePath ?? sf.fileName, + `type __T = ${text};`, + ts.ScriptTarget.Latest, + true, + ); + const stmt = parsed.statements[0]; + if (!ts.isTypeAliasDeclaration(stmt)) return null; + registerSyntheticTypeSourceFile(stmt.type, parsed); + return stmt.type; +} + +/** A recorded call-site for later replacement. */ +export interface CallSiteRecord { + fnName: CanonicalProtobufFn; + exprStart: number; // position of identifier start + typeArgsEnd: number; // position after closing '>' + firstTypeArg: ts.TypeNode; // the type argument node + line: number; // 1-based line for runtime map lookup + column: number; // 1-based column for runtime map lookup +} + +export interface ResolvedCallSiteRecord extends CallSiteRecord { + typeName: string; +} + +export interface AnalysisResult { + registry: MessageRegistry; + callSites: CallSiteRecord[]; + sourceFile: ts.SourceFile; +} + +export interface UsedRegistryResult { + registry: MessageRegistry; + roots: Set; + callSites: ResolvedCallSiteRecord[]; +} + +/** + * Analyze TypeScript source in a **single parse + single walk**. + * + * One walk handles both: + * - Collecting concrete + generic interfaces + * - Recording protobuf_encode/decode call-sites + * + * Then post-processes: monomorphize → resolve wire types → topo sort. + */ +export function analyze(code: string, filePath: string, imported?: ImportedDefinitions): AnalysisResult { + const sf = ts.createSourceFile(filePath, code, ts.ScriptTarget.Latest, true); + const concrete: ProtobufMessage[] = []; + const templates = new Map(); + const mono = new Map(); + const callSites: CallSiteRecord[] = []; + const deferredTypeArgs: ts.TypeNode[] = []; + const importBindings = collectProtobufImportBindings(sf); + const resolveImportedTypeName = createImportedTypeNameResolver(sf); + const wrapperBindings = imported?.wrapperBindings ?? new Map(); + + // Seed with imported definitions + if (imported) { + concrete.push(...imported.concrete); + for (const [k, v] of imported.templates) templates.set(k, v); + } + + // ── single walk ───────────────────────────────────────────────────── + ts.forEachChild(sf, function visit(node) { + if (ts.isInterfaceDeclaration(node)) { + if (node.typeParameters?.length) { + const tpl = collectGenericInterface(node, sf, resolveImportedTypeName); + if (tpl) templates.set(tpl.name, tpl); + } else { + const msg = collectInterface(node, sf, resolveImportedTypeName); + if (msg) concrete.push(msg); + // Queue any generic-instantiated type-args appearing as field types + // (e.g. `wrapped: pb<5, Wrapper>`) for monomorphization. + // The call-site queue only sees the outer concrete type, so without + // this the nested instantiation would never reach the registry. + for (const ta of collectConcreteFieldGenericTypeArgs(node, resolveImportedTypeName)) { + deferredTypeArgs.push(ta); + } + } + } + + if (ts.isCallExpression(node)) { + const cs = matchProtobufCallSite(node, sf, importBindings, { + allowLegacyUnboundCanonical: true, + }); + if (cs) { + deferredTypeArgs.push(cs.firstTypeArg); + callSites.push(cs); + } else if ( + node.typeArguments?.length && + getCallableName(node.expression) && + wrapperBindings.has(getCallableName(node.expression)!) + ) { + const binding = wrapperBindings.get(getCallableName(node.expression)!)!; + const firstTypeArg = instantiateWrapperTypePattern(binding, node.typeArguments, sf); + if (!firstTypeArg) { + ts.forEachChild(node, visit); + return; + } + const exprStart = node.expression.getStart(sf); + const lc = sf.getLineAndCharacterOfPosition(exprStart); + deferredTypeArgs.push(firstTypeArg); + callSites.push({ + fnName: binding.fnName, + exprStart, + typeArgsEnd: node.typeArguments.end + 1, + firstTypeArg, + line: lc.line + 1, + column: lc.character + 1, + }); + } + } + + ts.forEachChild(node, visit); + }); + + // ── post-walk: monomorphize deferred type args ────────────────────── + for (const typeArg of deferredTypeArgs) { + const typeSf = resolveSourceFileForTypeNode(typeArg, sf); + const typeResolver = createImportedTypeNameResolver(typeSf); + monomorphizeTypeNode(typeArg, typeSf, templates, mono, typeResolver); + } + for (const m of mono.values()) concrete.push(m); + + // ── resolve wire types ────────────────────────────────────────────── + // Anything that doesn't resolve to a primitive or a registered message is + // a type-tracking miss — historically these leaked the placeholder + // `WireType.Varint` into codegen and corrupted the wire format silently. + // Throw loudly instead so future analyzer gaps surface immediately. + const names = new Set(concrete.map(m => m.name)); + for (const msg of concrete) { + for (const f of msg.fields) { + const prim = PRIMITIVE_TYPE_MAP[f.typeName]; + if (prim) { + f.wireType = prim.wireType; + f.isMessage = false; + } else if (names.has(f.typeName)) { + f.wireType = WireType.LengthDelim; + f.isMessage = true; + } else { + throw new Error( + `Cannot resolve protobuf field type "${f.typeName}" on message "${msg.name}" ` + + `(field "${f.name}", field number ${f.fieldNumber}). The analyzer did not produce ` + + `a primitive or registered message for this type. Common causes: union / intersection / ` + + `mapped / conditional types, TypeScript utility types (Partial, Pick, …), ` + + `qualified names (ns.Type), or a missing import.`, + ); + } + } + } + + return { registry: topoSort(concrete), callSites, sourceFile: sf }; +} + +/** + * Backward-compatible wrapper: returns only the MessageRegistry. + * Uses the same single-walk analysis internally. + */ +export function analyzeSource(code: string, filePath: string, imported?: ImportedDefinitions): MessageRegistry { + return analyze(code, filePath, imported).registry; +} + +/** + * Build a minimal message registry by collecting only call-site root types and + * their transitive message dependencies. + */ +export function selectUsedRegistry( + registry: MessageRegistry, + callSites: CallSiteRecord[], + sourceFile: ts.SourceFile, +): UsedRegistryResult { + const roots = new Set(); + const resolved: ResolvedCallSiteRecord[] = []; + const resolveImportedTypeName = createImportedTypeNameResolver(sourceFile); + + for (const cs of callSites) { + const typeSf = resolveSourceFileForTypeNode(cs.firstTypeArg, sourceFile); + const typeName = typeNodeToMangledName(cs.firstTypeArg, typeSf, createImportedTypeNameResolver(typeSf)); + if (!registry.has(typeName)) continue; + roots.add(typeName); + resolved.push({ ...cs, typeName }); + } + + if (roots.size === 0) { + return { registry: new Map(), roots, callSites: resolved }; + } + + return { + registry: buildDependencyRegistry(registry, roots), + roots, + callSites: resolved, + }; +} + +// ── topological sort ────────────────────────────────────────────────── + +function topoSort(messages: ProtobufMessage[]): MessageRegistry { + const map = new Map(messages.map(m => [m.name, m])); + const deps = new Map(messages.map(m => [ + m.name, + new Set(m.fields.filter(f => map.has(f.typeName)).map(f => f.typeName)), + ])); + + const sorted: ProtobufMessage[] = []; + const visited = new Set(); + const visiting = new Set(); + + function dfs(name: string): void { + if (visited.has(name)) return; + if (visiting.has(name)) throw new Error(`Circular dependency: ${name}`); + visiting.add(name); + for (const d of deps.get(name) || []) dfs(d); + visiting.delete(name); + visited.add(name); + sorted.push(map.get(name)!); + } + + for (const m of messages) dfs(m.name); + return new Map(sorted.map(m => [m.name, m])); +} diff --git a/packages/proton/src/ast/callsite.ts b/packages/proton/src/ast/callsite.ts new file mode 100644 index 00000000..75fa7422 --- /dev/null +++ b/packages/proton/src/ast/callsite.ts @@ -0,0 +1,119 @@ +import ts from 'typescript'; + +export type CanonicalProtobufFn = 'protobuf_encode' | 'protobuf_decode'; + +const CANONICAL = new Set(['protobuf_encode', 'protobuf_decode']); +const PROTOBUF_RUNTIME_MODULES = new Set([ + '@snowluma/proton', +]); + +export interface ProtobufImportBindings { + identifierToCanonical: Map; + namespaceAliases: Set; + blockedLegacyCanonical: Set; + hasRuntimeImport: boolean; +} + +export interface ProtobufCallSite { + fnName: CanonicalProtobufFn; + exprStart: number; + typeArgsEnd: number; + firstTypeArg: ts.TypeNode; + line: number; + column: number; +} + +export function collectProtobufImportBindings(sf: ts.SourceFile): ProtobufImportBindings { + const identifierToCanonical = new Map(); + const namespaceAliases = new Set(); + const blockedLegacyCanonical = new Set(); + let hasRuntimeImport = false; + + for (const stmt of sf.statements) { + if (!ts.isImportDeclaration(stmt) || !stmt.importClause) continue; + if (!ts.isStringLiteral(stmt.moduleSpecifier)) continue; + const fromRuntime = PROTOBUF_RUNTIME_MODULES.has(stmt.moduleSpecifier.text); + if (fromRuntime) hasRuntimeImport = true; + + const bindings = stmt.importClause.namedBindings; + const defaultImport = stmt.importClause.name?.text; + if (defaultImport && CANONICAL.has(defaultImport as CanonicalProtobufFn) && !fromRuntime) { + blockedLegacyCanonical.add(defaultImport as CanonicalProtobufFn); + } + + if (!bindings) continue; + + if (ts.isNamedImports(bindings)) { + for (const el of bindings.elements) { + const imported = (el.propertyName ?? el.name).text; + if (fromRuntime && CANONICAL.has(imported as CanonicalProtobufFn)) { + identifierToCanonical.set(el.name.text, imported as CanonicalProtobufFn); + continue; + } + + if (CANONICAL.has(el.name.text as CanonicalProtobufFn)) { + blockedLegacyCanonical.add(el.name.text as CanonicalProtobufFn); + } + } + continue; + } + + if (fromRuntime && ts.isNamespaceImport(bindings)) { + namespaceAliases.add(bindings.name.text); + } else if (CANONICAL.has(bindings.name.text as CanonicalProtobufFn)) { + blockedLegacyCanonical.add(bindings.name.text as CanonicalProtobufFn); + } + } + + return { identifierToCanonical, namespaceAliases, blockedLegacyCanonical, hasRuntimeImport }; +} + +interface MatchOptions { + allowLegacyUnboundCanonical?: boolean; +} + +export function matchProtobufCallSite( + node: ts.CallExpression, + sf: ts.SourceFile, + bindings: ProtobufImportBindings, + options?: MatchOptions, +): ProtobufCallSite | null { + const ta = node.typeArguments; + if (!ta?.length) return null; + + const expr = node.expression; + const allowLegacy = options?.allowLegacyUnboundCanonical === true; + + let fnName: CanonicalProtobufFn | null = null; + let exprStart = expr.getStart(sf); + + if (ts.isIdentifier(expr)) { + fnName = bindings.identifierToCanonical.get(expr.text) ?? null; + if ( + !fnName && + allowLegacy && + !bindings.hasRuntimeImport && + CANONICAL.has(expr.text as CanonicalProtobufFn) && + !bindings.blockedLegacyCanonical.has(expr.text as CanonicalProtobufFn) + ) { + fnName = expr.text as CanonicalProtobufFn; + } + } else if (ts.isPropertyAccessExpression(expr) && ts.isIdentifier(expr.expression)) { + if (bindings.namespaceAliases.has(expr.expression.text) && CANONICAL.has(expr.name.text as CanonicalProtobufFn)) { + fnName = expr.name.text as CanonicalProtobufFn; + exprStart = expr.getStart(sf); + } + } + + if (!fnName) return null; + const lc = sf.getLineAndCharacterOfPosition(exprStart); + + return { + fnName, + exprStart, + typeArgsEnd: ta.end + 1, + firstTypeArg: ta[0], + line: lc.line + 1, + column: lc.character + 1, + }; +} diff --git a/packages/proton/src/ast/collector.ts b/packages/proton/src/ast/collector.ts new file mode 100644 index 00000000..7bdc321c --- /dev/null +++ b/packages/proton/src/ast/collector.ts @@ -0,0 +1,157 @@ +import ts from 'typescript'; +import { + WireType, + PB_MARKER, PB_REPEATED_MARKER, + type ProtobufField, type ProtobufMessage, + type GenericProtobufTemplate, type GenericFieldTemplate, +} from './types.js'; +import { isKeywordTypeNode, typeNodeToMangledName, type ImportedTypeNameResolver } from './utils.js'; + +function identityImportedTypeName(name: string): string { + return name; +} + +/** + * Yield generic-instantiated type-arg nodes appearing as field types on a + * **concrete** (non-generic) interface — e.g. `wrapped: pb<5, Wrapper>` + * yields the `Wrapper` node so the analyzer can enqueue it for + * monomorphization. (The call-site-driven queue only sees the outer concrete + * type; nested generic instantiations on its fields would otherwise be missed.) + */ +export function* collectConcreteFieldGenericTypeArgs( + node: ts.InterfaceDeclaration, + resolveImportedTypeName: ImportedTypeNameResolver = identityImportedTypeName, +): IterableIterator { + if (node.typeParameters?.length) return; + for (const m of node.members) { + if (!ts.isPropertySignature(m) || !m.type) continue; + const parsed = parsePbTypeRef(m, resolveImportedTypeName); + if (!parsed) continue; + const ta = parsed.typeArgNode; + if (ts.isTypeReferenceNode(ta) && ta.typeArguments && ta.typeArguments.length > 0) { + yield ta; + } + } +} + +/** Collect a concrete (non-generic) interface with pb<>/pb_repeated<> fields. */ +export function collectInterface( + node: ts.InterfaceDeclaration, + sf: ts.SourceFile, + resolveImportedTypeName: ImportedTypeNameResolver = identityImportedTypeName, +): ProtobufMessage | null { + const fields: ProtobufField[] = []; + for (const m of node.members) { + if (!ts.isPropertySignature(m) || !m.type) continue; + const f = extractField(m, sf, resolveImportedTypeName); + if (f) fields.push(f); + } + return fields.length ? { name: node.name.text, fields } : null; +} + +/** Collect a generic interface template. */ +export function collectGenericInterface( + node: ts.InterfaceDeclaration, + sf: ts.SourceFile, + resolveImportedTypeName: ImportedTypeNameResolver = identityImportedTypeName, +): GenericProtobufTemplate | null { + const typeParams = node.typeParameters!.map(p => p.name.text); + const tpSet = new Set(typeParams); + const fields: GenericFieldTemplate[] = []; + for (const m of node.members) { + if (!ts.isPropertySignature(m) || !m.type) continue; + const f = extractGenericField(m, sf, tpSet, resolveImportedTypeName); + if (f) fields.push(f); + } + return fields.length ? { name: node.name.text, typeParams, fields } : null; +} + +// ── helpers ─────────────────────────────────────────────────────────── + +function parsePbTypeRef( + member: ts.PropertySignature, + resolveImportedTypeName: ImportedTypeNameResolver = identityImportedTypeName, +): { marker: string; fieldNumber: number; typeArgNode: ts.TypeNode } | null { + const t = member.type!; + if (!ts.isTypeReferenceNode(t) || !ts.isIdentifier(t.typeName)) return null; + // Resolve the marker name through aliased imports so `import { pb as P }` + // / `import { pb_repeated as PR }` still match the marker constants. + const marker = resolveImportedTypeName(t.typeName.text); + if (marker !== PB_MARKER && marker !== PB_REPEATED_MARKER) return null; + const ta = t.typeArguments; + if (!ta || ta.length !== 2) return null; + const fnNode = ta[0]; + if (!ts.isLiteralTypeNode(fnNode) || !ts.isNumericLiteral(fnNode.literal)) return null; + return { marker, fieldNumber: Number(fnNode.literal.text), typeArgNode: ta[1] }; +} + +function resolveTypeName( + node: ts.TypeNode, + sf: ts.SourceFile, + resolveImportedTypeName: ImportedTypeNameResolver, +): string | null { + if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName)) { + // Generic instantiations (e.g. `Wrapper`) must resolve to the + // mangled name produced by monomorphization so wire-type resolution can + // find the message in the registry. Without this the field would carry + // the bare identifier `"Wrapper"` and never link to `Wrapper__uint_32`. + if (node.typeArguments && node.typeArguments.length > 0) { + return typeNodeToMangledName(node, sf, resolveImportedTypeName); + } + return resolveImportedTypeName(node.typeName.text); + } + if (isKeywordTypeNode(node)) return node.getText(sf); + return null; +} + +function extractField( + member: ts.PropertySignature, + sf: ts.SourceFile, + resolveImportedTypeName: ImportedTypeNameResolver, +): ProtobufField | null { + const parsed = parsePbTypeRef(member, resolveImportedTypeName); + if (!parsed) return null; + const typeName = resolveTypeName(parsed.typeArgNode, sf, resolveImportedTypeName); + if (!typeName || !ts.isIdentifier(member.name)) return null; + return { + name: (member.name as ts.Identifier).text, + fieldNumber: parsed.fieldNumber, + typeName, + wireType: WireType.Varint, // placeholder + isMessage: false, // placeholder + isOptional: member.questionToken != null, + isRepeated: parsed.marker === PB_REPEATED_MARKER, + }; +} + +function extractGenericField( + member: ts.PropertySignature, + sf: ts.SourceFile, + tpSet: Set, + resolveImportedTypeName: ImportedTypeNameResolver, +): GenericFieldTemplate | null { + const parsed = parsePbTypeRef(member, resolveImportedTypeName); + if (!parsed) return null; + const raw = resolveTypeName(parsed.typeArgNode, sf, resolveImportedTypeName); + if (!raw || !ts.isIdentifier(member.name)) return null; + const result: GenericFieldTemplate = { + name: (member.name as ts.Identifier).text, + fieldNumber: parsed.fieldNumber, + rawTypeName: tpSet.has(raw) ? raw : resolveImportedTypeName(raw), + isTypeParam: tpSet.has(raw), + isOptional: member.questionToken != null, + isRepeated: parsed.marker === PB_REPEATED_MARKER, + }; + // If the field's type-arg is itself a generic instantiation (`Wrapper`, + // where U is a type param of the enclosing template), capture the original + // source text so monomorphization can substitute U and re-instantiate the + // inner generic. Without this the field's `rawTypeName` would stay at the + // unsubstituted `'Wrapper__U'` form and the substituted instantiation + // would never reach the registry. + const ta = parsed.typeArgNode; + if (ts.isTypeReferenceNode(ta) && ta.typeArguments && ta.typeArguments.length > 0) { + result.genericTypeArgText = ta.getText(sf); + result.genericTypeArgSourceFilePath = sf.fileName; + } + return result; +} diff --git a/packages/proton/src/ast/dependency-graph.ts b/packages/proton/src/ast/dependency-graph.ts new file mode 100644 index 00000000..3edcf83f --- /dev/null +++ b/packages/proton/src/ast/dependency-graph.ts @@ -0,0 +1,32 @@ +import type { MessageRegistry } from './types.js'; + +export function collectDependencyClosure(registry: MessageRegistry, roots: Iterable): Set { + const selected = new Set(); + + function visit(name: string): void { + if (selected.has(name)) return; + const msg = registry.get(name); + if (!msg) return; + + selected.add(name); + for (const field of msg.fields) { + if (registry.has(field.typeName)) visit(field.typeName); + } + } + + for (const root of roots) visit(root); + return selected; +} + +export function pickRegistrySubset(registry: MessageRegistry, selectedNames: Set): MessageRegistry { + const subset: MessageRegistry = new Map(); + for (const [name, msg] of registry) { + if (selectedNames.has(name)) subset.set(name, msg); + } + return subset; +} + +export function buildDependencyRegistry(registry: MessageRegistry, roots: Iterable): MessageRegistry { + const selected = collectDependencyClosure(registry, roots); + return pickRegistrySubset(registry, selected); +} diff --git a/packages/proton/src/ast/import-resolver.ts b/packages/proton/src/ast/import-resolver.ts new file mode 100644 index 00000000..0d1a4f6a --- /dev/null +++ b/packages/proton/src/ast/import-resolver.ts @@ -0,0 +1,659 @@ +import ts from 'typescript'; +import { readFileSync, existsSync } from 'fs'; +import { dirname, resolve } from 'path'; +import { collectInterface, collectGenericInterface } from './collector.js'; +import { PRIMITIVE_TYPE_MAP, type ProtobufMessage, type GenericProtobufTemplate } from './types.js'; +import { createImportedTypeNameResolver, isKeywordTypeNode, type ImportedTypeNameResolver } from './utils.js'; +import { collectProtobufImportBindings, matchProtobufCallSite, type CanonicalProtobufFn } from './callsite.js'; + +export interface WrapperBinding { + fnName: CanonicalProtobufFn; + typeArgIndex: number; + typePattern?: string; + typeParamNames?: string[]; + sourceFilePath?: string; +} + +export interface ParsedFileEntry { + filePath: string; + concrete: ProtobufMessage[]; + templates: Map; + importedTypeSources: Map; + resolveImportedTypeName: ImportedTypeNameResolver; + exportedWrappers: Map; +} + +export interface ImportedDefinitions { + concrete: ProtobufMessage[]; + templates: Map; + wrapperBindings: Map; +} + +interface ImportClause { + importedName: string; + localName: string; + specifier: string; +} + +function getCallableName(expr: ts.Expression): string | null { + if (ts.isIdentifier(expr)) return expr.text; + if (ts.isPropertyAccessExpression(expr)) return expr.name.text; + return null; +} + +/** Extract all named imports from the source file (both type and value imports). */ +function extractImports(sf: ts.SourceFile): ImportClause[] { + const result: ImportClause[] = []; + for (const stmt of sf.statements) { + if (!ts.isImportDeclaration(stmt) || !stmt.importClause) continue; + const spec = stmt.moduleSpecifier; + if (!ts.isStringLiteral(spec)) continue; + const specifier = spec.text; + + const clause = stmt.importClause; + if (clause.namedBindings && ts.isNamedImports(clause.namedBindings)) { + for (const el of clause.namedBindings.elements) { + result.push({ + importedName: (el.propertyName ?? el.name).text, + localName: el.name.text, + specifier, + }); + } + } + } + return result; +} + +/** Like `extractImports`, but skips `import type { ... }` and `import { type X }` + * entries. Wrapper functions are values, so type-only imports can't introduce + * one and we shouldn't eagerly parse their source files just to look for wrappers. */ +function extractValueImports(sf: ts.SourceFile): ImportClause[] { + const result: ImportClause[] = []; + for (const stmt of sf.statements) { + if (!ts.isImportDeclaration(stmt) || !stmt.importClause) continue; + if (stmt.importClause.isTypeOnly) continue; + const spec = stmt.moduleSpecifier; + if (!ts.isStringLiteral(spec)) continue; + const specifier = spec.text; + + const clause = stmt.importClause; + if (clause.namedBindings && ts.isNamedImports(clause.namedBindings)) { + for (const el of clause.namedBindings.elements) { + if (el.isTypeOnly) continue; + result.push({ + importedName: (el.propertyName ?? el.name).text, + localName: el.name.text, + specifier, + }); + } + } + } + return result; +} + +/** Resolve a relative module specifier to an absolute file path. Returns null if not found. */ +function resolveModulePath(specifier: string, importerPath: string): string | null { + if (!specifier.startsWith('.')) return null; // skip bare/alias specifiers + + const base = resolve(dirname(importerPath), specifier); + + // Try exact path (e.g., './types.ts') + if (existsSync(base) && !base.endsWith('.ts') === false) return base; + if (base.endsWith('.ts') && existsSync(base)) return base; + + // Try appending .ts + const withTs = base + '.ts'; + if (existsSync(withTs)) return withTs; + + // Try as directory with index.ts + const indexTs = resolve(base, 'index.ts'); + if (existsSync(indexTs)) return indexTs; + + return null; +} + +function hasExportModifier(node: ts.Node): boolean { + return ts.canHaveModifiers(node) && !!ts.getModifiers(node)?.some(m => m.kind === ts.SyntaxKind.ExportKeyword); +} + +function matchForwardedProtobufFn( + body: ts.ConciseBody | ts.Block | undefined, + sf: ts.SourceFile, + typeParams: readonly ts.TypeParameterDeclaration[] | undefined, +): WrapperBinding | null { + if (!body || !typeParams?.length) return null; + const typeParamIndexes = new Map(typeParams.map((p, index) => [p.name.text, index])); + const typeParamNames = typeParams.map(p => p.name.text); + const bindings = collectProtobufImportBindings(sf); + let found: WrapperBinding | null = null; + + function visit(node: ts.Node): void { + if (found) return; + if (ts.isCallExpression(node)) { + const cs = matchProtobufCallSite(node, sf, bindings, { + allowLegacyUnboundCanonical: true, + }); + if ( + cs && + ts.isTypeReferenceNode(cs.firstTypeArg) && + ts.isIdentifier(cs.firstTypeArg.typeName) && + typeParamIndexes.has(cs.firstTypeArg.typeName.text) + ) { + found = { + fnName: cs.fnName, + typeArgIndex: typeParamIndexes.get(cs.firstTypeArg.typeName.text)!, + sourceFilePath: sf.fileName, + }; + return; + } + + if (cs && containsTypeParameter(cs.firstTypeArg, typeParamIndexes)) { + found = { + fnName: cs.fnName, + typeArgIndex: firstTypeParameterIndex(cs.firstTypeArg, typeParamIndexes) ?? 0, + typePattern: cs.firstTypeArg.getText(sf), + typeParamNames, + sourceFilePath: sf.fileName, + }; + return; + } + } + ts.forEachChild(node, visit); + } + + visit(body); + return found; +} + +function containsTypeParameter(typeNode: ts.TypeNode, typeParamIndexes: Map): boolean { + let found = false; + function visit(node: ts.Node): void { + if (found) return; + if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && typeParamIndexes.has(node.typeName.text)) { + found = true; + return; + } + ts.forEachChild(node, visit); + } + visit(typeNode); + return found; +} + +function firstTypeParameterIndex(typeNode: ts.TypeNode, typeParamIndexes: Map): number | null { + let index: number | null = null; + function visit(node: ts.Node): void { + if (index !== null) return; + if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && typeParamIndexes.has(node.typeName.text)) { + index = typeParamIndexes.get(node.typeName.text)!; + return; + } + ts.forEachChild(node, visit); + } + visit(typeNode); + return index; +} + +function instantiateWrapperTypePattern( + binding: WrapperBinding, + callerTypeArgs: ts.NodeArray, + sf: ts.SourceFile, +): ts.TypeNode | null { + if (!binding.typePattern || !binding.typeParamNames?.length) return callerTypeArgs[binding.typeArgIndex] ?? null; + + let text = binding.typePattern; + for (let i = 0; i < binding.typeParamNames.length; i++) { + const arg = callerTypeArgs[i]; + if (!arg) return null; + text = text.replace(new RegExp(`\\b${binding.typeParamNames[i]}\\b`, 'g'), arg.getText(sf)); + } + + const parsed = ts.createSourceFile('wrapper-type.ts', `type __T = ${text};`, ts.ScriptTarget.Latest, true); + const stmt = parsed.statements[0]; + if (!ts.isTypeAliasDeclaration(stmt)) return null; + return stmt.type; +} + +function matchForwardedKnownWrapper( + body: ts.ConciseBody | ts.Block | undefined, + typeParams: readonly ts.TypeParameterDeclaration[] | undefined, + knownWrappers: Map, +): WrapperBinding | null { + if (!body || !typeParams?.length) return null; + const tps = typeParams; // narrowed copy for closure scope + const typeParamIndexes = new Map(tps.map((p, index) => [p.name.text, index])); + let found: WrapperBinding | null = null; + + function visit(node: ts.Node): void { + if (found) return; + if (ts.isCallExpression(node) && node.typeArguments?.length) { + const callableName = getCallableName(node.expression); + const wrapper = callableName ? knownWrappers.get(callableName) : undefined; + const forwardedTypeArg = wrapper ? node.typeArguments[wrapper.typeArgIndex] : undefined; + if ( + wrapper && + forwardedTypeArg && + ts.isTypeReferenceNode(forwardedTypeArg) && + ts.isIdentifier(forwardedTypeArg.typeName) && + !forwardedTypeArg.typeArguments?.length && + typeParamIndexes.has(forwardedTypeArg.typeName.text) + ) { + const chainTypeArgIndex = typeParamIndexes.get(forwardedTypeArg.typeName.text)!; + const binding: WrapperBinding = { + fnName: wrapper.fnName, + typeArgIndex: chainTypeArgIndex, + }; + // Propagate the typePattern from the inner wrapper, substituting + // its type-param names with the chain's own. Otherwise the chain + // would treat its own `` as the encoded type rather than the + // wrapped form (e.g. `Wrapper`). + if (wrapper.typePattern && wrapper.typeParamNames?.length === 1) { + const chainParamName = tps[chainTypeArgIndex].name.text; + const wrapperParamName = wrapper.typeParamNames[0]; + binding.typePattern = wrapperParamName === chainParamName + ? wrapper.typePattern + : wrapper.typePattern.replace(new RegExp(`\\b${wrapperParamName}\\b`, 'g'), chainParamName); + binding.typeParamNames = [chainParamName]; + binding.sourceFilePath = wrapper.sourceFilePath; + } + found = binding; + return; + } + } + + ts.forEachChild(node, visit); + } + + visit(body); + return found; +} + +function collectWrapperCandidates( + sf: ts.SourceFile, + exportedOnly: boolean, +): Array<{ name: string; body: ts.ConciseBody | ts.Block | undefined; typeParameters: readonly ts.TypeParameterDeclaration[] | undefined }> { + const candidates: Array<{ name: string; body: ts.ConciseBody | ts.Block | undefined; typeParameters: readonly ts.TypeParameterDeclaration[] | undefined }> = []; + + for (const stmt of sf.statements) { + if (ts.isFunctionDeclaration(stmt) && stmt.name && (!exportedOnly || hasExportModifier(stmt))) { + candidates.push({ name: stmt.name.text, body: stmt.body, typeParameters: stmt.typeParameters }); + continue; + } + + if (!ts.isVariableStatement(stmt) || (exportedOnly && !hasExportModifier(stmt))) continue; + for (const decl of stmt.declarationList.declarations) { + if (!ts.isIdentifier(decl.name) || !decl.initializer) continue; + const init = decl.initializer; + if (ts.isArrowFunction(init) || ts.isFunctionExpression(init)) { + candidates.push({ name: decl.name.text, body: init.body, typeParameters: init.typeParameters }); + continue; + } + + if (ts.isObjectLiteralExpression(init)) { + for (const prop of init.properties) { + if (ts.isPropertyAssignment(prop)) { + const propName = ts.isIdentifier(prop.name) || ts.isStringLiteral(prop.name) ? prop.name.text : null; + const propInit = prop.initializer; + if (propName && (ts.isArrowFunction(propInit) || ts.isFunctionExpression(propInit))) { + candidates.push({ name: propName, body: propInit.body, typeParameters: propInit.typeParameters }); + } + continue; + } + + if (ts.isMethodDeclaration(prop)) { + const propName = ts.isIdentifier(prop.name) || ts.isStringLiteral(prop.name) ? prop.name.text : null; + if (propName) candidates.push({ name: propName, body: prop.body, typeParameters: prop.typeParameters }); + } + } + } + } + } + + return candidates; +} + +function collectWrappers( + sf: ts.SourceFile, + exportedOnly: boolean, + externalKnownWrappers: Map = new Map(), +): Map { + const wrappers = new Map(); + const localWrapperMembers = new Map>(); + const candidates = collectWrapperCandidates(sf, exportedOnly); + + for (const candidate of candidates) { + const fn = matchForwardedProtobufFn(candidate.body, sf, candidate.typeParameters); + if (fn) wrappers.set(candidate.name, fn); + } + + // Detect both intra-file forwarders (`encodeFoo(v) { return encodeBar(v); }` + // where `encodeBar` is local) AND cross-file forwarders to wrappers imported + // from already-parsed modules. Externally known wrappers are seeded by the + // caller (`parseFileForDefinitions`) after it resolves imports. + const knownForForwarding = new Map(); + for (const [k, v] of externalKnownWrappers) knownForForwarding.set(k, v); + for (const [k, v] of wrappers) knownForForwarding.set(k, v); + + for (const candidate of candidates) { + if (wrappers.has(candidate.name)) continue; + const fn = matchForwardedKnownWrapper(candidate.body, candidate.typeParameters, knownForForwarding); + if (fn) wrappers.set(candidate.name, fn); + } + + for (const stmt of sf.statements) { + if (!ts.isVariableStatement(stmt) || (exportedOnly && !hasExportModifier(stmt))) continue; + for (const decl of stmt.declarationList.declarations) { + if (!ts.isIdentifier(decl.name) || !decl.initializer) continue; + const init = decl.initializer; + if (ts.isObjectLiteralExpression(init)) { + const memberWrappers = new Map(); + for (const prop of init.properties) { + if (!('name' in prop) || !prop.name) continue; + const propName = ts.isIdentifier(prop.name) || ts.isStringLiteral(prop.name) ? prop.name.text : null; + if (!propName) continue; + const fn = wrappers.get(propName); + if (fn) { + memberWrappers.set(propName, fn); + } + } + if (memberWrappers.size) localWrapperMembers.set(decl.name.text, memberWrappers); + } + } + } + + for (const stmt of sf.statements) { + if (exportedOnly || !ts.isVariableStatement(stmt)) continue; + for (const decl of stmt.declarationList.declarations) { + if (!ts.isIdentifier(decl.name) || !decl.initializer || !ts.isPropertyAccessExpression(decl.initializer)) continue; + if (!ts.isIdentifier(decl.initializer.expression)) continue; + const memberWrappers = localWrapperMembers.get(decl.initializer.expression.text); + const fn = memberWrappers?.get(decl.initializer.name.text); + if (fn) wrappers.set(decl.name.text, fn); + } + } + + return wrappers; +} + +function collectExportedWrappers( + sf: ts.SourceFile, + externalKnownWrappers: Map = new Map(), +): Map { + return collectWrappers(sf, true, externalKnownWrappers); +} + +/** + * Parse a file and extract its protobuf interfaces and generic templates. + * + * When `cache` is provided, this resolves the file's imports recursively + * (with cycle protection) so cross-file forwarded wrappers — e.g. + * `export function encodeChain(v) { return encodeBase(v); }` + * where `encodeBase` is imported from another module — can be detected. + */ +function parseFileForDefinitions( + absolutePath: string, + code?: string, + cache?: Map, + parsing?: Set, +): ParsedFileEntry { + const sourceText = code ?? readFileSync(absolutePath, 'utf-8'); + const sf = ts.createSourceFile(absolutePath, sourceText, ts.ScriptTarget.Latest, true); + const concrete: ProtobufMessage[] = []; + const templates = new Map(); + const resolveImportedTypeName = createImportedTypeNameResolver(sf); + const importedTypeSources = new Map(); + + // Collect imported wrapper bindings under their LOCAL names so this file's + // forwarders can match against them. Skip work entirely if there's no cache + // (legacy callers that don't care about cross-file forwarding). + // + // Only descends into value imports (not `import type { ... }`), since + // type-only imports can never introduce a wrapper function. This avoids + // pulling unrelated type-only modules into the cache. + const importedKnownWrappers = new Map(); + if (cache) { + const inProgress = parsing ?? new Set(); + inProgress.add(absolutePath); + for (const imp of extractValueImports(sf)) { + const resolved = resolveModulePath(imp.specifier, absolutePath); + if (!resolved) continue; + if (inProgress.has(resolved)) continue; // cycle guard + let entry = cache.get(resolved); + if (!entry) { + entry = parseFileForDefinitions(resolved, undefined, cache, inProgress); + cache.set(resolved, entry); + } + const wrapperFn = entry.exportedWrappers.get(imp.importedName); + if (wrapperFn) importedKnownWrappers.set(imp.localName, wrapperFn); + } + inProgress.delete(absolutePath); + } + + const exportedWrappers = collectExportedWrappers(sf, importedKnownWrappers); + + for (const imp of extractImports(sf)) { + const resolved = resolveModulePath(imp.specifier, absolutePath); + if (!resolved) continue; + importedTypeSources.set(imp.importedName, resolved); + importedTypeSources.set(imp.localName, resolved); + } + + for (const stmt of sf.statements) { + if (!ts.isInterfaceDeclaration(stmt)) continue; + if (stmt.typeParameters?.length) { + const tpl = collectGenericInterface(stmt, sf, resolveImportedTypeName); + if (tpl) templates.set(tpl.name, tpl); + } else { + const msg = collectInterface(stmt, sf, resolveImportedTypeName); + if (msg) concrete.push(msg); + } + } + + return { + filePath: absolutePath, + concrete, + templates, + importedTypeSources, + resolveImportedTypeName, + exportedWrappers, + }; +} + +function collectCallRootTypeNodes(sf: ts.SourceFile): ts.TypeNode[] { + const roots: ts.TypeNode[] = []; + const importBindings = collectProtobufImportBindings(sf); + + ts.forEachChild(sf, function visit(node) { + if (ts.isCallExpression(node)) { + const cs = matchProtobufCallSite(node, sf, importBindings, { + allowLegacyUnboundCanonical: true, + }); + if (cs) roots.push(cs.firstTypeArg); + } + + ts.forEachChild(node, visit); + }); + + return roots; +} + +interface RootTypeNode { + typeNode: ts.TypeNode; + from: ParsedFileEntry; +} + +/** + * Resolve only the import definitions reachable from protobuf call-site roots. + */ +export function resolveImports( + code: string, + importerPath: string, + cache: Map, +): ImportedDefinitions { + const entryPath = resolve(importerPath); + const entry = parseFileForDefinitions(entryPath, code, cache); + const concrete = new Map(); + const templates = new Map(); + const fileEntries = new Map([[entryPath, entry]]); + const visitedConcrete = new Set(); + const visitedTemplates = new Set(); + const importedObjectWrapperMembers = new Map>(); + + function getEntry(filePath: string): ParsedFileEntry { + const abs = resolve(filePath); + const known = fileEntries.get(abs); + if (known) return known; + + let parsed = cache.get(abs); + if (!parsed) { + parsed = parseFileForDefinitions(abs, undefined, cache); + cache.set(abs, parsed); + } + + fileEntries.set(abs, parsed); + return parsed; + } + + function collectCalledGenericIdentifiers(sf: ts.SourceFile): Set { + const names = new Set(); + + ts.forEachChild(sf, function visit(node) { + if (ts.isCallExpression(node) && node.typeArguments?.length) { + const callableName = getCallableName(node.expression); + if (callableName) names.add(callableName); + } + + ts.forEachChild(node, visit); + }); + + return names; + } + + function collectWrapperBindings(from: ParsedFileEntry, sf: ts.SourceFile): Map { + const bindings = new Map(); + const localWrappers = from.filePath === entryPath ? collectWrappers(sf, false) : from.exportedWrappers; + for (const [name, fn] of localWrappers) bindings.set(name, fn); + + const calledGenericIdentifiers = collectCalledGenericIdentifiers(sf); + for (const imp of extractImports(sf)) { + if (!calledGenericIdentifiers.has(imp.localName)) continue; + const resolved = resolveModulePath(imp.specifier, from.filePath); + if (!resolved) continue; + const wrapperFn = getEntry(resolved).exportedWrappers.get(imp.importedName); + if (wrapperFn) bindings.set(imp.localName, wrapperFn); + + const importedEntry = getEntry(resolved); + const memberNames = [...importedEntry.exportedWrappers.keys()].filter(name => calledGenericIdentifiers.has(name)); + if (memberNames.length) { + const members = new Map(); + for (const name of memberNames) { + const memberBinding = importedEntry.exportedWrappers.get(name)!; + members.set(name, memberBinding); + bindings.set(name, memberBinding); + } + importedObjectWrapperMembers.set(imp.localName, members); + } + } + + return bindings; + } + + function resolveTypeName(typeName: string, from: ParsedFileEntry): void { + if (typeName in PRIMITIVE_TYPE_MAP) return; + + const concreteMsg = from.concrete.find(msg => msg.name === typeName); + if (concreteMsg) { + const visitKey = `${from.filePath}:message:${typeName}`; + if (visitedConcrete.has(visitKey)) return; + visitedConcrete.add(visitKey); + + if (from.filePath !== entryPath && !concrete.has(concreteMsg.name)) { + concrete.set(concreteMsg.name, concreteMsg); + } + + for (const field of concreteMsg.fields) { + resolveTypeName(field.typeName, from); + } + return; + } + + const template = from.templates.get(typeName); + if (template) { + const visitKey = `${from.filePath}:template:${typeName}`; + if (visitedTemplates.has(visitKey)) return; + visitedTemplates.add(visitKey); + + if (from.filePath !== entryPath && !templates.has(template.name)) { + templates.set(template.name, template); + } + + for (const field of template.fields) { + if (!field.isTypeParam) resolveTypeName(field.rawTypeName, from); + } + return; + } + + const importedPath = from.importedTypeSources.get(typeName); + if (!importedPath) return; + + resolveTypeName(typeName, getEntry(importedPath)); + } + + function resolveTypeNode(typeNode: ts.TypeNode, from: ParsedFileEntry): void { + if (isKeywordTypeNode(typeNode)) return; + if (!ts.isTypeReferenceNode(typeNode) || !ts.isIdentifier(typeNode.typeName)) return; + + const typeName = from.resolveImportedTypeName(typeNode.typeName.text); + resolveTypeName(typeName, from); + + if (!typeNode.typeArguments?.length) return; + for (const typeArg of typeNode.typeArguments) { + resolveTypeNode(typeArg, from); + } + } + + const rootTypeNodes: RootTypeNode[] = collectCallRootTypeNodes(ts.createSourceFile(entryPath, code, ts.ScriptTarget.Latest, true)) + .map(typeNode => ({ typeNode, from: entry })); + const entrySourceFile = ts.createSourceFile(entryPath, code, ts.ScriptTarget.Latest, true); + const wrapperBindings = collectWrapperBindings(entry, entrySourceFile); + + ts.forEachChild(entrySourceFile, function visit(node) { + if ( + ts.isCallExpression(node) && + node.typeArguments?.length && + getCallableName(node.expression) && + ( + wrapperBindings.has(getCallableName(node.expression)!) || + ( + ts.isPropertyAccessExpression(node.expression) && + ts.isIdentifier(node.expression.expression) && + importedObjectWrapperMembers.get(node.expression.expression.text)?.has(node.expression.name.text) + ) + ) + ) { + const binding = wrapperBindings.get(getCallableName(node.expression)!) ?? ( + ts.isPropertyAccessExpression(node.expression) && ts.isIdentifier(node.expression.expression) + ? importedObjectWrapperMembers.get(node.expression.expression.text)?.get(node.expression.name.text) + : undefined + ); + if (!binding) return; + const typeArg = instantiateWrapperTypePattern(binding, node.typeArguments, entrySourceFile); + if (typeArg) rootTypeNodes.push({ + typeNode: typeArg, + from: binding.typePattern && binding.sourceFilePath ? getEntry(binding.sourceFilePath) : entry, + }); + if (binding.typePattern) { + for (const callerTypeArg of node.typeArguments) { + rootTypeNodes.push({ typeNode: callerTypeArg, from: entry }); + } + } + } + + ts.forEachChild(node, visit); + }); + + for (const root of rootTypeNodes) { + resolveTypeNode(root.typeNode, root.from); + } + + return { concrete: [...concrete.values()], templates, wrapperBindings }; +} diff --git a/packages/proton/src/ast/monomorphizer.ts b/packages/proton/src/ast/monomorphizer.ts new file mode 100644 index 00000000..219c5d1a --- /dev/null +++ b/packages/proton/src/ast/monomorphizer.ts @@ -0,0 +1,131 @@ +import ts from 'typescript'; +import { WireType, type ProtobufField, type ProtobufMessage, type GenericProtobufTemplate } from './types.js'; +import { + isKeywordTypeNode, + createImportedTypeNameResolver, + resolveSourceFileForTypeNode, + type ImportedTypeNameResolver, + typeNodeToMangledName, +} from './utils.js'; + +function identityImportedTypeName(name: string): string { + return name; +} + +/** Resolved value for a single template type parameter. */ +interface ResolvedTypeArg { + /** Mangled-name form used when substituting into a `rawTypeName` slot + * for an `isTypeParam` field. */ + mangled: string; + /** Original TypeScript source text — used when re-substituting into a + * field's `genericTypeArgText` so the substituted text remains parseable. */ + text: string; +} + +/** + * Recursively monomorphize a generic type instantiation into concrete ProtobufMessages. + * E.g. `Wrapper>` → creates `Wrapper__string` and `Wrapper__Wrapper__string`. + * Returns the mangled name of the concrete type, or null if it cannot be resolved. + */ +export function monomorphizeTypeNode( + typeNode: ts.TypeNode, + sf: ts.SourceFile, + templates: Map, + out: Map, + resolveImportedTypeName: ImportedTypeNameResolver = identityImportedTypeName, +): string | null { + if (!ts.isTypeReferenceNode(typeNode) || !ts.isIdentifier(typeNode.typeName)) return null; + + const baseName = resolveImportedTypeName(typeNode.typeName.text); + const typeArgs = typeNode.typeArguments; + if (!typeArgs || typeArgs.length === 0) return baseName; // already concrete + + const tpl = templates.get(baseName); + if (!tpl || typeArgs.length !== tpl.typeParams.length) return null; + + const mangledName = typeNodeToMangledName(typeNode, sf, resolveImportedTypeName); + if (out.has(mangledName)) return mangledName; // already done + + // Resolve each type parameter → both mangled name AND source text. + const paramMap = new Map(); + for (let i = 0; i < tpl.typeParams.length; i++) { + const resolved = resolveTypeArg(typeArgs[i], sf, templates, out, resolveImportedTypeName); + if (!resolved) return null; + paramMap.set(tpl.typeParams[i], resolved); + } + + // Substitute type params in template fields. + const fields: ProtobufField[] = tpl.fields.map(f => { + if (f.genericTypeArgText) { + // Field type is an inner generic instantiation referencing template + // type params (e.g. `pb>`). Substitute the params into + // the captured text, re-parse, and re-monomorphize so the resulting + // concrete instantiation (`Wrapper`) lands in `out`. + let substituted = f.genericTypeArgText; + for (const [paramName, value] of paramMap) { + substituted = substituted.replace( + new RegExp(`\\b${paramName}\\b`, 'g'), + value.text, + ); + } + const innerSfPath = f.genericTypeArgSourceFilePath ?? sf.fileName; + const innerSf = ts.createSourceFile( + innerSfPath, + `type __X = ${substituted};`, + ts.ScriptTarget.Latest, + true, + ); + const stmt = innerSf.statements[0]; + let resolvedTypeName: string | null = null; + if (ts.isTypeAliasDeclaration(stmt)) { + const innerResolver = createImportedTypeNameResolver(innerSf); + resolvedTypeName = monomorphizeTypeNode(stmt.type, innerSf, templates, out, innerResolver); + } + return { + name: f.name, + fieldNumber: f.fieldNumber, + typeName: resolvedTypeName ?? f.rawTypeName, + wireType: WireType.Varint, + isMessage: false, + isOptional: f.isOptional, + isRepeated: f.isRepeated, + }; + } + return { + name: f.name, + fieldNumber: f.fieldNumber, + typeName: f.isTypeParam ? (paramMap.get(f.rawTypeName)?.mangled ?? f.rawTypeName) : f.rawTypeName, + wireType: WireType.Varint, + isMessage: false, + isOptional: f.isOptional, + isRepeated: f.isRepeated, + }; + }); + + out.set(mangledName, { name: mangledName, fields }); + return mangledName; +} + +function resolveTypeArg( + node: ts.TypeNode, + sf: ts.SourceFile, + templates: Map, + out: Map, + resolveImportedTypeName: ImportedTypeNameResolver, +): ResolvedTypeArg | null { + const effectiveSf = resolveSourceFileForTypeNode(node, sf); + // Try recursive monomorphization first (handles nested generics). + const mono = monomorphizeTypeNode(node, effectiveSf, templates, out, resolveImportedTypeName); + if (mono) return { mangled: mono, text: node.getText(effectiveSf) }; + // Keyword type (string, number, …) + if (isKeywordTypeNode(node)) { + const text = node.getText(effectiveSf); + return { mangled: text, text }; + } + // Simple identifier (uint_32, SomeMsg, …) + if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && !node.typeArguments) { + const name = resolveImportedTypeName(node.typeName.text); + return { mangled: name, text: name }; + } + return null; +} diff --git a/packages/proton/src/ast/types.ts b/packages/proton/src/ast/types.ts new file mode 100644 index 00000000..37f80ea2 --- /dev/null +++ b/packages/proton/src/ast/types.ts @@ -0,0 +1,72 @@ +export enum WireType { + Varint = 0, + Bit64 = 1, + LengthDelim = 2, + Bit32 = 5, +} + +export interface ProtobufField { + name: string; + fieldNumber: number; + typeName: string; + wireType: WireType; + isMessage: boolean; + isOptional: boolean; + isRepeated: boolean; +} + +export interface ProtobufMessage { + name: string; + fields: ProtobufField[]; +} + +/** Generic interface template, e.g. `interface Wrapper { val: pb<1, T>; }` */ +export interface GenericProtobufTemplate { + name: string; + typeParams: string[]; + fields: GenericFieldTemplate[]; +} + +export interface GenericFieldTemplate { + name: string; + fieldNumber: number; + rawTypeName: string; + isTypeParam: boolean; + isOptional: boolean; + isRepeated: boolean; + /** + * For fields whose type-arg is itself a generic instantiation + * (e.g. `wrapped: pb<5, Wrapper>` where `U` is a template type + * parameter), the original type-arg source text. At monomorphization + * time the substituted text is re-parsed and re-instantiated so + * `Wrapper` ends up in the registry under its mangled name. + */ + genericTypeArgText?: string; + /** Source-file path captured alongside `genericTypeArgText`, used as + * the synthetic file name when re-parsing the substituted text. */ + genericTypeArgSourceFilePath?: string; +} + +export type MessageRegistry = Map; + +export const PRIMITIVE_TYPE_MAP: Record = { + uint_32: { wireType: WireType.Varint, defaultValue: '0' }, + int_32: { wireType: WireType.Varint, defaultValue: '0' }, + uint_64: { wireType: WireType.Varint, defaultValue: '0' }, + int_64: { wireType: WireType.Varint, defaultValue: '0' }, + sint_32: { wireType: WireType.Varint, defaultValue: '0' }, + sint_64: { wireType: WireType.Varint, defaultValue: '0' }, + bool: { wireType: WireType.Varint, defaultValue: 'false' }, + string: { wireType: WireType.LengthDelim, defaultValue: '""' }, + bytes: { wireType: WireType.LengthDelim, defaultValue: 'new Uint8Array(0)' }, + float: { wireType: WireType.Bit32, defaultValue: '0' }, + double: { wireType: WireType.Bit64, defaultValue: '0' }, + fixed_32: { wireType: WireType.Bit32, defaultValue: '0' }, + fixed_64: { wireType: WireType.Bit64, defaultValue: '0' }, + sfixed_32: { wireType: WireType.Bit32, defaultValue: '0' }, + sfixed_64: { wireType: WireType.Bit64, defaultValue: '0' }, +}; + +/** Marker identifiers recognised in type references */ +export const PB_MARKER = 'pb'; +export const PB_REPEATED_MARKER = 'pb_repeated'; diff --git a/packages/proton/src/ast/utils.ts b/packages/proton/src/ast/utils.ts new file mode 100644 index 00000000..04a0590f --- /dev/null +++ b/packages/proton/src/ast/utils.ts @@ -0,0 +1,85 @@ +import ts from 'typescript'; + +export type ImportedTypeNameResolver = (name: string) => string; + +function identityImportedTypeName(name: string): string { + return name; +} + +// Synthetic type-arg nodes (produced by wrapper-binding instantiation) live in +// their own SourceFile, not in the caller's. Anyone that needs to read text or +// resolve imports against such a node must use the registered SF; otherwise +// `node.getText(callerSf)` reads garbage from the wrong buffer. +const syntheticTypeSourceFiles = new WeakMap(); + +export function registerSyntheticTypeSourceFile(node: ts.TypeNode, sf: ts.SourceFile): void { + syntheticTypeSourceFiles.set(node, sf); +} + +export function resolveSourceFileForTypeNode(node: ts.TypeNode, fallback: ts.SourceFile): ts.SourceFile { + return syntheticTypeSourceFiles.get(node) ?? fallback; +} + +// TS 5.9+ removed ts.isKeywordTypeNode — manual kind-based check +const KEYWORD_TYPE_KINDS = new Set([ + ts.SyntaxKind.StringKeyword, + ts.SyntaxKind.NumberKeyword, + ts.SyntaxKind.BooleanKeyword, + ts.SyntaxKind.AnyKeyword, + ts.SyntaxKind.VoidKeyword, + ts.SyntaxKind.UndefinedKeyword, + ts.SyntaxKind.NullKeyword, + ts.SyntaxKind.NeverKeyword, + ts.SyntaxKind.UnknownKeyword, + ts.SyntaxKind.BigIntKeyword, + ts.SyntaxKind.SymbolKeyword, + ts.SyntaxKind.ObjectKeyword, +]); + +export function isKeywordTypeNode(node: ts.Node): boolean { + return KEYWORD_TYPE_KINDS.has(node.kind); +} + +export function createImportedTypeNameResolver(sf: ts.SourceFile): ImportedTypeNameResolver { + const localToImported = new Map(); + + for (const stmt of sf.statements) { + if (!ts.isImportDeclaration(stmt) || !stmt.importClause) continue; + const bindings = stmt.importClause.namedBindings; + if (!bindings || !ts.isNamedImports(bindings)) continue; + + for (const el of bindings.elements) { + localToImported.set(el.name.text, (el.propertyName ?? el.name).text); + } + } + + return (name: string) => localToImported.get(name) ?? name; +} + +/** + * Deterministic mangled name for a type node. + * `Foo` → `Foo` + * `Foo` → `Foo__string` + * `Foo>` → `Foo__Bar__uint_32` + * + * If `typeNode` is a synthetic node produced by wrapper-binding instantiation, + * its registered source file is used automatically so `getText()` returns + * the substituted type text rather than garbage from `sf`. + */ +export function typeNodeToMangledName( + typeNode: ts.TypeNode, + sf: ts.SourceFile, + resolveImportedTypeName: ImportedTypeNameResolver = identityImportedTypeName, +): string { + const effectiveSf = resolveSourceFileForTypeNode(typeNode, sf); + if (ts.isTypeReferenceNode(typeNode) && ts.isIdentifier(typeNode.typeName)) { + const base = resolveImportedTypeName(typeNode.typeName.text); + if (typeNode.typeArguments && typeNode.typeArguments.length > 0) { + const args = typeNode.typeArguments.map(a => typeNodeToMangledName(a, effectiveSf, resolveImportedTypeName)); + return base + '__' + args.join('__'); + } + return base; + } + if (isKeywordTypeNode(typeNode)) return typeNode.getText(effectiveSf); + return typeNode.getText(effectiveSf); +} diff --git a/packages/proton/src/codegen/decoder.ts b/packages/proton/src/codegen/decoder.ts new file mode 100644 index 00000000..0d8b87d2 --- /dev/null +++ b/packages/proton/src/codegen/decoder.ts @@ -0,0 +1,154 @@ +import { WireType, PRIMITIVE_TYPE_MAP, type ProtobufField, type ProtobufMessage, type MessageRegistry } from '../ast/types.js'; + +function tagValue(field: ProtobufField): number { + const wireType = field.isMessage || field.typeName === 'string' || field.typeName === 'bytes' + ? WireType.LengthDelim + : field.wireType; + return ((field.fieldNumber << 3) | wireType) >>> 0; +} + +/** Emit inline varint decode, storing result in `varName`. */ +function varintDec(varName: string, ind: string): string { + return [ + `${ind}let ${varName} = data[offset++];`, + `${ind}if (${varName} & 0x80) {`, + `${ind} let _s = 7, _b;`, + `${ind} ${varName} &= 0x7f;`, + `${ind} do { _b = data[offset++]; ${varName} |= (_b & 0x7f) << _s; _s += 7; } while (_b & 0x80);`, + `${ind}}`, + ].join('\n'); +} + +function varintDec64(varName: string, ind: string): string { + return [ + `${ind}let ${varName} = 0n, _s = 0n, _b;`, + `${ind}do { _b = data[offset++]; ${varName} |= BigInt(_b & 0x7f) << _s; _s += 7n; } while (_b & 0x80);`, + ].join('\n'); +} + +function isVarint64(typeName: string): boolean { + return typeName === 'uint_64' || typeName === 'int_64' || typeName === 'sint_64'; +} + +function isFixed64BigInt(typeName: string): boolean { + return typeName === 'fixed_64' || typeName === 'sfixed_64'; +} + +const INLINE_SKIP = [ + ` const wireType = _tag & 0x7;`, + ` if (wireType === 0) { while (data[offset] & 0x80) offset++; offset++; }`, + ` else if (wireType === 1) offset += 8;`, + ` else if (wireType === 2) { let _l = data[offset++]; if (_l & 0x80) { let _s = 7, _b; _l &= 0x7f; do { _b = data[offset++]; _l |= (_b & 0x7f) << _s; _s += 7; } while (_b & 0x80); } offset += _l; }`, + ` else if (wireType === 5) offset += 4;`, +].join('\n'); + +export function generateDecoder(msg: ProtobufMessage, _registry: MessageRegistry): string { + const locals = msg.fields.map((field, index) => { + const keyword = field.isRepeated ? 'const' : 'let'; + return ` ${keyword} _f${index} = ${getDefault(field)};`; + }); + const result = msg.fields.map((field, index) => `${field.name}: _f${index}`).join(', '); + + const L = [ + `function protobuf_decode_${msg.name}(data, offset = 0, end = data.length) {`, + ...locals, + ` while (offset < end) {`, + ` let _tag = data[offset++];`, + ` if (_tag & 0x80) {`, + ` let _ts = 7, _tb;`, + ` _tag &= 0x7f;`, + ` do { _tb = data[offset++]; _tag |= (_tb & 0x7f) << _ts; _ts += 7; } while (_tb & 0x80);`, + ` }`, + ` switch (_tag) {`, + ]; + + msg.fields.forEach((field, index) => { + L.push(decodeField(field, index)); + }); + + L.push( + ` default: {`, + INLINE_SKIP, + ` break;`, + ` }`, + ` }`, + ` }`, + ` return { ${result} };`, + `}`, + ); + return L.join('\n'); +} + +function decodeField(field: ProtobufField, index: number): string { + const { typeName, wireType, isMessage, isRepeated } = field; + const I = ' '; + const local = `_f${index}`; + const assign = (expr: string) => isRepeated + ? `${I}${local}.push(${expr});` + : `${I}${local} = ${expr};`; + + const L: string[] = [` case ${tagValue(field)}: {`]; + + if (isMessage) { + L.push(varintDec('_len', I)); + L.push(assign(`protobuf_decode_${typeName}(data, offset, offset + _len)`)); + L.push(`${I}offset += _len;`); + } else if (typeName === 'string') { + L.push(varintDec('_len', I)); + L.push(`${I}const _end = offset + _len;`); + L.push(assign(`__td.decode(data.subarray(offset, _end))`)); + L.push(`${I}offset = _end;`); + } else if (typeName === 'bytes') { + L.push(varintDec('_len', I)); + L.push(`${I}const _end = offset + _len;`); + L.push(assign(`data.slice(offset, _end)`)); + L.push(`${I}offset = _end;`); + } else if (typeName === 'bool') { + L.push(varintDec('_val', I)); + L.push(assign(`_val !== 0`)); + } else if (isVarint64(typeName)) { + L.push(varintDec64('_val', I)); + if (typeName === 'uint_64') { + L.push(assign(`_val`)); + } else if (typeName === 'int_64') { + L.push(assign(`BigInt.asIntN(64, _val)`)); + } else { + L.push(assign(`__zigZagDecode64(_val)`)); + } + } else if (typeName === 'sint_32') { + L.push(varintDec('_val', I)); + L.push(assign(`(_val >>> 1) ^ -(_val & 1)`)); + } else if (wireType === WireType.Varint) { + L.push(varintDec('_val', I)); + L.push(assign(`_val >>> 0`)); + } else if (typeName === 'float') { + L.push(assign(`__readFloat32(data, offset)`)); + L.push(`${I}offset += 4;`); + } else if (wireType === WireType.Bit32) { + L.push(assign(`data[offset] | (data[offset + 1] << 8) | (data[offset + 2] << 16) | (data[offset + 3] << 24)`)); + L.push(`${I}offset += 4;`); + } else if (typeName === 'double') { + L.push(assign(`__readFloat64(data, offset)`)); + L.push(`${I}offset += 8;`); + } else if (isFixed64BigInt(typeName)) { + if (typeName === 'fixed_64') { + L.push(assign(`__readFixed64(data, offset)`)); + } else { + L.push(assign(`BigInt.asIntN(64, __readFixed64(data, offset))`)); + } + L.push(`${I}offset += 8;`); + } else if (wireType === WireType.Bit64) { + L.push(assign(`data[offset] | (data[offset + 1] << 8) | (data[offset + 2] << 16) | (data[offset + 3] << 24)`)); + L.push(`${I}offset += 8;`); + } + + L.push(`${I}break;`, ` }`); + return L.join('\n'); +} + +function getDefault(field: ProtobufField): string { + if (field.isRepeated) return '[]'; + if (field.isOptional || field.isMessage) return 'null'; + const primitive = PRIMITIVE_TYPE_MAP[field.typeName]; + return primitive ? primitive.defaultValue : 'null'; +} diff --git a/packages/proton/src/codegen/encoder.ts b/packages/proton/src/codegen/encoder.ts new file mode 100644 index 00000000..372898e7 --- /dev/null +++ b/packages/proton/src/codegen/encoder.ts @@ -0,0 +1,590 @@ +import { WireType, type ProtobufField, type ProtobufMessage, type MessageRegistry } from '../ast/types.js'; + +/** + * Pre-compute tag bytes at codegen time. + * Field 1 + Varint(0) -> [0x08], Field 1 + LenDelim(2) -> [0x0a], etc. + */ +function computeTagBytes(fieldNumber: number, wireType: number): number[] { + let value = ((fieldNumber << 3) | wireType) >>> 0; + const bytes: number[] = []; + while (value > 0x7f) { + bytes.push((value & 0x7f) | 0x80); + value >>>= 7; + } + bytes.push(value & 0x7f); + return bytes; +} + +function writeTag(fieldNumber: number, wireType: number, ind: string): string { + return computeTagBytes(fieldNumber, wireType) + .map(byte => `${ind}buf[offset++] = ${byte};`) + .join('\n'); +} + +function varintSize(varName: string, ind: string): string { + return `${ind}size += ${varName} < 0x80 ? 1 : ${varName} < 0x4000 ? 2 : ${varName} < 0x200000 ? 3 : ${varName} < 0x10000000 ? 4 : 5;`; +} + +function writeVarint(expr: string, ind: string): string { + return [ + `${ind}let _v = ${expr};`, + `${ind}if (_v < 0x80) {`, + `${ind} buf[offset++] = _v;`, + `${ind}} else if (_v < 0x4000) {`, + `${ind} buf[offset++] = (_v & 0x7f) | 0x80;`, + `${ind} buf[offset++] = _v >>> 7;`, + `${ind}} else if (_v < 0x200000) {`, + `${ind} buf[offset++] = (_v & 0x7f) | 0x80;`, + `${ind} buf[offset++] = ((_v >>> 7) & 0x7f) | 0x80;`, + `${ind} buf[offset++] = _v >>> 14;`, + `${ind}} else if (_v < 0x10000000) {`, + `${ind} buf[offset++] = (_v & 0x7f) | 0x80;`, + `${ind} buf[offset++] = ((_v >>> 7) & 0x7f) | 0x80;`, + `${ind} buf[offset++] = ((_v >>> 14) & 0x7f) | 0x80;`, + `${ind} buf[offset++] = _v >>> 21;`, + `${ind}} else {`, + `${ind} buf[offset++] = (_v & 0x7f) | 0x80;`, + `${ind} buf[offset++] = ((_v >>> 7) & 0x7f) | 0x80;`, + `${ind} buf[offset++] = ((_v >>> 14) & 0x7f) | 0x80;`, + `${ind} buf[offset++] = ((_v >>> 21) & 0x7f) | 0x80;`, + `${ind} buf[offset++] = _v >>> 28;`, + `${ind}}`, + ].join('\n'); +} + +function isVarint64(typeName: string): boolean { + return typeName === 'uint_64' || typeName === 'int_64' || typeName === 'sint_64'; +} + +function isFixed64BigInt(typeName: string): boolean { + return typeName === 'fixed_64' || typeName === 'sfixed_64'; +} + +function bigintVarintExpr(typeName: string, expr: string): string { + if (typeName === 'uint_64') return `BigInt.asUintN(64, ${expr})`; + if (typeName === 'int_64') return `BigInt.asUintN(64, ${expr})`; + return `__zigZagEncode64(${expr})`; +} + +interface EncoderBlock { + declare: string[]; + size: string[]; + write: string[]; +} + +export function generateEncoder(msg: ProtobufMessage, _registry: MessageRegistry): string { + const blocks = msg.fields.map((field, index) => field.isRepeated ? buildRepeatedBlock(field, index) : buildSingularBlock(field, index)); + + const L = [ + `function protobuf_encode_${msg.name}(obj) {`, + ` let size = 0;`, + ...blocks.flatMap(block => block.declare), + ...blocks.flatMap(block => block.size), + ` const buf = new Uint8Array(size);`, + ` let offset = 0;`, + ...blocks.flatMap(block => block.write), + ` return buf;`, + `}`, + ]; + return L.join('\n'); +} + +function buildSingularBlock(field: ProtobufField, index: number): EncoderBlock { + const { name, fieldNumber, typeName, wireType, isMessage } = field; + const valueVar = `_f${index}`; + const cacheVar = `_c${index}`; + const tagLength = computeTagBytes(fieldNumber, isMessage || typeName === 'string' || typeName === 'bytes' ? 2 : wireType).length; + + if (isMessage) { + return { + declare: [` const ${valueVar} = obj.${name};`, ` let ${cacheVar};`], + size: [ + ` if (${valueVar} != null) {`, + ` ${cacheVar} = protobuf_encode_${typeName}(${valueVar});`, + ` const _len = ${cacheVar}.length;`, + ` size += ${tagLength};`, + varintSize('_len', ' '), + ` size += _len;`, + ` }`, + ], + write: [ + ` if (${valueVar} != null) {`, + ` const _data = ${cacheVar};`, + writeTag(fieldNumber, 2, ' '), + ` const _len = _data.length;`, + writeVarint('_len', ' '), + ` buf.set(_data, offset);`, + ` offset += _len;`, + ` }`, + ], + }; + } + + if (typeName === 'string') { + return { + declare: [` const ${valueVar} = obj.${name};`, ` let ${cacheVar};`], + size: [ + ` if (${valueVar} != null && ${valueVar} !== "") {`, + ` ${cacheVar} = __utf8Len(${valueVar});`, + ` const _len = ${cacheVar};`, + ` size += ${tagLength};`, + varintSize('_len', ' '), + ` size += _len;`, + ` }`, + ], + write: [ + ` if (${valueVar} != null && ${valueVar} !== "") {`, + writeTag(fieldNumber, 2, ' '), + ` const _len = ${cacheVar};`, + writeVarint('_len', ' '), + ` offset = __utf8Write(buf, offset, ${valueVar});`, + ` }`, + ], + }; + } + + if (typeName === 'bytes') { + return { + declare: [` const ${valueVar} = obj.${name};`], + size: [ + ` if (${valueVar} != null && ${valueVar}.length > 0) {`, + ` const _len = ${valueVar}.length;`, + ` size += ${tagLength};`, + varintSize('_len', ' '), + ` size += _len;`, + ` }`, + ], + write: [ + ` if (${valueVar} != null && ${valueVar}.length > 0) {`, + writeTag(fieldNumber, 2, ' '), + ` const _len = ${valueVar}.length;`, + writeVarint('_len', ' '), + ` buf.set(${valueVar}, offset);`, + ` offset += _len;`, + ` }`, + ], + }; + } + + if (typeName === 'bool') { + return { + declare: [` const ${valueVar} = obj.${name};`], + size: [` if (${valueVar} === true) size += ${tagLength + 1};`], + write: [ + ` if (${valueVar} === true) {`, + writeTag(fieldNumber, 0, ' '), + ` buf[offset++] = 1;`, + ` }`, + ], + }; + } + + if (isVarint64(typeName)) { + const bigintExpr = bigintVarintExpr(typeName, valueVar); + return { + declare: [` const ${valueVar} = obj.${name};`], + size: [ + ` if (${valueVar} != null && ${valueVar} !== 0n) {`, + ` const _val = ${bigintExpr};`, + ` size += ${tagLength};`, + ` size += __varint64Size(_val);`, + ` }`, + ], + write: [ + ` if (${valueVar} != null && ${valueVar} !== 0n) {`, + ` const _val = ${bigintExpr};`, + writeTag(fieldNumber, 0, ' '), + ` offset = __writeVarint64(buf, offset, _val);`, + ` }`, + ], + }; + } + + if (typeName === 'sint_32') { + return { + declare: [` const ${valueVar} = obj.${name};`], + size: [ + ` if (${valueVar} != null && ${valueVar} !== 0) {`, + ` const _val = ((${valueVar} << 1) ^ (${valueVar} >> 31)) >>> 0;`, + ` size += ${tagLength};`, + varintSize('_val', ' '), + ` }`, + ], + write: [ + ` if (${valueVar} != null && ${valueVar} !== 0) {`, + writeTag(fieldNumber, 0, ' '), + writeVarint(`((${valueVar} << 1) ^ (${valueVar} >> 31)) >>> 0`, ' '), + ` }`, + ], + }; + } + + if (wireType === WireType.Varint) { + return { + declare: [` const ${valueVar} = obj.${name};`], + size: [ + ` if (${valueVar} != null && ${valueVar} !== 0) {`, + ` const _val = ${valueVar} >>> 0;`, + ` size += ${tagLength};`, + varintSize('_val', ' '), + ` }`, + ], + write: [ + ` if (${valueVar} != null && ${valueVar} !== 0) {`, + writeTag(fieldNumber, 0, ' '), + writeVarint(`${valueVar} >>> 0`, ' '), + ` }`, + ], + }; + } + + if (typeName === 'float') { + return { + declare: [` const ${valueVar} = obj.${name};`], + size: [` if (${valueVar} != null && ${valueVar} !== 0) size += ${tagLength + 4};`], + write: [ + ` if (${valueVar} != null && ${valueVar} !== 0) {`, + writeTag(fieldNumber, 5, ' '), + ` offset = __writeFloat32(buf, offset, ${valueVar});`, + ` }`, + ], + }; + } + + if (wireType === WireType.Bit32) { + return { + declare: [` const ${valueVar} = obj.${name};`], + size: [` if (${valueVar} != null && ${valueVar} !== 0) size += ${tagLength + 4};`], + write: [ + ` if (${valueVar} != null && ${valueVar} !== 0) {`, + writeTag(fieldNumber, 5, ' '), + ` const _val = ${valueVar};`, + ` buf[offset++] = _val & 0xff;`, + ` buf[offset++] = (_val >> 8) & 0xff;`, + ` buf[offset++] = (_val >> 16) & 0xff;`, + ` buf[offset++] = (_val >> 24) & 0xff;`, + ` }`, + ], + }; + } + + if (typeName === 'double') { + return { + declare: [` const ${valueVar} = obj.${name};`], + size: [` if (${valueVar} != null && ${valueVar} !== 0) size += ${tagLength + 8};`], + write: [ + ` if (${valueVar} != null && ${valueVar} !== 0) {`, + writeTag(fieldNumber, 1, ' '), + ` offset = __writeFloat64(buf, offset, ${valueVar});`, + ` }`, + ], + }; + } + + if (isFixed64BigInt(typeName)) { + return { + declare: [` const ${valueVar} = obj.${name};`], + size: [` if (${valueVar} != null && ${valueVar} !== 0n) size += ${tagLength + 8};`], + write: [ + ` if (${valueVar} != null && ${valueVar} !== 0n) {`, + writeTag(fieldNumber, 1, ' '), + ` offset = __writeFixed64(buf, offset, ${valueVar});`, + ` }`, + ], + }; + } + + if (wireType === WireType.Bit64) { + return { + declare: [` const ${valueVar} = obj.${name};`], + size: [` if (${valueVar} != null && ${valueVar} !== 0) size += ${tagLength + 8};`], + write: [ + ` if (${valueVar} != null && ${valueVar} !== 0) {`, + writeTag(fieldNumber, 1, ' '), + ` const _val = ${valueVar};`, + ` buf[offset++] = _val & 0xff;`, + ` buf[offset++] = (_val >> 8) & 0xff;`, + ` buf[offset++] = (_val >> 16) & 0xff;`, + ` buf[offset++] = (_val >> 24) & 0xff;`, + ` buf[offset++] = 0;`, + ` buf[offset++] = 0;`, + ` buf[offset++] = 0;`, + ` buf[offset++] = 0;`, + ` }`, + ], + }; + } + + return { declare: [], size: [], write: [] }; +} + +function buildRepeatedBlock(field: ProtobufField, index: number): EncoderBlock { + const { name, fieldNumber, typeName, wireType, isMessage } = field; + const arrayVar = `_f${index}`; + const cacheVar = `_c${index}`; + const tagWireType = isMessage || typeName === 'string' || typeName === 'bytes' ? 2 : wireType; + const tagLength = computeTagBytes(fieldNumber, tagWireType).length; + + if (isMessage) { + return { + declare: [` const ${arrayVar} = obj.${name};`, ` let ${cacheVar};`], + size: [ + ` if (${arrayVar} != null && ${arrayVar}.length > 0) {`, + ` ${cacheVar} = new Array(${arrayVar}.length);`, + ` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`, + ` const _data = protobuf_encode_${typeName}(${arrayVar}[_i]);`, + ` ${cacheVar}[_i] = _data;`, + ` const _len = _data.length;`, + ` size += ${tagLength};`, + varintSize('_len', ' '), + ` size += _len;`, + ` }`, + ` }`, + ], + write: [ + ` if (${arrayVar} != null && ${arrayVar}.length > 0) {`, + ` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`, + ` const _data = ${cacheVar}[_i];`, + writeTag(fieldNumber, 2, ' '), + ` const _len = _data.length;`, + writeVarint('_len', ' '), + ` buf.set(_data, offset);`, + ` offset += _len;`, + ` }`, + ` }`, + ], + }; + } + + if (typeName === 'string') { + return { + declare: [` const ${arrayVar} = obj.${name};`, ` let ${cacheVar};`], + size: [ + ` if (${arrayVar} != null && ${arrayVar}.length > 0) {`, + ` ${cacheVar} = new Array(${arrayVar}.length);`, + ` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`, + ` const _len = __utf8Len(${arrayVar}[_i]);`, + ` ${cacheVar}[_i] = _len;`, + ` size += ${tagLength};`, + varintSize('_len', ' '), + ` size += _len;`, + ` }`, + ` }`, + ], + write: [ + ` if (${arrayVar} != null && ${arrayVar}.length > 0) {`, + ` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`, + ` const _len = ${cacheVar}[_i];`, + writeTag(fieldNumber, 2, ' '), + writeVarint('_len', ' '), + ` offset = __utf8Write(buf, offset, ${arrayVar}[_i]);`, + ` }`, + ` }`, + ], + }; + } + + if (typeName === 'bytes') { + return { + declare: [` const ${arrayVar} = obj.${name};`], + size: [ + ` if (${arrayVar} != null && ${arrayVar}.length > 0) {`, + ` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`, + ` const _data = ${arrayVar}[_i];`, + ` const _len = _data.length;`, + ` size += ${tagLength};`, + varintSize('_len', ' '), + ` size += _len;`, + ` }`, + ` }`, + ], + write: [ + ` if (${arrayVar} != null && ${arrayVar}.length > 0) {`, + ` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`, + ` const _data = ${arrayVar}[_i];`, + writeTag(fieldNumber, 2, ' '), + ` const _len = _data.length;`, + writeVarint('_len', ' '), + ` buf.set(_data, offset);`, + ` offset += _len;`, + ` }`, + ` }`, + ], + }; + } + + if (typeName === 'bool') { + return { + declare: [` const ${arrayVar} = obj.${name};`], + size: [` if (${arrayVar} != null && ${arrayVar}.length > 0) size += ${arrayVar}.length * ${tagLength + 1};`], + write: [ + ` if (${arrayVar} != null && ${arrayVar}.length > 0) {`, + ` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`, + writeTag(fieldNumber, 0, ' '), + ` buf[offset++] = ${arrayVar}[_i] ? 1 : 0;`, + ` }`, + ` }`, + ], + }; + } + + if (isVarint64(typeName)) { + const bigintExpr = bigintVarintExpr(typeName, `${arrayVar}[_i]`); + return { + declare: [` const ${arrayVar} = obj.${name};`], + size: [ + ` if (${arrayVar} != null && ${arrayVar}.length > 0) {`, + ` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`, + ` const _val = ${bigintExpr};`, + ` size += ${tagLength};`, + ` size += __varint64Size(_val);`, + ` }`, + ` }`, + ], + write: [ + ` if (${arrayVar} != null && ${arrayVar}.length > 0) {`, + ` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`, + ` const _val = ${bigintExpr};`, + writeTag(fieldNumber, 0, ' '), + ` offset = __writeVarint64(buf, offset, _val);`, + ` }`, + ` }`, + ], + }; + } + + if (typeName === 'sint_32') { + return { + declare: [` const ${arrayVar} = obj.${name};`], + size: [ + ` if (${arrayVar} != null && ${arrayVar}.length > 0) {`, + ` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`, + ` const _val = ((${arrayVar}[_i] << 1) ^ (${arrayVar}[_i] >> 31)) >>> 0;`, + ` size += ${tagLength};`, + varintSize('_val', ' '), + ` }`, + ` }`, + ], + write: [ + ` if (${arrayVar} != null && ${arrayVar}.length > 0) {`, + ` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`, + writeTag(fieldNumber, 0, ' '), + writeVarint(`((${arrayVar}[_i] << 1) ^ (${arrayVar}[_i] >> 31)) >>> 0`, ' '), + ` }`, + ` }`, + ], + }; + } + + if (wireType === WireType.Varint) { + return { + declare: [` const ${arrayVar} = obj.${name};`], + size: [ + ` if (${arrayVar} != null && ${arrayVar}.length > 0) {`, + ` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`, + ` const _val = ${arrayVar}[_i] >>> 0;`, + ` size += ${tagLength};`, + varintSize('_val', ' '), + ` }`, + ` }`, + ], + write: [ + ` if (${arrayVar} != null && ${arrayVar}.length > 0) {`, + ` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`, + writeTag(fieldNumber, 0, ' '), + writeVarint(`${arrayVar}[_i] >>> 0`, ' '), + ` }`, + ` }`, + ], + }; + } + + if (typeName === 'float') { + return { + declare: [` const ${arrayVar} = obj.${name};`], + size: [` if (${arrayVar} != null && ${arrayVar}.length > 0) size += ${arrayVar}.length * ${tagLength + 4};`], + write: [ + ` if (${arrayVar} != null && ${arrayVar}.length > 0) {`, + ` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`, + writeTag(fieldNumber, 5, ' '), + ` offset = __writeFloat32(buf, offset, ${arrayVar}[_i]);`, + ` }`, + ` }`, + ], + }; + } + + if (wireType === WireType.Bit32) { + return { + declare: [` const ${arrayVar} = obj.${name};`], + size: [` if (${arrayVar} != null && ${arrayVar}.length > 0) size += ${arrayVar}.length * ${tagLength + 4};`], + write: [ + ` if (${arrayVar} != null && ${arrayVar}.length > 0) {`, + ` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`, + writeTag(fieldNumber, 5, ' '), + ` const _val = ${arrayVar}[_i];`, + ` buf[offset++] = _val & 0xff;`, + ` buf[offset++] = (_val >> 8) & 0xff;`, + ` buf[offset++] = (_val >> 16) & 0xff;`, + ` buf[offset++] = (_val >> 24) & 0xff;`, + ` }`, + ` }`, + ], + }; + } + + if (typeName === 'double') { + return { + declare: [` const ${arrayVar} = obj.${name};`], + size: [` if (${arrayVar} != null && ${arrayVar}.length > 0) size += ${arrayVar}.length * ${tagLength + 8};`], + write: [ + ` if (${arrayVar} != null && ${arrayVar}.length > 0) {`, + ` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`, + writeTag(fieldNumber, 1, ' '), + ` offset = __writeFloat64(buf, offset, ${arrayVar}[_i]);`, + ` }`, + ` }`, + ], + }; + } + + if (isFixed64BigInt(typeName)) { + return { + declare: [` const ${arrayVar} = obj.${name};`], + size: [` if (${arrayVar} != null && ${arrayVar}.length > 0) size += ${arrayVar}.length * ${tagLength + 8};`], + write: [ + ` if (${arrayVar} != null && ${arrayVar}.length > 0) {`, + ` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`, + writeTag(fieldNumber, 1, ' '), + ` offset = __writeFixed64(buf, offset, ${arrayVar}[_i]);`, + ` }`, + ` }`, + ], + }; + } + + if (wireType === WireType.Bit64) { + return { + declare: [` const ${arrayVar} = obj.${name};`], + size: [` if (${arrayVar} != null && ${arrayVar}.length > 0) size += ${arrayVar}.length * ${tagLength + 8};`], + write: [ + ` if (${arrayVar} != null && ${arrayVar}.length > 0) {`, + ` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`, + writeTag(fieldNumber, 1, ' '), + ` const _val = ${arrayVar}[_i];`, + ` buf[offset++] = _val & 0xff;`, + ` buf[offset++] = (_val >> 8) & 0xff;`, + ` buf[offset++] = (_val >> 16) & 0xff;`, + ` buf[offset++] = (_val >> 24) & 0xff;`, + ` buf[offset++] = 0;`, + ` buf[offset++] = 0;`, + ` buf[offset++] = 0;`, + ` buf[offset++] = 0;`, + ` }`, + ` }`, + ], + }; + } + + return { declare: [], size: [], write: [] }; +} diff --git a/packages/proton/src/codegen/generator.ts b/packages/proton/src/codegen/generator.ts new file mode 100644 index 00000000..ee4ee9ca --- /dev/null +++ b/packages/proton/src/codegen/generator.ts @@ -0,0 +1,171 @@ +import type { MessageRegistry } from '../ast/types.js'; +import { generateEncoder } from './encoder.js'; +import { generateDecoder } from './decoder.js'; + +/** Shared preamble: UTF-8 string helpers plus TextDecoder for decode. */ +const CODEGEN_PREAMBLE = `const __td = new TextDecoder(); +const __scratch = new DataView(new ArrayBuffer(8)); +function __utf8Len(value) { + let length = 0; + for (let i = 0; i < value.length; i++) { + const code = value.charCodeAt(i); + if (code < 0x80) { + length++; + continue; + } + if (code < 0x800) { + length += 2; + continue; + } + if ((code & 0xfc00) === 0xd800) { + if (i + 1 < value.length) { + const next = value.charCodeAt(i + 1); + if ((next & 0xfc00) === 0xdc00) { + length += 4; + i++; + continue; + } + } + length += 3; + continue; + } + if ((code & 0xfc00) === 0xdc00) { + length += 3; + continue; + } + length += 3; + } + return length; +} +function __utf8Write(buf, offset, value) { + for (let i = 0; i < value.length; i++) { + let code = value.charCodeAt(i); + if (code < 0x80) { + buf[offset++] = code; + continue; + } + if (code < 0x800) { + buf[offset++] = 0xc0 | (code >> 6); + buf[offset++] = 0x80 | (code & 0x3f); + continue; + } + if ((code & 0xfc00) === 0xd800) { + if (i + 1 < value.length) { + const next = value.charCodeAt(i + 1); + if ((next & 0xfc00) === 0xdc00) { + const point = ((code - 0xd800) << 10) + (next - 0xdc00) + 0x10000; + buf[offset++] = 0xf0 | (point >> 18); + buf[offset++] = 0x80 | ((point >> 12) & 0x3f); + buf[offset++] = 0x80 | ((point >> 6) & 0x3f); + buf[offset++] = 0x80 | (point & 0x3f); + i++; + continue; + } + } + code = 0xfffd; + } else if ((code & 0xfc00) === 0xdc00) { + code = 0xfffd; + } + buf[offset++] = 0xe0 | (code >> 12); + buf[offset++] = 0x80 | ((code >> 6) & 0x3f); + buf[offset++] = 0x80 | (code & 0x3f); + } + return offset; +} +function __varint64Size(value) { + let size = 1; + while (value > 0x7fn) { + value >>= 7n; + size++; + } + return size; +} +function __writeVarint64(buf, offset, value) { + while (value > 0x7fn) { + buf[offset++] = Number((value & 0x7fn) | 0x80n); + value >>= 7n; + } + buf[offset++] = Number(value); + return offset; +} +function __zigZagEncode64(value) { + value = BigInt.asIntN(64, value); + return BigInt.asUintN(64, (value << 1n) ^ (value >> 63n)); +} +function __zigZagDecode64(value) { + return BigInt.asIntN(64, (value >> 1n) ^ -(value & 1n)); +} +function __writeFloat32(buf, offset, value) { + __scratch.setFloat32(0, value, true); + buf[offset++] = __scratch.getUint8(0); + buf[offset++] = __scratch.getUint8(1); + buf[offset++] = __scratch.getUint8(2); + buf[offset++] = __scratch.getUint8(3); + return offset; +} +function __readFloat32(data, offset) { + __scratch.setUint8(0, data[offset]); + __scratch.setUint8(1, data[offset + 1]); + __scratch.setUint8(2, data[offset + 2]); + __scratch.setUint8(3, data[offset + 3]); + return __scratch.getFloat32(0, true); +} +function __writeFloat64(buf, offset, value) { + __scratch.setFloat64(0, value, true); + buf[offset++] = __scratch.getUint8(0); + buf[offset++] = __scratch.getUint8(1); + buf[offset++] = __scratch.getUint8(2); + buf[offset++] = __scratch.getUint8(3); + buf[offset++] = __scratch.getUint8(4); + buf[offset++] = __scratch.getUint8(5); + buf[offset++] = __scratch.getUint8(6); + buf[offset++] = __scratch.getUint8(7); + return offset; +} +function __readFloat64(data, offset) { + __scratch.setUint8(0, data[offset]); + __scratch.setUint8(1, data[offset + 1]); + __scratch.setUint8(2, data[offset + 2]); + __scratch.setUint8(3, data[offset + 3]); + __scratch.setUint8(4, data[offset + 4]); + __scratch.setUint8(5, data[offset + 5]); + __scratch.setUint8(6, data[offset + 6]); + __scratch.setUint8(7, data[offset + 7]); + return __scratch.getFloat64(0, true); +} +function __writeFixed64(buf, offset, value) { + value = BigInt.asUintN(64, value); + buf[offset++] = Number(value & 0xffn); + buf[offset++] = Number((value >> 8n) & 0xffn); + buf[offset++] = Number((value >> 16n) & 0xffn); + buf[offset++] = Number((value >> 24n) & 0xffn); + buf[offset++] = Number((value >> 32n) & 0xffn); + buf[offset++] = Number((value >> 40n) & 0xffn); + buf[offset++] = Number((value >> 48n) & 0xffn); + buf[offset++] = Number((value >> 56n) & 0xffn); + return offset; +} +function __readFixed64(data, offset) { + return BigInt(data[offset]) + | (BigInt(data[offset + 1]) << 8n) + | (BigInt(data[offset + 2]) << 16n) + | (BigInt(data[offset + 3]) << 24n) + | (BigInt(data[offset + 4]) << 32n) + | (BigInt(data[offset + 5]) << 40n) + | (BigInt(data[offset + 6]) << 48n) + | (BigInt(data[offset + 7]) << 56n); +}`; + +/** + * Generate fully self-contained encode/decode source code. + * No runtime imports needed — all wire-format logic is inlined. + */ +export function generateCode(registry: MessageRegistry): string { + if (registry.size === 0) return ''; + const parts: string[] = [CODEGEN_PREAMBLE]; + for (const msg of registry.values()) { + parts.push(generateEncoder(msg, registry)); + parts.push(generateDecoder(msg, registry)); + } + return parts.join('\n'); +} diff --git a/packages/proton/src/codegen/wire.ts b/packages/proton/src/codegen/wire.ts new file mode 100644 index 00000000..9f2764b6 --- /dev/null +++ b/packages/proton/src/codegen/wire.ts @@ -0,0 +1,52 @@ +// Protobuf wire format helpers — used directly by wire.test.ts +// The generated code no longer depends on these (everything is inlined). + +export function encodeVarint(value: number, buf: number[]): void { + value = value >>> 0; + while (value > 0x7f) { + buf.push((value & 0x7f) | 0x80); + value = value >>> 7; + } + buf.push(value & 0x7f); +} + +export function decodeVarint(data: Uint8Array, offset: number): [number, number] { + let result = 0; + let shift = 0; + let byte: number; + do { + byte = data[offset++]; + result |= (byte & 0x7f) << shift; + shift += 7; + } while (byte & 0x80); + return [result >>> 0, offset]; +} + +export function writeTag(fieldNumber: number, wireType: number, buf: number[]): void { + encodeVarint((fieldNumber << 3) | wireType, buf); +} + +export function writeString(value: string, buf: number[]): void { + const encoded = new TextEncoder().encode(value); + encodeVarint(encoded.length, buf); + for (let i = 0; i < encoded.length; i++) buf.push(encoded[i]); +} + +export function readString(data: Uint8Array, offset: number, length: number): string { + return new TextDecoder().decode(data.subarray(offset, offset + length)); +} + +export function writeBytes(value: Uint8Array, buf: number[]): void { + encodeVarint(value.length, buf); + for (let i = 0; i < value.length; i++) buf.push(value[i]); +} + +export function skipField(data: Uint8Array, offset: number, wireType: number): number { + switch (wireType) { + case 0: while (data[offset] & 0x80) offset++; return offset + 1; + case 1: return offset + 8; + case 2: { const [len, o] = decodeVarint(data, offset); return o + len; } + case 5: return offset + 4; + default: throw new Error(`Unknown wire type: ${wireType}`); + } +} diff --git a/packages/proton/src/index.ts b/packages/proton/src/index.ts new file mode 100644 index 00000000..370f9f54 --- /dev/null +++ b/packages/proton/src/index.ts @@ -0,0 +1,113 @@ +import type { Plugin } from 'vite'; +import { analyze, analyzeSource, selectUsedRegistry, typeNodeToMangledName } from './ast/analyzer.js'; +import { generateCode } from './codegen/generator.js'; +import { applyReplacements, replaceCallSites } from './transform/replacer.js'; +import type { MessageRegistry } from './ast/types.js'; +import { resolveImports, type ParsedFileEntry } from './ast/import-resolver.js'; +import { createRuntimeMap, type RuntimeMapCallSite } from './runtime-map.js'; + +export interface ProtobufRuntimeMapPluginOptions { + enabled?: boolean; + fileName?: string; +} + +export interface ProtobufVitePluginOptions { + runtimeMap?: ProtobufRuntimeMapPluginOptions; +} + +interface RuntimeMapFileEntry { + messages: MessageRegistry; + callSites: RuntimeMapCallSite[]; +} + +export default function protobufVitePlugin(options: ProtobufVitePluginOptions = {}): Plugin { + const fileCache = new Map(); + const runtimeMapByFile = new Map(); + const runtimeMapEnabled = options.runtimeMap?.enabled === true; + const runtimeMapFileName = options.runtimeMap?.fileName ?? 'snowluma-proton.runtime-map.json'; + + return { + name: 'vite-plugin-protobuf', + enforce: 'pre', + + transform(code, id) { + const cleanId = id.split('?')[0]; + if (!cleanId.endsWith('.ts') || cleanId.endsWith('.d.ts')) return null; + + const imported = resolveImports(code, cleanId, fileCache); + const { registry, callSites, sourceFile } = analyze(code, cleanId, imported); + if (registry.size === 0 && callSites.length === 0) return null; + + const used = selectUsedRegistry(registry, callSites, sourceFile); + if (used.registry.size === 0) { + runtimeMapByFile.delete(cleanId); + return null; + } + + if (runtimeMapEnabled) { + runtimeMapByFile.set(cleanId, { + messages: used.registry, + callSites: used.callSites.map(cs => ({ + file: cleanId, + line: cs.line, + column: cs.column, + fnName: cs.fnName as RuntimeMapCallSite['fnName'], + typeName: cs.typeName, + })), + }); + } + + const generatedCode = generateCode(used.registry); + const { transformedCode, hasReplacements } = applyReplacements(code, sourceFile, callSites, used.registry); + if (!hasReplacements && generatedCode === '') return null; + + return { code: generatedCode + '\n' + transformedCode, map: null }; + }, + + handleHotUpdate({ file }) { + if (file.endsWith('.ts')) { + fileCache.delete(file); + runtimeMapByFile.delete(file); + } + }, + + generateBundle() { + if (!runtimeMapEnabled) return; + + const mergedMessages: MessageRegistry = new Map(); + const mergedCallSites: RuntimeMapCallSite[] = []; + + for (const entry of runtimeMapByFile.values()) { + for (const [name, msg] of entry.messages) mergedMessages.set(name, msg); + mergedCallSites.push(...entry.callSites); + } + + if (mergedMessages.size === 0 || mergedCallSites.length === 0) return; + + const runtimeMap = createRuntimeMap({ + messages: mergedMessages, + callSites: mergedCallSites, + }); + + this.emitFile({ + type: 'asset', + fileName: runtimeMapFileName, + source: JSON.stringify(runtimeMap, null, 2), + }); + }, + }; +} + +export { + analyze, + analyzeSource, + generateCode, + replaceCallSites, + applyReplacements, + typeNodeToMangledName, + resolveImports, + selectUsedRegistry, + createRuntimeMap, +}; + +export type { ProtobufRuntimeMap, RuntimeMapCallSite } from './runtime-map.js'; diff --git a/packages/proton/src/runtime-map.ts b/packages/proton/src/runtime-map.ts new file mode 100644 index 00000000..8406d194 --- /dev/null +++ b/packages/proton/src/runtime-map.ts @@ -0,0 +1,71 @@ +import type { MessageRegistry, ProtobufField, ProtobufMessage } from './ast/types.js'; + +export type RuntimeMapFnName = 'protobuf_encode' | 'protobuf_decode'; + +export interface RuntimeMapCallSite { + file: string; + line: number; + column: number; + fnName: RuntimeMapFnName; + typeName: string; +} + +export interface ProtobufRuntimeMap { + version: 1; + messages: ProtobufMessage[]; + callSites: RuntimeMapCallSite[]; +} + +function cloneField(field: ProtobufField): ProtobufField { + return { + name: field.name, + fieldNumber: field.fieldNumber, + typeName: field.typeName, + wireType: field.wireType, + isMessage: field.isMessage, + isOptional: field.isOptional, + isRepeated: field.isRepeated, + }; +} + +function cloneMessage(msg: ProtobufMessage): ProtobufMessage { + return { + name: msg.name, + fields: msg.fields.map(cloneField), + }; +} + +export function registryToRuntimeMapMessages(registry: MessageRegistry): ProtobufMessage[] { + return [...registry.values()].map(cloneMessage); +} + +export function runtimeMapToRegistry(map: ProtobufRuntimeMap): MessageRegistry { + const registry: MessageRegistry = new Map(); + for (const msg of map.messages) { + registry.set(msg.name, cloneMessage(msg)); + } + return registry; +} + +export function normalizeRuntimeMapPath(filePath: string): string { + const noQuery = filePath.replace(/[?#].*$/, ''); + return noQuery.replace(/\\/g, '/').replace(/^file:\/\//, ''); +} + +export function createRuntimeMap(map: { messages: MessageRegistry; callSites: RuntimeMapCallSite[] }): ProtobufRuntimeMap { + const dedupedCallSites = new Map(); + for (const cs of map.callSites) { + const normalized = { + ...cs, + file: normalizeRuntimeMapPath(cs.file), + }; + const key = `${normalized.file}:${normalized.line}:${normalized.column}:${normalized.fnName}:${normalized.typeName}`; + dedupedCallSites.set(key, normalized); + } + + return { + version: 1, + messages: registryToRuntimeMapMessages(map.messages), + callSites: [...dedupedCallSites.values()], + }; +} diff --git a/packages/proton/src/runtime.ts b/packages/proton/src/runtime.ts new file mode 100644 index 00000000..a4236fbc --- /dev/null +++ b/packages/proton/src/runtime.ts @@ -0,0 +1,220 @@ +/** + * Runtime fallback functions. + * If the Vite plugin is active, calls to protobuf_encode/decode are replaced + * at compile-time with generated type-specific functions. + * If NOT transformed, these fallbacks throw to alert the developer. + */ +import type { MessageRegistry } from './ast/types.js'; +import { buildDependencyRegistry } from './ast/dependency-graph.js'; +import { generateCode } from './codegen/generator.js'; +import { + normalizeRuntimeMapPath, + runtimeMapToRegistry, + type ProtobufRuntimeMap, + type RuntimeMapCallSite, + type RuntimeMapFnName, +} from './runtime-map.js'; + +type DynamicEncode = (params: unknown) => Uint8Array; +type DynamicDecode = (data: Uint8Array) => unknown; + +interface DynamicTypeFns { + encode?: DynamicEncode; + decode?: DynamicDecode; +} + +interface StackFrame { + file: string; + line: number; + column: number; +} + +const DYNAMIC_MISS = Symbol('snowluma-proton-dynamic-miss'); + +let runtimeMapFallback: ProtobufRuntimeMap | null = null; +let runtimeMapRegistry: MessageRegistry | null = null; +let runtimeMapCallSites: RuntimeMapCallSite[] = []; +const dynamicTypeCache = new Map(); + +/** + * Enable dynamic runtime fallback from a pre-collected map file. + * This is disabled by default. + */ +export function protobuf_enableRuntimeMapFallback(map: ProtobufRuntimeMap): void { + runtimeMapFallback = map; + runtimeMapRegistry = runtimeMapToRegistry(map); + runtimeMapCallSites = map.callSites.map(cs => ({ + ...cs, + file: normalizeRuntimeMapPath(cs.file), + })); + dynamicTypeCache.clear(); +} + +/** Disable dynamic runtime fallback and clear all generated function caches. */ +export function protobuf_disableRuntimeMapFallback(): void { + runtimeMapFallback = null; + runtimeMapRegistry = null; + runtimeMapCallSites = []; + dynamicTypeCache.clear(); +} + +export function protobuf_encode(_params: T): Uint8Array { + const dynamic = tryDynamicInvoke('protobuf_encode', _params); + if (dynamic !== DYNAMIC_MISS) return dynamic as Uint8Array; + + throw new Error( + 'protobuf_encode() was not transformed by the @snowluma/proton Vite plugin. ' + + 'Make sure protobufVitePlugin() is added to your vite.config.ts plugins array.', + ); +} + +export function protobuf_decode(_data: Uint8Array): T { + const dynamic = tryDynamicInvoke('protobuf_decode', _data); + if (dynamic !== DYNAMIC_MISS) return dynamic as T; + + throw new Error( + 'protobuf_decode() was not transformed by the @snowluma/proton Vite plugin. ' + + 'Make sure protobufVitePlugin() is added to your vite.config.ts plugins array.', + ); +} + +function tryDynamicInvoke(fnName: RuntimeMapFnName, payload: unknown): unknown { + if (!runtimeMapFallback || runtimeMapFallback.version !== 1 || !runtimeMapRegistry) { + return DYNAMIC_MISS; + } + + const caller = getFirstUserFrame(); + if (!caller) return DYNAMIC_MISS; + + const callSite = resolveCallSite(fnName, caller); + if (!callSite) return DYNAMIC_MISS; + + const typeFns = ensureTypeFunctions(callSite.typeName); + if (!typeFns) return DYNAMIC_MISS; + + const fn = fnName === 'protobuf_encode' ? typeFns.encode : typeFns.decode; + if (typeof fn !== 'function') return DYNAMIC_MISS; + + return fn(payload as never); +} + +function ensureTypeFunctions(typeName: string): DynamicTypeFns | null { + const cached = dynamicTypeCache.get(typeName); + if (cached) return cached; + if (!runtimeMapRegistry || !runtimeMapRegistry.has(typeName)) return null; + + const subset = buildDependencyRegistry(runtimeMapRegistry, [typeName]); + if (subset.size === 0) return null; + + const generated = generateCode(subset); + if (!generated) return null; + + const factory = new Function( + `${generated}\nreturn {\n` + + ` encode: typeof protobuf_encode_${typeName} === 'function' ? protobuf_encode_${typeName} : undefined,\n` + + ` decode: typeof protobuf_decode_${typeName} === 'function' ? protobuf_decode_${typeName} : undefined,\n` + + `};`, + ) as () => DynamicTypeFns; + + const compiled = factory(); + dynamicTypeCache.set(typeName, compiled); + return compiled; +} + +function resolveCallSite(fnName: RuntimeMapFnName, caller: StackFrame): RuntimeMapCallSite | null { + const callerFile = normalizeRuntimeMapPath(caller.file); + + const candidates = runtimeMapCallSites.filter(cs => + cs.fnName === fnName && + cs.line === caller.line && + pathsLikelySame(callerFile, cs.file), + ); + + if (candidates.length === 0) return null; + if (candidates.length === 1) return candidates[0]; + + let best = candidates[0]; + let bestDistance = Math.abs(best.column - caller.column); + for (let i = 1; i < candidates.length; i++) { + const dist = Math.abs(candidates[i].column - caller.column); + if (dist < bestDistance) { + best = candidates[i]; + bestDistance = dist; + } + } + return best; +} + +function getFirstUserFrame(): StackFrame | null { + const err = new Error(); + if (!err.stack) return null; + + const lines = err.stack.split('\n').slice(1); + for (const raw of lines) { + const frame = parseStackLine(raw); + if (!frame) continue; + + const file = normalizeRuntimeMapPath(frame.file); + if (isRuntimeInternalFile(file)) continue; + + return { + file, + line: frame.line, + column: frame.column, + }; + } + + return null; +} + +function parseStackLine(line: string): StackFrame | null { + const trimmed = line.trim(); + if (!trimmed) return null; + + let location = trimmed; + const atPrefix = 'at '; + if (location.startsWith(atPrefix)) { + location = location.slice(atPrefix.length).trim(); + } + + const openParen = location.lastIndexOf('('); + if (openParen >= 0 && location.endsWith(')')) { + location = location.slice(openParen + 1, -1); + } + + const lastColon = location.lastIndexOf(':'); + if (lastColon < 0) return null; + const secondLastColon = location.lastIndexOf(':', lastColon - 1); + if (secondLastColon < 0) return null; + + const file = location.slice(0, secondLastColon); + const linePart = location.slice(secondLastColon + 1, lastColon); + const colPart = location.slice(lastColon + 1); + + const parsedLine = Number(linePart); + const parsedCol = Number(colPart); + if (!Number.isFinite(parsedLine) || !Number.isFinite(parsedCol)) return null; + + return { + file, + line: parsedLine, + column: parsedCol, + }; +} + +function isRuntimeInternalFile(file: string): boolean { + return file.endsWith('/runtime.ts') || file.endsWith('/runtime.js') || file.includes('/dist/runtime.js'); +} + +function pathsLikelySame(a: string, b: string): boolean { + if (a === b) return true; + const aBase = basename(a); + const bBase = basename(b); + return aBase !== '' && aBase === bBase; +} + +function basename(file: string): string { + const normalized = normalizeRuntimeMapPath(file); + const idx = normalized.lastIndexOf('/'); + return idx >= 0 ? normalized.slice(idx + 1) : normalized; +} diff --git a/packages/proton/src/transform/replacer.ts b/packages/proton/src/transform/replacer.ts new file mode 100644 index 00000000..e40569d8 --- /dev/null +++ b/packages/proton/src/transform/replacer.ts @@ -0,0 +1,61 @@ +import type { MessageRegistry } from '../ast/types.js'; +import type { CallSiteRecord } from '../ast/analyzer.js'; +import { createImportedTypeNameResolver, typeNodeToMangledName } from '../ast/utils.js'; +import { collectProtobufImportBindings, matchProtobufCallSite } from '../ast/callsite.js'; +import ts from 'typescript'; + +interface TextEdit { start: number; end: number; replacement: string } + +/** + * Apply replacements using pre-recorded call-sites from analyze(). + * No parsing or AST walking — just position-based string edits. + */ +export function applyReplacements( + code: string, + sf: ts.SourceFile, + callSites: CallSiteRecord[], + registry: MessageRegistry, +): { transformedCode: string; hasReplacements: boolean } { + const edits: TextEdit[] = []; + const resolveImportedTypeName = createImportedTypeNameResolver(sf); + + for (const cs of callSites) { + const mangled = typeNodeToMangledName(cs.firstTypeArg, sf, resolveImportedTypeName); + if (registry.has(mangled)) { + edits.push({ + start: cs.exprStart, + end: cs.typeArgsEnd, + replacement: `${cs.fnName}_${mangled}`, + }); + } + } + + if (!edits.length) return { transformedCode: code, hasReplacements: false }; + + edits.sort((a, b) => b.start - a.start); + let result = code; + for (const ed of edits) result = result.slice(0, ed.start) + ed.replacement + result.slice(ed.end); + return { transformedCode: result, hasReplacements: true }; +} + +/** + * Backward-compatible: parses + walks on its own. + * Prefer applyReplacements() with pre-recorded call-sites from analyze(). + */ +export function replaceCallSites(code: string, registry: MessageRegistry): { transformedCode: string; hasReplacements: boolean } { + const sf = ts.createSourceFile('input.ts', code, ts.ScriptTarget.Latest, true); + const callSites: CallSiteRecord[] = []; + const importBindings = collectProtobufImportBindings(sf); + + ts.forEachChild(sf, function visit(node) { + if (ts.isCallExpression(node)) { + const cs = matchProtobufCallSite(node, sf, importBindings, { + allowLegacyUnboundCanonical: true, + }); + if (cs) callSites.push(cs); + } + ts.forEachChild(node, visit); + }); + + return applyReplacements(code, sf, callSites, registry); +} diff --git a/packages/proton/test/__tests__/analyzer.test.ts b/packages/proton/test/__tests__/analyzer.test.ts new file mode 100644 index 00000000..f2390d2b --- /dev/null +++ b/packages/proton/test/__tests__/analyzer.test.ts @@ -0,0 +1,145 @@ +import { describe, it, expect } from 'vitest'; +import { analyzeSource } from '../../src/ast/analyzer'; +import { WireType } from '../../src/ast/types'; +import { loadFixture } from '../helpers'; + +describe('AST analyzer', () => { + it('collects TestProtobuf with correct fields', () => { + const registry = analyzeSource(loadFixture('real.ts'), 'real.ts'); + const msg = registry.get('TestProtobuf')!; + expect(msg).toBeDefined(); + expect(msg.fields).toHaveLength(1); + expect(msg.fields[0]).toMatchObject({ name: 'name', fieldNumber: 1, typeName: 'uint_32', isMessage: false }); + }); + + it('collects nested message field', () => { + const registry = analyzeSource(loadFixture('real.ts'), 'real.ts'); + const msg = registry.get('TestProtobufOutput')!; + expect(msg.fields[0]).toMatchObject({ name: 'name', fieldNumber: 1, typeName: 'TestProtobuf', isMessage: true }); + }); + + it('topological order: dependencies first', () => { + const keys = [...analyzeSource(loadFixture('real.ts'), 'real.ts').keys()]; + expect(keys.indexOf('TestProtobuf')).toBeLessThan(keys.indexOf('TestProtobufOutput')); + }); + + it('skips generic interfaces (no call sites)', () => { + expect(analyzeSource(loadFixture('generic-template.ts'), 'g.ts').size).toBe(0); + }); + + it('returns empty for non-pb interfaces', () => { + expect(analyzeSource(loadFixture('no-pb.ts'), 'no.ts').size).toBe(0); + }); + + it('handles multiple fields', () => { + const msg = analyzeSource(loadFixture('multi-field.ts'), 't.ts').get('UserProfile')!; + expect(msg.fields).toHaveLength(3); + expect(msg.fields[0]).toMatchObject({ name: 'id', fieldNumber: 1, typeName: 'uint_32' }); + expect(msg.fields[1]).toMatchObject({ name: 'username', fieldNumber: 2, typeName: 'string' }); + expect(msg.fields[2]).toMatchObject({ name: 'active', fieldNumber: 3, typeName: 'bool' }); + }); + + it('collects repeated fields', () => { + const msg = analyzeSource(loadFixture('repeated.ts'), 't.ts').get('RepeatedMsg')!; + expect(msg.fields).toHaveLength(2); + expect(msg.fields[0]).toMatchObject({ name: 'ids', fieldNumber: 1, typeName: 'uint_32', isRepeated: true }); + expect(msg.fields[1]).toMatchObject({ name: 'names', fieldNumber: 2, typeName: 'string', isRepeated: true }); + }); + + it('monomorphizes generics from call sites', () => { + const registry = analyzeSource(loadFixture('generic-usage.ts'), 'g.ts'); + expect(registry.has('TestProtobufAny__string')).toBe(true); + expect(registry.has('TestProtobufAny__TestProtobufAny__string')).toBe(true); + }); + + // ── Edge cases (originally silently dropped / wrong wire type) ────── + + it('edge: monomorphizes a generic-instantiated field on a concrete interface', () => { + // Regression: a concrete interface with `pb>` previously + // resolved the field's typeName to the bare identifier `"Wrapper"` and + // never enqueued `Wrapper` for monomorphization. The field was left + // with the placeholder WireType.Varint, corrupting the wire format. + const registry = analyzeSource(loadFixture('nested-generic-field.ts'), 'n.ts'); + + expect(registry.has('Wrapper__uint_32')).toBe(true); + + const container = registry.get('Container')!; + expect(container).toBeDefined(); + expect(container.fields[0]).toMatchObject({ + name: 'wrapped', + fieldNumber: 5, + typeName: 'Wrapper__uint_32', + isMessage: true, + wireType: WireType.LengthDelim, + }); + }); + + it('edge: monomorphizes a generic-instantiated field on a generic template', () => { + // Regression: a generic template field typed as `pb>` — + // where `U` is the outer template's type param — was stored with the + // mangled-but-unsubstituted name `'Wrapper__U'` and never re-instantiated + // with the concrete substitution at monomorphization time. The field + // ended up referencing `Wrapper__U` instead of `Wrapper__uint_32` and the + // inner mangled instantiation was missing from the registry. + const registry = analyzeSource(loadFixture('generic-with-generic-field.ts'), 'g.ts'); + + expect(registry.has('Outer__uint_32')).toBe(true); + expect(registry.has('Wrapper__uint_32')).toBe(true); + + const outer = registry.get('Outer__uint_32')!; + expect(outer.fields[0]).toMatchObject({ + name: 'wrapped', + fieldNumber: 5, + typeName: 'Wrapper__uint_32', + isMessage: true, + wireType: WireType.LengthDelim, + }); + + const wrapper = registry.get('Wrapper__uint_32')!; + expect(wrapper.fields[0]).toMatchObject({ + name: 'value', + fieldNumber: 1, + typeName: 'uint_32', + isMessage: false, + }); + }); + + it('edge: throws when a field references an unresolved type name', () => { + // Defensive guard: anything that escapes the analyzer's type tracking + // (unions, intersections, mapped/conditional types, `Partial`, etc.) + // used to silently leak `WireType.Varint` into the codegen. Now it has + // to fail loudly so future edge cases surface immediately. + const source = ` + interface BadMsg { + weird: pb<1, MissingType>; + } + const buf = protobuf_encode({} as any); + `; + expect(() => analyzeSource(source, 'b.ts')).toThrow(/MissingType/); + }); + + it('edge: recognises aliased pb / pb_repeated marker imports', () => { + // Regression: `parsePbTypeRef` compared the literal type-ref identifier + // text against the constants `'pb'` / `'pb_repeated'`. With + // `import { pb as P }` the text became `'P'`, so every field on the + // interface was silently dropped and `Aliased` never made it into the + // registry. + const registry = analyzeSource(loadFixture('aliased-pb-marker.ts'), 'a.ts'); + + const aliased = registry.get('Aliased')!; + expect(aliased).toBeDefined(); + expect(aliased.fields).toHaveLength(2); + expect(aliased.fields[0]).toMatchObject({ + name: 'id', + fieldNumber: 1, + typeName: 'uint_32', + isRepeated: false, + }); + expect(aliased.fields[1]).toMatchObject({ + name: 'tags', + fieldNumber: 2, + typeName: 'string', + isRepeated: true, + }); + }); +}); diff --git a/packages/proton/test/__tests__/cross-file.test.ts b/packages/proton/test/__tests__/cross-file.test.ts new file mode 100644 index 00000000..9f553cba --- /dev/null +++ b/packages/proton/test/__tests__/cross-file.test.ts @@ -0,0 +1,342 @@ +import { describe, it, expect } from 'vitest'; +import { readFileSync } from 'fs'; +import { resolve, dirname } from 'path'; +import { fileURLToPath } from 'url'; +import { analyze, analyzeSource, selectUsedRegistry } from '../../src/ast/analyzer'; +import { generateCode } from '../../src/codegen/generator'; +import { applyReplacements } from '../../src/transform/replacer'; +import { resolveImports, type ParsedFileEntry } from '../../src/ast/import-resolver'; +import { execAndGet } from '../helpers'; + +const crossDir = resolve(dirname(fileURLToPath(import.meta.url)), '..', 'fixtures', 'cross-file'); + +function loadCross(name: string): { code: string; path: string } { + const path = resolve(crossDir, name); + return { code: readFileSync(path, 'utf-8'), path }; +} + +describe('cross-file import resolution', () => { + // ── Scenario A: imported type in encode/decode call site ────────── + + it('resolves imported type for protobuf_encode/decode call site', () => { + const { code, path } = loadCross('consumer.ts'); + const cache = new Map(); + const imported = resolveImports(code, path, cache); + + expect(imported.concrete.some(m => m.name === 'UserMsg')).toBe(true); + + const { registry, callSites, sourceFile } = analyze(code, path, imported); + expect(registry.has('UserMsg')).toBe(true); + + const { transformedCode, hasReplacements } = applyReplacements(code, sourceFile, callSites, registry); + expect(hasReplacements).toBe(true); + expect(transformedCode).toContain('protobuf_encode_UserMsg'); + expect(transformedCode).toContain('protobuf_decode_UserMsg'); + }); + + it('Scenario A round-trip', () => { + const { code, path } = loadCross('consumer.ts'); + const cache = new Map(); + const imported = resolveImports(code, path, cache); + const registry = analyzeSource(code, path, imported); + const gen = generateCode(registry); + + const result = execAndGet(gen + `\n + const enc = protobuf_encode_UserMsg({ id: 42, name: 'alice' }); + globalThis.__r = protobuf_decode_UserMsg(enc); + `, '__r'); + expect(result.id).toBe(42); + expect(result.name).toBe('alice'); + }); + + // ── Scenario B: imported type as pb<> field ────────────────────── + + it('resolves imported nested message type', () => { + const { code, path } = loadCross('outer.ts'); + const cache = new Map(); + const imported = resolveImports(code, path, cache); + + expect(imported.concrete.some(m => m.name === 'Inner')).toBe(true); + + const registry = analyzeSource(code, path, imported); + expect(registry.has('Inner')).toBe(true); + expect(registry.has('Outer')).toBe(true); + + const outer = registry.get('Outer')!; + const innerField = outer.fields.find(f => f.name === 'inner')!; + expect(innerField.isMessage).toBe(true); + }); + + it('Scenario B round-trip', () => { + const { code, path } = loadCross('outer.ts'); + const cache = new Map(); + const imported = resolveImports(code, path, cache); + const registry = analyzeSource(code, path, imported); + const gen = generateCode(registry); + + const result = execAndGet(gen + `\n + const enc = protobuf_encode_Outer({ inner: { value: 42 } }); + globalThis.__r = protobuf_decode_Outer(enc); + `, '__r'); + expect(result.inner.value).toBe(42); + }); + + // ── Generic template import ────────────────────────────────────── + + it('resolves imported generic template', () => { + const { code, path } = loadCross('generic-consumer.ts'); + const cache = new Map(); + const imported = resolveImports(code, path, cache); + + expect(imported.templates.has('Wrapper')).toBe(true); + + const registry = analyzeSource(code, path, imported); + expect(registry.has('Wrapper__string')).toBe(true); + }); + + it('generic import round-trip', () => { + const { code, path } = loadCross('generic-consumer.ts'); + const cache = new Map(); + const imported = resolveImports(code, path, cache); + const registry = analyzeSource(code, path, imported); + const gen = generateCode(registry); + + const result = execAndGet(gen + `\n + const enc = protobuf_encode_Wrapper__string({ value: 'hello' }); + globalThis.__r = protobuf_decode_Wrapper__string(enc); + `, '__r'); + expect(result.value).toBe('hello'); + }); + + it('resolves generic type passed through imported wrapper functions', () => { + const { code, path } = loadCross('wrapper-consumer.ts'); + const cache = new Map(); + const imported = resolveImports(code, path, cache); + + expect(imported.templates.has('Wrapper')).toBe(true); + + const { registry, callSites, sourceFile } = analyze(code, path, imported); + const used = selectUsedRegistry(registry, callSites, sourceFile); + + expect(used.registry.has('Wrapper__string')).toBe(true); + expect(used.callSites).toHaveLength(2); + expect(used.callSites[0].fnName).toBe('protobuf_encode'); + expect(used.callSites[1].fnName).toBe('protobuf_decode'); + + const { transformedCode, hasReplacements } = applyReplacements(code, sourceFile, callSites, used.registry); + expect(hasReplacements).toBe(true); + expect(transformedCode).toContain('protobuf_encode_Wrapper__string('); + expect(transformedCode).toContain('protobuf_decode_Wrapper__string('); + }); + + it('handles wrapper aliases, arrows, nested generics, and non-first generic forwarding', () => { + const { code, path } = loadCross('wrapper-edge-consumer.ts'); + const cache = new Map(); + const imported = resolveImports(code, path, cache); + + const { registry, callSites, sourceFile } = analyze(code, path, imported); + const used = selectUsedRegistry(registry, callSites, sourceFile); + + expect(used.registry.has('Wrapper__string')).toBe(true); + expect(used.registry.has('Wrapper__Wrapper__string')).toBe(true); + expect(used.callSites).toHaveLength(5); + + const { transformedCode, hasReplacements } = applyReplacements(code, sourceFile, callSites, used.registry); + expect(hasReplacements).toBe(true); + expect(transformedCode).toContain('protobuf_encode_Wrapper__string('); + expect(transformedCode).toContain('protobuf_decode_Wrapper__string('); + expect(transformedCode).toContain('protobuf_encode_Wrapper__Wrapper__string('); + expect(transformedCode).toContain('protobuf_decode_Wrapper__Wrapper__string('); + expect(transformedCode).toContain('passthroughOnly>'); + }); + + it('handles local wrapper functions in the entry file', () => { + const { code, path } = loadCross('local-wrapper-consumer.ts'); + const cache = new Map(); + const imported = resolveImports(code, path, cache); + + const { registry, callSites, sourceFile } = analyze(code, path, imported); + const used = selectUsedRegistry(registry, callSites, sourceFile); + + expect(used.registry.has('Wrapper__string')).toBe(true); + expect(used.callSites).toHaveLength(2); + + const { transformedCode, hasReplacements } = applyReplacements(code, sourceFile, callSites, used.registry); + expect(hasReplacements).toBe(true); + expect(transformedCode).toContain('protobuf_encode_Wrapper__string('); + expect(transformedCode).toContain('protobuf_decode_Wrapper__string('); + }); + + it('handles complex wrapper objects, branches, nested helpers, and chains', () => { + const { code, path } = loadCross('wrapper-complex-consumer.ts'); + const cache = new Map(); + const imported = resolveImports(code, path, cache); + + const { registry, callSites, sourceFile } = analyze(code, path, imported); + const used = selectUsedRegistry(registry, callSites, sourceFile); + + expect(used.registry.has('Wrapper__string')).toBe(true); + expect(used.registry.has('Wrapper__Wrapper__string')).toBe(true); + expect(used.callSites).toHaveLength(7); + + const { transformedCode, hasReplacements } = applyReplacements(code, sourceFile, callSites, used.registry); + expect(hasReplacements).toBe(true); + expect(transformedCode).toContain('protobuf_encode_Wrapper__string('); + expect(transformedCode).toContain('protobuf_decode_Wrapper__string('); + expect(transformedCode).toContain('protobuf_encode_Wrapper__Wrapper__string('); + expect(transformedCode).not.toContain('encodeChained>'); + }); + + it('handles wrapper protobuf type derived from another generic type', () => { + const { code, path } = loadCross('wrapper-type-source-consumer.ts'); + const cache = new Map(); + const imported = resolveImports(code, path, cache); + + const { registry, callSites, sourceFile } = analyze(code, path, imported); + const used = selectUsedRegistry(registry, callSites, sourceFile); + + expect(used.registry.has('Wrapper__string')).toBe(true); + expect(used.registry.has('Wrapper__Wrapper__string')).toBe(true); + expect(used.callSites).toHaveLength(5); + + const { transformedCode, hasReplacements } = applyReplacements(code, sourceFile, callSites, used.registry); + expect(hasReplacements).toBe(true); + expect(transformedCode).toContain('protobuf_encode_Wrapper__string('); + expect(transformedCode).toContain('protobuf_decode_Wrapper__string('); + expect(transformedCode).toContain('protobuf_encode_Wrapper__Wrapper__string('); + expect(transformedCode).not.toContain('encodeBoxed'); + }); + + // ── Transitive imports ─────────────────────────────────────────── + + it('resolves transitive imports (A → B → C)', () => { + const { code, path } = loadCross('top.ts'); + const cache = new Map(); + const imported = resolveImports(code, path, cache); + + expect(imported.concrete.some(m => m.name === 'Mid')).toBe(true); + expect(imported.concrete.some(m => m.name === 'Deep')).toBe(true); + + const registry = analyzeSource(code, path, imported); + expect(registry.has('Top')).toBe(true); + expect(registry.has('Mid')).toBe(true); + expect(registry.has('Deep')).toBe(true); + }); + + it('transitive import round-trip', () => { + const { code, path } = loadCross('top.ts'); + const cache = new Map(); + const imported = resolveImports(code, path, cache); + const registry = analyzeSource(code, path, imported); + const gen = generateCode(registry); + + const result = execAndGet(gen + `\n + const enc = protobuf_encode_Top({ nested: { inner: { val: 99 } } }); + globalThis.__r = protobuf_decode_Top(enc); + `, '__r'); + expect(result.nested.inner.val).toBe(99); + }); + + // ── Cache behavior ─────────────────────────────────────────────── + + it('uses cache on repeated resolves', () => { + const { code, path } = loadCross('consumer.ts'); + const cache = new Map(); + + resolveImports(code, path, cache); + expect(cache.size).toBeGreaterThan(0); + + const cached = new Map(cache); + resolveImports(code, path, cache); + + // Same entries, not re-created + for (const [key, val] of cache) { + expect(val).toBe(cached.get(key)); + } + }); + + // ── Graceful fallback ──────────────────────────────────────────── + + it('handles missing import file gracefully', () => { + const code = `import type { Ghost } from './nonexistent';\nconst x = 1;`; + const fakePath = resolve(crossDir, 'fake.ts'); + const cache = new Map(); + + const imported = resolveImports(code, fakePath, cache); + expect(imported.concrete).toEqual([]); + expect(imported.templates.size).toBe(0); + }); + + it('only resolves imports reachable from protobuf call roots', () => { + const code = ` +import { protobuf_encode } from '@snowluma/proton'; +import type { UserMsg } from './types'; +import type { Inner } from './inner'; + +const buf = protobuf_encode({ id: 42, name: 'alice' }); +`; + const fakePath = resolve(crossDir, 'on-demand.ts'); + const cache = new Map(); + + const imported = resolveImports(code, fakePath, cache); + + expect(imported.concrete.map(m => m.name)).toEqual(['UserMsg']); + expect(cache.has(resolve(crossDir, 'types.ts'))).toBe(true); + expect(cache.has(resolve(crossDir, 'inner.ts'))).toBe(false); + }); + + // ── Value import (non-type import) ─────────────────────────────── + + it('resolves value import { SimpleMessage } (not import type)', () => { + const { code, path } = loadCross('value-import-consumer.ts'); + const cache = new Map(); + const imported = resolveImports(code, path, cache); + + expect(imported.concrete.some(m => m.name === 'SimpleMessage')).toBe(true); + + const { registry, callSites, sourceFile } = analyze(code, path, imported); + expect(registry.has('SimpleMessage')).toBe(true); + expect(callSites.length).toBe(2); + + const { transformedCode, hasReplacements } = applyReplacements(code, sourceFile, callSites, registry); + expect(hasReplacements).toBe(true); + expect(transformedCode).toContain('protobuf_encode_SimpleMessage('); + expect(transformedCode).toContain('protobuf_decode_SimpleMessage('); + }); + + it('value import round-trip', () => { + const { code, path } = loadCross('value-import-consumer.ts'); + const cache = new Map(); + const imported = resolveImports(code, path, cache); + const registry = analyzeSource(code, path, imported); + const gen = generateCode(registry); + + const result = execAndGet(gen + `\n + const enc = protobuf_encode_SimpleMessage({ id: 42 }); + globalThis.__r = protobuf_decode_SimpleMessage(enc); + `, '__r'); + expect(result.id).toBe(42); + }); + + it('canonicalizes imported type aliases to the original message name', () => { + const { code, path } = loadCross('aliased-consumer.ts'); + const cache = new Map(); + const imported = resolveImports(code, path, cache); + + const { registry, callSites, sourceFile } = analyze(code, path, imported); + const used = selectUsedRegistry(registry, callSites, sourceFile); + + expect(used.registry.has('UserMsg')).toBe(true); + expect(used.registry.has('AliasMsg')).toBe(false); + expect(used.callSites).toHaveLength(2); + expect(used.callSites[0].typeName).toBe('UserMsg'); + expect(used.callSites[1].typeName).toBe('UserMsg'); + + const { transformedCode, hasReplacements } = applyReplacements(code, sourceFile, callSites, used.registry); + expect(hasReplacements).toBe(true); + expect(transformedCode).toContain('protobuf_encode_UserMsg('); + expect(transformedCode).toContain('protobuf_decode_UserMsg('); + expect(transformedCode).not.toContain('protobuf_encode_AliasMsg('); + expect(transformedCode).not.toContain('protobuf_decode_AliasMsg('); + }); +}); diff --git a/packages/proton/test/__tests__/generator.test.ts b/packages/proton/test/__tests__/generator.test.ts new file mode 100644 index 00000000..cc1bbae5 --- /dev/null +++ b/packages/proton/test/__tests__/generator.test.ts @@ -0,0 +1,141 @@ +import { describe, it, expect } from 'vitest'; +import { analyzeSource } from '../../src/ast/analyzer'; +import { generateCode } from '../../src/codegen/generator'; +import { loadFixture, execAndGet } from '../helpers'; + +/** Analyze fixture → generate → eval → return encode/decode pair */ +function makeRoundTrip(fixtureName: string, msgName: string) { + const gen = generateCode(analyzeSource(loadFixture(fixtureName), fixtureName)); + new Function(gen + `\nglobalThis.__enc = protobuf_encode_${msgName}; globalThis.__dec = protobuf_decode_${msgName};`)(); + const enc = (globalThis as any).__enc as (obj: any) => Uint8Array; + const dec = (globalThis as any).__dec as (data: Uint8Array) => any; + delete (globalThis as any).__enc; + delete (globalThis as any).__dec; + return { enc, dec }; +} + +function makeRoundTripFromSchema(schema: string, msgName: string) { + const gen = generateCode(analyzeSource(schema, `${msgName}.ts`)); + new Function(gen + `\nglobalThis.__enc = protobuf_encode_${msgName}; globalThis.__dec = protobuf_decode_${msgName};`)(); + const enc = (globalThis as any).__enc as (obj: any) => Uint8Array; + const dec = (globalThis as any).__dec as (data: Uint8Array) => any; + delete (globalThis as any).__enc; + delete (globalThis as any).__dec; + return { enc, dec }; +} + +describe('code generator', () => { + it('generates encode/decode for simple uint_32', () => { + const gen = generateCode(analyzeSource(loadFixture('simple.ts'), 't.ts')); + expect(gen).toContain('function protobuf_encode_SimpleMsg(obj)'); + expect(gen).toContain('function protobuf_decode_SimpleMsg(data'); + // Tag for field 1, varint should be pre-computed as 0x08 + expect(gen).toContain('buf[offset++] = 8;'); + }); + + it('generates nested message code', () => { + const gen = generateCode(analyzeSource(loadFixture('nested.ts'), 't.ts')); + expect(gen).toContain('protobuf_encode_Inner('); + expect(gen).toContain('protobuf_decode_Inner(data, offset, offset + _len)'); + }); + + it('round-trip uint_32', () => { + const { enc, dec } = makeRoundTrip('simple.ts', 'SimpleMsg'); + expect(dec(enc({ value: 42 })).value).toBe(42); + }); + + it('round-trip nested message', () => { + const { enc, dec } = makeRoundTrip('nested.ts', 'Outer'); + expect(dec(enc({ inner: { value: 999 } })).inner.value).toBe(999); + }); + + it('round-trip string', () => { + const { enc, dec } = makeRoundTrip('string-msg.ts', 'StringMsg'); + expect(dec(enc({ text: 'hello world' })).text).toBe('hello world'); + }); + + it('round-trip unicode string', () => { + const { enc, dec } = makeRoundTrip('string-msg.ts', 'StringMsg'); + expect(dec(enc({ text: '你好,protobuf🚀' })).text).toBe('你好,protobuf🚀'); + }); + + it('round-trip bool', () => { + const { enc, dec } = makeRoundTrip('bool-msg.ts', 'BoolMsg'); + expect(dec(enc({ active: true })).active).toBe(true); + const empty = enc({ active: false }); + expect(empty.length).toBe(0); + expect(dec(empty).active).toBe(false); + }); + + it('proto3 default encoding (0 → empty)', () => { + const { enc } = makeRoundTrip('simple.ts', 'SimpleMsg'); + expect(enc({ value: 0 }).length).toBe(0); + }); + + it('round-trip repeated uint_32', () => { + const { enc, dec } = makeRoundTrip('repeated.ts', 'RepeatedMsg'); + const result = dec(enc({ ids: [10, 20, 30], names: [] })); + expect(result.ids).toEqual([10, 20, 30]); + expect(result.names).toEqual([]); + }); + + it('round-trip repeated string', () => { + const { enc, dec } = makeRoundTrip('repeated.ts', 'RepeatedMsg'); + const result = dec(enc({ ids: [], names: ['hello', 'world'] })); + expect(result.ids).toEqual([]); + expect(result.names).toEqual(['hello', 'world']); + }); + + it('repeated empty arrays round-trip', () => { + const { enc, dec } = makeRoundTrip('repeated.ts', 'RepeatedMsg'); + const result = dec(enc({ ids: [], names: [] })); + expect(result.ids).toEqual([]); + expect(result.names).toEqual([]); + }); + + it('round-trip bigint-backed 64-bit integers', () => { + const schema = ` +interface BigIntMsg { + unsigned: pb<1, uint_64>; + signed: pb<2, int_64>; + zigzag: pb<3, sint_64>; + fixed: pb<4, fixed_64>; + sfixed: pb<5, sfixed_64>; + ids: pb_repeated<6, uint_64>; +}`; + const { enc, dec } = makeRoundTripFromSchema(schema, 'BigIntMsg'); + const input = { + unsigned: 18446744073709551615n, + signed: -1n, + zigzag: -1234567890123456789n, + fixed: 0x0102030405060708n, + sfixed: -0x0102030405060708n, + ids: [1n, 2n, 9007199254740993n], + }; + expect(dec(enc(input))).toEqual(input); + }); + + it('round-trip sint_32 with negative values', () => { + const schema = ` +interface Sint32Msg { + value: pb<1, sint_32>; + values: pb_repeated<2, sint_32>; +}`; + const { enc, dec } = makeRoundTripFromSchema(schema, 'Sint32Msg'); + const input = { value: -789, values: [-1, 0, 1, -789, 2147483647, -2147483648] }; + expect(dec(enc(input))).toEqual(input); + }); + + it('round-trip double as ieee754 number', () => { + const schema = ` +interface DoubleMsg { + value: pb<1, double>; + values: pb_repeated<2, double>; +}`; + const { enc, dec } = makeRoundTripFromSchema(schema, 'DoubleMsg'); + const result = dec(enc({ value: Math.PI, values: [Math.E, -0.5] })); + expect(result.value).toBeCloseTo(Math.PI); + expect(result.values[0]).toBeCloseTo(Math.E); + expect(result.values[1]).toBeCloseTo(-0.5); + }); +}); diff --git a/packages/proton/test/__tests__/plugin.test.ts b/packages/proton/test/__tests__/plugin.test.ts new file mode 100644 index 00000000..3e42c955 --- /dev/null +++ b/packages/proton/test/__tests__/plugin.test.ts @@ -0,0 +1,307 @@ +import { describe, it, expect } from 'vitest'; +import protobufVitePlugin from '../../src/index'; +import { analyze, analyzeSource, selectUsedRegistry } from '../../src/ast/analyzer'; +import { generateCode } from '../../src/codegen/generator'; +import { replaceCallSites } from '../../src/transform/replacer'; +import { loadFixture, execAndGet } from '../helpers'; + +describe('plugin integration', () => { + it('full transform pipeline', () => { + const code = loadFixture('real.ts'); + const registry = analyzeSource(code, 'real.ts'); + expect(registry.size).toBe(2); + expect([...registry.keys()]).toEqual(['TestProtobuf', 'TestProtobufOutput']); + + const gen = generateCode(registry); + expect(gen).toContain('protobuf_encode_TestProtobuf'); + expect(gen).toContain('protobuf_decode_TestProtobufOutput'); + + const { transformedCode, hasReplacements } = replaceCallSites(code, registry); + expect(hasReplacements).toBe(true); + expect(transformedCode).toContain('protobuf_encode_TestProtobuf({ name: 123 })'); + expect(transformedCode).toContain('protobuf_decode_TestProtobufOutput(data)'); + }); + + it('end-to-end round-trip', () => { + const gen = generateCode(analyzeSource(loadFixture('real.ts'), 'real.ts')); + const result = execAndGet(gen + `\n + const wr = protobuf_encode_TestProtobufOutput({ name: { name: 123 } }); + globalThis.__r = protobuf_decode_TestProtobufOutput(wr); + `, '__r'); + expect(result.name.name).toBe(123); + }); + + it('wire format: TestProtobuf { name: 123 }', () => { + const gen = generateCode(analyzeSource(loadFixture('real.ts'), 'real.ts')); + const enc = execAndGet(gen + `\n + globalThis.__r = protobuf_encode_TestProtobuf({ name: 123 }); + `, '__r'); + expect(enc.length).toBe(2); + expect(enc[0]).toBe(0x08); + expect(enc[1]).toBe(123); + }); + + it('wire format: nested message', () => { + const gen = generateCode(analyzeSource(loadFixture('real.ts'), 'real.ts')); + const enc = execAndGet(gen + `\n + globalThis.__r = protobuf_encode_TestProtobufOutput({ name: { name: 456 } }); + `, '__r'); + expect(enc[0]).toBe(0x0a); + expect(enc[1]).toBe(3); + expect(enc[2]).toBe(0x08); + expect(enc[3]).toBe(0xc8); + expect(enc[4]).toBe(0x03); + }); + + it('multi-field round-trip', () => { + const gen = generateCode(analyzeSource(loadFixture('multi-field.ts'), 't.ts')); + const result = execAndGet(gen + `\n + const enc = protobuf_encode_UserProfile({ id: 42, username: "alice", active: true }); + globalThis.__r = protobuf_decode_UserProfile(enc); + `, '__r'); + expect(result.id).toBe(42); + expect(result.username).toBe('alice'); + expect(result.active).toBe(true); + }); + + // ── generic monomorphization ─────────────────────────────────────── + + it('generic monomorphization registry', () => { + const registry = analyzeSource(loadFixture('generic-usage.ts'), 'g.ts'); + expect(registry.has('TestProtobufAny__string')).toBe(true); + expect(registry.has('TestProtobufAny__TestProtobufAny__string')).toBe(true); + }); + + it('generic round-trip', () => { + const gen = generateCode(analyzeSource(loadFixture('generic-usage.ts'), 'g.ts')); + const result = execAndGet(gen + `\n + const enc = protobuf_encode_TestProtobufAny__TestProtobufAny__string({ name: { name: "hello" } }); + globalThis.__r = protobuf_decode_TestProtobufAny__TestProtobufAny__string(enc); + `, '__r'); + expect(result.name.name).toBe('hello'); + }); + + // ── repeated fields ──────────────────────────────────────────────── + + it('repeated fields round-trip', () => { + const gen = generateCode(analyzeSource(loadFixture('repeated.ts'), 't.ts')); + const result = execAndGet(gen + `\n + const enc = protobuf_encode_RepeatedMsg({ ids: [10, 20, 30], names: ["foo", "bar"] }); + globalThis.__r = protobuf_decode_RepeatedMsg(enc); + `, '__r'); + expect(result.ids).toEqual([10, 20, 30]); + expect(result.names).toEqual(['foo', 'bar']); + }); + + it('repeated empty arrays', () => { + const gen = generateCode(analyzeSource(loadFixture('repeated.ts'), 't.ts')); + const result = execAndGet(gen + `\n + const enc = protobuf_encode_RepeatedMsg({ ids: [], names: [] }); + globalThis.__r = protobuf_decode_RepeatedMsg(enc); + `, '__r'); + expect(result.ids).toEqual([]); + expect(result.names).toEqual([]); + }); + + // ── import-based usage ────────────────────────────────────────────── + + it('handles code with import { protobuf_encode } from "@snowluma/proton"', () => { + const code = ` +import { protobuf_encode, protobuf_decode } from '@snowluma/proton'; + +interface Msg { id: pb<1, uint_32>; } + +const buf = protobuf_encode({ id: 1 }); +const decoded = protobuf_decode(buf); +`; + const registry = analyzeSource(code, 'import-test.ts'); + expect(registry.has('Msg')).toBe(true); + + const { transformedCode, hasReplacements } = replaceCallSites(code, registry); + expect(hasReplacements).toBe(true); + expect(transformedCode).toContain('protobuf_encode_Msg('); + expect(transformedCode).toContain('protobuf_decode_Msg('); + // import line preserved + expect(transformedCode).toContain("from '@snowluma/proton'"); + }); + + it('import-based round-trip', () => { + const code = ` +import { protobuf_encode, protobuf_decode } from '@snowluma/proton'; + +interface Msg { id: pb<1, uint_32>; name: pb<2, string>; } + +const buf = protobuf_encode({ id: 42, name: 'test' }); +const decoded = protobuf_decode(buf); +`; + const registry = analyzeSource(code, 'import-test.ts'); + const gen = generateCode(registry); + const result = execAndGet(gen + `\n + const enc = protobuf_encode_Msg({ id: 42, name: 'test' }); + globalThis.__r = protobuf_decode_Msg(enc); + `, '__r'); + expect(result.id).toBe(42); + expect(result.name).toBe('test'); + }); + + it('runtime fallback throws error', async () => { + const { protobuf_encode, protobuf_decode } = await import('../../src/runtime'); + expect(() => protobuf_encode({})).toThrow('not transformed'); + expect(() => protobuf_decode(new Uint8Array())).toThrow('not transformed'); + }); + + // ── import rename alias ───────────────────────────────────────────── + + it('handles import { protobuf_encode as encode }', () => { + const code = ` +import { protobuf_encode as encode, protobuf_decode as decode } from '@snowluma/proton'; + +interface Msg { id: pb<1, uint_32>; } + +const buf = encode({ id: 1 }); +const decoded = decode(buf); +`; + const registry = analyzeSource(code, 'alias-test.ts'); + expect(registry.has('Msg')).toBe(true); + + const { transformedCode, hasReplacements } = replaceCallSites(code, registry); + expect(hasReplacements).toBe(true); + expect(transformedCode).toContain('protobuf_encode_Msg('); + expect(transformedCode).toContain('protobuf_decode_Msg('); + // alias calls replaced, import preserved + expect(transformedCode).not.toContain('encode'); + expect(transformedCode).not.toContain('decode'); + }); + + it('rename alias round-trip', () => { + const code = ` +import { protobuf_encode as enc } from '@snowluma/proton'; + +interface Item { val: pb<1, uint_32>; name: pb<2, string>; } + +const buf = enc({ val: 99, name: 'x' }); +`; + const registry = analyzeSource(code, 'alias-rt.ts'); + const gen = generateCode(registry); + const result = execAndGet(gen + `\n + const enc = protobuf_encode_Item({ val: 99, name: 'x' }); + globalThis.__r = protobuf_decode_Item(enc); + `, '__r'); + expect(result.val).toBe(99); + expect(result.name).toBe('x'); + }); + + it('collects call roots first and generates only used dependency closure', () => { + const code = ` +import { protobuf_encode } from '@snowluma/proton'; + +interface Inner { id: pb<1, uint_32>; } +interface UsedMsg { inner: pb<1, Inner>; } +interface UnusedMsg { value: pb<1, string>; } + +const buf = protobuf_encode({ inner: { id: 1 } }); +`; + + const { registry, callSites, sourceFile } = analyze(code, 'used-only.ts'); + const used = selectUsedRegistry(registry, callSites, sourceFile); + + expect(used.registry.has('UsedMsg')).toBe(true); + expect(used.registry.has('Inner')).toBe(true); + expect(used.registry.has('UnusedMsg')).toBe(false); + + const gen = generateCode(used.registry); + expect(gen).toContain('protobuf_encode_UsedMsg'); + expect(gen).toContain('protobuf_encode_Inner'); + expect(gen).not.toContain('protobuf_encode_UnusedMsg'); + }); + + it('emits runtime map asset when runtimeMap is enabled', () => { + const code = ` +import { protobuf_encode } from '@snowluma/proton'; + +interface Msg { id: pb<1, uint_32>; } +const buf = protobuf_encode({ id: 1 }); +`; + + const plugin = protobufVitePlugin({ + runtimeMap: { + enabled: true, + fileName: 'pb.runtime-map.json', + }, + }); + + const transformHook = plugin.transform!; + const transform = typeof transformHook === 'function' ? transformHook : transformHook.handler; + const transformResult = transform.call({} as any, code, 'entry.ts'); + expect(transformResult).toBeTruthy(); + + const emitted: any[] = []; + const generateHook = plugin.generateBundle!; + const generateBundle = typeof generateHook === 'function' ? generateHook : generateHook.handler; + const testContext: any = { + emitFile(asset: any) { + emitted.push(asset); + return 'asset-id'; + }, + }; + + generateBundle.call( + testContext, + {} as any, + {} as any, + false, + ); + + expect(emitted).toHaveLength(1); + expect(emitted[0].type).toBe('asset'); + expect(emitted[0].fileName).toBe('pb.runtime-map.json'); + + const payload = JSON.parse(emitted[0].source); + expect(payload.version).toBe(1); + expect(payload.callSites).toHaveLength(1); + expect(payload.callSites[0].fnName).toBe('protobuf_encode'); + expect(payload.callSites[0].typeName).toBe('Msg'); + }); + + it('emits canonical runtime map entries for imported type aliases', () => { + const code = ` +import { protobuf_encode, protobuf_decode } from '@snowluma/proton'; +import type { UserMsg as AliasMsg } from './types'; + +const buf = protobuf_encode({ id: 1, name: 'a' }); +const decoded = protobuf_decode(buf); +`; + + const plugin = protobufVitePlugin({ + runtimeMap: { + enabled: true, + fileName: 'pb.runtime-map.json', + }, + }); + + const transformHook = plugin.transform!; + const transform = typeof transformHook === 'function' ? transformHook : transformHook.handler; + const transformResult = transform.call({} as any, code, 'test/fixtures/cross-file/aliased-consumer.ts'); + expect(transformResult).toBeTruthy(); + + const emitted: any[] = []; + const generateHook = plugin.generateBundle!; + const generateBundle = typeof generateHook === 'function' ? generateHook : generateHook.handler; + const testContext: any = { + emitFile(asset: any) { + emitted.push(asset); + return 'asset-id'; + }, + }; + + generateBundle.call(testContext, {} as any, {} as any, false); + + expect(emitted).toHaveLength(1); + const payload = JSON.parse(emitted[0].source); + expect(payload.messages.some((msg: { name: string }) => msg.name === 'UserMsg')).toBe(true); + expect(payload.messages.some((msg: { name: string }) => msg.name === 'AliasMsg')).toBe(false); + expect(payload.callSites).toHaveLength(2); + expect(payload.callSites[0].typeName).toBe('UserMsg'); + expect(payload.callSites[1].typeName).toBe('UserMsg'); + }); +}); diff --git a/packages/proton/test/__tests__/replacer.test.ts b/packages/proton/test/__tests__/replacer.test.ts new file mode 100644 index 00000000..fd92aa88 --- /dev/null +++ b/packages/proton/test/__tests__/replacer.test.ts @@ -0,0 +1,94 @@ +import { describe, it, expect } from 'vitest'; +import { analyzeSource } from '../../src/ast/analyzer'; +import { replaceCallSites } from '../../src/transform/replacer'; +import { loadFixture } from '../helpers'; + +describe('call-site replacer', () => { + it('replaces protobuf_encode with protobuf_encode_T', () => { + const code = loadFixture('simple.ts') + `\nconst data = protobuf_encode({ value: 1 });\n`; + const registry = analyzeSource(code, 't.ts'); + const { transformedCode, hasReplacements } = replaceCallSites(code, registry); + expect(hasReplacements).toBe(true); + expect(transformedCode).toContain('protobuf_encode_SimpleMsg({ value: 1 })'); + expect(transformedCode).not.toContain('protobuf_encode'); + }); + + it('replaces protobuf_decode', () => { + const code = loadFixture('simple.ts') + `\nconst result = protobuf_decode(data);\n`; + const registry = analyzeSource(code, 't.ts'); + const { transformedCode, hasReplacements } = replaceCallSites(code, registry); + expect(hasReplacements).toBe(true); + expect(transformedCode).toContain('protobuf_decode_SimpleMsg(data)'); + }); + + it('replaces multiple calls', () => { + const code = loadFixture('simple.ts') + ` +const a = protobuf_encode({ value: 1 }); +const b = protobuf_decode(a); +`; + const registry = analyzeSource(code, 't.ts'); + const { transformedCode } = replaceCallSites(code, registry); + expect(transformedCode).toContain('protobuf_encode_SimpleMsg({ value: 1 })'); + expect(transformedCode).toContain('protobuf_decode_SimpleMsg(a)'); + }); + + it('preserves await keyword', () => { + const code = loadFixture('simple.ts') + `\nconst a = await protobuf_encode({ value: 1 });\n`; + const registry = analyzeSource(code, 't.ts'); + const { transformedCode } = replaceCallSites(code, registry); + expect(transformedCode).toContain('await protobuf_encode_SimpleMsg({ value: 1 })'); + }); + + it('returns hasReplacements=false when no calls match', () => { + const code = loadFixture('simple.ts') + `\nconst x = 123;\n`; + const registry = analyzeSource(code, 't.ts'); + expect(replaceCallSites(code, registry).hasReplacements).toBe(false); + }); + + it('does not replace unknown type arguments', () => { + const code = loadFixture('simple.ts') + `\nconst a = protobuf_encode({ v: 1 });\n`; + const registry = analyzeSource(code, 't.ts'); + const { hasReplacements, transformedCode } = replaceCallSites(code, registry); + expect(hasReplacements).toBe(false); + expect(transformedCode).toContain('protobuf_encode'); + }); + + it('replaces generic call-sites with mangled names', () => { + const code = loadFixture('generic-usage.ts'); + const registry = analyzeSource(code, 't.ts'); + const { transformedCode, hasReplacements } = replaceCallSites(code, registry); + expect(hasReplacements).toBe(true); + expect(transformedCode).toContain('protobuf_encode_TestProtobufAny__TestProtobufAny__string'); + expect(transformedCode).toContain('protobuf_decode_TestProtobufAny__TestProtobufAny__string'); + }); + + it('replaces namespace import calls', () => { + const code = ` +import * as pbx from '@snowluma/proton'; + +interface Msg { id: pb<1, uint_32>; } + +const a = pbx.protobuf_encode({ id: 1 }); +const b = pbx.protobuf_decode(a); +`; + const registry = analyzeSource(code, 'ns.ts'); + const { transformedCode, hasReplacements } = replaceCallSites(code, registry); + expect(hasReplacements).toBe(true); + expect(transformedCode).toContain('const a = protobuf_encode_Msg({ id: 1 });'); + expect(transformedCode).toContain('const b = protobuf_decode_Msg(a);'); + }); + + it('does not replace same-name imports from non-runtime modules', () => { + const code = ` +import { protobuf_encode } from './other'; + +interface Msg { id: pb<1, uint_32>; } + +const a = protobuf_encode({ id: 1 }); +`; + const registry = analyzeSource(code, 'guard.ts'); + const { transformedCode, hasReplacements } = replaceCallSites(code, registry); + expect(hasReplacements).toBe(false); + expect(transformedCode).toContain('protobuf_encode({ id: 1 })'); + }); +}); diff --git a/packages/proton/test/__tests__/runtime-map-fallback.test.ts b/packages/proton/test/__tests__/runtime-map-fallback.test.ts new file mode 100644 index 00000000..f31763e7 --- /dev/null +++ b/packages/proton/test/__tests__/runtime-map-fallback.test.ts @@ -0,0 +1,98 @@ +import { afterEach, describe, expect, it } from 'vitest'; +import { analyzeSource } from '../../src/ast/analyzer'; +import { createRuntimeMap } from '../../src/runtime-map'; +import { + protobuf_decode, + protobuf_disableRuntimeMapFallback, + protobuf_enableRuntimeMapFallback, + protobuf_encode, +} from '../../src/runtime'; + +function captureFrameFromThrow(fn: () => unknown, sourceFile: string): { line: number; column: number } { + try { + fn(); + } catch (err) { + const stack = err instanceof Error ? err.stack ?? '' : ''; + for (const raw of stack.split('\n')) { + const line = raw.trim(); + if (!line.includes(sourceFile)) continue; + + const location = line.endsWith(')') && line.includes('(') + ? line.slice(line.lastIndexOf('(') + 1, -1) + : line.replace(/^at\s+/, ''); + + const lastColon = location.lastIndexOf(':'); + const secondLastColon = location.lastIndexOf(':', lastColon - 1); + if (lastColon < 0 || secondLastColon < 0) continue; + + const parsedLine = Number(location.slice(secondLastColon + 1, lastColon)); + const parsedColumn = Number(location.slice(lastColon + 1)); + if (Number.isFinite(parsedLine) && Number.isFinite(parsedColumn)) { + return { line: parsedLine, column: parsedColumn }; + } + } + } + + throw new Error(`Unable to capture stack frame for ${sourceFile}`); +} + +function invokeEncode(): Uint8Array { + return new Function( + 'protobuf_encode', + `\n//# sourceURL=runtime-map-encode.js\nreturn protobuf_encode({ value: 7 });`, + )(protobuf_encode) as Uint8Array; +} + +function invokeDecode(data: Uint8Array): any { + return new Function( + 'protobuf_decode', + 'data', + `\n//# sourceURL=runtime-map-decode.js\nreturn protobuf_decode(data);`, + )(protobuf_decode, data); +} + +describe('runtime map fallback', () => { + afterEach(() => { + protobuf_disableRuntimeMapFallback(); + }); + + it('dynamically generates encode/decode from runtime map when enabled', () => { + const schema = ` +interface SimpleMsg { + value: pb<1, uint_32>; +} +`; + const registry = analyzeSource(schema, 'schema.ts'); + + const encodeFrame = captureFrameFromThrow(invokeEncode, 'runtime-map-encode.js'); + const decodeFrame = captureFrameFromThrow(() => invokeDecode(new Uint8Array([0x08, 0x07])), 'runtime-map-decode.js'); + + const runtimeMap = createRuntimeMap({ + messages: registry, + callSites: [ + { + file: 'runtime-map-encode.js', + line: encodeFrame.line, + column: encodeFrame.column, + fnName: 'protobuf_encode', + typeName: 'SimpleMsg', + }, + { + file: 'runtime-map-decode.js', + line: decodeFrame.line, + column: decodeFrame.column, + fnName: 'protobuf_decode', + typeName: 'SimpleMsg', + }, + ], + }); + + protobuf_enableRuntimeMapFallback(runtimeMap); + + const encoded = invokeEncode(); + expect([...encoded]).toEqual([0x08, 0x07]); + + const decoded = invokeDecode(encoded); + expect(decoded.value).toBe(7); + }); +}); diff --git a/packages/proton/test/__tests__/wire.test.ts b/packages/proton/test/__tests__/wire.test.ts new file mode 100644 index 00000000..bd9a6260 --- /dev/null +++ b/packages/proton/test/__tests__/wire.test.ts @@ -0,0 +1,110 @@ +import { describe, it, expect } from 'vitest'; +import { encodeVarint, decodeVarint, writeTag, writeString, readString, skipField } from '../../src/codegen/wire'; + +describe('wire format primitives', () => { + describe('varint', () => { + const cases: [number, number[]][] = [ + [0, [0x00]], + [1, [0x01]], + [127, [0x7f]], + [128, [0x80, 0x01]], + [300, [0xac, 0x02]], + [16384, [0x80, 0x80, 0x01]], + ]; + + it.each(cases)('encodeVarint(%i) produces correct bytes', (value, expected) => { + const buf: number[] = []; + encodeVarint(value, buf); + expect(buf).toEqual(expected); + }); + + it.each(cases)('decodeVarint round-trip for %i', (value) => { + const buf: number[] = []; + encodeVarint(value, buf); + const data = new Uint8Array(buf); + const [decoded, offset] = decodeVarint(data, 0); + expect(decoded).toBe(value); + expect(offset).toBe(buf.length); + }); + + it('handles max uint32', () => { + const value = 0xFFFFFFFF; + const buf: number[] = []; + encodeVarint(value, buf); + const [decoded] = decodeVarint(new Uint8Array(buf), 0); + expect(decoded).toBe(value); + }); + }); + + describe('tag encoding', () => { + it('field 1, varint (wire type 0) produces 0x08', () => { + const buf: number[] = []; + writeTag(1, 0, buf); + expect(buf).toEqual([0x08]); + }); + + it('field 1, length-delimited (wire type 2) produces 0x0A', () => { + const buf: number[] = []; + writeTag(1, 2, buf); + expect(buf).toEqual([0x0a]); + }); + + it('field 2, varint produces 0x10', () => { + const buf: number[] = []; + writeTag(2, 0, buf); + expect(buf).toEqual([0x10]); + }); + }); + + describe('string encoding', () => { + it('encodes and decodes "hello"', () => { + const buf: number[] = []; + writeString('hello', buf); + const data = new Uint8Array(buf); + // First byte is length (5), followed by UTF-8 bytes + expect(data[0]).toBe(5); + const decoded = readString(data, 1, 5); + expect(decoded).toBe('hello'); + }); + + it('handles empty string', () => { + const buf: number[] = []; + writeString('', buf); + expect(buf).toEqual([0]); // length 0 + }); + + it('handles unicode', () => { + const buf: number[] = []; + writeString('你好', buf); + const data = new Uint8Array(buf); + const [len, offset] = [data[0], 1]; + const decoded = readString(data, offset, len); + expect(decoded).toBe('你好'); + }); + }); + + describe('skipField', () => { + it('skips varint field', () => { + const buf: number[] = []; + encodeVarint(300, buf); // multi-byte varint + const data = new Uint8Array(buf); + const newOffset = skipField(data, 0, 0); + expect(newOffset).toBe(buf.length); + }); + + it('skips length-delimited field', () => { + // length=3 followed by 3 bytes + const data = new Uint8Array([3, 0x41, 0x42, 0x43]); + const newOffset = skipField(data, 0, 2); + expect(newOffset).toBe(4); + }); + + it('skips 32-bit field', () => { + expect(skipField(new Uint8Array(4), 0, 5)).toBe(4); + }); + + it('skips 64-bit field', () => { + expect(skipField(new Uint8Array(8), 0, 1)).toBe(8); + }); + }); +}); diff --git a/packages/proton/test/fixtures/aliased-pb-marker.ts b/packages/proton/test/fixtures/aliased-pb-marker.ts new file mode 100644 index 00000000..52c55d74 --- /dev/null +++ b/packages/proton/test/fixtures/aliased-pb-marker.ts @@ -0,0 +1,21 @@ +// Aliased import of the pb / pb_repeated markers. +// +// `parsePbTypeRef` compared the literal type-ref identifier text against +// the constants `'pb'` / `'pb_repeated'`. With `import { pb as P }` the +// identifier text becomes `'P'`, so the field was silently dropped from +// the message — interfaces ended up looking empty. +// +// Fix: resolve the marker name through the imported-name resolver before +// comparing. + +import type { pb as P, pb_repeated as PR, uint_32 } from '@snowluma/proton'; + +interface Aliased { + id: P<1, uint_32>; + tags: PR<2, string>; +} + +const data = protobuf_encode({ id: 1, tags: ['a', 'b'] }); +const decoded = protobuf_decode(data); + +export { }; diff --git a/packages/proton/test/fixtures/bool-msg.ts b/packages/proton/test/fixtures/bool-msg.ts new file mode 100644 index 00000000..f3eed9f1 --- /dev/null +++ b/packages/proton/test/fixtures/bool-msg.ts @@ -0,0 +1,3 @@ +interface BoolMsg { + active: pb<1, bool>; +} diff --git a/packages/proton/test/fixtures/cross-file/aliased-consumer.ts b/packages/proton/test/fixtures/cross-file/aliased-consumer.ts new file mode 100644 index 00000000..adb3cccf --- /dev/null +++ b/packages/proton/test/fixtures/cross-file/aliased-consumer.ts @@ -0,0 +1,7 @@ +import { protobuf_encode, protobuf_decode } from '@snowluma/proton'; +import type { UserMsg as AliasMsg } from './types'; + +const buf = protobuf_encode({ id: 42, name: 'alice' }); +const decoded = protobuf_decode(buf); + +export { }; \ No newline at end of file diff --git a/packages/proton/test/fixtures/cross-file/consumer.ts b/packages/proton/test/fixtures/cross-file/consumer.ts new file mode 100644 index 00000000..03dc04d1 --- /dev/null +++ b/packages/proton/test/fixtures/cross-file/consumer.ts @@ -0,0 +1,6 @@ +import type { UserMsg } from './types'; + +const buf = protobuf_encode({ id: 42, name: 'alice' }); +const decoded = protobuf_decode(buf); + +export { }; diff --git a/packages/proton/test/fixtures/cross-file/deep.ts b/packages/proton/test/fixtures/cross-file/deep.ts new file mode 100644 index 00000000..eccfaca7 --- /dev/null +++ b/packages/proton/test/fixtures/cross-file/deep.ts @@ -0,0 +1,5 @@ +interface Deep { + val: pb<1, uint_32>; +} + +export type { Deep }; diff --git a/packages/proton/test/fixtures/cross-file/generic-consumer.ts b/packages/proton/test/fixtures/cross-file/generic-consumer.ts new file mode 100644 index 00000000..64e927bc --- /dev/null +++ b/packages/proton/test/fixtures/cross-file/generic-consumer.ts @@ -0,0 +1,6 @@ +import type { Wrapper } from './generic-types'; + +const buf = protobuf_encode>({ value: 'hello' }); +const decoded = protobuf_decode>(buf); + +export { }; diff --git a/packages/proton/test/fixtures/cross-file/generic-types.ts b/packages/proton/test/fixtures/cross-file/generic-types.ts new file mode 100644 index 00000000..8315901d --- /dev/null +++ b/packages/proton/test/fixtures/cross-file/generic-types.ts @@ -0,0 +1,5 @@ +interface Wrapper { + value: pb<1, T>; +} + +export type { Wrapper }; diff --git a/packages/proton/test/fixtures/cross-file/inner.ts b/packages/proton/test/fixtures/cross-file/inner.ts new file mode 100644 index 00000000..a086d31e --- /dev/null +++ b/packages/proton/test/fixtures/cross-file/inner.ts @@ -0,0 +1,5 @@ +interface Inner { + value: pb<1, uint_32>; +} + +export type { Inner }; diff --git a/packages/proton/test/fixtures/cross-file/local-wrapper-consumer.ts b/packages/proton/test/fixtures/cross-file/local-wrapper-consumer.ts new file mode 100644 index 00000000..8d07ddef --- /dev/null +++ b/packages/proton/test/fixtures/cross-file/local-wrapper-consumer.ts @@ -0,0 +1,11 @@ +import type { Wrapper } from './generic-types'; +import { protobuf_encode, protobuf_decode } from '@snowluma/proton'; + +function localEncode(value: T): Uint8Array { + return protobuf_encode(value); +} + +const buf = localEncode>({ value: 'local' }); +const decoded = protobuf_decode>(buf); + +export { }; \ No newline at end of file diff --git a/packages/proton/test/fixtures/cross-file/mid.ts b/packages/proton/test/fixtures/cross-file/mid.ts new file mode 100644 index 00000000..5a902861 --- /dev/null +++ b/packages/proton/test/fixtures/cross-file/mid.ts @@ -0,0 +1,7 @@ +import type { Deep } from './deep'; + +interface Mid { + inner: pb<1, Deep>; +} + +export type { Mid }; diff --git a/packages/proton/test/fixtures/cross-file/outer.ts b/packages/proton/test/fixtures/cross-file/outer.ts new file mode 100644 index 00000000..01c0a94d --- /dev/null +++ b/packages/proton/test/fixtures/cross-file/outer.ts @@ -0,0 +1,10 @@ +import type { Inner } from './inner'; + +interface Outer { + inner: pb<1, Inner>; +} + +const buf = protobuf_encode({ inner: { value: 42 } }); +const decoded = protobuf_decode(buf); + +export { }; diff --git a/packages/proton/test/fixtures/cross-file/protobuf.ts b/packages/proton/test/fixtures/cross-file/protobuf.ts new file mode 100644 index 00000000..8514d7c8 --- /dev/null +++ b/packages/proton/test/fixtures/cross-file/protobuf.ts @@ -0,0 +1,5 @@ +interface SimpleMessage { + id: pb<1, uint_32>; +} + +export { SimpleMessage }; diff --git a/packages/proton/test/fixtures/cross-file/top.ts b/packages/proton/test/fixtures/cross-file/top.ts new file mode 100644 index 00000000..44a563ca --- /dev/null +++ b/packages/proton/test/fixtures/cross-file/top.ts @@ -0,0 +1,10 @@ +import type { Mid } from './mid'; + +interface Top { + nested: pb<1, Mid>; +} + +const buf = protobuf_encode({ nested: { inner: { val: 99 } } }); +const decoded = protobuf_decode(buf); + +export { }; diff --git a/packages/proton/test/fixtures/cross-file/types.ts b/packages/proton/test/fixtures/cross-file/types.ts new file mode 100644 index 00000000..d1e1d944 --- /dev/null +++ b/packages/proton/test/fixtures/cross-file/types.ts @@ -0,0 +1,6 @@ +interface UserMsg { + id: pb<1, uint_32>; + name: pb<2, string>; +} + +export type { UserMsg }; diff --git a/packages/proton/test/fixtures/cross-file/value-import-consumer.ts b/packages/proton/test/fixtures/cross-file/value-import-consumer.ts new file mode 100644 index 00000000..afdaf22e --- /dev/null +++ b/packages/proton/test/fixtures/cross-file/value-import-consumer.ts @@ -0,0 +1,7 @@ +import { SimpleMessage } from './protobuf'; +import { protobuf_encode, protobuf_decode } from '@snowluma/proton'; + +const bytes = protobuf_encode({ id: 42 }); +const decoded = protobuf_decode(bytes); + +export { }; diff --git a/packages/proton/test/fixtures/cross-file/wrapper-api.ts b/packages/proton/test/fixtures/cross-file/wrapper-api.ts new file mode 100644 index 00000000..dc3a697e --- /dev/null +++ b/packages/proton/test/fixtures/cross-file/wrapper-api.ts @@ -0,0 +1,49 @@ +import { protobuf_encode, protobuf_decode } from '@snowluma/proton'; + +export function encodeViaWrapper(value: T): Uint8Array { + return protobuf_encode(value); +} + +export function decodeViaWrapper(data: Uint8Array): T { + return protobuf_decode(data); +} + +export const encodeArrowWrapper = (value: T): Uint8Array => protobuf_encode(value); + +export const decodeArrowWrapper = (data: Uint8Array): T => protobuf_decode(data); + +export function encodeSecondGeneric(_ignored: Ignored, value: T): Uint8Array { + return protobuf_encode(value); +} + +export function passthroughOnly(value: T): T { + return value; +} + +export const wrapperObject = { + encode(value: T): Uint8Array { + return protobuf_encode(value); + }, + decode(data: Uint8Array): T { + return protobuf_decode(data); + }, + encodeArrow: (value: T): Uint8Array => protobuf_encode(value), +}; + +export function encodeWithBranch(value: T, enabled: boolean): Uint8Array { + if (enabled) { + return protobuf_encode(value); + } + return protobuf_encode(value); +} + +export function encodeWithNestedHelper(value: T): Uint8Array { + function inner(payload: T): Uint8Array { + return protobuf_encode(payload); + } + return inner(value); +} + +export function encodeChained(value: T): Uint8Array { + return encodeViaWrapper(value); +} \ No newline at end of file diff --git a/packages/proton/test/fixtures/cross-file/wrapper-complex-consumer.ts b/packages/proton/test/fixtures/cross-file/wrapper-complex-consumer.ts new file mode 100644 index 00000000..373dbe70 --- /dev/null +++ b/packages/proton/test/fixtures/cross-file/wrapper-complex-consumer.ts @@ -0,0 +1,21 @@ +import type { Wrapper } from './generic-types'; +import { + wrapperObject, + encodeWithBranch, + encodeWithNestedHelper, + encodeChained, +} from './wrapper-api'; + +const objectBuf = wrapperObject.encode>({ value: 'object' }); +const objectDecoded = wrapperObject.decode>(objectBuf); + +const arrowMemberBuf = wrapperObject.encodeArrow>>({ value: { value: 'member' } }); + +const { encodeArrow } = wrapperObject; +const destructuredBuf = encodeArrow>({ value: 'destructured' }); + +const branchBuf = encodeWithBranch>({ value: 'branch' }, true); +const nestedHelperBuf = encodeWithNestedHelper>({ value: 'nested-helper' }); +const chainedBuf = encodeChained>({ value: 'chained' }); + +export { }; \ No newline at end of file diff --git a/packages/proton/test/fixtures/cross-file/wrapper-consumer.ts b/packages/proton/test/fixtures/cross-file/wrapper-consumer.ts new file mode 100644 index 00000000..8976bd19 --- /dev/null +++ b/packages/proton/test/fixtures/cross-file/wrapper-consumer.ts @@ -0,0 +1,7 @@ +import type { Wrapper } from './generic-types'; +import { encodeViaWrapper, decodeViaWrapper } from './wrapper-api'; + +const buf = encodeViaWrapper>({ value: 'hello' }); +const decoded = decodeViaWrapper>(buf); + +export { }; \ No newline at end of file diff --git a/packages/proton/test/fixtures/cross-file/wrapper-edge-consumer.ts b/packages/proton/test/fixtures/cross-file/wrapper-edge-consumer.ts new file mode 100644 index 00000000..242f8948 --- /dev/null +++ b/packages/proton/test/fixtures/cross-file/wrapper-edge-consumer.ts @@ -0,0 +1,21 @@ +import type { Wrapper } from './generic-types'; +import { + encodeViaWrapper as encAlias, + decodeViaWrapper as decAlias, + encodeArrowWrapper, + decodeArrowWrapper, + encodeSecondGeneric, + passthroughOnly, +} from './wrapper-api'; + +const aliasBuf = encAlias>({ value: 'alias' }); +const aliasDecoded = decAlias>(aliasBuf); + +const arrowBuf = encodeArrowWrapper>>({ value: { value: 'nested' } }); +const arrowDecoded = decodeArrowWrapper>>(arrowBuf); + +const secondBuf = encodeSecondGeneric>(1, { value: 'second' }); + +const passthrough = passthroughOnly>({ value: 'ignored' }); + +export { }; \ No newline at end of file diff --git a/packages/proton/test/fixtures/cross-file/wrapper-type-source-base.ts b/packages/proton/test/fixtures/cross-file/wrapper-type-source-base.ts new file mode 100644 index 00000000..636b8ddf --- /dev/null +++ b/packages/proton/test/fixtures/cross-file/wrapper-type-source-base.ts @@ -0,0 +1,6 @@ +import type { Wrapper } from './generic-types'; +import { protobuf_encode } from '@snowluma/proton'; + +export function encodeBoxed(value: Wrapper): Uint8Array { + return protobuf_encode>(value); +} \ No newline at end of file diff --git a/packages/proton/test/fixtures/cross-file/wrapper-type-source-consumer.ts b/packages/proton/test/fixtures/cross-file/wrapper-type-source-consumer.ts new file mode 100644 index 00000000..4cf55089 --- /dev/null +++ b/packages/proton/test/fixtures/cross-file/wrapper-type-source-consumer.ts @@ -0,0 +1,15 @@ +import { + encodeBoxed, + decodeBoxed, + encodeAliasBoxed, + encodeNestedBoxed, + encodeBoxedChain, +} from './wrapper-type-source'; + +const boxedBuf = encodeBoxed({ value: 'boxed' }); +const boxedDecoded = decodeBoxed(boxedBuf); +const aliasBuf = encodeAliasBoxed({ value: 'alias' }); +const nestedBuf = encodeNestedBoxed({ value: { value: 'nested' } }); +const chainedBuf = encodeBoxedChain({ value: 'chain' }); + +export { }; \ No newline at end of file diff --git a/packages/proton/test/fixtures/cross-file/wrapper-type-source.ts b/packages/proton/test/fixtures/cross-file/wrapper-type-source.ts new file mode 100644 index 00000000..7e3ac616 --- /dev/null +++ b/packages/proton/test/fixtures/cross-file/wrapper-type-source.ts @@ -0,0 +1,25 @@ +import type { Wrapper } from './generic-types'; +import { protobuf_encode, protobuf_decode } from '@snowluma/proton'; +import { encodeBoxed as encodeBoxedBase } from './wrapper-type-source-base'; + +export type AliasWrapper = Wrapper; + +export function encodeBoxed(value: Wrapper): Uint8Array { + return protobuf_encode>(value); +} + +export function decodeBoxed(data: Uint8Array): Wrapper { + return protobuf_decode>(data); +} + +export function encodeAliasBoxed(value: AliasWrapper): Uint8Array { + return protobuf_encode>(value); +} + +export function encodeNestedBoxed(value: Wrapper>): Uint8Array { + return protobuf_encode>>(value); +} + +export function encodeBoxedChain(value: Wrapper): Uint8Array { + return encodeBoxedBase(value); +} \ No newline at end of file diff --git a/packages/proton/test/fixtures/generic-template.ts b/packages/proton/test/fixtures/generic-template.ts new file mode 100644 index 00000000..6b2b9685 --- /dev/null +++ b/packages/proton/test/fixtures/generic-template.ts @@ -0,0 +1,3 @@ +interface TestProtobufAny { + name?: pb<1, T>; +} diff --git a/packages/proton/test/fixtures/generic-usage.ts b/packages/proton/test/fixtures/generic-usage.ts new file mode 100644 index 00000000..a23e869f --- /dev/null +++ b/packages/proton/test/fixtures/generic-usage.ts @@ -0,0 +1,8 @@ +interface TestProtobufAny { + name?: pb<1, T>; +} + +const dataT = protobuf_encode>>({ name: { name: "test" } }); +const decodedT = protobuf_decode>>(dataT); + +export { }; diff --git a/packages/proton/test/fixtures/generic-with-generic-field.ts b/packages/proton/test/fixtures/generic-with-generic-field.ts new file mode 100644 index 00000000..cbe86190 --- /dev/null +++ b/packages/proton/test/fixtures/generic-with-generic-field.ts @@ -0,0 +1,24 @@ +// Generic template with a generic-instantiated message field. +// +// The outer template's type param (`U`) shows up *inside* an inner generic +// instantiation (`Wrapper`). When the outer is monomorphized at the call +// site (`Outer`), the inner instantiation must be re-instantiated +// with the substitution (becoming `Wrapper`) and put into the +// registry under its mangled name `Wrapper__uint_32`. +// +// Without the fix, the field's `rawTypeName` was `'Wrapper__U'` and the +// substituted-mono never produced `Wrapper__uint_32`, leaving the field's +// wire-type unresolved. + +interface Wrapper { + value: pb<1, T>; +} + +interface Outer { + wrapped: pb<5, Wrapper>; +} + +const data = protobuf_encode>({ wrapped: { value: 42 } }); +const decoded = protobuf_decode>(data); + +export { }; diff --git a/packages/proton/test/fixtures/multi-field.ts b/packages/proton/test/fixtures/multi-field.ts new file mode 100644 index 00000000..708eec73 --- /dev/null +++ b/packages/proton/test/fixtures/multi-field.ts @@ -0,0 +1,5 @@ +interface UserProfile { + id: pb<1, uint_32>; + username: pb<2, string>; + active: pb<3, bool>; +} diff --git a/packages/proton/test/fixtures/nested-generic-field.ts b/packages/proton/test/fixtures/nested-generic-field.ts new file mode 100644 index 00000000..cfaaa9df --- /dev/null +++ b/packages/proton/test/fixtures/nested-generic-field.ts @@ -0,0 +1,24 @@ +// Concrete interface with a generic-instantiated message field. +// +// The call site only references the concrete outer type (`Container`), so +// the analyzer must independently: +// 1) resolve the field's typeName to the *mangled* form (`Wrapper__uint_32`) +// so it matches what monomorphization produces, +// 2) enqueue `Wrapper` for monomorphization itself, since the +// call-site-driven queue only sees `Container`. +// +// Without both, wire-type resolution silently leaves the field at the +// `WireType.Varint` placeholder and codegen emits a wrong wire format. + +interface Wrapper { + value: pb<1, T>; +} + +interface Container { + wrapped: pb<5, Wrapper>; +} + +const data = protobuf_encode({ wrapped: { value: 42 } }); +const decoded = protobuf_decode(data); + +export { }; diff --git a/packages/proton/test/fixtures/nested.ts b/packages/proton/test/fixtures/nested.ts new file mode 100644 index 00000000..71fb451c --- /dev/null +++ b/packages/proton/test/fixtures/nested.ts @@ -0,0 +1,7 @@ +interface Inner { + value: pb<1, uint_32>; +} + +interface Outer { + inner: pb<1, Inner>; +} diff --git a/packages/proton/test/fixtures/no-pb.ts b/packages/proton/test/fixtures/no-pb.ts new file mode 100644 index 00000000..f1a6d072 --- /dev/null +++ b/packages/proton/test/fixtures/no-pb.ts @@ -0,0 +1,3 @@ +interface Foo { + bar: string; +} diff --git a/packages/proton/test/fixtures/real.ts b/packages/proton/test/fixtures/real.ts new file mode 100644 index 00000000..b1f8df1b --- /dev/null +++ b/packages/proton/test/fixtures/real.ts @@ -0,0 +1,12 @@ +interface TestProtobuf { + name: pb<1, uint_32>; +} + +interface TestProtobufOutput { + name: pb<1, TestProtobuf>; +} + +const data = protobuf_encode({ name: 123 }); +const decoded = protobuf_decode(data); + +export { }; diff --git a/packages/proton/test/fixtures/repeated.ts b/packages/proton/test/fixtures/repeated.ts new file mode 100644 index 00000000..4ec14de6 --- /dev/null +++ b/packages/proton/test/fixtures/repeated.ts @@ -0,0 +1,9 @@ +interface RepeatedMsg { + ids: pb_repeated<1, uint_32>; + names: pb_repeated<2, string>; +} + +const data = protobuf_encode({ ids: [1, 2, 3], names: ["a", "b"] }); +const decoded = protobuf_decode(data); + +export { }; diff --git a/packages/proton/test/fixtures/simple.ts b/packages/proton/test/fixtures/simple.ts new file mode 100644 index 00000000..c656214e --- /dev/null +++ b/packages/proton/test/fixtures/simple.ts @@ -0,0 +1,3 @@ +interface SimpleMsg { + value: pb<1, uint_32>; +} diff --git a/packages/proton/test/fixtures/string-msg.ts b/packages/proton/test/fixtures/string-msg.ts new file mode 100644 index 00000000..62bc79c7 --- /dev/null +++ b/packages/proton/test/fixtures/string-msg.ts @@ -0,0 +1,3 @@ +interface StringMsg { + text: pb<1, string>; +} diff --git a/packages/proton/test/helpers/index.ts b/packages/proton/test/helpers/index.ts new file mode 100644 index 00000000..9ac63567 --- /dev/null +++ b/packages/proton/test/helpers/index.ts @@ -0,0 +1,21 @@ +import { readFileSync } from 'fs'; +import { dirname, resolve } from 'path'; +import { fileURLToPath } from 'url'; + +const fixturesDir = resolve(dirname(fileURLToPath(import.meta.url)), '..', 'fixtures'); + +/** Load a fixture file as a string. */ +export function loadFixture(name: string): string { + return readFileSync(resolve(fixturesDir, name), 'utf-8'); +} + +/** + * Run generated code via `new Function()` and return a named global value. + * Cleans up the global after retrieval. + */ +export function execAndGet(code: string, globalKey: string): T { + new Function(code)(); + const val = (globalThis as any)[globalKey] as T; + delete (globalThis as any)[globalKey]; + return val; +} diff --git a/packages/proton/tsconfig.json b/packages/proton/tsconfig.json new file mode 100644 index 00000000..2d718364 --- /dev/null +++ b/packages/proton/tsconfig.json @@ -0,0 +1,19 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "types": ["node"], + "noEmit": true + }, + "include": [ + "src/**/*", + "test/__tests__/**/*", + "test/helpers/**/*", + "protobuf.d.ts" + ], + "exclude": [ + "node_modules", + "dist", + "test/fixtures" + ] +} + diff --git a/packages/proton/vitest.config.ts b/packages/proton/vitest.config.ts new file mode 100644 index 00000000..066a88a5 --- /dev/null +++ b/packages/proton/vitest.config.ts @@ -0,0 +1,7 @@ +import { defineConfig } from 'vitest/config'; + +export default defineConfig({ + test: { + include: ['test/__tests__/**/*.test.ts'], + }, +}); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index be5db7cb..822219b5 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -64,6 +64,22 @@ importers: specifier: ^4.1.4 version: 4.1.4(@types/node@24.12.2)(vite@8.0.8(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)) + packages/proton: + dependencies: + typescript: + specifier: 'catalog:' + version: 6.0.2 + devDependencies: + '@types/node': + specifier: ^24.12.2 + version: 24.12.2 + vite: + specifier: 'catalog:' + version: 8.0.8(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0) + vitest: + specifier: ^4.1.4 + version: 4.1.4(@types/node@24.12.2)(vite@8.0.8(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)) + packages/runtime: {} packages/sdk: From 3d739c255a83fd60715861c51fe4d6caa77f843f Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Mon, 18 May 2026 23:14:29 +0800 Subject: [PATCH 12/48] =?UTF-8?q?feat(proton):=20proof-of-concept=20migrat?= =?UTF-8?q?ion=20=E2=80=94=20longmsg=20parity=20test?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Migrates a self-contained subset of bridge/proto/longmsg.ts to the new @snowluma/proton compile-time DSL form and verifies wire-format parity against the legacy runtime ProtoSchema encoder. End-to-end proof that the toolchain works in core's vitest pipeline. What's covered: - LongMsgUid / LongMsgSettings / SendLongMsgInfo / SendLongMsgReq / SendLongMsgResp / SendLongMsgRespResult / RecvLongMsgInfo / RecvLongMsgReq / RecvLongMsgResp / RecvLongMsgRespResult - The three schemas that pull in PushMsgBody (LongMsgContent / LongMsgAction / LongMsgResult) stay on the legacy API for now, since migrating them requires also migrating message.ts and element.ts. Toolchain changes: - @snowluma/proton gets a tsup build step. The ./vite subpath now points at the built dist/index.js so it is loadable as plain Node ESM from vite.config.ts / vitest.config.ts (the source-only .ts layout can't be consumed from outside the Vite transform pipeline). The . (runtime) subpath stays at TS source — it's only ever imported from user code, which IS Vite-transformed. - prepare script ensures dist/ exists after pnpm install. - @snowluma/core depends on @snowluma/proton (workspace:*) and adds protobufVitePlugin() to its vitest config so test files get transformed. Documented divergence: proton follows proto3 semantics: fields equal to their default value (0 / false / "" / empty bytes) are NOT emitted on the wire. The legacy runtime encoder always emits them. Both forms are round-trippable through a conforming proto3 reader. The parity test pins this behaviour explicitly. 8/8 parity tests pass. --- packages/core/package.json | 1 + .../core/src/bridge/proto/proton/longmsg.ts | 65 ++++++++++ packages/core/tests/proton-parity.test.ts | 120 ++++++++++++++++++ packages/core/vitest.config.ts | 2 + packages/proton/package.json | 7 +- pnpm-lock.yaml | 6 + 6 files changed, 199 insertions(+), 2 deletions(-) create mode 100644 packages/core/src/bridge/proto/proton/longmsg.ts create mode 100644 packages/core/tests/proton-parity.test.ts diff --git a/packages/core/package.json b/packages/core/package.json index c832ad06..7d7d855e 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -14,6 +14,7 @@ "typecheck": "tsc --noEmit" }, "dependencies": { + "@snowluma/proton": "workspace:*", "@snowluma/websocket": "workspace:*" }, "devDependencies": { diff --git a/packages/core/src/bridge/proto/proton/longmsg.ts b/packages/core/src/bridge/proto/proton/longmsg.ts new file mode 100644 index 00000000..6f8fa331 --- /dev/null +++ b/packages/core/src/bridge/proto/proton/longmsg.ts @@ -0,0 +1,65 @@ +// Proton (compile-time) form of the long-message schemas. +// +// Mirror of the self-contained subset of `bridge/proto/longmsg.ts`. Only the +// schemas that DON'T reach into `PushMsgBodySchema` (and thus into element.ts) +// are migrated here — `LongMsgContent` / `LongMsgAction` / `LongMsgResult` +// stay on the legacy runtime API until message.ts + element.ts get migrated. +// +// This file is the proof-of-concept target for the @snowluma/proton plugin. +// The parity test at `tests/proton-parity.test.ts` asserts that proton's +// generated codec produces the exact same wire bytes as `protoEncode`. + +import type { pb, uint_32, bool, bytes } from '@snowluma/proton'; + +export interface LongMsgUid { + uid?: pb<2, string>; +} + +export interface LongMsgSettings { + field1?: pb<1, uint_32>; + field2?: pb<2, uint_32>; + field3?: pb<3, uint_32>; + field4?: pb<4, uint_32>; +} + +export interface SendLongMsgInfo { + type?: pb<1, uint_32>; + uid?: pb<2, LongMsgUid>; + groupUin?: pb<3, uint_32>; + payload?: pb<4, bytes>; +} + +export interface SendLongMsgReq { + info?: pb<2, SendLongMsgInfo>; + settings?: pb<15, LongMsgSettings>; +} + +export interface SendLongMsgRespResult { + resId?: pb<3, string>; +} + +export interface SendLongMsgResp { + result?: pb<2, SendLongMsgRespResult>; + settings?: pb<15, LongMsgSettings>; +} + +export interface RecvLongMsgInfo { + uid?: pb<1, LongMsgUid>; + resId?: pb<2, string>; + acquire?: pb<3, bool>; +} + +export interface RecvLongMsgReq { + info?: pb<1, RecvLongMsgInfo>; + settings?: pb<15, LongMsgSettings>; +} + +export interface RecvLongMsgRespResult { + resId?: pb<3, string>; + payload?: pb<4, bytes>; +} + +export interface RecvLongMsgResp { + result?: pb<1, RecvLongMsgRespResult>; + settings?: pb<15, LongMsgSettings>; +} diff --git a/packages/core/tests/proton-parity.test.ts b/packages/core/tests/proton-parity.test.ts new file mode 100644 index 00000000..e4f07898 --- /dev/null +++ b/packages/core/tests/proton-parity.test.ts @@ -0,0 +1,120 @@ +// Proof-of-concept: verify that codec generated by @snowluma/proton's Vite +// plugin produces wire bytes byte-identical to the legacy runtime schema +// encoder for the same input. If this passes, the migration pattern is sound +// for the schemas covered here. + +import { describe, it, expect } from 'vitest'; +import { protobuf_encode, protobuf_decode } from '@snowluma/proton'; +import { protoEncode, protoDecode } from '../src/protobuf/decode'; + +import { + SendLongMsgRespSchema, + SendLongMsgReqSchema, + RecvLongMsgReqSchema, + RecvLongMsgRespSchema, + LongMsgSettingsSchema, +} from '../src/bridge/proto/longmsg'; + +import type { + SendLongMsgResp, + SendLongMsgReq, + RecvLongMsgReq, + RecvLongMsgResp, + LongMsgSettings, +} from '../src/bridge/proto/proton/longmsg'; + +function hex(buf: Uint8Array): string { + return Buffer.from(buf).toString('hex'); +} + +describe('proton ↔ legacy parity (longmsg subset)', () => { + it('encodes LongMsgSettings identically', () => { + const data: LongMsgSettings = { field1: 1, field2: 2, field3: 3, field4: 4 }; + const legacy = protoEncode(data, LongMsgSettingsSchema); + const proton = protobuf_encode(data); + expect(hex(proton)).toBe(hex(legacy)); + }); + + it('encodes SendLongMsgResp (nested message) identically', () => { + const data: SendLongMsgResp = { result: { resId: 'res-001' } }; + const legacy = protoEncode(data, SendLongMsgRespSchema); + const proton = protobuf_encode(data); + expect(hex(proton)).toBe(hex(legacy)); + }); + + it('encodes SendLongMsgReq with bytes + nested + settings identically', () => { + // NOTE: all numeric fields are non-zero — proton follows proto3 semantics + // and omits default-valued fields from the wire, whereas the legacy runtime + // encoder always writes them. Parity is therefore only expected when no + // numeric field equals its default. See the explicit divergence test below. + const data: SendLongMsgReq = { + info: { + type: 1, + uid: { uid: 'u_test' }, + groupUin: 123456, + payload: new Uint8Array([0xde, 0xad, 0xbe, 0xef]), + }, + settings: { field1: 4, field2: 1, field3: 7, field4: 2 }, + }; + const legacy = protoEncode(data, SendLongMsgReqSchema); + const proton = protobuf_encode(data); + expect(hex(proton)).toBe(hex(legacy)); + }); + + it('encodes RecvLongMsgReq with bool field identically', () => { + const data: RecvLongMsgReq = { + info: { uid: { uid: 'u_recv' }, resId: 'r-9', acquire: true }, + settings: { field1: 4, field2: 1, field3: 7, field4: 2 }, + }; + const legacy = protoEncode(data, RecvLongMsgReqSchema); + const proton = protobuf_encode(data); + expect(hex(proton)).toBe(hex(legacy)); + }); + + it('encodes RecvLongMsgResp (with bytes payload) identically', () => { + const data: RecvLongMsgResp = { + result: { resId: 'r-1', payload: new Uint8Array([1, 2, 3, 4, 5]) }, + settings: { field1: 4, field2: 1, field3: 7, field4: 2 }, + }; + const legacy = protoEncode(data, RecvLongMsgRespSchema); + const proton = protobuf_encode(data); + expect(hex(proton)).toBe(hex(legacy)); + }); + + // ── Documented divergence: proto3 default-value omission ──────────── + + it('proton omits default-valued numeric fields (legacy emits them)', () => { + // proto3 wire format says fields equal to their default value MUST NOT be + // emitted. Proton follows that; the legacy runtime encoder always emits. + // Either form is round-trippable through a conforming proto3 reader — the + // missing field decodes as its default. This test pins that behaviour. + const data: LongMsgSettings = { field1: 0, field2: 0, field3: 0, field4: 0 }; + const legacy = protoEncode(data, LongMsgSettingsSchema); + const proton = protobuf_encode(data); + expect(hex(proton)).toBe(''); // nothing on the wire + expect(legacy.length).toBeGreaterThan(0); // legacy emits all zeros + // Legacy emits explicit zero values; a proto3-conforming reader sees them + // back when decoding. (Decoding the empty wire returns null because the + // legacy decoder treats an empty buffer as "no message at all" — that's + // also semantically equivalent to "all-default values" in proto3.) + expect(protoDecode(legacy, LongMsgSettingsSchema)).toMatchObject({ + field1: 0, field2: 0, field3: 0, field4: 0, + }); + }); + + // ── round-trip via decode ─────────────────────────────────────────── + + it('round-trips SendLongMsgResp through proton encode → legacy decode', () => { + const data: SendLongMsgResp = { result: { resId: 'rt-1' } }; + const encoded = protobuf_encode(data); + const decoded = protoDecode(encoded, SendLongMsgRespSchema); + expect(decoded?.result?.resId).toBe('rt-1'); + }); + + it('round-trips SendLongMsgResp through legacy encode → proton decode', () => { + const data: SendLongMsgResp = { result: { resId: 'rt-2' } }; + const encoded = protoEncode(data, SendLongMsgRespSchema); + const decoded = protobuf_decode(encoded); + expect(decoded.result?.resId).toBe('rt-2'); + }); +}); diff --git a/packages/core/vitest.config.ts b/packages/core/vitest.config.ts index cae60282..a7afd6b4 100644 --- a/packages/core/vitest.config.ts +++ b/packages/core/vitest.config.ts @@ -1,10 +1,12 @@ import { defineConfig } from 'vitest/config'; import path from 'path'; import { fileURLToPath } from 'url'; +import protobufVitePlugin from '@snowluma/proton/vite'; const __dirname = path.dirname(fileURLToPath(import.meta.url)); export default defineConfig({ + plugins: [protobufVitePlugin()], resolve: { alias: { '@': path.resolve(__dirname, 'src') diff --git a/packages/proton/package.json b/packages/proton/package.json index d300cecb..8edd7e33 100644 --- a/packages/proton/package.json +++ b/packages/proton/package.json @@ -13,13 +13,15 @@ }, "./vite": { "types": "./src/index.ts", - "default": "./src/index.ts" + "default": "./dist/index.js" } }, "scripts": { + "build": "tsup src/index.ts --format esm --out-dir dist --target node20 --external typescript --external vite", "test": "vitest run", "test:watch": "vitest", - "typecheck": "tsc --noEmit" + "typecheck": "tsc --noEmit", + "prepare": "test -f dist/index.js || pnpm build" }, "dependencies": { "typescript": "catalog:" @@ -34,6 +36,7 @@ }, "devDependencies": { "@types/node": "^24.12.2", + "tsup": "^8.5.0", "vite": "catalog:", "vitest": "^4.1.4" } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 822219b5..4efb92fd 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -29,6 +29,9 @@ importers: packages/core: dependencies: + '@snowluma/proton': + specifier: workspace:* + version: link:../proton '@snowluma/websocket': specifier: workspace:* version: link:../websocket @@ -73,6 +76,9 @@ importers: '@types/node': specifier: ^24.12.2 version: 24.12.2 + tsup: + specifier: ^8.5.0 + version: 8.5.1(jiti@2.6.1)(postcss@8.5.10)(tsx@4.21.0)(typescript@6.0.2) vite: specifier: 'catalog:' version: 8.0.8(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0) From 31079673c6133ff344ef265ea02425211460e03c Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Mon, 18 May 2026 23:15:41 +0800 Subject: [PATCH 13/48] docs(proton): add README Covers quick start, primitive types, generic templates, cross-file wrapper bindings, the proto3 default-value divergence vs the legacy runtime encoder, build-time diagnostics, and the optional runtime-map fallback. Also lists every edge case fixed on top of upstream with a pointer to the corresponding regression test. --- packages/proton/README.md | 273 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 273 insertions(+) create mode 100644 packages/proton/README.md diff --git a/packages/proton/README.md b/packages/proton/README.md new file mode 100644 index 00000000..268ecb1f --- /dev/null +++ b/packages/proton/README.md @@ -0,0 +1,273 @@ +# @snowluma/proton + +Compile-time protobuf encoder/decoder generator for SnowLuma. TypeScript +interfaces in, fully-inlined zero-runtime codec functions out. + +> Vendored from [SnowLuma/protobuf-dsl](https://github.com/SnowLuma/protobuf-dsl) +> with edge-case fixes applied. The unmodified upstream is kept under +> `dev/protobuf-dsl/` as a reference copy. + +## What it does + +You declare your wire schema as plain TypeScript interfaces marked up with +`pb`. At build time a Vite plugin walks the call sites of +`protobuf_encode` / `protobuf_decode` and replaces them with +type-specific, fully-inlined codec functions. No runtime schema lookup, +no reflection, no `.proto` files, no `protoc`. + +```ts +import type { pb, pb_repeated, uint_32, bool } from '@snowluma/proton'; +import { protobuf_encode, protobuf_decode } from '@snowluma/proton'; + +interface UserProfile { + id?: pb<1, uint_32>; + username?: pb<2, string>; + active?: pb<3, bool>; + tags?: pb_repeated<4, string>; +} + +const bytes = protobuf_encode({ + id: 42, username: 'alice', active: true, tags: ['admin'], +}); +const user = protobuf_decode(bytes); +``` + +After the plugin transform, this becomes: + +```js +// pre-computed tag literals, inlined varint loops, no function-call overhead +const bytes = protobuf_encode_UserProfile({ id: 42, ... }); +const user = protobuf_decode_UserProfile(bytes); +``` + +If the plugin **isn't** installed, calling `protobuf_encode` / `protobuf_decode` +throws a loud error rather than silently producing wrong bytes. + +## Setup in SnowLuma + +The package is already wired into `@snowluma/core`'s `vitest.config.ts`. To use +it elsewhere in the monorepo: + +```ts +// vite.config.ts (or vitest.config.ts) +import { defineConfig } from 'vite'; +import protobufVitePlugin from '@snowluma/proton/vite'; + +export default defineConfig({ + plugins: [protobufVitePlugin()], +}); +``` + +Add the workspace dep: + +```json +{ + "dependencies": { "@snowluma/proton": "workspace:*" } +} +``` + +## Primitive types + +The marker is `pb` (or `pb_repeated` for +arrays). Available primitives: + +| Marker | TS type | Wire | +| ----------- | ------------ | ---------------- | +| `bool` | `boolean` | varint | +| `uint_32` | `number` | varint | +| `int_32` | `number` | varint | +| `sint_32` | `number` | varint (zigzag) | +| `uint_64` | `bigint` | varint | +| `int_64` | `bigint` | varint | +| `sint_64` | `bigint` | varint (zigzag) | +| `fixed_32` | `number` | 32-bit | +| `fixed_64` | `bigint` | 64-bit | +| `sfixed_32` | `number` | 32-bit | +| `sfixed_64` | `bigint` | 64-bit | +| `float` | `number` | 32-bit | +| `double` | `number` | 64-bit | +| `string` | `string` | length-delimited | +| `bytes` | `Uint8Array` | length-delimited | + +Plus message types (any other interface marked with `pb<>` fields) used as +the second type-arg to `pb<>` / `pb_repeated<>`. + +## Generic templates + +You can declare reusable wrappers as generic interfaces: + +```ts +interface Wrapper { + value?: pb<1, T>; +} + +const bytes = protobuf_encode>({ value: 42 }); +// ^ instantiated at the call site +``` + +Nested instantiations work too — `Wrapper>` mono-morphizes to +`Wrapper__string` + `Wrapper__Wrapper__string` and both end up in the registry +at build time. + +Compose them in concrete interfaces: + +```ts +interface Container { + wrapped?: pb<5, Wrapper>; +} +``` + +…or in other generic templates: + +```ts +interface Outer { + wrapped?: pb<5, Wrapper>; +} +const bytes = protobuf_encode>({ wrapped: { value: 42 } }); +``` + +Both forms are covered by regression tests. + +## Cross-file & wrapper-binding + +Schemas can live in one file and call sites in another: + +```ts +// schema/user.ts +export interface UserProfile { id?: pb<1, uint_32>; } + +// usage.ts +import type { UserProfile } from './schema/user'; +import { protobuf_encode } from '@snowluma/proton'; +const bytes = protobuf_encode({ id: 42 }); +``` + +You can also build thin generic wrappers around `protobuf_encode` / `_decode` +and the plugin will trace through them, including across file boundaries: + +```ts +// schema/wrap.ts +export function encodeWrapped(v: Wrapper): Uint8Array { + return protobuf_encode>(v); +} + +// usage.ts +import { encodeWrapped } from './schema/wrap'; +const bytes = encodeWrapped({ value: 'hi' }); +// ^ plugin rewrites to protobuf_encode_Wrapper__string(...) +``` + +Chained forwarders also work (`A` forwards to `B` which is imported from +another module, etc.). + +## proto3 default-value semantics + +**Important behavioural detail.** Proton follows the proto3 wire format spec: +fields whose value equals the type's default (`0` / `false` / `""` / +empty bytes) are **not emitted** on the wire. This is byte-different from +SnowLuma's legacy `protoEncode` runtime, which always emits every field. + +Both forms are wire-compatible with any conforming proto3 reader (missing +fields decode as the default value). When migrating legacy schemas to proton, +do **not** treat byte-level inequality on default values as a regression — see +[`packages/core/tests/proton-parity.test.ts`](../../packages/core/tests/proton-parity.test.ts) +for the test that pins this divergence. + +If you have a wire consumer that depends on byte-level identity (e.g. for +hashing or signing), prefer to set non-default values explicitly rather than +relying on the encoder. + +## Diagnostics + +Anything that doesn't resolve to a primitive or a registered message **throws +at build time** rather than silently leaking a wrong wire type: + +``` +Cannot resolve protobuf field type "Partial__UserProfile" on message "Foo" +(field "bar", field number 3). The analyzer did not produce a primitive or +registered message for this type. Common causes: union / intersection / +mapped / conditional types, TypeScript utility types (Partial, Pick, …), +qualified names (ns.Type), or a missing import. +``` + +This is the safety net for TypeScript constructs the analyzer doesn't model. +Currently unsupported: + +- Union / intersection types (`A | B`, `A & B`) +- Conditional / mapped types (`T extends X ? A : B`, `{ [K in keyof T]: ... }`) +- TS utility types (`Partial`, `Pick`, `Readonly`, …) +- Qualified type names (`ns.Type`) +- Wrapper functions reached via namespace import (`import * as ns from`) + +…all of these will throw with a clear message instead of producing bad bytes. + +## Optional: runtime-map fallback + +If a call site can't be statically resolved (e.g. dynamic loading after build), +the plugin can emit a JSON map that the runtime can consume to generate codecs +on the fly. Off by default. + +```ts +import protobufVitePlugin from '@snowluma/proton/vite'; + +export default defineConfig({ + plugins: [protobufVitePlugin({ + runtimeMap: { enabled: true, fileName: 'snowluma-proton.runtime-map.json' }, + })], +}); +``` + +```ts +import runtimeMap from './snowluma-proton.runtime-map.json'; +import { protobuf_enableRuntimeMapFallback } from '@snowluma/proton'; + +protobuf_enableRuntimeMapFallback(runtimeMap); +``` + +## Edge cases fixed on top of upstream + +Each has a regression test in `test/__tests__/analyzer.test.ts`: + +| # | What used to break | +| - | --------------------- | +| 1 | `import { pb as P }` — aliased markers were ignored; fields dropped silently | +| 2 | `interface Foo { x: pb<1, Wrapper> }` — typeName stuck at `"Wrapper"`, no mono of the inner instantiation | +| 3 | `interface Outer { x: pb<1, Wrapper> }` — outer mono didn't re-instantiate the inner generic | +| 4 | Wrapper-binding synthetic SourceFile had empty text → `getText()` returned garbage | +| 5 | Cross-file forwarded wrappers (chain → imported base) not detected | +| 6 | `matchForwardedKnownWrapper` didn't propagate `typePattern` — chain treated `` as the encoded type instead of `Wrapper` | +| 7 | Synthetic-SF WeakMap was private to analyzer.ts → replacer used the wrong SF | + +Plus the build-time guard (above) that turns future analyzer gaps into hard +errors instead of silent miscodes. + +## Scripts + +``` +pnpm --filter @snowluma/proton build # bundle src/index.ts → dist/index.js +pnpm --filter @snowluma/proton test # vitest run (95 tests) +pnpm --filter @snowluma/proton typecheck # tsc --noEmit +``` + +## Layout + +``` +src/ + ast/ analyzer + type-tracking pipeline + analyzer.ts single-walk message + call-site collection + collector.ts interface → ProtobufField/GenericFieldTemplate + monomorphizer.ts generic instantiation → concrete ProtobufMessage + import-resolver.ts cross-file definition + wrapper resolution + callsite.ts matches protobuf_encode/decode invocations + utils.ts name resolution + synthetic-SF tracking + dependency-graph.ts topo sort + reachability + types.ts shared schema types + codegen/ inlined wire-format emitters + transform/ Vite plugin string edits + index.ts plugin entry (./vite) + runtime.ts runtime stubs + map fallback (.) + runtime-map.ts serialized map format + +protobuf.d.ts public types (pb<>, pb_repeated<>, primitive aliases) +test/ vitest suite (analyzer + cross-file + plugin) +``` From d323318a7eb38a3d6e0b88a5fad146d21a763e36 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Mon, 18 May 2026 23:17:44 +0800 Subject: [PATCH 14/48] bench(proton): proton vs legacy runtime encoder/decoder MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Standalone tsx script benchmarking the codecs generated by @snowluma/proton against the existing src/protobuf/decode.ts runtime implementation, using the actual long-message schemas already in the codebase (the proton interface form + the legacy *Schema constants). Proton codecs are materialised at bench startup via the public analyzeSource + generateCode API — exactly what the Vite plugin does at build time — so there is no chicken-and-egg dependency on a Vite build. Headline numbers on Node 24 / darwin-arm64: - simple 4×uint32 encode: ~8.5× speedup - simple 4×uint32 decode: ~35× speedup - deeply nested SendLongMsgReq encode: ~9.5×, decode: ~13× - 64-byte payload RecvLongMsgResp encode: ~4.3×, decode: ~10× Run with: pnpm --filter @snowluma/core exec tsx bench/proton-vs-legacy.ts --- packages/core/bench/proton-vs-legacy.ts | 172 ++++++++++++++++++++++++ 1 file changed, 172 insertions(+) create mode 100644 packages/core/bench/proton-vs-legacy.ts diff --git a/packages/core/bench/proton-vs-legacy.ts b/packages/core/bench/proton-vs-legacy.ts new file mode 100644 index 00000000..3f8eb304 --- /dev/null +++ b/packages/core/bench/proton-vs-legacy.ts @@ -0,0 +1,172 @@ +// Proton vs legacy runtime ProtoSchema encoder/decoder benchmark. +// +// Compares the codec functions generated at build time by @snowluma/proton +// against the runtime schema-walking implementation in src/protobuf/decode.ts, +// using the actual long-message schemas already in the codebase. +// +// Methodology: +// - Proton codecs are produced by calling its `analyzeSource` + `generateCode` +// API on the existing proto/proton/longmsg.ts source file, then `new +// Function`-eval'd into a callable. This is identical to what the Vite +// plugin does at build time, minus the file-replacement step. +// - Legacy codecs are the existing `protoEncode` / `protoDecode` functions +// called against the existing `*Schema` constants. +// - Each measurement does 2 000 warmup iterations, then N timed iterations. +// - Operation cost is reported as ops/sec and ns/op. The first row's +// ops/sec is the relative baseline. +// +// Run: +// pnpm --filter @snowluma/core exec tsx bench/proton-vs-legacy.ts + +import { readFileSync } from 'fs'; +import { resolve, dirname } from 'path'; +import { fileURLToPath } from 'url'; +import { analyzeSource, generateCode } from '@snowluma/proton/vite'; +import { protoEncode, protoDecode } from '../src/protobuf/decode'; +import { + LongMsgSettingsSchema, + SendLongMsgRespSchema, + SendLongMsgReqSchema, + RecvLongMsgRespSchema, +} from '../src/bridge/proto/longmsg'; + +// ── proton codec materialisation ───────────────────────────────────── + +const __dirname = dirname(fileURLToPath(import.meta.url)); +const protonSchemaPath = resolve(__dirname, '..', 'src', 'bridge', 'proto', 'proton', 'longmsg.ts'); +const protonSchemaSource = readFileSync(protonSchemaPath, 'utf-8'); + +function materialiseProton(messageNames: readonly string[]): Record Uint8Array; decode: (b: Uint8Array) => unknown }> { + // Append synthetic call sites so the registry actually contains the messages + // we want — `selectUsedRegistry` only retains call-site roots, and the + // proton/longmsg.ts source itself has no `protobuf_encode` calls. + const callSites = messageNames + .map((n) => `protobuf_encode<${n}>({} as any); protobuf_decode<${n}>(new Uint8Array());`) + .join('\n'); + const sourceWithCallSites = protonSchemaSource + `\n\n// synthetic call sites for bench codegen\n` + callSites; + + const registry = analyzeSource(sourceWithCallSites, protonSchemaPath); + const code = generateCode(registry); + const factoryBody = ` + ${code} + const out = {}; + ${messageNames.map(n => `out.${n} = { encode: protobuf_encode_${n}, decode: protobuf_decode_${n} };`).join('\n')} + return out; + `; + return new Function(factoryBody)() as Record Uint8Array; decode: (b: Uint8Array) => unknown }>; +} + +const proton = materialiseProton([ + 'LongMsgSettings', + 'SendLongMsgResp', + 'SendLongMsgReq', + 'RecvLongMsgResp', +]); + +// ── bench harness ──────────────────────────────────────────────────── + +interface BenchResult { name: string; opsPerSec: number; nsPerOp: number; } + +function bench(name: string, fn: () => void, iterations: number): BenchResult { + for (let i = 0; i < 2000; i++) fn(); + const start = performance.now(); + for (let i = 0; i < iterations; i++) fn(); + const ms = performance.now() - start; + return { + name, + opsPerSec: Math.round((iterations / ms) * 1000), + nsPerOp: Math.round((ms / iterations) * 1_000_000), + }; +} + +function printSection(title: string, results: BenchResult[]) { + console.log(`\n## ${title}`); + console.log('| Encoder | ops/sec | ns/op | relative |'); + console.log('|------------|-------------|--------|----------|'); + const baseline = results[0].opsPerSec; + for (const r of results) { + const rel = r.opsPerSec / baseline; + const relStr = r === results[0] ? '1.00×' : `${rel.toFixed(2)}×`; + console.log( + `| ${r.name.padEnd(10)} | ${r.opsPerSec.toLocaleString().padStart(11)} | ${String(r.nsPerOp).padStart(6)} | ${relStr.padStart(8)} |`, + ); + } +} + +// ── workloads ──────────────────────────────────────────────────────── + +const settingsObj = { field1: 4, field2: 1, field3: 7, field4: 2 }; + +const sendRespObj = { result: { resId: 'res-001' } }; + +const sendReqObj = { + info: { + type: 1, + uid: { uid: 'u_test' }, + groupUin: 123456, + payload: new Uint8Array([0xde, 0xad, 0xbe, 0xef]), + }, + settings: { field1: 4, field2: 1, field3: 7, field4: 2 }, +}; + +const recvRespObj = { + result: { resId: 'r-1', payload: new Uint8Array(64).fill(0x42) }, + settings: { field1: 4, field2: 1, field3: 7, field4: 2 }, +}; + +// Pre-encoded bytes for decode benches (use proton output so both sides see +// identical, proto3-conforming input). +const settingsBytes = proton.LongMsgSettings.encode(settingsObj); +const sendRespBytes = proton.SendLongMsgResp.encode(sendRespObj); +const sendReqBytes = proton.SendLongMsgReq.encode(sendReqObj); +const recvRespBytes = proton.RecvLongMsgResp.encode(recvRespObj); + +// ── run ────────────────────────────────────────────────────────────── + +console.log('# @snowluma/proton vs legacy runtime benchmark\n'); +console.log(`Node ${process.version} | ${process.platform} ${process.arch}`); +console.log(`Date: ${new Date().toISOString().slice(0, 19).replace('T', ' ')}`); + +const N = 300_000; + +printSection('Encode — LongMsgSettings (4× uint32)', [ + { ...bench('proton', () => proton.LongMsgSettings.encode(settingsObj), N) }, + { ...bench('legacy', () => protoEncode(settingsObj, LongMsgSettingsSchema), N) }, +]); + +printSection('Decode — LongMsgSettings (4× uint32)', [ + { ...bench('proton', () => proton.LongMsgSettings.decode(settingsBytes), N) }, + { ...bench('legacy', () => protoDecode(settingsBytes, LongMsgSettingsSchema), N) }, +]); + +printSection('Encode — SendLongMsgResp (1 nested message, 1 string)', [ + { ...bench('proton', () => proton.SendLongMsgResp.encode(sendRespObj), N) }, + { ...bench('legacy', () => protoEncode(sendRespObj, SendLongMsgRespSchema), N) }, +]); + +printSection('Decode — SendLongMsgResp', [ + { ...bench('proton', () => proton.SendLongMsgResp.decode(sendRespBytes), N) }, + { ...bench('legacy', () => protoDecode(sendRespBytes, SendLongMsgRespSchema), N) }, +]); + +printSection('Encode — SendLongMsgReq (deeply nested, bytes + uint32 + string)', [ + { ...bench('proton', () => proton.SendLongMsgReq.encode(sendReqObj), N) }, + { ...bench('legacy', () => protoEncode(sendReqObj, SendLongMsgReqSchema), N) }, +]); + +printSection('Decode — SendLongMsgReq', [ + { ...bench('proton', () => proton.SendLongMsgReq.decode(sendReqBytes), N) }, + { ...bench('legacy', () => protoDecode(sendReqBytes, SendLongMsgReqSchema), N) }, +]); + +printSection('Encode — RecvLongMsgResp (64-byte payload + settings)', [ + { ...bench('proton', () => proton.RecvLongMsgResp.encode(recvRespObj), N) }, + { ...bench('legacy', () => protoEncode(recvRespObj, RecvLongMsgRespSchema), N) }, +]); + +printSection('Decode — RecvLongMsgResp', [ + { ...bench('proton', () => proton.RecvLongMsgResp.decode(recvRespBytes), N) }, + { ...bench('legacy', () => protoDecode(recvRespBytes, RecvLongMsgRespSchema), N) }, +]); + +console.log(''); From b7d8952163bf7ba6d648c916270d71febc7194a4 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Mon, 18 May 2026 23:27:35 +0800 Subject: [PATCH 15/48] feat(proton): full longmsg + element + message migration; forward.ts on new API MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Completes the proton migration started in the previous PoC commit. All schemas needed by actions/forward.ts are now mirrored as proton interface forms, the legacy ProtoSchema constants stay in place for back-compat, and forward.ts has been switched over to the new compile-time codecs. Migrated schemas: - element.ts (35 schemas: TextElem, FaceElem, OnlineImage, NotOnlineImage, TransElem, MarketFace, CustomFace, RichMsg, GroupFileElem, ExtraInfo, VideoFile, SrcMsg, LightAppElem, CommonElem, GeneralFlags, Elem, MentionExtra, QFaceExtra, QSmallFaceExtra, FileType, FileInfo, IndexNode, PicUrlExtInfo, PictureInfo, PicExtData, PicExtBizInfo, VideoExtBizInfo, PttExtBizInfo, ExtBizInfo, C2cSource, TroopSource, HashSum, MsgInfoBody, MsgInfo, GroupFileInfo, GroupFileExtraInner, GroupFileExtra, Preserve, …) - message.ts (PushMsg, PushMsgBody, ResponseHead, ContentHead, Ptt, NotOnlineFile, RichText, MessageBody, FileExtra, …) - longmsg.ts — the three remaining schemas (LongMsgContent / LongMsgAction / LongMsgResult) that depend on PushMsgBody forward.ts now calls: protobuf_encode(...) // upload payload protobuf_encode(...) protobuf_decode(...) protobuf_encode(...) protobuf_decode(...) protobuf_decode(...) // download payload protobuf_encode(...) // re-wrap for parseMsgPush The unused legacy schema constants are intentionally left in place — they still back the existing forward.test.ts mock encoder and any other consumer that hasn't been migrated yet. They will be removed in a follow-up once every consumer is on the new API. Verification: - 18/18 parity tests pass (encode + decode equivalence for every representative shape across element / message / longmsg) - 585/585 core test suite passes (network-manager.test.ts fails to load due to a missing native binary in this environment — pre-existing) - tsc --noEmit clean --- packages/core/src/bridge/actions/forward.ts | 46 +- .../core/src/bridge/proto/proton/element.ts | 421 ++++++++++++++++++ .../core/src/bridge/proto/proton/longmsg.ts | 30 +- .../core/src/bridge/proto/proton/message.ts | 113 +++++ packages/core/tests/proton-parity.test.ts | 219 ++++++++- 5 files changed, 790 insertions(+), 39 deletions(-) create mode 100644 packages/core/src/bridge/proto/proton/element.ts create mode 100644 packages/core/src/bridge/proto/proton/message.ts diff --git a/packages/core/src/bridge/actions/forward.ts b/packages/core/src/bridge/actions/forward.ts index 9ade79e2..8a85336a 100644 --- a/packages/core/src/bridge/actions/forward.ts +++ b/packages/core/src/bridge/actions/forward.ts @@ -5,19 +5,19 @@ import type { Bridge } from '../bridge'; import { gunzipSync, gzipSync } from 'zlib'; -import { protoDecode, protoEncode } from '../../protobuf/decode'; +import { protobuf_encode, protobuf_decode } from '@snowluma/proton'; import { buildSendElems } from '../element-builder'; import { parseMsgPush } from '../msg-push'; import type { ForwardNodePayload } from '../events'; import type { PacketInfo } from '../../protocol/types'; -import { - LongMsgResultSchema, - RecvLongMsgReqSchema, - RecvLongMsgRespSchema, - SendLongMsgReqSchema, - SendLongMsgRespSchema, -} from '../proto/longmsg'; -import { PushMsgSchema } from '../proto/message'; +import type { + LongMsgResult, + RecvLongMsgReq, + RecvLongMsgResp, + SendLongMsgReq, + SendLongMsgResp, +} from '../proto/proton/longmsg'; +import type { PushMsg, PushMsgBody } from '../proto/proton/message'; import { resolveSelfUid, toInt } from './shared'; // Module-scoped cache, keyed by res_id. Survives only for the lifetime @@ -30,7 +30,7 @@ async function buildForwardPushBody( node: ForwardNodePayload, groupId?: number, userUid?: string, -): Promise> { +): Promise { const fromUin = node.userUin > 0 ? node.userUin : toInt(bridge.identity.uin); if (fromUin <= 0) throw new Error('forward node user uin is invalid'); @@ -99,24 +99,24 @@ export async function uploadForwardNodes( } const msgBody = await Promise.all(nodes.map(node => buildForwardPushBody(bridge, node, groupId, userUid))); - const longMsgResult = protoEncode({ + const longMsgResult = protobuf_encode({ action: [ { actionCommand: 'MultiMsg', - actionData: { msgBody: msgBody as any }, + actionData: { msgBody }, }, ], - }, LongMsgResultSchema); + }); const selfUid = await resolveSelfUid(bridge); - const info: any = { + const info: SendLongMsgReq['info'] = { type: groupId ? 3 : 1, uid: { uid: groupId ? String(groupId) : selfUid }, payload: gzipSync(Buffer.from(longMsgResult)), }; if (groupId) info.groupUin = groupId; - const request = protoEncode({ + const request = protobuf_encode({ info, settings: { field1: 4, @@ -124,14 +124,14 @@ export async function uploadForwardNodes( field3: 7, field4: 0, }, - }, SendLongMsgReqSchema); + }); const result = await bridge.sendRawPacket('trpc.group.long_msg_interface.MsgService.SsoSendLongMsg', request); if (!result.success || !result.gotResponse || !result.responseData) { throw new Error(result.errorMessage || 'upload forward message failed'); } - const resp = protoDecode(result.responseData, SendLongMsgRespSchema); + const resp = protobuf_decode(result.responseData); const resId = typeof resp?.result?.resId === 'string' ? resp.result.resId : ''; if (!resId) { throw new Error('upload forward message response missing res_id'); @@ -169,7 +169,7 @@ export async function fetchForwardNodes(bridge: Bridge, resId: string): Promise< } const selfUid = await resolveSelfUid(bridge); - const request = protoEncode({ + const request = protobuf_encode({ info: { uid: { uid: selfUid }, resId, @@ -181,27 +181,27 @@ export async function fetchForwardNodes(bridge: Bridge, resId: string): Promise< field3: 0, field4: 0, }, - }, RecvLongMsgReqSchema); + }); const result = await bridge.sendRawPacket('trpc.group.long_msg_interface.MsgService.SsoRecvLongMsg', request); if (!result.success || !result.gotResponse || !result.responseData) { throw new Error(result.errorMessage || 'download forward message failed'); } - const resp = protoDecode(result.responseData, RecvLongMsgRespSchema); + const resp = protobuf_decode(result.responseData); const payload = resp?.result?.payload; if (!(payload instanceof Uint8Array) || payload.length === 0) { throw new Error('download forward message payload is empty'); } const inflate = gunzipSync(Buffer.from(payload)); - const longMsg = protoDecode(inflate, LongMsgResultSchema); - const action = longMsg?.action?.find((item: any) => item?.actionCommand === 'MultiMsg'); + const longMsg = protobuf_decode(inflate); + const action = longMsg?.action?.find((item) => item?.actionCommand === 'MultiMsg'); const msgBodyList = Array.isArray(action?.actionData?.msgBody) ? action.actionData.msgBody : []; const nodes: ForwardNodePayload[] = []; for (const msgBody of msgBodyList) { - const wrapped = protoEncode({ message: msgBody }, PushMsgSchema); + const wrapped = protobuf_encode({ message: msgBody }); const pkt: PacketInfo = { pid: 0, uin: bridge.identity.uin, diff --git a/packages/core/src/bridge/proto/proton/element.ts b/packages/core/src/bridge/proto/proton/element.ts new file mode 100644 index 00000000..3da2ac6f --- /dev/null +++ b/packages/core/src/bridge/proto/proton/element.ts @@ -0,0 +1,421 @@ +// Proton (compile-time) form of bridge/proto/element.ts. +// +// One-to-one mirror of every schema in element.ts. The legacy `*Schema` +// constants stay in place for back-compat; both forms produce wire-equivalent +// output (modulo the proto3 default-value omission — see README). + +import type { pb, pb_repeated, int_32, uint_32, uint_64, bool, bytes } from '@snowluma/proton'; + +// ── Nested / helper schemas ───────────────────────────────────────── + +export interface CustomFacePbReserve { + subType?: pb<1, int_32>; + summary?: pb<9, string>; +} + +export interface NotOnlineImagePbReserve2 { + field1?: pb<1, int_32>; + field2?: pb<2, string>; + field3?: pb<3, int_32>; + field4?: pb<4, int_32>; + field5?: pb<5, int_32>; + field7?: pb<7, string>; +} + +export interface NotOnlineImagePbReserve { + subType?: pb<1, int_32>; + field3?: pb<3, int_32>; + field4?: pb<4, int_32>; + summary?: pb<8, string>; + field10?: pb<10, int_32>; + field20?: pb<20, NotOnlineImagePbReserve2>; + url?: pb<30, string>; + md5Str?: pb<31, string>; +} + +// ── Core element schemas ──────────────────────────────────────────── + +export interface TextElem { + str?: pb<1, string>; + link?: pb<2, string>; + attr6Buf?: pb<3, bytes>; + attr7Buf?: pb<4, bytes>; + buf?: pb<11, bytes>; + pbReserve?: pb<12, bytes>; +} + +export interface FaceElem { + index?: pb<1, int_32>; + oldData?: pb<2, bytes>; + buf?: pb<11, bytes>; +} + +export interface OnlineImage { + guid?: pb<1, bytes>; + filePath?: pb<2, bytes>; + oldVerSendFile?: pb<3, bytes>; +} + +export interface NotOnlineImage { + filePath?: pb<1, string>; + fileLen?: pb<2, uint_32>; + downloadPath?: pb<3, string>; + oldVerSendFile?:pb<4, bytes>; + imgType?: pb<5, int_32>; + previewsImage?: pb<6, bytes>; + picMd5?: pb<7, bytes>; + picHeight?: pb<8, uint_32>; + picWidth?: pb<9, uint_32>; + resId?: pb<10, string>; + flag?: pb<11, bytes>; + thumbUrl?: pb<12, string>; + original?: pb<13, int_32>; + bigUrl?: pb<14, string>; + origUrl?: pb<15, string>; + bizType?: pb<16, int_32>; + result?: pb<17, int_32>; + index?: pb<18, int_32>; + opFaceBuf?: pb<19, bytes>; + oldPicMd5?: pb<20, bool>; + thumbWidth?: pb<21, int_32>; + thumbHeight?: pb<22, int_32>; + fileId?: pb<23, int_32>; + showLen?: pb<24, uint_32>; + downloadLen?: pb<25, uint_32>; + x400Url?: pb<26, string>; + x400Width?: pb<27, int_32>; + x400Height?: pb<28, int_32>; + pbRes?: pb<29, NotOnlineImagePbReserve>; +} + +export interface TransElem { + elemType?: pb<1, int_32>; + elemValue?: pb<2, bytes>; +} + +export interface MarketFace { + faceName?: pb<1, string>; + itemType?: pb<2, uint_32>; + faceInfo?: pb<3, uint_32>; + faceId?: pb<4, bytes>; + tabId?: pb<5, uint_32>; + subType?: pb<6, uint_32>; + key?: pb<7, bytes>; + param?: pb<8, bytes>; + mediaType?: pb<9, uint_32>; + imageWidth?: pb<10, uint_32>; + imageHeight?: pb<11, uint_32>; + mobileParam?: pb<12, bytes>; + pbReserve?: pb<13, bytes>; +} + +export interface CustomFace { + guid?: pb<1, bytes>; + filePath?: pb<2, string>; + shortcut?: pb<3, string>; + buffer?: pb<4, bytes>; + flag?: pb<5, bytes>; + oldData?: pb<6, bytes>; + fileId?: pb<7, uint_32>; + serverIp?: pb<8, int_32>; + serverPort?: pb<9, int_32>; + fileType?: pb<10, int_32>; + signature?: pb<11, bytes>; + useful?: pb<12, int_32>; + md5?: pb<13, bytes>; + thumbUrl?: pb<14, string>; + bigUrl?: pb<15, string>; + origUrl?: pb<16, string>; + bizType?: pb<17, int_32>; + repeatIndex?: pb<18, int_32>; + repeatImage?: pb<19, int_32>; + imageType?: pb<20, int_32>; + index?: pb<21, int_32>; + width?: pb<22, int_32>; + height?: pb<23, int_32>; + source?: pb<24, int_32>; + size?: pb<25, uint_32>; + origin?: pb<26, int_32>; + thumbWidth?: pb<27, int_32>; + thumbHeight?: pb<28, int_32>; + showLen?: pb<29, int_32>; + downloadLen?: pb<30, int_32>; + x400Url?: pb<31, string>; + x400Width?: pb<32, int_32>; + x400Height?: pb<33, int_32>; + pbRes?: pb<34, CustomFacePbReserve>; +} + +export interface RichMsg { + template1?: pb<1, bytes>; + serviceId?: pb<2, int_32>; + msgResId?: pb<3, bytes>; + rand?: pb<4, int_32>; + seq?: pb<5, uint_32>; +} + +export interface GroupFileElem { + filename?: pb<1, string>; + fileSize?: pb<2, uint_64>; + fileId?: pb<3, string>; + batchId?: pb<4, string>; + fileKey?: pb<5, string>; + mark?: pb<6, bytes>; + sequence?: pb<7, uint_64>; + batchItemId?: pb<8, bytes>; + feedMsgTime?: pb<9, int_32>; + pbReserve?: pb<10, bytes>; +} + +export interface ExtraInfo { + nick?: pb<1, bytes>; + groupCard?: pb<2, bytes>; + level?: pb<3, int_32>; + flags?: pb<4, int_32>; + groupMask?: pb<5, int_32>; + msgTailId?: pb<6, int_32>; + senderTitle?: pb<7, bytes>; + apnsTips?: pb<8, bytes>; + uin?: pb<9, uint_64>; + msgStateFlag?: pb<10, int_32>; + apnsSoundType?: pb<11, int_32>; + newGroupFlag?: pb<12, int_32>; +} + +export interface VideoFile { + fileUuid?: pb<1, string>; + fileMd5?: pb<2, bytes>; + fileName?: pb<3, string>; + fileFormat?: pb<4, int_32>; + fileTime?: pb<5, int_32>; + fileSize?: pb<6, int_32>; + thumbWidth?: pb<7, int_32>; + thumbHeight?: pb<8, int_32>; + thumbFileMd5?: pb<9, bytes>; + source?: pb<10, bytes>; + thumbFileSize?: pb<11, int_32>; + busiType?: pb<12, int_32>; + fromChatType?: pb<13, int_32>; + toChatType?: pb<14, int_32>; + supportProgressive?: pb<15, bool>; + fileWidth?: pb<16, int_32>; + fileHeight?: pb<17, int_32>; + subBusiType?: pb<18, int_32>; + videoAttr?: pb<19, int_32>; + pbReserve?: pb<24, bytes>; +} + +export interface SrcMsg { + origSeqs?: pb_repeated<1, uint_32>; + senderUin?: pb<2, uint_64>; + time?: pb<3, int_32>; + flag?: pb<4, int_32>; + elemsRaw?: pb_repeated<5, bytes>; + type?: pb<6, int_32>; + richMsg?: pb<7, bytes>; + pbReserve?: pb<8, bytes>; + sourceMsg?: pb<9, bytes>; + toUin?: pb<10, uint_64>; + troopName?: pb<11, bytes>; +} + +export interface LightAppElem { + data?: pb<1, bytes>; + msgResid?: pb<2, bytes>; +} + +export interface CommonElem { + serviceType?: pb<1, int_32>; + pbElem?: pb<2, bytes>; + businessType?: pb<3, uint_32>; +} + +export interface GeneralFlags { + bubbleDiyTextId?: pb<1, int_32>; + groupFlagNew?: pb<2, int_32>; + uin?: pb<3, uint_64>; + longTextFlag?: pb<6, int_32>; + longTextResId?: pb<7, string>; +} + +// ── Elem (union of all element types) ─────────────────────────────── + +export interface Elem { + text?: pb<1, TextElem>; + face?: pb<2, FaceElem>; + onlineImage?: pb<3, OnlineImage>; + notOnlineImage?: pb<4, NotOnlineImage>; + transElem?: pb<5, TransElem>; + marketFace?: pb<6, MarketFace>; + customFace?: pb<8, CustomFace>; + richMsg?: pb<12, RichMsg>; + groupFile?: pb<13, GroupFileElem>; + extraInfo?: pb<16, ExtraInfo>; + videoFile?: pb<19, VideoFile>; + generalFlags?: pb<37, GeneralFlags>; + srcMsg?: pb<45, SrcMsg>; + lightApp?: pb<51, LightAppElem>; + commonElem?: pb<53, CommonElem>; +} + +// ── Extra decode types (for CommonElem.pbElem sub-messages) ───────── + +export interface MentionExtra { + type?: pb<3, int_32>; + uin?: pb<4, uint_32>; + field5?: pb<5, int_32>; + uid?: pb<9, string>; +} + +export interface QFaceExtra { + packId?: pb<1, string>; + stickerId?: pb<2, string>; + qsid?: pb<3, int_32>; + sourceType?: pb<4, int_32>; + stickerType?: pb<5, int_32>; + resultId?: pb<6, string>; + text?: pb<7, string>; + randomType?: pb<9, int_32>; +} + +export interface QSmallFaceExtra { + faceId?: pb<1, uint_32>; + preview?: pb<2, string>; + preview2?: pb<3, string>; +} + +// ── NTQQ MsgInfo types (CommonElem service_type 48) ───────────────── + +export interface FileType { + type?: pb<1, uint_32>; + picFormat?: pb<2, uint_32>; + videoFormat?: pb<3, uint_32>; + voiceFormat?: pb<4, uint_32>; +} + +export interface FileInfo { + fileSize?: pb<1, uint_32>; + fileHash?: pb<2, string>; + fileSha1?: pb<3, string>; + fileName?: pb<4, string>; + type?: pb<5, FileType>; + width?: pb<6, uint_32>; + height?: pb<7, uint_32>; + time?: pb<8, uint_32>; + original?: pb<9, uint_32>; +} + +export interface IndexNode { + info?: pb<1, FileInfo>; + fileUuid?: pb<2, string>; + storeId?: pb<3, uint_32>; + uploadTime?: pb<4, uint_32>; + ttl?: pb<5, uint_32>; + subType?: pb<6, uint_32>; +} + +export interface PicUrlExtInfo { + originalParameter?: pb<1, string>; + bigParameter?: pb<2, string>; + thumbParameter?: pb<3, string>; +} + +export interface PictureInfo { + urlPath?: pb<1, string>; + ext?: pb<2, PicUrlExtInfo>; + domain?: pb<3, string>; +} + +export interface PicExtData { + subType?: pb<1, uint_32>; + textSummary?: pb<9, string>; +} + +export interface PicExtBizInfo { + bizType?: pb<1, uint_32>; + textSummary?: pb<2, string>; + bytesPbReserveC2c?: pb<11, bytes>; + extData?: pb<12, PicExtData>; + fromScene?: pb<1001, uint_32>; + toScene?: pb<1002, uint_32>; + oldFileId?: pb<1003, uint_32>; +} + +export interface VideoExtBizInfo { + fromScene?: pb<1, uint_32>; + toScene?: pb<2, uint_32>; + bytesPbReserve?: pb<3, bytes>; +} + +export interface PttExtBizInfo { + srcUin?: pb<1, uint_64>; + pttScene?: pb<2, uint_32>; + pttType?: pb<3, uint_32>; + changeVoice?: pb<4, uint_32>; + waveform?: pb<5, bytes>; + autoConvertText?: pb<6, uint_32>; + bytesReserve?: pb<11, bytes>; + bytesPbReserve?: pb<12, bytes>; + bytesGeneralFlags?: pb<13, bytes>; +} + +export interface ExtBizInfo { + pic?: pb<1, PicExtBizInfo>; + video?: pb<2, VideoExtBizInfo>; + ptt?: pb<3, PttExtBizInfo>; + busiType?: pb<10, uint_32>; +} + +export interface C2cSource { + friendUid?: pb<2, string>; +} + +export interface TroopSource { + groupUin?: pb<1, uint_32>; +} + +export interface HashSum { + bytesPbReserveC2c?: pb<201, C2cSource>; + troopSource?: pb<202, TroopSource>; +} + +export interface MsgInfoBody { + index?: pb<1, IndexNode>; + picture?: pb<2, PictureInfo>; + fileExist?: pb<5, bool>; + hashSum?: pb<6, HashSum>; +} + +export interface MsgInfo { + msgInfoBody?: pb_repeated<1, MsgInfoBody>; + extBizInfo?: pb<2, ExtBizInfo>; +} + +// ── GroupFileExtra (TransElem type=24) ────────────────────────────── + +export interface GroupFileInfo { + busId?: pb<1, uint_32>; + fileId?: pb<2, string>; + fileSize?: pb<3, uint_64>; + fileName?: pb<4, string>; + fileSha?: pb<5, bytes>; + extInfoString?: pb<6, string>; + fileMd5?: pb<7, bytes>; +} + +export interface GroupFileExtraInner { + info?: pb<2, GroupFileInfo>; +} + +export interface GroupFileExtra { + inner?: pb<7, GroupFileExtraInner>; +} + +// ── Preserve (for message receipt info) ───────────────────────────── + +export interface Preserve { + messageId?: pb<3, uint_64>; + senderUid?: pb<6, string>; + receiverUid?: pb<7, string>; + clientSequence?: pb<8, uint_32>; +} diff --git a/packages/core/src/bridge/proto/proton/longmsg.ts b/packages/core/src/bridge/proto/proton/longmsg.ts index 6f8fa331..ef634a96 100644 --- a/packages/core/src/bridge/proto/proton/longmsg.ts +++ b/packages/core/src/bridge/proto/proton/longmsg.ts @@ -1,15 +1,12 @@ // Proton (compile-time) form of the long-message schemas. // -// Mirror of the self-contained subset of `bridge/proto/longmsg.ts`. Only the -// schemas that DON'T reach into `PushMsgBodySchema` (and thus into element.ts) -// are migrated here — `LongMsgContent` / `LongMsgAction` / `LongMsgResult` -// stay on the legacy runtime API until message.ts + element.ts get migrated. -// -// This file is the proof-of-concept target for the @snowluma/proton plugin. -// The parity test at `tests/proton-parity.test.ts` asserts that proton's -// generated codec produces the exact same wire bytes as `protoEncode`. +// One-to-one mirror of `bridge/proto/longmsg.ts`. All 12 schemas are now +// migrated — the three (`LongMsgContent` / `LongMsgAction` / `LongMsgResult`) +// that reach into `PushMsgBody` resolve via the proton-form `message.ts` +// migration alongside this file. -import type { pb, uint_32, bool, bytes } from '@snowluma/proton'; +import type { pb, pb_repeated, uint_32, bool, bytes } from '@snowluma/proton'; +import type { PushMsgBody } from './message'; export interface LongMsgUid { uid?: pb<2, string>; @@ -63,3 +60,18 @@ export interface RecvLongMsgResp { result?: pb<1, RecvLongMsgRespResult>; settings?: pb<15, LongMsgSettings>; } + +// ── Schemas that reach into PushMsgBody (via message.ts) ──────────── + +export interface LongMsgContent { + msgBody?: pb_repeated<1, PushMsgBody>; +} + +export interface LongMsgAction { + actionCommand?: pb<1, string>; + actionData?: pb<2, LongMsgContent>; +} + +export interface LongMsgResult { + action?: pb_repeated<2, LongMsgAction>; +} diff --git a/packages/core/src/bridge/proto/proton/message.ts b/packages/core/src/bridge/proto/proton/message.ts new file mode 100644 index 00000000..1727c90a --- /dev/null +++ b/packages/core/src/bridge/proto/proton/message.ts @@ -0,0 +1,113 @@ +// Proton (compile-time) form of bridge/proto/message.ts. +// One-to-one mirror; legacy `*Schema` constants stay alongside for back-compat. + +import type { pb, pb_repeated, int_32, uint_32, uint_64, bytes } from '@snowluma/proton'; +import type { Elem } from './element'; + +// ── ResponseHead.Grp ──────────────────────────────────────────────── + +export interface ResponseGrp { + groupUin?: pb<1, uint_32>; + memberName?: pb<2, string>; + groupName?: pb<4, string>; +} + +export interface ResponseForward { + friendName?: pb<6, string>; +} + +// ── ResponseHead ──────────────────────────────────────────────────── + +export interface ResponseHead { + fromUin?: pb<1, uint_32>; + fromUid?: pb<2, string>; + type?: pb<3, uint_32>; + sigMap?: pb<4, uint_32>; + toUin?: pb<5, uint_32>; + toUid?: pb<6, string>; + forward?: pb<7, ResponseForward>; + grp?: pb<8, ResponseGrp>; +} + +// ── ContentHead ───────────────────────────────────────────────────── + +export interface ContentHead { + msgType?: pb<1, uint_32>; + subType?: pb<2, uint_32>; + divSeq?: pb<3, uint_32>; + msgId?: pb<4, uint_32>; + sequence?: pb<5, uint_32>; + timestamp?: pb<6, uint_32>; + field7?: pb<7, uint_64>; + newId?: pb<12, uint_64>; +} + +// ── Ptt (voice) ───────────────────────────────────────────────────── + +export interface Ptt { + fileType?: pb<1, uint_32>; + fileId?: pb<2, uint_64>; + fileUuid?: pb<3, bytes>; + fileMd5?: pb<4, bytes>; + fileName?: pb<5, string>; + fileSize?: pb<6, uint_32>; + groupFileKey?: pb<10, string>; + fileKey?: pb<14, bytes>; + time?: pb<19, uint_32>; + format?: pb<29, uint_32>; +} + +// ── NotOnlineFile (C2C file) ──────────────────────────────────────── + +export interface NotOnlineFile { + fileType?: pb<1, uint_32>; + fileUuid?: pb<3, string>; + fileMd5?: pb<4, bytes>; + fileName?: pb<5, string>; + fileSize?: pb<6, uint_64>; + fileHash?: pb<57, string>; +} + +// ── RichText ──────────────────────────────────────────────────────── + +export interface RichText { + elems?: pb_repeated<2, Elem>; + notOnlineFile?: pb<3, NotOnlineFile>; + ptt?: pb<4, Ptt>; +} + +// ── MessageBody ───────────────────────────────────────────────────── + +export interface MessageBody { + richText?: pb<1, RichText>; + msgContent?: pb<2, bytes>; +} + +// ── FileExtra (for C2C file in msg_content) ───────────────────────── + +export interface FileExtraInfo { + fileSize?: pb<1, uint_64>; + fileName?: pb<2, string>; + fileMd5?: pb<3, bytes>; + fileUuid?: pb<4, string>; + fileHash?: pb<5, string>; +} + +export interface FileExtra { + file?: pb<1, FileExtraInfo>; +} + +// ── PushMsgBody ───────────────────────────────────────────────────── + +export interface PushMsgBody { + responseHead?: pb<1, ResponseHead>; + contentHead?: pb<2, ContentHead>; + body?: pb<3, MessageBody>; +} + +// ── PushMsg (top-level) ───────────────────────────────────────────── + +export interface PushMsg { + message?: pb<1, PushMsgBody>; + status?: pb<3, int_32>; +} diff --git a/packages/core/tests/proton-parity.test.ts b/packages/core/tests/proton-parity.test.ts index e4f07898..9b356973 100644 --- a/packages/core/tests/proton-parity.test.ts +++ b/packages/core/tests/proton-parity.test.ts @@ -13,7 +13,21 @@ import { RecvLongMsgReqSchema, RecvLongMsgRespSchema, LongMsgSettingsSchema, + LongMsgResultSchema, } from '../src/bridge/proto/longmsg'; +import { + TextElemSchema, + NotOnlineImageSchema, + ExtraInfoSchema, + SrcMsgSchema, + ElemSchema, + MsgInfoSchema, +} from '../src/bridge/proto/element'; +import { + ResponseHeadSchema, + PushMsgBodySchema, + PushMsgSchema, +} from '../src/bridge/proto/message'; import type { SendLongMsgResp, @@ -21,7 +35,21 @@ import type { RecvLongMsgReq, RecvLongMsgResp, LongMsgSettings, + LongMsgResult, } from '../src/bridge/proto/proton/longmsg'; +import type { + TextElem, + NotOnlineImage, + ExtraInfo, + SrcMsg, + Elem, + MsgInfo, +} from '../src/bridge/proto/proton/element'; +import type { + ResponseHead, + PushMsgBody, + PushMsg, +} from '../src/bridge/proto/proton/message'; function hex(buf: Uint8Array): string { return Buffer.from(buf).toString('hex'); @@ -30,14 +58,14 @@ function hex(buf: Uint8Array): string { describe('proton ↔ legacy parity (longmsg subset)', () => { it('encodes LongMsgSettings identically', () => { const data: LongMsgSettings = { field1: 1, field2: 2, field3: 3, field4: 4 }; - const legacy = protoEncode(data, LongMsgSettingsSchema); + const legacy = protoEncode(data as any, LongMsgSettingsSchema); const proton = protobuf_encode(data); expect(hex(proton)).toBe(hex(legacy)); }); it('encodes SendLongMsgResp (nested message) identically', () => { const data: SendLongMsgResp = { result: { resId: 'res-001' } }; - const legacy = protoEncode(data, SendLongMsgRespSchema); + const legacy = protoEncode(data as any, SendLongMsgRespSchema); const proton = protobuf_encode(data); expect(hex(proton)).toBe(hex(legacy)); }); @@ -56,7 +84,7 @@ describe('proton ↔ legacy parity (longmsg subset)', () => { }, settings: { field1: 4, field2: 1, field3: 7, field4: 2 }, }; - const legacy = protoEncode(data, SendLongMsgReqSchema); + const legacy = protoEncode(data as any, SendLongMsgReqSchema); const proton = protobuf_encode(data); expect(hex(proton)).toBe(hex(legacy)); }); @@ -66,7 +94,7 @@ describe('proton ↔ legacy parity (longmsg subset)', () => { info: { uid: { uid: 'u_recv' }, resId: 'r-9', acquire: true }, settings: { field1: 4, field2: 1, field3: 7, field4: 2 }, }; - const legacy = protoEncode(data, RecvLongMsgReqSchema); + const legacy = protoEncode(data as any, RecvLongMsgReqSchema); const proton = protobuf_encode(data); expect(hex(proton)).toBe(hex(legacy)); }); @@ -76,11 +104,188 @@ describe('proton ↔ legacy parity (longmsg subset)', () => { result: { resId: 'r-1', payload: new Uint8Array([1, 2, 3, 4, 5]) }, settings: { field1: 4, field2: 1, field3: 7, field4: 2 }, }; - const legacy = protoEncode(data, RecvLongMsgRespSchema); + const legacy = protoEncode(data as any, RecvLongMsgRespSchema); const proton = protobuf_encode(data); expect(hex(proton)).toBe(hex(legacy)); }); + // ── element.ts coverage ───────────────────────────────────────────── + + it('encodes TextElem (only primitive bytes + strings) identically', () => { + const data: TextElem = { + str: 'hello', + link: 'https://example.com', + attr6Buf: new Uint8Array([1, 2, 3]), + buf: new Uint8Array([0xff, 0xee]), + }; + const legacy = protoEncode(data as any, TextElemSchema); + const proton = protobuf_encode(data); + expect(hex(proton)).toBe(hex(legacy)); + }); + + it('encodes NotOnlineImage with nested PbReserve identically', () => { + const data: NotOnlineImage = { + filePath: 'pic.jpg', + fileLen: 12345, + picMd5: new Uint8Array([0x11, 0x22, 0x33, 0x44]), + picHeight: 600, + picWidth: 800, + resId: 'res-abc', + original: 1, + bigUrl: 'https://q.qq.com/big/abc', + bizType: 5, + pbRes: { + subType: 1, + summary: '[picture]', + field10: 7, + field20: { field1: 1, field2: 'inner', field3: 2, field4: 3, field5: 4, field7: 'tail' }, + url: 'https://q.qq.com/abc', + md5Str: 'abc123', + }, + }; + const legacy = protoEncode(data as any, NotOnlineImageSchema); + const proton = protobuf_encode(data); + expect(hex(proton)).toBe(hex(legacy)); + }); + + it('encodes ExtraInfo (mix of bytes + int32 + uint64) identically', () => { + const data: ExtraInfo = { + nick: new Uint8Array([0x41, 0x42]), + groupCard: new Uint8Array([0x43]), + level: 7, + flags: 1, + groupMask: 2, + msgTailId: 3, + uin: 10001n, + msgStateFlag: 4, + }; + const legacy = protoEncode(data as any, ExtraInfoSchema); + const proton = protobuf_encode(data); + expect(hex(proton)).toBe(hex(legacy)); + }); + + it('encodes SrcMsg with repeated_uint32 + repeated_bytes identically', () => { + const data: SrcMsg = { + origSeqs: [100, 200, 300, 400], + senderUin: 10001n, + time: 1234567890, + flag: 1, + elemsRaw: [new Uint8Array([1, 2]), new Uint8Array([3, 4]), new Uint8Array([5, 6])], + type: 1, + toUin: 20002n, + }; + const legacy = protoEncode(data as any, SrcMsgSchema); + const proton = protobuf_encode(data); + expect(hex(proton)).toBe(hex(legacy)); + }); + + it('encodes Elem (oneOf-style union) identically across multiple shapes', () => { + const textOnly: Elem = { text: { str: 'hi', link: 'lnk' } }; + expect(hex(protobuf_encode(textOnly))).toBe(hex(protoEncode(textOnly as any, ElemSchema))); + + const faceOnly: Elem = { face: { index: 42, buf: new Uint8Array([1, 2, 3]) } }; + expect(hex(protobuf_encode(faceOnly))).toBe(hex(protoEncode(faceOnly as any, ElemSchema))); + + const generalFlags: Elem = { generalFlags: { uin: 10001n, longTextFlag: 1, longTextResId: 'rs' } }; + expect(hex(protobuf_encode(generalFlags))).toBe(hex(protoEncode(generalFlags as any, ElemSchema))); + }); + + it('encodes MsgInfo with repeated_message + deeply nested ExtBizInfo identically', () => { + const data: MsgInfo = { + msgInfoBody: [ + { + index: { + info: { fileSize: 1024, fileHash: 'sha-1', fileSha1: 'sha-2', fileName: 'a.png', type: { type: 1, picFormat: 2, videoFormat: 3, voiceFormat: 4 }, width: 100, height: 200, time: 99, original: 1 }, + fileUuid: 'uuid-1', storeId: 5, uploadTime: 1000, ttl: 86400, subType: 1, + }, + picture: { + urlPath: '/p/1', + ext: { originalParameter: 'op', bigParameter: 'bp', thumbParameter: 'tp' }, + domain: 'q.qq.com', + }, + fileExist: true, + }, + ], + extBizInfo: { + pic: { + bizType: 5, textSummary: '[pic]', + extData: { subType: 2, textSummary: 'sum' }, + fromScene: 1, toScene: 2, oldFileId: 999, + }, + busiType: 3, + }, + }; + const legacy = protoEncode(data as any, MsgInfoSchema); + const proton = protobuf_encode(data); + expect(hex(proton)).toBe(hex(legacy)); + }); + + // ── message.ts coverage ───────────────────────────────────────────── + + it('encodes ResponseHead (nested forward + grp) identically', () => { + const data: ResponseHead = { + fromUin: 10001, fromUid: 'u_a', type: 1, sigMap: 2, toUin: 20002, toUid: 'u_b', + forward: { friendName: 'Alice' }, + grp: { groupUin: 555, memberName: 'Bob', groupName: 'TestGroup' }, + }; + const legacy = protoEncode(data as any, ResponseHeadSchema); + const proton = protobuf_encode(data); + expect(hex(proton)).toBe(hex(legacy)); + }); + + it('encodes PushMsgBody (with RichText holding Elem[]) identically', () => { + const data: PushMsgBody = { + responseHead: { fromUin: 1, toUin: 2, type: 1, sigMap: 3, fromUid: 'a', toUid: 'b' }, + contentHead: { msgType: 1, subType: 1, divSeq: 1, msgId: 99, sequence: 100, timestamp: 1234567890 }, + body: { + richText: { + elems: [ + { text: { str: 'hi ' } }, + { text: { str: 'world', link: 'lnk' } }, + ], + }, + }, + }; + const legacy = protoEncode(data as any, PushMsgBodySchema); + const proton = protobuf_encode(data); + expect(hex(proton)).toBe(hex(legacy)); + }); + + it('encodes PushMsg (top-level) identically', () => { + const data: PushMsg = { + message: { + responseHead: { fromUin: 1, toUin: 2, type: 1, sigMap: 1, fromUid: 'a', toUid: 'b' }, + contentHead: { msgType: 1, subType: 1, divSeq: 1, msgId: 1, sequence: 1, timestamp: 1 }, + body: { richText: { elems: [{ text: { str: 'x' } }] } }, + }, + status: 1, + }; + const legacy = protoEncode(data as any, PushMsgSchema); + const proton = protobuf_encode(data); + expect(hex(proton)).toBe(hex(legacy)); + }); + + // ── longmsg.ts: full migration (Content / Action / Result) ───────── + + it('encodes LongMsgResult (repeated Action → Content → PushMsgBody[]) identically', () => { + const inner: PushMsgBody = { + responseHead: { fromUin: 1, toUin: 2, type: 1, sigMap: 1, fromUid: 'a', toUid: 'b' }, + contentHead: { msgType: 1, subType: 1, divSeq: 1, msgId: 1, sequence: 1, timestamp: 1 }, + body: { richText: { elems: [{ text: { str: 'forwarded' } }] } }, + }; + const data: LongMsgResult = { + action: [ + { + actionCommand: 'MultiMsg', + actionData: { msgBody: [inner, inner] }, + }, + ], + }; + const legacy = protoEncode(data as any, LongMsgResultSchema); + const proton = protobuf_encode(data); + expect(hex(proton)).toBe(hex(legacy)); + }); + // ── Documented divergence: proto3 default-value omission ──────────── it('proton omits default-valued numeric fields (legacy emits them)', () => { @@ -89,7 +294,7 @@ describe('proton ↔ legacy parity (longmsg subset)', () => { // Either form is round-trippable through a conforming proto3 reader — the // missing field decodes as its default. This test pins that behaviour. const data: LongMsgSettings = { field1: 0, field2: 0, field3: 0, field4: 0 }; - const legacy = protoEncode(data, LongMsgSettingsSchema); + const legacy = protoEncode(data as any, LongMsgSettingsSchema); const proton = protobuf_encode(data); expect(hex(proton)).toBe(''); // nothing on the wire expect(legacy.length).toBeGreaterThan(0); // legacy emits all zeros @@ -113,7 +318,7 @@ describe('proton ↔ legacy parity (longmsg subset)', () => { it('round-trips SendLongMsgResp through legacy encode → proton decode', () => { const data: SendLongMsgResp = { result: { resId: 'rt-2' } }; - const encoded = protoEncode(data, SendLongMsgRespSchema); + const encoded = protoEncode(data as any, SendLongMsgRespSchema); const decoded = protobuf_decode(encoded); expect(decoded.result?.resId).toBe('rt-2'); }); From 9f32dbd60cc363c86ef55f70dd4eb4925f65cd10 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Mon, 18 May 2026 23:34:26 +0800 Subject: [PATCH 16/48] feat(proton): migrate notify.ts schemas + all 6 msg-push consumers MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Mirrors all 27 notify.ts schemas as proton interface forms and switches the entire msg-push decoder family over to the new compile-time API. Migrated schemas (proton/notify.ts): OperatorField1, OperatorInfo, GroupChange, GroupAdminExtra, GroupAdminBody, GroupAdmin, InvitationInner, InvitationInfo, GroupInvitation, GroupInvite, GroupJoin, FriendRequestInfo, FriendRequest, FriendRecallTipInfo, FriendRecallInfo, FriendRecall, GroupMuteState, GroupMuteData, GroupMute, RecallMessage, GroupRecallTipInfo, GroupRecall, TemplParam, GeneralGrayTipInfo, EssenceMessage, NotifyMessageBody, GroupReactionDataInnerDataTarget, GroupReactionDataContent, GroupReactionDataInnerData, GroupReactionDataInner, GroupReactionData, GroupReactNotify Consumer files switched to protobuf_decode(): - msg-push/helpers.ts (decodeOperatorUid) - msg-push/decoders/event-0x2dc.ts (5 call sites: GroupMute, GroupRecall, GroupGreyTip, GroupEssence, GroupMsgEmojiLike) - msg-push/decoders/event-0x210.ts (3 call sites: FriendRequest, FriendRecall, FriendPoke) - msg-push/decoders/group-admin.ts - msg-push/decoders/group-member-change.ts (join + leave) - msg-push/decoders/group-join-request.ts (join request + invitation + invite) The notify.ts FriendRecall interface collides with events.ts's own FriendRecall event type; the decoder imports it under the local alias FriendRecallNotify to keep the existing event type intact. Verification: - 6 new parity tests pinning notify wire equivalence - 591/591 core test suite passes (the existing decoder tests — group-msg-emoji-like, group-admin, etc. — implicitly validated wire format equivalence against real captured QQ payloads) - tsc --noEmit clean --- .../bridge/msg-push/decoders/event-0x210.ts | 16 +- .../bridge/msg-push/decoders/event-0x2dc.ts | 18 +- .../bridge/msg-push/decoders/group-admin.ts | 6 +- .../msg-push/decoders/group-join-request.ts | 14 +- .../msg-push/decoders/group-member-change.ts | 8 +- packages/core/src/bridge/msg-push/helpers.ts | 6 +- .../core/src/bridge/proto/proton/notify.ts | 239 ++++++++++++++++++ packages/core/tests/proton-parity.test.ts | 99 ++++++++ 8 files changed, 373 insertions(+), 33 deletions(-) create mode 100644 packages/core/src/bridge/proto/proton/notify.ts diff --git a/packages/core/src/bridge/msg-push/decoders/event-0x210.ts b/packages/core/src/bridge/msg-push/decoders/event-0x210.ts index cbce944f..4cbc479f 100644 --- a/packages/core/src/bridge/msg-push/decoders/event-0x210.ts +++ b/packages/core/src/bridge/msg-push/decoders/event-0x210.ts @@ -1,10 +1,12 @@ // Handles Event0x210 wrapper (528). Internal switch on subType dispatches // to FriendRequest (35) / FriendRecall (138) / FriendPoke (290). -import { protoDecode } from '../../../protobuf/decode'; -import { - FriendRequestSchema, FriendRecallSchema, GeneralGrayTipInfoSchema, -} from '../../proto/notify'; +import { protobuf_decode } from '@snowluma/proton'; +import type { + FriendRequest as FriendRequestNotify, + FriendRecall as FriendRecallNotify, + GeneralGrayTipInfo, +} from '../../proto/proton/notify'; import type { FriendRequestEvent, FriendRecall, FriendPokeEvent, QQEventVariant, } from '../../events'; @@ -29,7 +31,7 @@ export const decodeEvent0x210: MsgPushDecoder = (ctx) => { }; function decodeFriendRequest(ctx: MsgPushContext): QQEventVariant[] { - const request = protoDecode(ctx.content, FriendRequestSchema); + const request = protobuf_decode(ctx.content); if (!request?.info) return []; const sourceUid = request.info.newSource || request.info.sourceUid || ''; const ev: FriendRequestEvent = { @@ -45,7 +47,7 @@ function decodeFriendRequest(ctx: MsgPushContext): QQEventVariant[] { } function decodeFriendRecall(ctx: MsgPushContext): QQEventVariant[] { - const recall = protoDecode(ctx.content, FriendRecallSchema); + const recall = protobuf_decode(ctx.content); if (!recall?.info) return []; const ev: FriendRecall = { kind: 'friend_recall', @@ -58,7 +60,7 @@ function decodeFriendRecall(ctx: MsgPushContext): QQEventVariant[] { } function decodeFriendPoke(ctx: MsgPushContext): QQEventVariant[] { - const grayTip = protoDecode(ctx.content, GeneralGrayTipInfoSchema); + const grayTip = protobuf_decode(ctx.content); if (!grayTip || (grayTip.busiType ?? 0n) !== 12n) return []; const templates = buildTemplateMap(grayTip.msgTemplParam ?? []); const actor = findTemplateValue(templates, 'uin_str1'); diff --git a/packages/core/src/bridge/msg-push/decoders/event-0x2dc.ts b/packages/core/src/bridge/msg-push/decoders/event-0x2dc.ts index 28efafe7..e16205ae 100644 --- a/packages/core/src/bridge/msg-push/decoders/event-0x2dc.ts +++ b/packages/core/src/bridge/msg-push/decoders/event-0x2dc.ts @@ -2,10 +2,10 @@ // to GroupMute (12) / GroupMsgEmojiLike (16) / GroupRecall (17) / // GroupGreyTip (20) / GroupEssence (21). -import { protoDecode } from '../../../protobuf/decode'; -import { - GroupMuteSchema, NotifyMessageBodySchema, GroupReactNotifySchema, -} from '../../proto/notify'; +import { protobuf_decode } from '@snowluma/proton'; +import type { + GroupMute, NotifyMessageBody, GroupReactNotify, +} from '../../proto/proton/notify'; import type { GroupMuteEvent, GroupRecallEvent, GroupPokeEvent, GroupEssenceEvent, GroupMsgEmojiLikeEvent, @@ -35,7 +35,7 @@ export const decodeEvent0x2DC: MsgPushDecoder = (ctx) => { }; function decodeGroupMute(ctx: MsgPushContext): QQEventVariant[] { - const mute = protoDecode(ctx.content, GroupMuteSchema); + const mute = protobuf_decode(ctx.content); if (!mute?.data?.state) return []; const duration = mute.data.state.duration ?? 0; const ev: GroupMuteEvent = { @@ -53,7 +53,7 @@ function decodeGroupMute(ctx: MsgPushContext): QQEventVariant[] { function decodeGroupRecall(ctx: MsgPushContext): QQEventVariant[] { const payload = unwrapGroupNotifyPayload(ctx.content); if (!payload) return []; - const notify = protoDecode(payload, NotifyMessageBodySchema); + const notify = protobuf_decode(payload); if (!notify?.recall?.recallMessages || notify.recall.recallMessages.length === 0) return []; const recalled = notify.recall.recallMessages[0]; const ev: GroupRecallEvent = { @@ -72,7 +72,7 @@ function decodeGroupRecall(ctx: MsgPushContext): QQEventVariant[] { function decodeGroupGreyTip(ctx: MsgPushContext): QQEventVariant[] { const payload = unwrapGroupNotifyPayload(ctx.content); if (!payload) return []; - const notify = protoDecode(payload, NotifyMessageBodySchema); + const notify = protobuf_decode(payload); if (!notify?.generalGrayTip || (notify.generalGrayTip.busiType ?? 0n) !== 12n) return []; const templates = buildTemplateMap(notify.generalGrayTip.msgTemplParam ?? []); const actor = findTemplateValue(templates, 'uin_str1'); @@ -94,7 +94,7 @@ function decodeGroupGreyTip(ctx: MsgPushContext): QQEventVariant[] { function decodeGroupEssence(ctx: MsgPushContext): QQEventVariant[] { const payload = unwrapGroupNotifyPayload(ctx.content); if (!payload) return []; - const notify = protoDecode(payload, NotifyMessageBodySchema); + const notify = protobuf_decode(payload); if (!notify?.essenceMessage) return []; const essence = notify.essenceMessage; const setFlag = essence.setFlag ?? essence.setFlag2 ?? 0; @@ -124,7 +124,7 @@ const GROUP_REACT_DISCRIMINATOR = 35; function decodeGroupMsgEmojiLike(ctx: MsgPushContext): QQEventVariant[] { if (ctx.content.length <= GROUP_REACT_PREFIX_BYTES) return []; const payload = ctx.content.subarray(GROUP_REACT_PREFIX_BYTES); - const notify = protoDecode(payload, GroupReactNotifySchema); + const notify = protobuf_decode(payload); if (!notify) return []; if ((notify.field13 ?? 0) !== GROUP_REACT_DISCRIMINATOR) { unknownLog.debug('Event0x2DC subType=16 unhandled field13=%d (expected %d for emoji react)', diff --git a/packages/core/src/bridge/msg-push/decoders/group-admin.ts b/packages/core/src/bridge/msg-push/decoders/group-admin.ts index 57bd9f23..d5c75087 100644 --- a/packages/core/src/bridge/msg-push/decoders/group-admin.ts +++ b/packages/core/src/bridge/msg-push/decoders/group-admin.ts @@ -1,14 +1,14 @@ // Handles GroupAdminChangedNotice (44). extraEnable / extraDisable // distinguishes set vs. unset. -import { protoDecode } from '../../../protobuf/decode'; -import { GroupAdminSchema } from '../../proto/notify'; +import { protobuf_decode } from '@snowluma/proton'; +import type { GroupAdmin } from '../../proto/proton/notify'; import type { GroupAdminEvent } from '../../events'; import type { MsgPushDecoder } from '../registry'; import { resolveUidToUin } from '../helpers'; export const decodeGroupAdmin: MsgPushDecoder = (ctx) => { - const admin = protoDecode(ctx.content, GroupAdminSchema); + const admin = protobuf_decode(ctx.content); if (!admin?.body) return []; const extra = admin.body.extraEnable ?? admin.body.extraDisable; if (!extra) return []; diff --git a/packages/core/src/bridge/msg-push/decoders/group-join-request.ts b/packages/core/src/bridge/msg-push/decoders/group-join-request.ts index 2cfdf6a3..50c589bc 100644 --- a/packages/core/src/bridge/msg-push/decoders/group-join-request.ts +++ b/packages/core/src/bridge/msg-push/decoders/group-join-request.ts @@ -2,16 +2,16 @@ // + GroupInviteNotice (87). All three produce GroupInviteEvent with // different subType ('add' / 'invite') and flag prefixes. -import { protoDecode } from '../../../protobuf/decode'; -import { - GroupJoinSchema, GroupInvitationSchema, GroupInviteSchema, -} from '../../proto/notify'; +import { protobuf_decode } from '@snowluma/proton'; +import type { + GroupJoin, GroupInvitation, GroupInvite, +} from '../../proto/proton/notify'; import type { GroupInviteEvent } from '../../events'; import type { MsgPushDecoder } from '../registry'; import { resolveUidToUin } from '../helpers'; export const decodeGroupJoinRequest: MsgPushDecoder = (ctx) => { - const join = protoDecode(ctx.content, GroupJoinSchema); + const join = protobuf_decode(ctx.content); if (!join) return []; const ev: GroupInviteEvent = { kind: 'group_invite', @@ -28,7 +28,7 @@ export const decodeGroupJoinRequest: MsgPushDecoder = (ctx) => { }; export const decodeGroupInvitation: MsgPushDecoder = (ctx) => { - const invitation = protoDecode(ctx.content, GroupInvitationSchema); + const invitation = protobuf_decode(ctx.content); if (!invitation?.info?.inner) return []; const inner = invitation.info.inner; const ev: GroupInviteEvent = { @@ -46,7 +46,7 @@ export const decodeGroupInvitation: MsgPushDecoder = (ctx) => { }; export const decodeGroupInvite: MsgPushDecoder = (ctx) => { - const invite = protoDecode(ctx.content, GroupInviteSchema); + const invite = protobuf_decode(ctx.content); if (!invite) return []; const ev: GroupInviteEvent = { kind: 'group_invite', diff --git a/packages/core/src/bridge/msg-push/decoders/group-member-change.ts b/packages/core/src/bridge/msg-push/decoders/group-member-change.ts index 25cdf59a..53386dfc 100644 --- a/packages/core/src/bridge/msg-push/decoders/group-member-change.ts +++ b/packages/core/src/bridge/msg-push/decoders/group-member-change.ts @@ -2,14 +2,14 @@ // Both share GroupChangeSchema; the decreaseType field distinguishes kick vs // voluntary leave (dt != 0 && dt != 130 means kicked). -import { protoDecode } from '../../../protobuf/decode'; -import { GroupChangeSchema } from '../../proto/notify'; +import { protobuf_decode } from '@snowluma/proton'; +import type { GroupChange } from '../../proto/proton/notify'; import type { GroupMemberJoin, GroupMemberLeave } from '../../events'; import type { MsgPushDecoder } from '../registry'; import { decodeOperatorUid, resolveUidToUin } from '../helpers'; export const decodeGroupMemberJoin: MsgPushDecoder = (ctx) => { - const change = protoDecode(ctx.content, GroupChangeSchema); + const change = protobuf_decode(ctx.content); if (!change) return []; const groupId = change.groupUin ?? 0; const userUid = change.memberUid ?? ''; @@ -28,7 +28,7 @@ export const decodeGroupMemberJoin: MsgPushDecoder = (ctx) => { }; export const decodeGroupMemberLeave: MsgPushDecoder = (ctx) => { - const change = protoDecode(ctx.content, GroupChangeSchema); + const change = protobuf_decode(ctx.content); if (!change) return []; const dt = change.decreaseType ?? 0; const groupId = change.groupUin ?? 0; diff --git a/packages/core/src/bridge/msg-push/helpers.ts b/packages/core/src/bridge/msg-push/helpers.ts index 125d5d9e..dc8cd1ec 100644 --- a/packages/core/src/bridge/msg-push/helpers.ts +++ b/packages/core/src/bridge/msg-push/helpers.ts @@ -2,8 +2,8 @@ // and the rich-body decoder. No state, no I/O. import { inflateSync } from 'zlib'; -import { protoDecode } from '../../protobuf/decode'; -import { OperatorInfoSchema } from '../proto/notify'; +import { protobuf_decode } from '@snowluma/proton'; +import type { OperatorInfo } from '../proto/proton/notify'; import type { IdentityService } from '../identity-service'; export function makeImageUrl(origUrl: string): string { @@ -52,7 +52,7 @@ export function resolveUidToUin(identity: IdentityService, groupId: number, uid: export function decodeOperatorUid(bytes: Uint8Array): string { if (!bytes || bytes.length === 0) return ''; - const info = protoDecode(bytes, OperatorInfoSchema); + const info = protobuf_decode(bytes); if (info?.operatorField?.uid) return info.operatorField.uid; return Buffer.from(bytes).toString('utf8'); } diff --git a/packages/core/src/bridge/proto/proton/notify.ts b/packages/core/src/bridge/proto/proton/notify.ts new file mode 100644 index 00000000..2640dcca --- /dev/null +++ b/packages/core/src/bridge/proto/proton/notify.ts @@ -0,0 +1,239 @@ +// Proton (compile-time) form of bridge/proto/notify.ts. +// One-to-one mirror; legacy `*Schema` constants stay alongside for back-compat. + +import type { pb, pb_repeated, int_32, uint_32, uint_64, bool, bytes } from '@snowluma/proton'; + +export interface OperatorField1 { + uid?: pb<1, string>; + field2?: pb<2, uint_32>; + field3?: pb<3, bytes>; + field4?: pb<4, uint_32>; + field5?: pb<5, bytes>; +} + +export interface OperatorInfo { + operatorField?: pb<1, OperatorField1>; +} + +export interface GroupChange { + groupUin?: pb<1, uint_32>; + flag?: pb<2, uint_32>; + memberUid?: pb<3, string>; + decreaseType?: pb<4, uint_32>; + operatorBytes?: pb<5, bytes>; + increaseType?: pb<6, uint_32>; + field7?: pb<7, bytes>; +} + +export interface GroupAdminExtra { + adminUid?: pb<1, string>; + isPromote?: pb<2, bool>; +} + +export interface GroupAdminBody { + extraDisable?: pb<1, GroupAdminExtra>; + extraEnable?: pb<2, GroupAdminExtra>; +} + +export interface GroupAdmin { + groupUin?: pb<1, uint_32>; + flag?: pb<2, uint_32>; + isPromote?: pb<3, bool>; + body?: pb<4, GroupAdminBody>; +} + +export interface InvitationInner { + groupUin?: pb<1, uint_32>; + field2?: pb<2, uint_32>; + field3?: pb<3, uint_32>; + field4?: pb<4, uint_32>; + targetUid?: pb<5, string>; + invitorUid?: pb<6, string>; + field7?: pb<7, uint_32>; + field9?: pb<9, uint_32>; + field10?: pb<10, bytes>; + field11?: pb<11, uint_32>; + field12?: pb<12, string>; +} + +export interface InvitationInfo { + inner?: pb<1, InvitationInner>; +} + +export interface GroupInvitation { + cmd?: pb<1, int_32>; + info?: pb<2, InvitationInfo>; +} + +export interface GroupInvite { + groupUin?: pb<1, uint_32>; + field2?: pb<2, uint_32>; + field3?: pb<3, uint_32>; + field4?: pb<4, uint_32>; + invitorUid?: pb<5, string>; + hashes?: pb<6, bytes>; +} + +export interface GroupJoin { + groupUin?: pb<1, uint_32>; + field2?: pb<2, uint_32>; + targetUid?: pb<3, string>; + field4?: pb<4, uint_32>; + field6?: pb<6, uint_32>; + field7?: pb<7, string>; + field8?: pb<8, uint_32>; + field9?: pb<9, bytes>; +} + +export interface FriendRequestInfo { + targetUid?: pb<1, string>; + sourceUid?: pb<2, string>; + newSource?: pb<5, string>; + message?: pb<10, string>; + source?: pb<11, string>; +} + +export interface FriendRequest { + info?: pb<1, FriendRequestInfo>; +} + +export interface FriendRecallTipInfo { + tip?: pb<2, string>; +} + +export interface FriendRecallInfo { + fromUid?: pb<1, string>; + toUid?: pb<2, string>; + clientSequence?: pb<3, uint_32>; + newId?: pb<4, uint_64>; + time?: pb<5, uint_32>; + random?: pb<6, uint_32>; + pkgNum?: pb<7, uint_32>; + pkgIndex?: pb<8, uint_32>; + divSeq?: pb<9, uint_32>; + tipInfo?: pb<13, FriendRecallTipInfo>; +} + +export interface FriendRecall { + info?: pb<1, FriendRecallInfo>; + instId?: pb<2, uint_32>; + appId?: pb<3, uint_32>; + longMessageFlag?: pb<4, uint_32>; + reserved?: pb<5, bytes>; +} + +export interface GroupMuteState { + targetUid?: pb<1, string>; + duration?: pb<2, uint_32>; +} + +export interface GroupMuteData { + timestamp?: pb<1, uint_32>; + type?: pb<2, uint_32>; + state?: pb<3, GroupMuteState>; +} + +export interface GroupMute { + groupUin?: pb<1, uint_32>; + subType?: pb<2, uint_32>; + field3?: pb<3, uint_32>; + operatorUid?: pb<4, string>; + data?: pb<5, GroupMuteData>; +} + +export interface RecallMessage { + sequence?: pb<1, uint_32>; + time?: pb<2, uint_32>; + random?: pb<3, uint_32>; + type?: pb<4, uint_32>; + flag?: pb<5, uint_32>; + authorUid?: pb<6, string>; +} + +export interface GroupRecallTipInfo { + tip?: pb<2, string>; +} + +export interface GroupRecall { + operatorUid?: pb<1, string>; + recallMessages?: pb_repeated<3, RecallMessage>; + userDef?: pb<5, bytes>; + groupType?: pb<6, int_32>; + opType?: pb<7, int_32>; + tipInfo?: pb<9, GroupRecallTipInfo>; +} + +export interface TemplParam { + name?: pb<1, string>; + value?: pb<2, string>; +} + +export interface GeneralGrayTipInfo { + busiType?: pb<1, uint_64>; + busiId?: pb<2, uint_64>; + ctrlFlag?: pb<3, uint_32>; + c2cType?: pb<4, uint_32>; + serviceType?: pb<5, uint_32>; + templId?: pb<6, uint_64>; + msgTemplParam?: pb_repeated<7, TemplParam>; + content?: pb<8, string>; +} + +export interface EssenceMessage { + groupUin?: pb<1, uint_32>; + msgSequence?: pb<2, uint_32>; + random?: pb<3, uint_32>; + setFlag?: pb<4, uint_32>; + memberUin?: pb<5, uint_32>; + operatorUin?: pb<6, uint_32>; + timestamp?: pb<7, uint_32>; + msgSequence2?: pb<8, uint_32>; + operatorNickname?: pb<9, string>; + memberNickname?: pb<10, string>; + setFlag2?: pb<11, uint_32>; +} + +export interface NotifyMessageBody { + type?: pb<1, uint_32>; + groupUin?: pb<4, uint_32>; + eventParam?: pb<5, bytes>; + recall?: pb<11, GroupRecall>; + field13?: pb<13, uint_32>; + operatorUid?: pb<21, string>; + generalGrayTip?: pb<26, GeneralGrayTipInfo>; + essenceMessage?: pb<33, EssenceMessage>; + msgSequence?: pb<37, uint_32>; + field39?: pb<39, uint_32>; +} + +// ─── Event0x2DC subType=16: GroupMsgEmojiLike ──────────────────────── + +export interface GroupReactionDataInnerDataTarget { + seq?: pb<1, uint_64>; +} + +export interface GroupReactionDataContent { + code?: pb<1, string>; + count?: pb<3, uint_32>; + operatorUid?: pb<4, string>; + type?: pb<5, uint_32>; +} + +export interface GroupReactionDataInnerData { + groupReactionTarget?: pb<2, GroupReactionDataInnerDataTarget>; + groupReactionDataContent?: pb<3, GroupReactionDataContent>; +} + +export interface GroupReactionDataInner { + data?: pb<1, GroupReactionDataInnerData>; +} + +export interface GroupReactionData { + data?: pb<1, GroupReactionDataInner>; +} + +export interface GroupReactNotify { + groupUin?: pb<4, uint_64>; + field13?: pb<13, uint_32>; + groupReactionData?: pb<44, GroupReactionData>; +} diff --git a/packages/core/tests/proton-parity.test.ts b/packages/core/tests/proton-parity.test.ts index 9b356973..5d53c497 100644 --- a/packages/core/tests/proton-parity.test.ts +++ b/packages/core/tests/proton-parity.test.ts @@ -28,6 +28,14 @@ import { PushMsgBodySchema, PushMsgSchema, } from '../src/bridge/proto/message'; +import { + GroupChangeSchema, + GroupAdminSchema, + NotifyMessageBodySchema, + GroupReactNotifySchema, + FriendRequestSchema, + GroupJoinSchema, +} from '../src/bridge/proto/notify'; import type { SendLongMsgResp, @@ -50,6 +58,14 @@ import type { PushMsgBody, PushMsg, } from '../src/bridge/proto/proton/message'; +import type { + GroupChange, + GroupAdmin, + NotifyMessageBody, + GroupReactNotify, + FriendRequest as FriendRequestNotify, + GroupJoin, +} from '../src/bridge/proto/proton/notify'; function hex(buf: Uint8Array): string { return Buffer.from(buf).toString('hex'); @@ -286,6 +302,89 @@ describe('proton ↔ legacy parity (longmsg subset)', () => { expect(hex(proton)).toBe(hex(legacy)); }); + // ── notify.ts coverage ────────────────────────────────────────────── + + it('encodes GroupChange identically', () => { + const data: GroupChange = { + groupUin: 555, + flag: 1, + memberUid: 'u_x', + decreaseType: 130, + operatorBytes: new Uint8Array([1, 2, 3]), + increaseType: 1, + }; + const legacy = protoEncode(data as any, GroupChangeSchema); + const proton = protobuf_encode(data); + expect(hex(proton)).toBe(hex(legacy)); + }); + + it('encodes GroupAdmin (extraEnable variant) identically', () => { + const data: GroupAdmin = { + groupUin: 777, flag: 1, isPromote: true, + body: { extraEnable: { adminUid: 'u_admin', isPromote: true } }, + }; + const legacy = protoEncode(data as any, GroupAdminSchema); + const proton = protobuf_encode(data); + expect(hex(proton)).toBe(hex(legacy)); + }); + + it('encodes NotifyMessageBody (recall variant with repeated RecallMessage) identically', () => { + const data: NotifyMessageBody = { + type: 17, + groupUin: 555, + recall: { + operatorUid: 'u_op', + recallMessages: [ + { sequence: 1, time: 100, random: 42, type: 1, flag: 1, authorUid: 'u_a' }, + { sequence: 2, time: 200, random: 43, type: 1, flag: 1, authorUid: 'u_a' }, + ], + groupType: 1, opType: 2, + tipInfo: { tip: 'recalled' }, + }, + msgSequence: 99, + }; + const legacy = protoEncode(data as any, NotifyMessageBodySchema); + const proton = protobuf_encode(data); + expect(hex(proton)).toBe(hex(legacy)); + }); + + it('encodes GroupReactNotify (deeply nested) identically', () => { + const data: GroupReactNotify = { + groupUin: 555n, + field13: 35, + groupReactionData: { + data: { + data: { + groupReactionTarget: { seq: 12345n }, + groupReactionDataContent: { code: '128516', count: 1, operatorUid: 'u_op', type: 1 }, + }, + }, + }, + }; + const legacy = protoEncode(data as any, GroupReactNotifySchema); + const proton = protobuf_encode(data); + expect(hex(proton)).toBe(hex(legacy)); + }); + + it('encodes FriendRequest identically', () => { + const data: FriendRequestNotify = { + info: { targetUid: 'u_me', sourceUid: 'u_them', newSource: 'qrcode', message: 'hello!', source: 'web' }, + }; + const legacy = protoEncode(data as any, FriendRequestSchema); + const proton = protobuf_encode(data); + expect(hex(proton)).toBe(hex(legacy)); + }); + + it('encodes GroupJoin identically', () => { + const data: GroupJoin = { + groupUin: 555, field2: 1, targetUid: 'u_them', field4: 1, + field6: 1, field7: 'reason', field8: 1, field9: new Uint8Array([0xaa]), + }; + const legacy = protoEncode(data as any, GroupJoinSchema); + const proton = protobuf_encode(data); + expect(hex(proton)).toBe(hex(legacy)); + }); + // ── Documented divergence: proto3 default-value omission ──────────── it('proton omits default-valued numeric fields (legacy emits them)', () => { From ccc31a760c0d0e5c163d78c276e76582bbc42c7d Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Mon, 18 May 2026 23:38:21 +0800 Subject: [PATCH 17/48] feat(proton): migrate action.ts schemas + bridge.ts + element-builder.ts MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Mirrors all 11 schemas in bridge/proto/action.ts as proton interface forms and switches the two consumers (element-builder.ts and the send-message paths in bridge.ts) over to the new compile-time API. Migrated schemas (proton/action.ts): RoutingC2C, RoutingGroup, RoutingHead, SendContentHead, MessageControl, SendRichText, SendMessageBody, SendMessageRequest, SendMessageResponse, MentionExtraSend, MarkdownData Consumer switches: - element-builder.ts: protobuf_encode for @ mention pbReserve payload; protobuf_encode for markdown elem - bridge.ts: protobuf_encode + protobuf_decode for both sendGroupMessage and sendPrivateMessage The `ProtoElem` type alias in element-builder.ts (Partial>) stays as-is — it's a pure TS type used internally for building elem objects and doesn't affect runtime behaviour. Replacing it with the proton Elem type is a larger refactor that can come later when there's a reason to. Verification: - 6 new parity tests for action schemas (RoutingHead c2c+grp, SendMessageRequest full shape, SendMessageResponse, MentionExtraSend, MarkdownData) - 591/591 core test suite passes — the existing send-message and element-builder tests implicitly validated wire format equivalence - tsc --noEmit clean --- packages/core/src/bridge/bridge.ts | 32 +++---- packages/core/src/bridge/element-builder.ts | 16 ++-- .../core/src/bridge/proto/proton/action.ts | 93 +++++++++++++++++++ packages/core/tests/proton-parity.test.ts | 78 ++++++++++++++++ 4 files changed, 195 insertions(+), 24 deletions(-) create mode 100644 packages/core/src/bridge/proto/proton/action.ts diff --git a/packages/core/src/bridge/bridge.ts b/packages/core/src/bridge/bridge.ts index b6c6c1fc..5f032774 100644 --- a/packages/core/src/bridge/bridge.ts +++ b/packages/core/src/bridge/bridge.ts @@ -7,16 +7,16 @@ import type { ForwardNodePayload, QQEventVariant, MessageElement } from './event import type { FriendInfo, QQGroupInfo, GroupMemberInfo, UserProfileInfo, GroupRequestInfo } from './qq-info'; import { MSG_PUSH_CMD, parseMsgPush } from './msg-push'; import type { PacketSender, SendPacketResult } from '../protocol/packet-sender'; -import { protoEncode, protoDecode } from '../protobuf/decode'; +import { protobuf_encode, protobuf_decode } from '@snowluma/proton'; import { buildSendElems } from './element-builder'; import { IdentityService } from './identity-service'; import type { BridgeInterface } from './bridge-interface'; import { IncomingPacketPipeline, type CmdParser } from './packet-pipeline'; import { createLogger } from '../utils/logger'; -import { - SendMessageRequestSchema, - SendMessageResponseSchema, -} from './proto/action'; +import type { + SendMessageRequest, + SendMessageResponse, +} from './proto/proton/action'; // Delegated modules import { @@ -282,13 +282,13 @@ export class Bridge implements BridgeInterface { const protoElems = await buildSendElems(elements, { bridge: this, groupId }); const random = this.nextMessageRandom(); - const request = protoEncode({ + const request = protobuf_encode({ routingHead: { grp: { groupCode: BigInt(groupId) }, - } as any, + }, contentHead: { type: 1, - } as any, + }, messageBody: { richText: { elems: protoElems, @@ -300,7 +300,7 @@ export class Bridge implements BridgeInterface { via: 0, dataStatist: 0, multiSendSeq: 0, - }, SendMessageRequestSchema); + }); const result = await this.sendRawPacket(Bridge.SEND_MSG_CMD, request); @@ -308,7 +308,7 @@ export class Bridge implements BridgeInterface { throw new Error(`send group message failed: ${result.errorMessage || 'no response'}`); } - const response = protoDecode(result.responseData, SendMessageResponseSchema); + const response = protobuf_decode(result.responseData); if (!response) { throw new Error('failed to decode SendMessageResponse'); } @@ -343,18 +343,18 @@ export class Bridge implements BridgeInterface { const random = this.nextMessageRandom(); const clientSeq = this.nextClientSequence(); - const request = protoEncode({ + const request = protobuf_encode({ routingHead: { c2c: { uin: userUin, ...(userUid ? { uid: userUid } : {}), }, - } as any, + }, contentHead: { type: 1, subType: 0, c2cCmd: 11, - } as any, + }, messageBody: { richText: { elems: protoElems, @@ -367,9 +367,9 @@ export class Bridge implements BridgeInterface { dataStatist: 0, ctrl: { msgFlag: Math.floor(Date.now() / 1000), - } as any, + }, multiSendSeq: 0, - }, SendMessageRequestSchema); + }); const result = await this.sendRawPacket(Bridge.SEND_MSG_CMD, request); @@ -377,7 +377,7 @@ export class Bridge implements BridgeInterface { throw new Error(`send private message failed: ${result.errorMessage || 'no response'}`); } - const response = protoDecode(result.responseData, SendMessageResponseSchema); + const response = protobuf_decode(result.responseData); if (!response) { throw new Error('failed to decode SendMessageResponse'); } diff --git a/packages/core/src/bridge/element-builder.ts b/packages/core/src/bridge/element-builder.ts index 74217fd4..a2840292 100644 --- a/packages/core/src/bridge/element-builder.ts +++ b/packages/core/src/bridge/element-builder.ts @@ -5,14 +5,14 @@ import type { Bridge } from './bridge'; import type { MessageElement } from './events'; import type { ProtoDecoded } from '../protobuf/decode'; -import { protoEncode } from '../protobuf/decode'; +import { protobuf_encode } from '@snowluma/proton'; import { ElemSchema, } from './proto/element'; -import { - MentionExtraSendSchema, - MarkdownDataSchema, -} from './proto/action'; +import type { + MentionExtraSend, + MarkdownData, +} from './proto/proton/action'; import { uploadImageMsgInfo } from './highway/image-upload'; import { uploadPttMsgInfo } from './highway/ptt-upload'; import { uploadVideoMsgInfo } from './highway/video-upload'; @@ -51,12 +51,12 @@ function makeMentionElem(element: MessageElement, ctx?: SendContext): ProtoElem const mentionAll = element.uid === 'all' || element.targetUin === 0; const targetUin = element.targetUin ?? 0; - const extra = protoEncode({ + const extra = protobuf_encode({ type: mentionAll ? 1 : 2, uin: mentionAll ? 0 : targetUin, field5: 0, uid: mentionAll ? 'all' : (element.uid ?? ''), - }, MentionExtraSendSchema); + }); // Prefer an explicit display string from the caller; otherwise look the // target up in the roster so QQ renders `@昵称` instead of `@QQ号`. @@ -128,7 +128,7 @@ function makeXmlElem(element: MessageElement): ProtoElem { } function makeMarkdownElem(element: MessageElement): ProtoElem { - const data = protoEncode({ content: element.text ?? '' }, MarkdownDataSchema); + const data = protobuf_encode({ content: element.text ?? '' }); return { commonElem: { diff --git a/packages/core/src/bridge/proto/proton/action.ts b/packages/core/src/bridge/proto/proton/action.ts new file mode 100644 index 00000000..b500f60e --- /dev/null +++ b/packages/core/src/bridge/proto/proton/action.ts @@ -0,0 +1,93 @@ +// Proton (compile-time) form of bridge/proto/action.ts. +// One-to-one mirror; legacy `*Schema` constants stay alongside for back-compat. + +import type { pb, pb_repeated, int_32, uint_32, uint_64, bytes } from '@snowluma/proton'; +import type { Elem } from './element'; + +// ── Routing ───────────────────────────────────────────────────────── + +export interface RoutingC2C { + uin?: pb<1, uint_32>; + uid?: pb<2, string>; +} + +export interface RoutingGroup { + groupCode?: pb<1, uint_64>; +} + +export interface RoutingHead { + c2c?: pb<1, RoutingC2C>; + grp?: pb<2, RoutingGroup>; +} + +// ── Content Head (for send) ───────────────────────────────────────── + +export interface SendContentHead { + type?: pb<1, uint_32>; + subType?: pb<2, uint_32>; + c2cCmd?: pb<3, uint_32>; +} + +// ── Message Control ───────────────────────────────────────────────── + +export interface MessageControl { + msgFlag?: pb<1, int_32>; +} + +// ── RichText (for send — only elems) ──────────────────────────────── + +export interface SendRichText { + elems?: pb_repeated<2, Elem>; +} + +// ── MessageBody (for send) ────────────────────────────────────────── + +export interface SendMessageBody { + richText?: pb<1, SendRichText>; +} + +// ── SendMessageRequest ────────────────────────────────────────────── + +export interface SendMessageRequest { + routingHead?: pb<1, RoutingHead>; + contentHead?: pb<2, SendContentHead>; + messageBody?: pb<3, SendMessageBody>; + clientSequence?: pb<4, uint_32>; + random?: pb<5, uint_32>; + syncCookie?: pb<6, bytes>; + via?: pb<8, uint_32>; + dataStatist?: pb<9, uint_32>; + ctrl?: pb<12, MessageControl>; + multiSendSeq?: pb<14, uint_32>; +} + +// ── SendMessageResponse ───────────────────────────────────────────── + +export interface SendMessageResponse { + result?: pb<1, int_32>; + errMsg?: pb<2, string>; + timestamp1?: pb<3, uint_32>; + field10?: pb<10, uint_32>; + groupSequence?: pb<11, uint_32>; + timestamp2?: pb<12, uint_32>; + privateSequence?: pb<14, uint_32>; +} + +// ── MentionExtra (for building @mention text element) ─────────────── +// +// Same wire shape as element.ts's MentionExtra (which is used for decoding +// inbound mentions) — kept under a distinct name to mark the send-side +// usage, matching the legacy convention. + +export interface MentionExtraSend { + type?: pb<3, int_32>; + uin?: pb<4, uint_32>; + field5?: pb<5, int_32>; + uid?: pb<9, string>; +} + +// ── MarkdownData ──────────────────────────────────────────────────── + +export interface MarkdownData { + content?: pb<1, string>; +} diff --git a/packages/core/tests/proton-parity.test.ts b/packages/core/tests/proton-parity.test.ts index 5d53c497..a53aad4d 100644 --- a/packages/core/tests/proton-parity.test.ts +++ b/packages/core/tests/proton-parity.test.ts @@ -36,6 +36,13 @@ import { FriendRequestSchema, GroupJoinSchema, } from '../src/bridge/proto/notify'; +import { + RoutingHeadSchema, + SendMessageRequestSchema, + SendMessageResponseSchema, + MentionExtraSendSchema, + MarkdownDataSchema, +} from '../src/bridge/proto/action'; import type { SendLongMsgResp, @@ -66,6 +73,13 @@ import type { FriendRequest as FriendRequestNotify, GroupJoin, } from '../src/bridge/proto/proton/notify'; +import type { + RoutingHead, + SendMessageRequest, + SendMessageResponse, + MentionExtraSend, + MarkdownData, +} from '../src/bridge/proto/proton/action'; function hex(buf: Uint8Array): string { return Buffer.from(buf).toString('hex'); @@ -385,6 +399,70 @@ describe('proton ↔ legacy parity (longmsg subset)', () => { expect(hex(proton)).toBe(hex(legacy)); }); + // ── action.ts coverage ───────────────────────────────────────────── + + it('encodes RoutingHead (c2c variant) identically', () => { + const data: RoutingHead = { c2c: { uin: 10001, uid: 'u_a' } }; + const legacy = protoEncode(data as any, RoutingHeadSchema); + const proton = protobuf_encode(data); + expect(hex(proton)).toBe(hex(legacy)); + }); + + it('encodes RoutingHead (group variant) identically', () => { + const data: RoutingHead = { grp: { groupCode: 555n } }; + const legacy = protoEncode(data as any, RoutingHeadSchema); + const proton = protobuf_encode(data); + expect(hex(proton)).toBe(hex(legacy)); + }); + + it('encodes SendMessageRequest (group with two text elements) identically', () => { + const data: SendMessageRequest = { + routingHead: { grp: { groupCode: 555n } }, + contentHead: { type: 1, subType: 1, c2cCmd: 11 }, + messageBody: { + richText: { + elems: [ + { text: { str: 'hi ' } }, + { text: { str: 'world', link: 'lnk' } }, + ], + }, + }, + clientSequence: 1, + random: 12345, + syncCookie: new Uint8Array([0xaa, 0xbb]), + via: 1, + dataStatist: 1, + multiSendSeq: 1, + }; + const legacy = protoEncode(data as any, SendMessageRequestSchema); + const proton = protobuf_encode(data); + expect(hex(proton)).toBe(hex(legacy)); + }); + + it('encodes SendMessageResponse identically', () => { + const data: SendMessageResponse = { + result: 1, errMsg: 'ok', timestamp1: 1234567890, + field10: 1, groupSequence: 100, timestamp2: 1234567891, privateSequence: 200, + }; + const legacy = protoEncode(data as any, SendMessageResponseSchema); + const proton = protobuf_encode(data); + expect(hex(proton)).toBe(hex(legacy)); + }); + + it('encodes MentionExtraSend identically', () => { + const data: MentionExtraSend = { type: 2, uin: 10001, field5: 1, uid: 'u_a' }; + const legacy = protoEncode(data as any, MentionExtraSendSchema); + const proton = protobuf_encode(data); + expect(hex(proton)).toBe(hex(legacy)); + }); + + it('encodes MarkdownData identically', () => { + const data: MarkdownData = { content: '**bold** _italic_' }; + const legacy = protoEncode(data as any, MarkdownDataSchema); + const proton = protobuf_encode(data); + expect(hex(proton)).toBe(hex(legacy)); + }); + // ── Documented divergence: proto3 default-value omission ──────────── it('proton omits default-valued numeric fields (legacy emits them)', () => { From 7526622917e34f850a849320d15167c90f203c3a Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Mon, 18 May 2026 23:44:17 +0800 Subject: [PATCH 18/48] feat(proton): migrate highway.ts schemas + highway-client + group-file MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Mirrors all 35 schemas in bridge/proto/highway.ts as proton interface forms and switches the two non-OIDB-wrapped consumers (highway/highway-client.ts and actions/group-file.ts) over to the new compile-time API. Migrated schemas (proton/highway.ts): DataHighwayHead, SegHead, LoginSigHead, ReqDataHighwayHead, RespDataHighwayHead, HighwayDomain, HighwayIPv4, HighwayNetwork, HighwayHash, HighwayMsgInfoBody, NTV2RichMediaHighwayExt, FileUploadUrl, FileUploadHost, FileUploadHostConfig, FileUploadNameInfo, FileUploadClientInfo, FileUploadFileEntry, FileUploadBusiInfo, FileUploadEntry, FileUploadExt, EncodableMediaExtBizInfo, EncodableMediaMsgInfo, HttpConn, HttpConn0x6FF501Request, ServerAddr, ServerInfo, HttpConnResponse, HttpConn0x6FF501Response, NTV2FileType, NTV2FileInfo, NTV2UploadInfo, NTV2ExtBizInfo, NTV2UploadReq, NTV2C2CUserInfo, NTV2GroupInfo, NTV2UploadSceneInfo, NTV2CommonHead, NTV2ClientMeta, NTV2UploadReqHead, NTV2UploadRichMediaReq, NTV2IPv4, NTV2SubFileInfoResp, NTV2UploadRespMsgInfo, NTV2UploadRespBody, NTV2UploadRespHead, NTV2UploadRichMediaResp Consumer switches: - highway/highway-client.ts: protobuf_encode/decode for HttpConn session fetch, ReqDataHighwayHead frames, NTV2RichMediaHighwayExt extend bytes, RespDataHighwayHead per-chunk responses - actions/group-file.ts: protobuf_encode for both group + private file upload ext bytes NOT migrated (depends on the OIDB factory pattern): - highway/pipeline.ts — uses makeOidbBaseSchema(NTV2UploadRichMediaReqSchema) to wrap the NTV2 upload in an OIDB envelope at runtime. Waits for the oidb.ts migration to land a generic OidbBase form. Verification: - 5 new parity tests for highway schemas (HttpConn0x6FF501 req+resp with the high-numbered 0x501 tag, ReqDataHighwayHead with multiple nested messages, NTV2RichMediaHighwayExt with repeated_bytes, FileUploadExt with the 100/200/400/600/700 high-numbered tags) - 602/602 core test suite passes — the existing image / ptt / video upload tests implicitly validated wire format equivalence - tsc --noEmit clean --- .../core/src/bridge/actions/group-file.ts | 12 +- .../core/src/bridge/highway/highway-client.ts | 33 +- .../core/src/bridge/proto/proton/highway.ts | 333 ++++++++++++++++++ packages/core/tests/proton-parity.test.ts | 116 ++++++ 4 files changed, 471 insertions(+), 23 deletions(-) create mode 100644 packages/core/src/bridge/proto/proton/highway.ts diff --git a/packages/core/src/bridge/actions/group-file.ts b/packages/core/src/bridge/actions/group-file.ts index 06f8c123..1db541e4 100644 --- a/packages/core/src/bridge/actions/group-file.ts +++ b/packages/core/src/bridge/actions/group-file.ts @@ -6,7 +6,7 @@ // stay as separate functions. import type { Bridge } from '../bridge'; -import { protoEncode } from '../../protobuf/decode'; +import { protobuf_encode } from '@snowluma/proton'; import { runOidb } from '../bridge-oidb'; import { fetchHighwaySession, uploadHighwayHttp } from '../highway/highway-client'; import { computeHashes, computeMd5, FILE_UPLOAD_MAX_BYTES, loadBinarySource } from '../highway/utils'; @@ -26,7 +26,7 @@ import { NTV2RichMediaReqSchema, NTV2RichMediaRespSchema, } from '../proto/oidb-action'; -import { FileUploadExtSchema } from '../proto/highway'; +import type { FileUploadExt } from '../proto/proton/highway'; import { toHexUpper } from '../../utils/hex'; import { ensureRetCodeZero, resolveSelfUid, toInt, type MediaIndexNode } from './shared'; @@ -104,7 +104,7 @@ function buildGroupFileUploadExt( uploadHost: string, uploadPort: number, ): Uint8Array { - return protoEncode({ + return protobuf_encode({ unknown1: 100, unknown2: 1, entry: { @@ -145,7 +145,7 @@ function buildGroupFileUploadExt( }, }, unknown200: 0, - }, FileUploadExtSchema); + }); } function buildPrivateFileUploadExt( @@ -159,7 +159,7 @@ function buildPrivateFileUploadExt( uploadHost: string, uploadPort: number, ): Uint8Array { - return protoEncode({ + return protobuf_encode({ unknown1: 100, unknown2: 1, entry: { @@ -201,7 +201,7 @@ function buildPrivateFileUploadExt( }, unknown3: 0, unknown200: 1, - }, FileUploadExtSchema); + }); } function normalizeMediaNode(node: MediaIndexNode): Record { diff --git a/packages/core/src/bridge/highway/highway-client.ts b/packages/core/src/bridge/highway/highway-client.ts index 99d3c385..bab560f8 100644 --- a/packages/core/src/bridge/highway/highway-client.ts +++ b/packages/core/src/bridge/highway/highway-client.ts @@ -3,15 +3,14 @@ import net from 'net'; import type { Bridge } from '../bridge'; -import { protoEncode, protoDecode } from '../../protobuf/decode'; -import { - HttpConn0x6FF501RequestSchema, - HttpConn0x6FF501ResponseSchema, - ReqDataHighwayHeadSchema, - RespDataHighwayHeadSchema, - NTV2RichMediaHighwayExtSchema, - HighwayMsgInfoBodySchema, -} from '../proto/highway'; +import { protobuf_encode, protobuf_decode } from '@snowluma/proton'; +import type { + HttpConn0x6FF501Request, + HttpConn0x6FF501Response, + ReqDataHighwayHead, + RespDataHighwayHead, + NTV2RichMediaHighwayExt, +} from '../proto/proton/highway'; import { packHighwayFrame, unpackHighwayFrame, computeMd5 } from './utils'; const HIGHWAY_APP_ID = 1600001604; @@ -32,20 +31,20 @@ function ipv4ToString(value: number): string { } export async function fetchHighwaySession(bridge: Bridge): Promise { - const request = protoEncode({ + const request = protobuf_encode({ httpConn: { field1: 0, field2: 0, field3: 16, field4: 1, field6: 3, serviceTypes: [1, 5, 10, 21], field9: 2, field10: 9, field11: 8, ver: '1.0.1', }, - }, HttpConn0x6FF501RequestSchema); + }); const result = await bridge.sendRawPacket('HttpConn.0x6ff_501', request); if (!result.success || !result.gotResponse || !result.responseData) { throw new Error(result.errorMessage || 'HttpConn request failed'); } - const resp = protoDecode(result.responseData, HttpConn0x6FF501ResponseSchema); + const resp = protobuf_decode(result.responseData); if (!resp?.httpConn) throw new Error('HttpConn response body missing'); if (!resp.httpConn.sigSession || (resp.httpConn.sigSession as Uint8Array).length === 0) { throw new Error('HttpConn response missing sig_session'); @@ -78,7 +77,7 @@ function makeHighwayHead( uin: string, commandId: number, fileSize: number, offset: number, length: number, chunkMd5: Uint8Array, fileMd5: Uint8Array, sigSession: Uint8Array, extend: Uint8Array, ): Uint8Array { - return protoEncode({ + return protobuf_encode({ msgBaseHead: { version: 1, uin, command: 'PicUp.DataUp', seq: 0, retryTimes: 0, appId: HIGHWAY_APP_ID, dataFlag: 16, commandId, @@ -90,7 +89,7 @@ function makeHighwayHead( bytesReqExtendInfo: extend, timestamp: 0n, msgLoginSigHead: { loginSigType: 8, appId: HIGHWAY_APP_ID }, - }, ReqDataHighwayHeadSchema); + }); } export function buildHighwayExtend( @@ -113,7 +112,7 @@ export function buildHighwayExtend( } } - return protoEncode({ + return protobuf_encode({ fileUuid: selected?.index?.fileUuid ?? '', uKey, network: { ipv4s: networkIpv4s }, @@ -122,7 +121,7 @@ export function buildHighwayExtend( })), blockSize: HIGHWAY_BLOCK_SIZE, hash: { fileSha1: Array.isArray(sha1) ? sha1 : [sha1] }, - }, NTV2RichMediaHighwayExtSchema); + }); } // --- TCP-based HTTP highway upload --- @@ -241,7 +240,7 @@ export async function uploadHighwayHttp( const frame = packHighwayFrame(head, chunk); const responseBody = await httpPostFrame(socket, session.host, pathStr, frame); const { head: respHead } = unpackHighwayFrame(responseBody); - const resp = protoDecode(respHead, RespDataHighwayHeadSchema); + const resp = protobuf_decode(respHead); if (resp?.errorCode && resp.errorCode !== 0) { throw new Error(`highway upload error_code=${resp.errorCode}`); } diff --git a/packages/core/src/bridge/proto/proton/highway.ts b/packages/core/src/bridge/proto/proton/highway.ts new file mode 100644 index 00000000..eef6ee84 --- /dev/null +++ b/packages/core/src/bridge/proto/proton/highway.ts @@ -0,0 +1,333 @@ +// Proton (compile-time) form of bridge/proto/highway.ts. +// One-to-one mirror; legacy `*Schema` constants stay alongside for back-compat. + +import type { pb, pb_repeated, int_32, uint_32, uint_64, bool, bytes } from '@snowluma/proton'; +import type { + IndexNode, + PictureInfo, + HashSum, + PicExtBizInfo, + VideoExtBizInfo, + PttExtBizInfo, +} from './element'; + +// ── DataHighwayHead ───────────────────────────────────────────────── + +export interface DataHighwayHead { + version?: pb<1, uint_32>; + uin?: pb<2, string>; + command?: pb<3, string>; + seq?: pb<4, uint_32>; + retryTimes?: pb<5, uint_32>; + appId?: pb<6, uint_32>; + dataFlag?: pb<7, uint_32>; + commandId?: pb<8, uint_32>; +} + +export interface SegHead { + serviceId?: pb<1, uint_32>; + filesize?: pb<2, uint_64>; + dataOffset?: pb<3, uint_64>; + dataLength?: pb<4, uint_32>; + retCode?: pb<5, uint_32>; + serviceTicket?: pb<6, bytes>; + flag?: pb<7, uint_32>; + md5?: pb<8, bytes>; + fileMd5?: pb<9, bytes>; + cacheAddr?: pb<10, uint_32>; + cachePort?: pb<13, uint_32>; +} + +export interface LoginSigHead { + loginSigType?: pb<1, uint_32>; + appId?: pb<3, uint_32>; +} + +export interface ReqDataHighwayHead { + msgBaseHead?: pb<1, DataHighwayHead>; + msgSegHead?: pb<2, SegHead>; + bytesReqExtendInfo?: pb<3, bytes>; + timestamp?: pb<4, uint_64>; + msgLoginSigHead?: pb<5, LoginSigHead>; +} + +export interface RespDataHighwayHead { + msgBaseHead?: pb<1, DataHighwayHead>; + msgSegHead?: pb<2, SegHead>; + errorCode?: pb<3, uint_32>; +} + +// ── Highway extend (NTV2RichMediaHighwayExt) ──────────────────────── + +export interface HighwayDomain { + isEnable?: pb<1, bool>; + ip?: pb<2, string>; +} + +export interface HighwayIPv4 { + domain?: pb<1, HighwayDomain>; + port?: pb<2, uint_32>; +} + +export interface HighwayNetwork { + ipv4s?: pb_repeated<1, HighwayIPv4>; +} + +export interface HighwayHash { + fileSha1?: pb_repeated<1, bytes>; +} + +export interface HighwayMsgInfoBody { + index?: pb<1, IndexNode>; + picture?: pb<2, PictureInfo>; + fileExist?: pb<5, bool>; + hashSum?: pb<6, HashSum>; +} + +export interface NTV2RichMediaHighwayExt { + fileUuid?: pb<1, string>; + uKey?: pb<2, string>; + network?: pb<5, HighwayNetwork>; + msgInfoBody?: pb_repeated<6, HighwayMsgInfoBody>; + blockSize?: pb<10, uint_32>; + hash?: pb<11, HighwayHash>; +} + +// ── File upload extend (group/private file highway) ───────────────── + +export interface FileUploadUrl { + unknown?: pb<1, int_32>; + host?: pb<2, string>; +} + +export interface FileUploadHost { + url?: pb<1, FileUploadUrl>; + port?: pb<2, uint_32>; +} + +export interface FileUploadHostConfig { + hosts?: pb_repeated<200, FileUploadHost>; +} + +export interface FileUploadNameInfo { + fileName?: pb<100, string>; +} + +export interface FileUploadClientInfo { + clientType?: pb<100, int_32>; + appId?: pb<200, string>; + terminalType?: pb<300, int_32>; + clientVer?: pb<400, string>; + unknown?: pb<600, int_32>; +} + +export interface FileUploadFileEntry { + fileSize?: pb<100, uint_64>; + md5?: pb<200, bytes>; + checkKey?: pb<300, bytes>; + md5S2?: pb<400, bytes>; + fileId?: pb<600, string>; + uploadKey?: pb<700, bytes>; +} + +export interface FileUploadBusiInfo { + busId?: pb<1, int_32>; + senderUin?: pb<100, uint_64>; + receiverUin?: pb<200, uint_64>; + groupCode?: pb<400, uint_64>; +} + +export interface FileUploadEntry { + busiBuff?: pb<100, FileUploadBusiInfo>; + fileEntry?: pb<200, FileUploadFileEntry>; + clientInfo?: pb<300, FileUploadClientInfo>; + fileNameInfo?: pb<400, FileUploadNameInfo>; + host?: pb<500, FileUploadHostConfig>; +} + +export interface FileUploadExt { + unknown1?: pb<1, int_32>; + unknown2?: pb<2, int_32>; + unknown3?: pb<3, int_32>; + entry?: pb<100, FileUploadEntry>; + unknown200?: pb<200, int_32>; +} + +// ── Encodable MsgInfo (for embedding in message element) ──────────── + +export interface EncodableMediaExtBizInfo { + pic?: pb<1, PicExtBizInfo>; + video?: pb<2, VideoExtBizInfo>; + ptt?: pb<3, PttExtBizInfo>; + busiType?: pb<10, uint_32>; +} + +export interface EncodableMediaMsgInfo { + msgInfoBody?: pb_repeated<1, HighwayMsgInfoBody>; + extBizInfo?: pb<2, EncodableMediaExtBizInfo>; +} + +// ── HttpConn.0x6ff_501 (highway session) ──────────────────────────── + +export interface HttpConn { + field1?: pb<1, int_32>; + field2?: pb<2, int_32>; + field3?: pb<3, int_32>; + field4?: pb<4, int_32>; + field6?: pb<6, int_32>; + serviceTypes?: pb_repeated<7, uint_32>; + field9?: pb<9, int_32>; + field10?: pb<10, int_32>; + field11?: pb<11, int_32>; + ver?: pb<15, string>; +} + +export interface HttpConn0x6FF501Request { + httpConn?: pb<0x501, HttpConn>; +} + +export interface ServerAddr { + type?: pb<1, uint_32>; + ip?: pb<2, uint_32>; + port?: pb<3, uint_32>; + area?: pb<4, uint_32>; +} + +export interface ServerInfo { + serviceType?: pb<1, uint_32>; + serverAddrs?: pb_repeated<2, ServerAddr>; +} + +export interface HttpConnResponse { + sigSession?: pb<1, bytes>; + sessionKey?: pb<2, bytes>; + serverInfos?: pb_repeated<3, ServerInfo>; +} + +export interface HttpConn0x6FF501Response { + httpConn?: pb<0x501, HttpConnResponse>; +} + +// ── NTV2 Upload Request (for OIDB 0x11C4/0x11C5) ──────────────────── + +export interface NTV2FileType { + type?: pb<1, uint_32>; + picFormat?: pb<2, uint_32>; + videoFormat?: pb<3, uint_32>; + voiceFormat?: pb<4, uint_32>; +} + +export interface NTV2FileInfo { + fileSize?: pb<1, uint_32>; + fileHash?: pb<2, string>; + fileSha1?: pb<3, string>; + fileName?: pb<4, string>; + type?: pb<5, NTV2FileType>; + width?: pb<6, uint_32>; + height?: pb<7, uint_32>; + time?: pb<8, uint_32>; + original?: pb<9, uint_32>; +} + +export interface NTV2UploadInfo { + fileInfo?: pb<1, NTV2FileInfo>; + subFileType?: pb<2, uint_32>; +} + +// The NTV2 upload request + response carry the same ExtBizInfo shape that +// element-side incoming-message decoding uses. See bridge/proto/highway.ts +// for the rationale (the video fromScene/toScene drop was responsible for +// c2c result=79 rejections on send_private_msg [{type:'video'}]). +export interface NTV2ExtBizInfo { + pic?: pb<1, PicExtBizInfo>; + video?: pb<2, VideoExtBizInfo>; + ptt?: pb<3, PttExtBizInfo>; + busiType?: pb<10, uint_32>; +} + +export interface NTV2UploadReq { + uploadInfo?: pb_repeated<1, NTV2UploadInfo>; + tryFastUploadCompleted?: pb<2, bool>; + srvSendMsg?: pb<3, bool>; + clientRandomId?: pb<4, uint_64>; + compatQmsgSceneType?: pb<5, uint_32>; + extBizInfo?: pb<6, NTV2ExtBizInfo>; + clientSeq?: pb<7, uint_32>; + noNeedCompatMsg?: pb<8, bool>; +} + +export interface NTV2C2CUserInfo { + accountType?: pb<1, uint_32>; + targetUid?: pb<2, string>; +} + +export interface NTV2GroupInfo { + groupUin?: pb<1, uint_32>; +} + +export interface NTV2UploadSceneInfo { + requestType?: pb<101, uint_32>; + businessType?: pb<102, uint_32>; + sceneType?: pb<200, uint_32>; + c2c?: pb<201, NTV2C2CUserInfo>; + group?: pb<202, NTV2GroupInfo>; +} + +export interface NTV2CommonHead { + requestId?: pb<1, uint_32>; + command?: pb<2, uint_32>; +} + +export interface NTV2ClientMeta { + agentType?: pb<1, uint_32>; +} + +export interface NTV2UploadReqHead { + common?: pb<1, NTV2CommonHead>; + scene?: pb<2, NTV2UploadSceneInfo>; + client?: pb<3, NTV2ClientMeta>; +} + +export interface NTV2UploadRichMediaReq { + reqHead?: pb<1, NTV2UploadReqHead>; + upload?: pb<2, NTV2UploadReq>; +} + +// ── NTV2 Upload Response ──────────────────────────────────────────── + +export interface NTV2IPv4 { + outIp?: pb<1, uint_32>; + outPort?: pb<2, uint_32>; +} + +export interface NTV2SubFileInfoResp { + subType?: pb<1, uint_32>; + uKey?: pb<2, string>; + uKeyTtl?: pb<3, uint_32>; + ipv4s?: pb_repeated<4, NTV2IPv4>; +} + +export interface NTV2UploadRespMsgInfo { + msgInfoBody?: pb_repeated<1, HighwayMsgInfoBody>; + extBizInfo?: pb<2, NTV2ExtBizInfo>; +} + +export interface NTV2UploadRespBody { + uKey?: pb<1, string>; + uKeyTtl?: pb<2, uint_32>; + ipv4s?: pb_repeated<3, NTV2IPv4>; + msgSeq?: pb<5, uint_64>; + msgInfo?: pb<6, NTV2UploadRespMsgInfo>; + subFileInfos?: pb_repeated<10, NTV2SubFileInfoResp>; +} + +export interface NTV2UploadRespHead { + common?: pb<1, NTV2CommonHead>; + retCode?: pb<2, uint_32>; + message?: pb<3, string>; +} + +export interface NTV2UploadRichMediaResp { + respHead?: pb<1, NTV2UploadRespHead>; + upload?: pb<2, NTV2UploadRespBody>; +} diff --git a/packages/core/tests/proton-parity.test.ts b/packages/core/tests/proton-parity.test.ts index a53aad4d..6459730c 100644 --- a/packages/core/tests/proton-parity.test.ts +++ b/packages/core/tests/proton-parity.test.ts @@ -43,6 +43,13 @@ import { MentionExtraSendSchema, MarkdownDataSchema, } from '../src/bridge/proto/action'; +import { + HttpConn0x6FF501RequestSchema, + HttpConn0x6FF501ResponseSchema, + ReqDataHighwayHeadSchema, + NTV2RichMediaHighwayExtSchema, + FileUploadExtSchema, +} from '../src/bridge/proto/highway'; import type { SendLongMsgResp, @@ -80,6 +87,13 @@ import type { MentionExtraSend, MarkdownData, } from '../src/bridge/proto/proton/action'; +import type { + HttpConn0x6FF501Request, + HttpConn0x6FF501Response, + ReqDataHighwayHead, + NTV2RichMediaHighwayExt, + FileUploadExt, +} from '../src/bridge/proto/proton/highway'; function hex(buf: Uint8Array): string { return Buffer.from(buf).toString('hex'); @@ -463,6 +477,108 @@ describe('proton ↔ legacy parity (longmsg subset)', () => { expect(hex(proton)).toBe(hex(legacy)); }); + // ── highway.ts coverage ──────────────────────────────────────────── + + it('encodes HttpConn0x6FF501Request (high-numbered field tag 0x501) identically', () => { + const data: HttpConn0x6FF501Request = { + httpConn: { + field1: 1, field2: 2, field3: 16, field4: 1, field6: 3, + serviceTypes: [1, 5, 10, 21], + field9: 2, field10: 9, field11: 8, ver: '1.0.1', + }, + }; + const legacy = protoEncode(data as any, HttpConn0x6FF501RequestSchema); + const proton = protobuf_encode(data); + expect(hex(proton)).toBe(hex(legacy)); + }); + + it('encodes HttpConn0x6FF501Response (with repeated server infos) identically', () => { + const data: HttpConn0x6FF501Response = { + httpConn: { + sigSession: new Uint8Array([1, 2, 3]), + sessionKey: new Uint8Array([4, 5, 6]), + serverInfos: [ + { serviceType: 1, serverAddrs: [{ type: 1, ip: 0x01020304, port: 8080, area: 1 }] }, + { serviceType: 2, serverAddrs: [{ type: 1, ip: 0x05060708, port: 8081, area: 2 }] }, + ], + }, + }; + const legacy = protoEncode(data as any, HttpConn0x6FF501ResponseSchema); + const proton = protobuf_encode(data); + expect(hex(proton)).toBe(hex(legacy)); + }); + + it('encodes ReqDataHighwayHead (multiple nested messages) identically', () => { + const data: ReqDataHighwayHead = { + msgBaseHead: { + version: 1, uin: '10001', command: 'PicUp.DataUp', seq: 1, retryTimes: 1, + appId: 1600001604, dataFlag: 16, commandId: 1003, + }, + msgSegHead: { + serviceId: 1, filesize: 100n, dataOffset: 50n, dataLength: 100, + retCode: 1, serviceTicket: new Uint8Array([1, 2, 3]), flag: 1, + md5: new Uint8Array([4, 5, 6]), fileMd5: new Uint8Array([7, 8, 9]), + cacheAddr: 1, cachePort: 80, + }, + bytesReqExtendInfo: new Uint8Array([0xab, 0xcd]), + timestamp: 1234567890n, + msgLoginSigHead: { loginSigType: 8, appId: 1600001604 }, + }; + const legacy = protoEncode(data as any, ReqDataHighwayHeadSchema); + const proton = protobuf_encode(data); + expect(hex(proton)).toBe(hex(legacy)); + }); + + it('encodes NTV2RichMediaHighwayExt (repeated_bytes hash) identically', () => { + const data: NTV2RichMediaHighwayExt = { + fileUuid: 'uuid-1', + uKey: 'key-1', + network: { ipv4s: [{ domain: { isEnable: true, ip: '127.0.0.1' }, port: 80 }] }, + blockSize: 1048576, + hash: { fileSha1: [new Uint8Array([1, 2]), new Uint8Array([3, 4])] }, + }; + const legacy = protoEncode(data as any, NTV2RichMediaHighwayExtSchema); + const proton = protobuf_encode(data); + expect(hex(proton)).toBe(hex(legacy)); + }); + + it('encodes FileUploadExt (high-numbered tags 100/200/400/600/700) identically', () => { + const data: FileUploadExt = { + unknown1: 100, + unknown2: 1, + unknown3: 1, + entry: { + busiBuff: { + busId: 102, + senderUin: 10001n, + receiverUin: 555n, + groupCode: 555n, + }, + fileEntry: { + fileSize: 12345n, + md5: new Uint8Array([0x11, 0x22]), + checkKey: new Uint8Array([0x33, 0x44]), + md5S2: new Uint8Array([0x55]), + fileId: 'file-1', + uploadKey: new Uint8Array([0x66]), + }, + clientInfo: { + clientType: 3, appId: '100', terminalType: 3, clientVer: '1.1.1', unknown: 4, + }, + fileNameInfo: { fileName: 'a.bin' }, + host: { + hosts: [ + { url: { unknown: 1, host: 'upload.qq.com' }, port: 80 }, + ], + }, + }, + unknown200: 1, + }; + const legacy = protoEncode(data as any, FileUploadExtSchema); + const proton = protobuf_encode(data); + expect(hex(proton)).toBe(hex(legacy)); + }); + // ── Documented divergence: proto3 default-value omission ──────────── it('proton omits default-valued numeric fields (legacy emits them)', () => { From c543ce922780e1829d924edeafdb26af0aa457ef Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Mon, 18 May 2026 23:47:42 +0800 Subject: [PATCH 19/48] feat(proton): add proton/oidb.ts with generic OidbBase envelope MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Phase 1 of the OIDB migration: stages the proton-side type definitions and pins their wire equivalence to the legacy makeOidbBaseSchema() runtime factory. No call sites are switched yet — that lands in phase 2 along with the proton/oidb-action.ts schema mirror and the runOidb refactor. The legacy bridge/proto/oidb.ts exports a `makeOidbBaseSchema(body)` factory function that synthesizes the OidbSvcTrpcTcpBase envelope ProtoSchema at runtime. Proton is compile-time, so the natural form is the generic interface OidbBase { command, subCommand, errorCode, body: T, errorMsg, properties, reserved } which the plugin monomorphizes per-instantiation. This is exactly the "generic template with generic-instantiated field" usage that this package's earlier edge-case fixes #2 and #3 were designed to support, and the new parity test pins that they actually work on the real shape (a fully populated OidbSvcTrpcTcp0xFE5_2Response with nested groupOwner/customInfo). Also added: - OidbProperty (for the envelope.properties repeated field) - OidbBaseMeta — envelope-only view for fire-and-check OIDB calls that just need to peek at errorCode without decoding the body - All 8 concrete schemas from oidb.ts (FriendList, GroupList, GroupMemberList, GroupRequest families) Verification: - 2 new parity tests * OidbBase ↔ makeOidbBaseSchema byte equivalence * round-trip encode → decode preserves nested body - 602+2 = 604 core tests pass (network-manager file still env-fails on missing native binary) - tsc --noEmit clean --- packages/core/src/bridge/proto/proton/oidb.ts | 180 ++++++++++++++++++ packages/core/tests/proton-parity.test.ts | 54 ++++++ 2 files changed, 234 insertions(+) create mode 100644 packages/core/src/bridge/proto/proton/oidb.ts diff --git a/packages/core/src/bridge/proto/proton/oidb.ts b/packages/core/src/bridge/proto/proton/oidb.ts new file mode 100644 index 00000000..43fc14a6 --- /dev/null +++ b/packages/core/src/bridge/proto/proton/oidb.ts @@ -0,0 +1,180 @@ +// Proton (compile-time) form of bridge/proto/oidb.ts. +// +// The legacy file exports a `makeOidbBaseSchema(body)` factory that builds the +// OidbSvcTrpcTcpBase envelope at runtime; here that wrapper is expressed +// once as the generic `OidbBase` interface. Every existing +// `makeOidbBaseSchema(InnerSchema)` call site becomes `OidbBase` +// at the type level, and the proton plugin monomorphizes the codec +// per-instantiation at build time. +// +// `OidbBaseMeta` is the envelope-only view used by fire-and-check calls +// that want to peek at the error code without decoding the body. + +import type { pb, pb_repeated, int_32, uint_32, uint_64, bytes } from '@snowluma/proton'; + +// ── OidbSvcTrpcTcpBase wrapper ────────────────────────────────────── + +export interface OidbProperty { + key?: pb<1, string>; + value?: pb<2, bytes>; +} + +export interface OidbBase { + command?: pb<1, uint_32>; + subCommand?: pb<2, uint_32>; + errorCode?: pb<3, uint_32>; + body?: pb<4, TBody>; + errorMsg?: pb<5, string>; + properties?: pb_repeated<11, OidbProperty>; + reserved?: pb<12, int_32>; +} + +/** + * Envelope-only view used by fire-and-check calls — proto3 wire format + * silently skips unknown fields, so decoding any OidbBase message with + * this shape returns just the metadata and ignores the inner body. + */ +export interface OidbBaseMeta { + command?: pb<1, uint_32>; + subCommand?: pb<2, uint_32>; + errorCode?: pb<3, uint_32>; + errorMsg?: pb<5, string>; + reserved?: pb<12, int_32>; +} + +// ── Friend list (0xFD4_1) ─────────────────────────────────────────── + +export interface OidbFriendProperty { + code?: pb<1, uint_32>; + value?: pb<2, string>; +} + +export interface OidbFriendLayer1 { + properties?: pb_repeated<2, OidbFriendProperty>; +} + +export interface OidbFriendAdditional { + type?: pb<1, uint_32>; + layer1?: pb<2, OidbFriendLayer1>; +} + +export interface OidbFriend { + uid?: pb<1, string>; + customGroup?: pb<2, uint_32>; + uin?: pb<3, uint_32>; + additional?: pb_repeated<10001, OidbFriendAdditional>; +} + +export interface OidbSvcTrpcTcp0xFD4_1ResponseUin { + uin?: pb<1, uint_32>; +} + +export interface OidbSvcTrpcTcp0xFD4_1Response { + next?: pb<2, OidbSvcTrpcTcp0xFD4_1ResponseUin>; + displayFriendCount?: pb<3, uint_32>; + timestamp?: pb<6, uint_32>; + selfUin?: pb<7, uint_32>; + friends?: pb_repeated<101, OidbFriend>; + groups?: pb_repeated<102, OidbFriendProperty>; +} + +// ── Group list (0xFE5_2) ──────────────────────────────────────────── + +export interface OidbSvcTrpcTcp0xFE5_2Member { + uid?: pb<2, string>; +} + +export interface OidbSvcTrpcTcp0xFE5_2GroupInfo { + groupOwner?: pb<1, OidbSvcTrpcTcp0xFE5_2Member>; + createdTime?: pb<2, uint_32>; + memberMax?: pb<3, uint_32>; + memberCount?: pb<4, uint_32>; + groupName?: pb<5, string>; + description?: pb<18, string>; + question?: pb<19, string>; + announcement?: pb<30, string>; +} + +export interface OidbSvcTrpcTcp0xFE5_2CustomInfo { + remark?: pb<3, string>; +} + +export interface OidbSvcTrpcTcp0xFE5_2Group { + groupUin?: pb<3, uint_32>; + info?: pb<4, OidbSvcTrpcTcp0xFE5_2GroupInfo>; + customInfo?: pb<5, OidbSvcTrpcTcp0xFE5_2CustomInfo>; +} + +export interface OidbSvcTrpcTcp0xFE5_2Response { + groups?: pb_repeated<2, OidbSvcTrpcTcp0xFE5_2Group>; +} + +// ── Group member list (0xFE7_3) ───────────────────────────────────── + +export interface OidbSvcTrpcTcp0xFE7_3Uin { + uid?: pb<2, string>; + uin?: pb<4, uint_32>; +} + +export interface OidbSvcTrpcTcp0xFE7_3Card { + memberCard?: pb<2, string>; +} + +export interface OidbSvcTrpcTcp0xFE7_3Level { + infos?: pb_repeated<1, uint_32>; + level?: pb<2, uint_32>; +} + +export interface OidbSvcTrpcTcp0xFE7_3Member { + uin?: pb<1, OidbSvcTrpcTcp0xFE7_3Uin>; + memberName?: pb<10, string>; + specialTitle?: pb<17, string>; + memberCard?: pb<11, OidbSvcTrpcTcp0xFE7_3Card>; + level?: pb<12, OidbSvcTrpcTcp0xFE7_3Level>; + joinTimestamp?: pb<100, uint_32>; + lastMsgTimestamp?: pb<101, uint_32>; + shutUpTimestamp?: pb<102, uint_32>; + permission?: pb<107, uint_32>; +} + +export interface OidbSvcTrpcTcp0xFE7_3Response { + groupUin?: pb<1, uint_32>; + members?: pb_repeated<2, OidbSvcTrpcTcp0xFE7_3Member>; + field3?: pb<3, uint_32>; + memberChangeSeq?: pb<5, uint_32>; + memberCardChangeSeq?: pb<6, uint_32>; + token?: pb<15, string>; +} + +// ── Group request (0x10C0) ────────────────────────────────────────── + +export interface OidbSvcTrpcTcp0x10C0ResponseUser { + uid?: pb<1, string>; + name?: pb<2, string>; +} + +export interface OidbSvcTrpcTcp0x10C0ResponseGroup { + groupUin?: pb<1, uint_32>; + groupName?: pb<2, string>; +} + +export interface OidbSvcTrpcTcp0x10C0ResponseRequest { + sequence?: pb<1, uint_64>; + eventType?: pb<2, uint_32>; + state?: pb<3, uint_32>; + group?: pb<4, OidbSvcTrpcTcp0x10C0ResponseGroup>; + target?: pb<5, OidbSvcTrpcTcp0x10C0ResponseUser>; + invitor?: pb<6, OidbSvcTrpcTcp0x10C0ResponseUser>; + operatorUser?: pb<7, OidbSvcTrpcTcp0x10C0ResponseUser>; + field9?: pb<9, string>; + comment?: pb<10, string>; +} + +export interface OidbSvcTrpcTcp0x10C0Response { + requests?: pb_repeated<1, OidbSvcTrpcTcp0x10C0ResponseRequest>; + field2?: pb<2, uint_64>; + newLatestSeq?: pb<3, uint_64>; + field4?: pb<4, uint_32>; + field5?: pb<5, uint_64>; + field6?: pb<6, uint_32>; +} diff --git a/packages/core/tests/proton-parity.test.ts b/packages/core/tests/proton-parity.test.ts index 6459730c..85e966c2 100644 --- a/packages/core/tests/proton-parity.test.ts +++ b/packages/core/tests/proton-parity.test.ts @@ -50,6 +50,7 @@ import { NTV2RichMediaHighwayExtSchema, FileUploadExtSchema, } from '../src/bridge/proto/highway'; +import { makeOidbBaseSchema, OidbSvcTrpcTcp0xFE5_2ResponseSchema } from '../src/bridge/proto/oidb'; import type { SendLongMsgResp, @@ -94,6 +95,10 @@ import type { NTV2RichMediaHighwayExt, FileUploadExt, } from '../src/bridge/proto/proton/highway'; +import type { + OidbBase, + OidbSvcTrpcTcp0xFE5_2Response, +} from '../src/bridge/proto/proton/oidb'; function hex(buf: Uint8Array): string { return Buffer.from(buf).toString('hex'); @@ -579,6 +584,55 @@ describe('proton ↔ legacy parity (longmsg subset)', () => { expect(hex(proton)).toBe(hex(legacy)); }); + // ── oidb.ts coverage (OidbBase generic envelope) ──────────────── + + it('encodes OidbBase identically to makeOidbBaseSchema', () => { + // This is the exact pattern runOidb uses for the OIDB envelope. Proton's + // OidbBase generic interface should monomorphize to a codec that is + // byte-equivalent to the legacy makeOidbBaseSchema(InnerSchema) factory. + // The inner Body type used here is a real schema (group-list response). + const body: OidbSvcTrpcTcp0xFE5_2Response = { + groups: [ + { + groupUin: 555, + info: { + groupOwner: { uid: 'u_owner' }, + createdTime: 1234567890, memberMax: 100, memberCount: 50, + groupName: 'TestGroup', description: 'desc', question: 'q?', + announcement: 'announcement', + }, + customInfo: { remark: 'remark' }, + }, + ], + }; + const envelope = { + command: 0xFE5, + subCommand: 2, + errorCode: 1, // non-zero so it isn't proto3-omitted + body, + errorMsg: 'ok', + reserved: 1, + }; + const legacy = protoEncode(envelope as any, makeOidbBaseSchema(OidbSvcTrpcTcp0xFE5_2ResponseSchema)); + const proton = protobuf_encode>(envelope); + expect(hex(proton)).toBe(hex(legacy)); + }); + + it('round-trips OidbBase with non-trivial nested body', () => { + const body: OidbSvcTrpcTcp0xFE5_2Response = { + groups: [{ groupUin: 100, info: { groupName: 'G' } }], + }; + const envelope: OidbBase = { + command: 0xFE5, subCommand: 2, errorCode: 1, body, errorMsg: 'ok', reserved: 1, + }; + const encoded = protobuf_encode>(envelope); + const decoded = protobuf_decode>(encoded); + expect(decoded.command).toBe(0xFE5); + expect(decoded.errorCode).toBe(1); + expect(decoded.body?.groups?.[0]?.groupUin).toBe(100); + expect(decoded.body?.groups?.[0]?.info?.groupName).toBe('G'); + }); + // ── Documented divergence: proto3 default-value omission ──────────── it('proton omits default-valued numeric fields (legacy emits them)', () => { From 6f3646e956cb27d3f89690fcdd0efa8b3a4aef64 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Mon, 18 May 2026 23:52:38 +0800 Subject: [PATCH 20/48] feat(proton): add proton/oidb-action.ts (183 schema mirrors) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Phase 2 of the OIDB migration: one-to-one mirror of every schema in bridge/proto/oidb-action.ts as a proton interface. Purely additive — the legacy `*Schema` constants stay in place; no call sites are switched yet. Translation is mechanical: - export const XxxSchema = { ... } satisfies ProtoSchema; → export interface Xxx { ... } - { field: N, type: 'uint32' as const } → pb - { field: N, type: 'repeated_message', schema: YSchema } → pb_repeated - … (etc, for every primitive + message + repeated_*) All section headers (`// --- 0x1253_1: Mute group member ---`) and inline NTQQ-specific comments (the FE1_2 field-2 note, the NTV2 default-value note, the Lagrange-observed annotations on GroupAvatarExtra, etc.) preserved verbatim. Verification: - 183 interfaces emitted, exact match to the legacy schema count - tsc --noEmit clean - 604/604 core test suite passes (no behaviour change — additive only) Phase 3 next: refactor runOidb to use protobuf_encode> and migrate the 67 runOidb call sites across 10 files + pipeline.ts. --- .../src/bridge/proto/proton/oidb-action.ts | 1279 +++++++++++++++++ 1 file changed, 1279 insertions(+) create mode 100644 packages/core/src/bridge/proto/proton/oidb-action.ts diff --git a/packages/core/src/bridge/proto/proton/oidb-action.ts b/packages/core/src/bridge/proto/proton/oidb-action.ts new file mode 100644 index 00000000..3d8b00e7 --- /dev/null +++ b/packages/core/src/bridge/proto/proton/oidb-action.ts @@ -0,0 +1,1279 @@ +// Proton (compile-time) form of bridge/proto/oidb-action.ts. +// One-to-one mirror; legacy `*Schema` constants stay alongside for back-compat. + +import type { pb, pb_repeated, int_32, uint_32, uint_64, bool, bytes } from '@snowluma/proton'; + +// --- 0x1253_1: Mute group member --- + +export interface OidbMuteMemberBody { + targetUid?: pb<1, string>; + duration?: pb<2, uint_32>; +} + +export interface OidbMuteMember { + groupUin?: pb<1, uint_32>; + type?: pb<2, uint_32>; + body?: pb<3, OidbMuteMemberBody>; +} + +// --- 0x89A_0: Mute group all --- + +export interface OidbMuteAllState { + state?: pb<17, uint_32>; +} + +export interface OidbMuteAll { + groupUin?: pb<1, uint_32>; + muteState?: pb<2, OidbMuteAllState>; +} + +// --- 0x89A_0: Set group add option --- + +export interface Oidb0x89a_0AddOptionSettings { + addType?: pb<16, uint_32>; +} + +export interface Oidb0x89a_0AddOption { + groupUin?: pb<1, uint_64>; + settings?: pb<2, Oidb0x89a_0AddOptionSettings>; + field12?: pb<12, uint_32>; +} + +// --- 0x89A_0: Set group search --- + +export interface Oidb0x89a_0Search { + groupUin?: pb<1, uint_64>; + settings?: pb<2, bytes>; + field12?: pb<12, uint_32>; +} + +// --- 0x8A0_1: Kick group member --- + +export interface OidbKickMember { + groupUin?: pb<1, uint_32>; + targetUid?: pb<3, string>; + rejectAddRequest?: pb<4, bool>; + reason?: pb<5, string>; +} + +// --- 0x1097_1: Leave group --- + +export interface OidbLeaveGroup { + groupUin?: pb<1, uint_32>; +} + +// --- 0xB5D_44: Friend add request --- + +export interface OidbFriendRequestAction { + accept?: pb<1, uint_32>; + targetUid?: pb<2, string>; +} + +// --- 0x126B_0: Delete friend --- + +export interface OidbDeleteFriendField2Field3 { + field1?: pb<1, uint_32>; + field2?: pb<2, uint_32>; + field3?: pb<3, uint_32>; +} + +export interface OidbDeleteFriendField2 { + field1?: pb<1, uint_32>; + field2?: pb<2, uint_32>; + field3?: pb<3, OidbDeleteFriendField2Field3>; +} + +export interface OidbDeleteFriendField1 { + targetUid?: pb<1, string>; + field2?: pb<2, OidbDeleteFriendField2>; + block?: pb<3, bool>; + field4?: pb<4, bool>; +} + +export interface OidbDeleteFriend { + field1?: pb<1, OidbDeleteFriendField1>; +} + +// --- 0x10C8: Group request action --- + +export interface OidbGroupRequestBody { + sequence?: pb<1, uint_64>; + eventType?: pb<2, uint_32>; + groupUin?: pb<3, uint_32>; + message?: pb<4, string>; +} + +export interface OidbGroupRequestAction { + accept?: pb<1, uint_32>; + body?: pb<2, OidbGroupRequestBody>; +} + +// --- 0xED3_1: Poke --- + +export interface OidbPoke { + uin?: pb<1, uint_32>; + groupUin?: pb<2, uint_32>; + friendUin?: pb<5, uint_32>; + ext?: pb<6, uint_32>; +} + +// --- 0xEAC: Group essence --- + +export interface OidbEssence { + groupUin?: pb<1, uint_32>; + sequence?: pb<2, uint_32>; + random?: pb<3, uint_32>; +} + +// --- 0x1096_1: Set group admin --- + +export interface OidbSetAdmin { + groupUin?: pb<1, uint_32>; + uid?: pb<2, string>; + isAdmin?: pb<3, bool>; +} + +// --- 0x8FC_3: Set group card (rename member) --- + +export interface OidbRenameMemberBody { + targetUid?: pb<1, string>; + targetName?: pb<2, string>; +} + +export interface OidbRenameMember { + groupUin?: pb<1, uint_32>; + body?: pb<2, OidbRenameMemberBody>; +} + +// --- 0x89A_15: Rename group --- + +export interface OidbRenameGroupBody { + targetName?: pb<1, string>; +} + +export interface OidbRenameGroup { + groupUin?: pb<1, uint_32>; + body?: pb<2, OidbRenameGroupBody>; +} + +// --- 0x8FC_2: Set group special title --- + +export interface OidbSpecialTitleBody { + targetUid?: pb<1, string>; + specialTitle?: pb<5, string>; + expireTime?: pb<6, int_32>; +} + +export interface OidbSpecialTitle { + groupUin?: pb<1, uint_32>; + body?: pb<2, OidbSpecialTitleBody>; +} + +// --- 0x7E5_104: Send like --- + +export interface OidbLike { + targetUin?: pb<1, uint_32>; + count?: pb<2, uint_32>; +} + +// --- 0x10C0_1 / 0x10C0_2: Group request list --- + +export interface OidbGroupRequestList { + count?: pb<1, uint_32>; + field2?: pb<2, uint_32>; +} + +// --- 0xFE1_2: User profile info --- + +export interface OidbUserInfoKey { + key?: pb<1, uint_32>; +} + +// Field 2 USED to be `field2: uint32 = 0`, but newer QQ NT versions +// reinterpret field 2 as `uid: string` / `openid: string` and reject +// the request with "one of uid/openid is invaild" when a varint 0 +// shows up there. NapCat's schema (Oidb.0XFE1_2.ts) only emits `uin` +// and `key[]`, so we match that exactly. +export interface OidbUserInfoRequest { + uin?: pb<1, uint_32>; + keys?: pb_repeated<3, OidbUserInfoKey>; +} + +export interface OidbTwoNumber { + number1?: pb<1, uint_32>; + number2?: pb<2, uint_32>; +} + +export interface OidbByteProperty { + code?: pb<1, uint_32>; + value?: pb<2, bytes>; +} + +export interface OidbUserInfoProperty { + numberProperties?: pb_repeated<1, OidbTwoNumber>; + bytesProperties?: pb_repeated<2, OidbByteProperty>; +} + +export interface OidbUserInfoResponseBody { + uid?: pb<1, string>; + properties?: pb<2, OidbUserInfoProperty>; + uin?: pb<3, uint_32>; +} + +export interface OidbUserInfoResponse { + body?: pb<1, OidbUserInfoResponseBody>; +} + +export interface AvatarInfo { + url?: pb<5, string>; +} + +// --- FD4_1: Friend list request body fields --- + +export interface OidbFriendListNumber { + numbers?: pb_repeated<1, uint_32>; +} + +export interface OidbFriendListBodyItem { + type?: pb<1, uint_32>; + number?: pb<2, OidbFriendListNumber>; +} + +export interface OidbFriendListNextUin { + uin?: pb<1, uint_32>; +} + +export interface OidbFriendListRequest { + friendCount?: pb<2, uint_32>; + field4?: pb<4, uint_32>; + nextUin?: pb<5, OidbFriendListNextUin>; + field6?: pb<6, uint_32>; + field7?: pb<7, uint_32>; + body?: pb_repeated<10001, OidbFriendListBodyItem>; + field10002?: pb_repeated<10002, uint_32>; + field10003?: pb<10003, uint_32>; +} + +// --- FE5_2: Group list request body (config fields) --- + +export interface OidbGroupListConfig1 { + groupOwner?: pb<1, bool>; + field2?: pb<2, bool>; + memberMax?: pb<3, bool>; + memberCount?: pb<4, bool>; + groupName?: pb<5, bool>; + field8?: pb<8, bool>; + field9?: pb<9, bool>; + field10?: pb<10, bool>; + field11?: pb<11, bool>; + field12?: pb<12, bool>; + field13?: pb<13, bool>; + field14?: pb<14, bool>; + field15?: pb<15, bool>; + field16?: pb<16, bool>; + field17?: pb<17, bool>; + field18?: pb<18, bool>; + question?: pb<19, bool>; + field20?: pb<20, bool>; + field22?: pb<22, bool>; + field23?: pb<23, bool>; + field24?: pb<24, bool>; + field25?: pb<25, bool>; + field26?: pb<26, bool>; + field27?: pb<27, bool>; + field28?: pb<28, bool>; + field29?: pb<29, bool>; + field30?: pb<30, bool>; + field31?: pb<31, bool>; + field32?: pb<32, bool>; + field5001?: pb<5001, bool>; + field5002?: pb<5002, bool>; + field5003?: pb<5003, bool>; +} + +export interface OidbGroupListConfig2 { + field1?: pb<1, bool>; + field2?: pb<2, bool>; + field3?: pb<3, bool>; + field4?: pb<4, bool>; + field5?: pb<5, bool>; + field6?: pb<6, bool>; + field7?: pb<7, bool>; + field8?: pb<8, bool>; +} + +export interface OidbGroupListConfig3 { + field5?: pb<5, bool>; + field6?: pb<6, bool>; +} + +export interface OidbGroupListConfig { + config1?: pb<1, OidbGroupListConfig1>; + config2?: pb<2, OidbGroupListConfig2>; + config3?: pb<3, OidbGroupListConfig3>; +} + +export interface OidbGroupListRequest { + config?: pb<1, OidbGroupListConfig>; +} + +// --- FE7_3: Group member list request body --- + +export interface OidbGroupMemberListBody { + memberName?: pb<10, bool>; + memberCard?: pb<11, bool>; + level?: pb<12, bool>; + field13?: pb<13, bool>; + field16?: pb<16, bool>; + specialTitle?: pb<17, bool>; + field18?: pb<18, bool>; + field20?: pb<20, bool>; + field21?: pb<21, bool>; + joinTimestamp?: pb<100, bool>; + lastMsgTimestamp?: pb<101, bool>; + shutUpTimestamp?: pb<102, bool>; + field103?: pb<103, bool>; + field104?: pb<104, bool>; + field105?: pb<105, bool>; + field106?: pb<106, bool>; + permission?: pb<107, bool>; + field200?: pb<200, bool>; + field201?: pb<201, bool>; +} + +export interface OidbGroupMemberListRequest { + groupUin?: pb<1, uint_32>; + field2?: pb<2, uint_32>; + field3?: pb<3, uint_32>; + body?: pb<4, OidbGroupMemberListBody>; + token?: pb<15, string>; +} + +// --- Group recall message (trpc.msg.msg_svc.MsgService.SsoGroupRecallMsg) --- + +export interface GroupRecallInfo { + sequence?: pb<1, uint_32>; + random?: pb<2, uint_32>; + field3?: pb<3, uint_32>; +} + +export interface GroupRecallSettings { + field1?: pb<1, uint_32>; +} + +export interface GroupRecallRequest { + type?: pb<1, uint_32>; + groupUin?: pb<2, uint_32>; + info?: pb<3, GroupRecallInfo>; + settings?: pb<4, GroupRecallSettings>; +} + +// --- C2C (private) recall message (trpc.msg.msg_svc.MsgService.SsoC2CRecallMsg) --- + +export interface C2CRecallInfo { + clientSequence?: pb<1, uint_32>; + random?: pb<2, uint_32>; + messageId?: pb<3, uint_64>; + timestamp?: pb<4, uint_32>; + field5?: pb<5, uint_32>; + messageSequence?: pb<6, uint_32>; +} + +export interface C2CRecallSettings { + field1?: pb<1, bool>; + field2?: pb<2, bool>; +} + +export interface C2CRecallRequest { + type?: pb<1, uint_32>; + targetUid?: pb<3, string>; + info?: pb<4, C2CRecallInfo>; + settings?: pb<5, C2CRecallSettings>; + field6?: pb<6, bool>; +} + +// --- 0x9082_1: Set group reaction --- + +export interface OidbGroupReaction { + groupUin?: pb<1, uint_32>; + sequence?: pb<2, uint_32>; + code?: pb<3, string>; + // 1 = legacy QQ face (short numeric id like "76"), 2 = unicode emoji + // (decimal codepoint string like "128516" for 😄). Omitting this + // field used to make unicode reactions fail server-side because the + // server defaulted to type=1 and couldn't resolve a 6-digit code. + type?: pb<4, uint_32>; +} + +// --- 0x6D8_1: Group file list --- + +export interface OidbGroupFileListReq { + groupUin?: pb<1, uint_32>; + appId?: pb<2, uint_32>; + targetDirectory?: pb<3, string>; + fileCount?: pb<5, uint_32>; + sortBy?: pb<9, uint_32>; + startIndex?: pb<13, uint_32>; + field17?: pb<17, uint_32>; + field18?: pb<18, uint_32>; +} + +export interface OidbGroupFileViewReq { + list?: pb<2, OidbGroupFileListReq>; +} + +export interface OidbGroupFileListFolderResp { + folderId?: pb<1, string>; + parentDirectoryId?: pb<2, string>; + folderName?: pb<3, string>; + createTime?: pb<4, uint_32>; + modifiedTime?: pb<5, uint_32>; + creatorUin?: pb<6, uint_32>; + creatorName?: pb<7, string>; + totalFileCount?: pb<8, uint_32>; +} + +export interface OidbGroupFileListFileResp { + fileId?: pb<1, string>; + fileName?: pb<2, string>; + fileSize?: pb<3, uint_64>; + busId?: pb<4, uint_32>; + uploadedTime?: pb<6, uint_32>; + expireTime?: pb<7, uint_32>; + modifiedTime?: pb<8, uint_32>; + downloadedTimes?: pb<9, uint_32>; + uploaderName?: pb<14, string>; + uploaderUin?: pb<15, uint_32>; + parentDirectory?: pb<16, string>; +} + +export interface OidbGroupFileListItemResp { + type?: pb<1, uint_32>; + folderInfo?: pb<2, OidbGroupFileListFolderResp>; + fileInfo?: pb<3, OidbGroupFileListFileResp>; +} + +export interface OidbGroupFileListResp { + retCode?: pb<1, uint_32>; + retMsg?: pb<2, string>; + clientWording?: pb<3, string>; + isEnd?: pb<4, bool>; + items?: pb_repeated<5, OidbGroupFileListItemResp>; +} + +export interface OidbGroupFileViewResp { + list?: pb<2, OidbGroupFileListResp>; +} + +// --- 0x6D6_2 / 0x6D6_3: Group file url & delete --- + +export interface OidbGroupFileUploadReq { + groupUin?: pb<1, uint_32>; + appId?: pb<2, uint_32>; + busId?: pb<3, uint_32>; + entrance?: pb<4, uint_32>; + targetDirectory?: pb<5, string>; + fileName?: pb<6, string>; + localDirectory?: pb<7, string>; + fileSize?: pb<8, uint_64>; + fileSha1?: pb<9, bytes>; + fileSha3?: pb<10, bytes>; + fileMd5?: pb<11, bytes>; + field15?: pb<15, bool>; +} + +export interface OidbGroupFileDownloadReq { + groupUin?: pb<1, uint_32>; + appId?: pb<2, uint_32>; + busId?: pb<3, uint_32>; + fileId?: pb<4, string>; +} + +export interface OidbGroupFileDeleteReq { + groupUin?: pb<1, uint_32>; + busId?: pb<3, uint_32>; + fileId?: pb<5, string>; +} + +export interface OidbGroupFileMoveReq { + groupUin?: pb<1, uint_32>; + appId?: pb<2, uint_32>; + busId?: pb<3, uint_32>; + fileId?: pb<4, string>; + parentDirectory?: pb<5, string>; + targetDirectory?: pb<6, string>; +} + +export interface OidbGroupFileReq { + file?: pb<1, OidbGroupFileUploadReq>; + download?: pb<3, OidbGroupFileDownloadReq>; + delete?: pb<4, OidbGroupFileDeleteReq>; + move?: pb<6, OidbGroupFileMoveReq>; +} + +export interface OidbGroupFileUploadResp { + retCode?: pb<1, int_32>; + retMsg?: pb<2, string>; + clientWording?: pb<3, string>; + uploadIp?: pb<4, string>; + serverDns?: pb<5, string>; + busId?: pb<6, int_32>; + fileId?: pb<7, string>; + checkKey?: pb<8, bytes>; + fileKey?: pb<9, bytes>; + boolFileExist?: pb<10, bool>; + uploadPort?: pb<14, uint_32>; +} + +export interface OidbGroupFileDownloadResp { + retCode?: pb<1, uint_32>; + retMsg?: pb<2, string>; + clientWording?: pb<3, string>; + downloadIp?: pb<4, string>; + downloadDns?: pb<5, string>; + downloadUrl?: pb<6, bytes>; + saveFileName?: pb<11, string>; +} + +export interface OidbGroupFileRetResp { + retCode?: pb<1, uint_32>; + retMsg?: pb<2, string>; + clientWording?: pb<3, string>; +} + +export interface OidbGroupFileResp { + upload?: pb<1, OidbGroupFileUploadResp>; + download?: pb<3, OidbGroupFileDownloadResp>; + delete?: pb<4, OidbGroupFileRetResp>; + move?: pb<6, OidbGroupFileRetResp>; +} + +// --- 0x6D7_0 / 0x6D7_1 / 0x6D7_2: Group file folder ops --- + +export interface OidbGroupFileCreateFolderReq { + groupUin?: pb<1, uint_32>; + rootDirectory?: pb<3, string>; + folderName?: pb<4, string>; +} + +export interface OidbGroupFileDeleteFolderReq { + groupUin?: pb<1, uint_32>; + folderId?: pb<3, string>; +} + +export interface OidbGroupFileRenameFolderReq { + groupUin?: pb<1, uint_32>; + folderId?: pb<3, string>; + newFolderName?: pb<4, string>; +} + +export interface OidbGroupFileFolderReq { + create?: pb<1, OidbGroupFileCreateFolderReq>; + delete?: pb<2, OidbGroupFileDeleteFolderReq>; + rename?: pb<3, OidbGroupFileRenameFolderReq>; +} + +export interface OidbGroupFileFolderRetResp { + retcode?: pb<1, uint_32>; + retMsg?: pb<2, string>; + clientWording?: pb<3, string>; +} + +export interface OidbGroupFileFolderResp { + create?: pb<1, OidbGroupFileFolderRetResp>; + delete?: pb<2, OidbGroupFileFolderRetResp>; + rename?: pb<3, OidbGroupFileFolderRetResp>; +} + +// --- 0xE37_1200: Private file download url --- + +export interface OidbPrivateFileDownloadReqBody { + receiverUid?: pb<10, string>; + fileUuid?: pb<20, string>; + type?: pb<30, uint_32>; + fileHash?: pb<60, string>; + t2?: pb<601, uint_32>; +} + +export interface OidbPrivateFileDownloadReq { + subCommand?: pb<1, uint_32>; + field2?: pb<2, uint_32>; + body?: pb<14, OidbPrivateFileDownloadReqBody>; + field101?: pb<101, uint_32>; + field102?: pb<102, uint_32>; + field200?: pb<200, uint_32>; + field99999?: pb<99999, bytes>; +} + +export interface OidbPrivateFileDownloadRespResult { + server?: pb<20, string>; + port?: pb<40, uint_32>; + url?: pb<50, string>; +} + +export interface OidbPrivateFileDownloadRespBody { + state?: pb<20, string>; + result?: pb<30, OidbPrivateFileDownloadRespResult>; +} + +export interface OidbPrivateFileDownloadResp { + body?: pb<14, OidbPrivateFileDownloadRespBody>; +} + +// --- 0xE37_1700: Private file upload --- + +export interface OidbPrivateFileUploadReqBody { + senderUid?: pb<10, string>; + receiverUid?: pb<20, string>; + fileSize?: pb<30, uint_32>; + fileName?: pb<40, string>; + md510MCheckSum?: pb<50, bytes>; + sha1CheckSum?: pb<60, bytes>; + localPath?: pb<70, string>; + md5CheckSum?: pb<110, bytes>; + sha3CheckSum?: pb<120, bytes>; +} + +export interface OidbPrivateFileUploadReq { + command?: pb<1, uint_32>; + seq?: pb<2, int_32>; + upload?: pb<19, OidbPrivateFileUploadReqBody>; + businessId?: pb<101, int_32>; + clientType?: pb<102, int_32>; + flagSupportMediaPlatform?: pb<200, int_32>; +} + +export interface OidbPrivateFileUploadRespBody { + retCode?: pb<10, int_32>; + retMsg?: pb<20, string>; + uploadIp?: pb<60, string>; + uploadPort?: pb<80, uint_32>; + uuid?: pb<90, string>; + uploadKey?: pb<100, bytes>; + boolFileExist?: pb<110, bool>; + fileAddon?: pb<200, string>; + mediaPlatformUploadKey?: pb<220, bytes>; +} + +export interface OidbPrivateFileUploadResp { + upload?: pb<19, OidbPrivateFileUploadRespBody>; +} + +// --- NTV2 Rich Media (0x9067_202): Download RKey --- + +export interface NTV2CommonHead { + requestId?: pb<1, uint_32>; + command?: pb<2, uint_32>; +} + +export interface NTV2C2CUserInfo { + accountType?: pb<1, uint_32>; + targetUid?: pb<2, string>; +} + +export interface NTV2GroupInfo { + groupUin?: pb<1, uint_32>; +} + +export interface NTV2SceneInfo { + requestType?: pb<101, uint_32>; + businessType?: pb<102, uint_32>; + sceneType?: pb<200, uint_32>; + c2c?: pb<201, NTV2C2CUserInfo>; + group?: pb<202, NTV2GroupInfo>; +} + +export interface NTV2ClientMeta { + agentType?: pb<1, uint_32>; +} + +export interface NTV2ReqHead { + common?: pb<1, NTV2CommonHead>; + scene?: pb<2, NTV2SceneInfo>; + client?: pb<3, NTV2ClientMeta>; +} + +export interface NTV2DownloadRKeyReq { + types?: pb_repeated<1, uint_32>; +} + +export interface NTV2FileType { + type?: pb<1, uint_32>; + picFormat?: pb<2, uint_32>; + videoFormat?: pb<3, uint_32>; + voiceFormat?: pb<4, uint_32>; +} + +export interface NTV2FileInfo { + fileSize?: pb<1, uint_32>; + fileHash?: pb<2, string>; + fileSha1?: pb<3, string>; + fileName?: pb<4, string>; + type?: pb<5, NTV2FileType>; + width?: pb<6, uint_32>; + height?: pb<7, uint_32>; + time?: pb<8, uint_32>; + original?: pb<9, uint_32>; +} + +export interface NTV2IndexNode { + info?: pb<1, NTV2FileInfo>; + fileUuid?: pb<2, string>; + storeId?: pb<3, uint_32>; + uploadTime?: pb<4, uint_32>; + ttl?: pb<5, uint_32>; + subType?: pb<6, uint_32>; +} + +export interface NTV2VideoDownloadExt { + busiType?: pb<1, uint_32>; + sceneType?: pb<2, uint_32>; + subBusiType?: pb<3, uint_32>; +} + +export interface NTV2DownloadExt { + video?: pb<2, NTV2VideoDownloadExt>; +} + +export interface NTV2DownloadReq { + node?: pb<1, NTV2IndexNode>; + download?: pb<2, NTV2DownloadExt>; +} + +export interface NTV2RichMediaReq { + reqHead?: pb<1, NTV2ReqHead>; + download?: pb<3, NTV2DownloadReq>; + downloadRkey?: pb<4, NTV2DownloadRKeyReq>; +} + +export interface NTV2RespHead { + common?: pb<1, NTV2CommonHead>; + retCode?: pb<2, uint_32>; + message?: pb<3, string>; +} + +export interface NTV2RKeyInfo { + rkey?: pb<1, string>; + rkeyTtlSec?: pb<2, uint_64>; + storeId?: pb<3, uint_32>; + rkeyCreateTime?: pb<4, uint_32>; + type?: pb<5, uint_32>; +} + +export interface NTV2DownloadRKeyResp { + rkeys?: pb_repeated<1, NTV2RKeyInfo>; +} + +export interface NTV2MediaDownloadInfo { + domain?: pb<1, string>; + urlPath?: pb<2, string>; + httpsPort?: pb<3, uint_32>; +} + +export interface NTV2MediaDownloadResp { + rKeyParam?: pb<1, string>; + rKeyTtlSecond?: pb<2, uint_32>; + info?: pb<3, NTV2MediaDownloadInfo>; + rKeyCreateTime?: pb<4, uint_32>; +} + +export interface NTV2RichMediaResp { + respHead?: pb<1, NTV2RespHead>; + download?: pb<3, NTV2MediaDownloadResp>; + downloadRkey?: pb<4, NTV2DownloadRKeyResp>; +} + +// --- 0xB6E_2: Set friend remark --- + +export interface OidbSetFriendRemark { + targetUid?: pb<1, string>; + remark?: pb<2, string>; +} + +// --- 0x9082_2: Set group reaction (remove) — same schema as set --- +// (0x9082_1 for add, 0x9082_2 for remove — both use OidbGroupReactionSchema) + +// --- Group file count (0x6D8_3) --- + +export interface OidbGroupFileCountReq { + groupUin?: pb<1, uint_32>; + appId?: pb<2, uint_32>; + busId?: pb<3, uint_32>; +} + +export interface OidbGroupFileCountResp { + fileCount?: pb<1, uint_32>; + maxCount?: pb<2, uint_32>; + isEnd?: pb<3, bool>; +} + +export interface OidbGroupFileCountViewReq { + count?: pb<3, OidbGroupFileCountReq>; +} + +export interface OidbGroupFileCountViewResp { + count?: pb<3, OidbGroupFileCountResp>; +} + + +// --- trpc.msg.msg_svc.MsgService.SsoReadedReport --- + +export interface GroupReadedReportItem { + groupUin?: pb<1, uint_64>; + lastReadSeq?: pb<2, uint_64>; +} + +export interface C2CReadedReportItem { + uid?: pb<2, string>; + lastReadTime?: pb<3, uint_64>; + lastReadSeq?: pb<4, uint_64>; +} + +export interface SsoReadedReportReq { + groupList?: pb_repeated<1, GroupReadedReportItem>; + c2cList?: pb_repeated<2, C2CReadedReportItem>; +} + + +// --- 0x102A_1: Get Client Key --- + +export interface OidbClientKeyReq { +} + +export interface OidbClientKeyResp { + keyIndex?: pb<2, uint_32>; + clientKey?: pb<3, string>; + expireTime?: pb<4, uint_32>; +} + + +// --- 0x102A_0: Get PSKey --- + +export interface OidbGetPskeyReq { + domainList?: pb_repeated<1, string>; +} + +export interface OidbPskeyItem { + domain?: pb<1, string>; + pskey?: pb<2, string>; + expireTime?: pb<3, uint_64>; +} + +export interface OidbGetPskeyResp { + pskeyItems?: pb_repeated<1, OidbPskeyItem>; +} + + +// customExt sub-message of SetStatus. Populated only by +// set_diy_online_status (status=10 + extStatus=2000 + this payload); +// regular set_online_status leaves field 4 unset. +// +// Wire (from napcat packet/transformer/proto/action/action.ts SetStatusCustomExt): +// 1 faceId (uint32) — face icon id, e.g. "Q我吧" sticker +// 2 text (string) — wording shown next to the icon +// 3 field3 (uint32) — face_type / template id; observed values 1..3 +export interface SetStatusCustomExt { + faceId?: pb<1, uint_32>; + text?: pb<2, string>; + faceType?: pb<3, uint_32>; +} + +export interface SetStatusReq { + status?: pb<1, int_32>; + extStatus?: pb<2, int_32>; + batteryStatus?: pb<3, int_32>; + customExt?: pb<4, SetStatusCustomExt>; +} + +export interface SetStatusResp { + errCode?: pb<1, int_32>; // 盲猜字段 1 是错误码(虽然成功时没下发,默认 0) + errMsg?: pb<2, string>; // 返回的 "set status success" +} + + +export interface OidbProfileStringItem { + fieldId?: pb<1, uint_32>; + value?: pb<2, string>; +} + +export interface OidbProfileIntItem { + fieldId?: pb<1, uint_32>; + value?: pb<2, uint_64>; +} + +export interface OidbSetProfile { + uin?: pb<1, uint_64>; + stringProfiles?: pb_repeated<2, OidbProfileStringItem>; + intProfiles?: pb_repeated<3, OidbProfileIntItem>; +} + + +export interface Oidb0x7edInteraction { + totalCount?: pb<1, uint_32>; + newCount?: pb<2, uint_32>; + todayCount?: pb<3, uint_32>; + lastTime?: pb<4, uint_64>; + // userInfos: { field: 7, type: 'repeated_message' ... } // 我没有这个字段,期待未来补全 +} + +export interface Oidb0x7edUserLikeInfo { + uid?: pb<1, string>; + time?: pb<2, uint_64>; + favoriteInfo?: pb<3, Oidb0x7edInteraction>; + voteInfo?: pb<4, Oidb0x7edInteraction>; +} + +export interface Oidb0x7edReq { + targetUid?: pb<1, string>; + basic?: pb<2, uint_32>; + vote?: pb<3, uint_32>; + favorite?: pb<4, uint_32>; + start?: pb<12, uint_32>; + limit?: pb<103, uint_32>; // 0xB8 0x06 +} + +export interface Oidb0x7edResp { + userLikeInfos?: pb_repeated<1, Oidb0x7edUserLikeInfo>; +} + + +export interface Oidb0x8a7Req { + basic1?: pb<1, uint_32>; + basic2?: pb<2, uint_32>; + basic3?: pb<3, uint_32>; + uin?: pb<4, uint_64>; + groupId?: pb<5, uint_64>; + type?: pb<12, uint_32>; +} + +export interface Oidb0x8a7Resp { + uinRemain?: pb<2, uint_32>; + groupRemain?: pb<3, uint_32>; + msg?: pb<4, string>; + canAtAll?: pb<6, bool>; +} + +export interface Oidb0xe17Req { + jsonBody?: pb<3, string>; +} + +export interface Oidb0xe17Resp { + jsonBody?: pb<4, string>; +} + +export interface Oidb0x112aProfileInfo { + tag?: pb<1, uint_32>; + value?: pb<2, string>; +} + +export interface Oidb0x112aReq { + uin?: pb<1, uint_64>; + profile?: pb<2, Oidb0x112aProfileInfo>; +} + +export interface Oidb0x112aResp {} + +export interface Oidb0xcd4ReqBody { + uid?: pb<1, string>; + chatType?: pb<2, uint_32>; // 默认为 0 + eventType?: pb<3, uint_32>; // 输入状态 1 等 +} + +export interface Oidb0xcd4Req { + reqBody?: pb<1, Oidb0xcd4ReqBody>; +} + +export interface Oidb0xcd4Resp {} + + +export interface Oidb0x990TranslateReq { + srcLang?: pb<1, string>; + dstLang?: pb<2, string>; + words?: pb_repeated<3, string>; +} + +export interface Oidb0x990Req { + translateReq?: pb<2, Oidb0x990TranslateReq>; + tag10?: pb<10, uint_32>; + tag12?: pb<12, uint_32>; +} + +export interface Oidb0x990TranslateResp { + errorCode?: pb<1, uint_32>; + errorMsg?: pb<2, string>; + srcLang?: pb<3, string>; + dstLang?: pb<4, string>; + srcWords?: pb_repeated<5, string>; + dstWords?: pb_repeated<6, string>; +} + +export interface Oidb0x990Resp { + translateResp?: pb<2, Oidb0x990TranslateResp>; +} + +export interface MiniAppShareReqBody { + appid?: pb<2, string>; + title?: pb<3, string>; + desc?: pb<4, string>; + picUrl?: pb<9, string>; + jumpUrl?: pb<11, string>; + iconUrl?: pb<12, string>; +} + +export interface MiniAppShareReq { + sdkVersion?: pb<2, string>; + body?: pb<4, MiniAppShareReqBody>; +} + +export interface MiniAppShareRespBody { + jsonStr?: pb<2, string>; +} + +export interface MiniAppShareResp { + status?: pb<2, uint_32>; + msg?: pb<3, string>; + body?: pb<4, MiniAppShareRespBody>; +} + +export interface Oidb0x112eReq { + botAppid?: pb<3, uint_64>; + msgSeq?: pb<4, uint_64>; + buttonId?: pb<5, string>; + callbackData?: pb<6, string>; + unknown7?: pb<7, uint_32>; + groupId?: pb<8, uint_64>; + unknown9?: pb<9, uint_32>; +} + +export interface Oidb0x112eResp { + result?: pb<3, uint_32>; + promptText?: pb<4, string>; + errMsg?: pb<5, string>; +} + +export interface Oidb0xeb7SignInInfo { + uin?: pb<1, string>; + groupId?: pb<2, string>; + version?: pb<3, string>; +} + +export interface Oidb0xeb7Req { + signInInfo?: pb<2, Oidb0xeb7SignInInfo>; +} + +export interface Oidb0xeb7Resp {} + +// --- Faceroam.OpReq: Fetch custom face --- + +export interface FaceroamOpReqInner { + field1?: pb<1, uint_32>; + osVersion?: pb<2, string>; + qqVersion?: pb<3, string>; +} + +export interface FaceroamOpReq { + inner?: pb<1, FaceroamOpReqInner>; + uin?: pb<2, uint_64>; + field3?: pb<3, uint_32>; + field6?: pb<6, uint_32>; +} + +export interface FaceroamOpRespItem { + faceIds?: pb_repeated<1, string>; + category?: pb<3, string>; + totalCount?: pb<4, uint_32>; +} + +export interface FaceroamOpResp { + retCode?: pb<1, uint_32>; + message?: pb<2, string>; + field3?: pb<3, uint_32>; + item?: pb<4, FaceroamOpRespItem>; +} + +// --- 0x9083_1: Get emoji likes --- + +export interface Oidb0x9083Req { + groupId?: pb<2, uint_64>; + sequence?: pb<3, uint_32>; + emojiType?: pb<4, uint_32>; + emojiId?: pb<5, string>; + cookie?: pb<6, bytes>; + field7?: pb<7, uint_32>; + count?: pb<8, uint_32>; + field12?: pb<12, uint_32>; +} + +export interface Oidb0x9083RespUserInfo { + uin?: pb<1, uint_64>; + field3?: pb<3, uint_32>; +} + +export interface Oidb0x9083RespInner { + userInfo?: pb<1, Oidb0x9083RespUserInfo>; + field4?: pb<4, uint_32>; +} + +export interface Oidb0x9083Resp { + inner?: pb<4, Oidb0x9083RespInner>; + cookie?: pb<5, bytes>; +} + +// --- 0x8a0_1: Kick group members (batch) --- + +export interface Oidb0x8a0Req { + groupId?: pb<1, uint_64>; + targetUids?: pb_repeated<3, string>; + rejectAddRequest?: pb<4, uint_32>; + kickReason?: pb<5, bytes>; + field12?: pb<12, uint_32>; +} + +export interface Oidb0x8a0Resp {} + +// --- 0xf16_1: Set group remark --- + +export interface Oidb0xf16Inner { + groupId?: pb<1, uint_64>; + remark?: pb<3, string>; +} + +export interface Oidb0xf16Req { + inner?: pb<1, Oidb0xf16Inner>; + field12?: pb<12, uint_32>; +} + +export interface Oidb0xf16Resp {} + +// --- 0xF90_{1,2,3}: Set / complete / cancel group todo --- +// All three subCmds share the same body (groupUin + msgSeq); only the +// envelope subCmd differs. Sources: napcat +// packet/transformer/action/{Set,Complete,Cancel}GroupTodo.ts. + +export interface OidbGroupTodo { + groupUin?: pb<1, uint_32>; + msgSeq?: pb<2, uint_64>; +} + +// --- 0xFE1_2: Get stranger profile (used for online/ext status lookup) --- + +export interface OidbStrangerStatusKey { + key?: pb<1, uint_32>; +} + +export interface OidbStrangerStatusReq { + uin?: pb<1, uint_32>; + key?: pb_repeated<3, OidbStrangerStatusKey>; +} + +export interface OidbStrangerStatusRespStatus { + key?: pb<1, uint_32>; + value?: pb<2, uint_64>; +} + +export interface OidbStrangerStatusRespData { + status?: pb<2, OidbStrangerStatusRespStatus>; +} + +export interface OidbStrangerStatusResp { + data?: pb<1, OidbStrangerStatusRespData>; +} + +// --- 0x929D_0: Fetch AI voice character list --- + +export interface OidbAiVoiceListReq { + groupUin?: pb<1, uint_32>; + chatType?: pb<2, uint_32>; +} + +export interface OidbAiVoiceListEntry { + voiceId?: pb<1, string>; + voiceDisplayName?: pb<2, string>; + voiceExampleUrl?: pb<3, string>; +} + +export interface OidbAiVoiceListCategory { + category?: pb<1, string>; + voices?: pb_repeated<2, OidbAiVoiceListEntry>; +} + +export interface OidbAiVoiceListResp { + content?: pb_repeated<1, OidbAiVoiceListCategory>; +} + +// --- 0x929B_0: Trigger AI voice synthesis (returns server-side IndexNode) --- + +export interface OidbAiVoiceSession { + sessionId?: pb<1, uint_32>; +} + +export interface OidbAiVoiceReq { + groupUin?: pb<1, uint_32>; + voiceId?: pb<2, string>; + text?: pb<3, string>; + chatType?: pb<4, uint_32>; + session?: pb<5, OidbAiVoiceSession>; +} + +// We only need the fields the OneBot adapter consumes back: the +// IndexNode payload (which feeds fetchGroupPttUrlByNode) and the +// statusCode that the server uses to signal "still rendering, retry". + +export interface OidbAiVoiceFileType { + type?: pb<1, uint_32>; + picFormat?: pb<2, uint_32>; + videoFormat?: pb<3, uint_32>; + voiceFormat?: pb<4, uint_32>; +} + +export interface OidbAiVoiceFileInfo { + fileSize?: pb<1, uint_32>; + fileHash?: pb<2, string>; + fileSha1?: pb<3, string>; + fileName?: pb<4, string>; + type?: pb<5, OidbAiVoiceFileType>; + width?: pb<6, uint_32>; + height?: pb<7, uint_32>; + time?: pb<8, uint_32>; + original?: pb<9, uint_32>; +} + +export interface OidbAiVoiceIndexNode { + info?: pb<1, OidbAiVoiceFileInfo>; + fileUuid?: pb<2, string>; + storeId?: pb<3, uint_32>; + uploadTime?: pb<4, uint_32>; + ttl?: pb<5, uint_32>; + subType?: pb<6, uint_32>; +} + +export interface OidbAiVoiceMsgInfoBody { + index?: pb<1, OidbAiVoiceIndexNode>; +} + +export interface OidbAiVoiceMsgInfo { + msgInfoBody?: pb_repeated<1, OidbAiVoiceMsgInfoBody>; +} + +export interface OidbAiVoiceResp { + statusCode?: pb<1, uint_32>; + field2?: pb<2, uint_32>; + field3?: pb<3, uint_32>; + msgInfo?: pb<4, OidbAiVoiceMsgInfo>; +} + +// --- Highway cmdId 3000: GroupAvatarExtra --- +// Ported from Lagrange.Core/Internal/Packets/Service/Highway/GroupAvatarExtra.cs. +// Field values are protocol-prescribed constants (Lagrange comments on each). + +export interface GroupAvatarExtraField3 { + field1?: pb<1, uint_32>; // observed value: 1 +} + +export interface GroupAvatarExtra { + type?: pb<1, uint_32>; // observed value: 101 + groupUin?: pb<2, uint_32>; + field3?: pb<3, GroupAvatarExtraField3>; + field5?: pb<5, uint_32>; // observed value: 3 + field6?: pb<6, uint_32>; // observed value: 1 +} From 58028123927df461acd30e12091116bf9d4a0817 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Tue, 19 May 2026 07:56:04 +0800 Subject: [PATCH 21/48] =?UTF-8?q?feat(proton):=20finish=20OIDB=20migration?= =?UTF-8?q?=20=E2=80=94=20runOidb=20on=20protobuf=5Fencode>?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Closes the OIDB phase of the proton migration. Every consumer that talked to the OIDB service through the old runtime `makeOidbBaseSchema()` factory now goes through the compile-time generic `OidbBase` instead — proton monomorphizes the codec per call-site instantiation. @snowluma/proton — two analyzer fixes uncovered by the migration: 1. Skip queuing call-site type-args that reference an *enclosing generic function's* type parameter for monomorphization. Before this, a wrapper like export function encodeOidbEnv(env: OidbBase): Uint8Array { return protobuf_encode>(env); } would cause the analyzer to mint a literal `OidbBase__T` registry entry with `body.typeName = 'T'`, which the post-walk wire-type guard then tripped on. The enclosing-scope type params are tracked on a stack as the walker descends into FunctionDeclaration, FunctionExpression, ArrowFunction, MethodDeclaration nodes; matching call sites are skipped (the wrapper-binding path is still responsible for materialising concrete codecs at downstream call sites). 2. Register *explicitly* empty interfaces (`interface X {}`) as zero-field proto messages. OIDB has a handful of these ('this call has no meaningful response body' placeholders — Oidb0xeb7Resp, Oidb0xcd4Resp, Oidb0x112aResp, Oidb0x8a0Resp, Oidb0xf16Resp, OidbClientKeyReq). Proto3 wire allows zero-field messages, and downstream code does `protobuf_decode>` where X is one of these — the wire-type guard would otherwise trip on the missing `X` registration. Interfaces that have members but no pb-marked fields are still NOT registered. @snowluma/core — the OIDB-layer refactor itself: bridge-oidb.ts ditches the runtime ProtoSchema factory and exposes: - makeOidbEnvelope(oidbCmd, subCmd, body, isUid) pure helper - encodeOidbEnv(env) pass-through - decodeOidbEnv(bytes) pass-through - runOidb(bridge, cmd, envelopeBytes) non-generic raw `encodeOidbEnv` / `decodeOidbEnv` are pure pass-through generic wrappers — proton wrapper-binds them and substitutes every call site with the inlined `protobuf_encode_OidbBase__X` / `protobuf_decode_…` function. `runOidb` is non-generic (proton leaves it alone) so it can be mocked in tests. `makeOidbEnvelope` is plain TS — also mockable for introspection. 56 `runOidb` call sites across 11 files migrated to the new API: - bridge-contacts.ts, actions/extras.ts, actions/friend.ts, actions/group-admin.ts, actions/group-file.ts, actions/group-message.ts, actions/interaction.ts, actions/misc.ts, actions/profile.ts, web-actions/cookies.ts, highway/pipeline.ts pipeline.ts also drops `makeOidbBaseSchema(NTV2UploadRichMediaReqSchema)` and the residual `protoEncode({...}, EncodableMediaMsgInfoSchema)` — both go through proton now. Tests: - 8 test files migrated from `vi.mocked(decodeOidbEnv).mockReturnValueOnce` to `vi.mocked(runOidb).mockResolvedValueOnce(protobuf_encode>({body: …}))` — the proton substitution means the old mock layer is bypassed at build time, so the only mockable point is the bytes layer at `runOidb`. - 2 new parity tests pinning `OidbBase` ↔ legacy `makeOidbBaseSchema(InnerSchema)` byte equivalence. Verification: - @snowluma/proton: 95/95 tests pass, tsc --noEmit clean - @snowluma/core: 605/605 tests pass (network-manager.test.ts fails to load due to a missing darwin-arm64 native binary in this environment — pre-existing), tsc --noEmit clean --- packages/core/src/bridge/actions/extras.ts | 93 ++--- packages/core/src/bridge/actions/friend.ts | 58 ++- .../core/src/bridge/actions/group-admin.ts | 169 +++----- .../core/src/bridge/actions/group-file.ts | 370 ++++++++---------- .../core/src/bridge/actions/group-message.ts | 11 +- .../core/src/bridge/actions/interaction.ts | 62 ++- packages/core/src/bridge/actions/misc.ts | 44 +-- packages/core/src/bridge/actions/profile.ts | 67 ++-- packages/core/src/bridge/bridge-contacts.ts | 90 ++--- packages/core/src/bridge/bridge-oidb.ts | 171 ++++---- packages/core/src/bridge/highway/pipeline.ts | 29 +- .../core/src/bridge/web-actions/cookies.ts | 32 +- packages/core/tests/actions/extras.test.ts | 138 ++++--- packages/core/tests/actions/forward.test.ts | 5 +- packages/core/tests/actions/friend.test.ts | 30 +- .../core/tests/actions/group-admin.test.ts | 79 ++-- .../core/tests/actions/group-file.test.ts | 187 +++++---- .../core/tests/actions/group-message.test.ts | 10 +- .../core/tests/actions/interaction.test.ts | 59 ++- packages/core/tests/actions/misc.test.ts | 51 ++- packages/core/tests/actions/profile.test.ts | 71 ++-- packages/core/tests/proton-parity.test.ts | 19 + .../core/tests/web-actions/cookies.test.ts | 128 ++++-- packages/proton/src/ast/analyzer.ts | 138 ++++--- packages/proton/src/ast/collector.ts | 10 +- 25 files changed, 1144 insertions(+), 977 deletions(-) diff --git a/packages/core/src/bridge/actions/extras.ts b/packages/core/src/bridge/actions/extras.ts index 3aca81ae..ae8e2a6f 100644 --- a/packages/core/src/bridge/actions/extras.ts +++ b/packages/core/src/bridge/actions/extras.ts @@ -4,42 +4,33 @@ // the NTQQ NodeIKernel — every wire trip is one runOidb round-trip. import type { Bridge } from '../bridge'; -import { runOidb } from '../bridge-oidb'; -import { - OidbGroupTodoSchema, - OidbStrangerStatusReqSchema, - OidbStrangerStatusRespSchema, - OidbAiVoiceListReqSchema, - OidbAiVoiceListRespSchema, - OidbAiVoiceReqSchema, - OidbAiVoiceRespSchema, -} from '../proto/oidb-action'; +import { runOidb, makeOidbEnvelope, encodeOidbEnv, decodeOidbEnv } from '../bridge-oidb'; +import type { + OidbAiVoiceListReq, + OidbAiVoiceListResp, + OidbAiVoiceReq, + OidbAiVoiceResp, + OidbGroupTodo, + OidbStrangerStatusReq, + OidbStrangerStatusResp, +} from '../proto/proton/oidb-action'; import type { MediaIndexNode } from './shared'; // ─────────────── Group todo (0xF90) ─────────────── export async function setGroupTodo(bridge: Bridge, groupId: number, msgSeq: bigint): Promise { - await runOidb(bridge, { - cmd: 'OidbSvcTrpcTcp.0xf90_1', - oidbCmd: 0xF90, subCmd: 1, - request: { schema: OidbGroupTodoSchema, value: { groupUin: groupId, msgSeq } }, - }); + const env = makeOidbEnvelope(0xF90, 1, { groupUin: groupId, msgSeq }); + await runOidb(bridge, 'OidbSvcTrpcTcp.0xf90_1', encodeOidbEnv(env)); } export async function completeGroupTodo(bridge: Bridge, groupId: number, msgSeq: bigint): Promise { - await runOidb(bridge, { - cmd: 'OidbSvcTrpcTcp.0xf90_2', - oidbCmd: 0xF90, subCmd: 2, - request: { schema: OidbGroupTodoSchema, value: { groupUin: groupId, msgSeq } }, - }); + const env = makeOidbEnvelope(0xF90, 2, { groupUin: groupId, msgSeq }); + await runOidb(bridge, 'OidbSvcTrpcTcp.0xf90_2', encodeOidbEnv(env)); } export async function cancelGroupTodo(bridge: Bridge, groupId: number, msgSeq: bigint): Promise { - await runOidb(bridge, { - cmd: 'OidbSvcTrpcTcp.0xf90_3', - oidbCmd: 0xF90, subCmd: 3, - request: { schema: OidbGroupTodoSchema, value: { groupUin: groupId, msgSeq } }, - }); + const env = makeOidbEnvelope(0xF90, 3, { groupUin: groupId, msgSeq }); + await runOidb(bridge, 'OidbSvcTrpcTcp.0xf90_3', encodeOidbEnv(env)); } // ─────────────── Stranger online/ext status (0xFE1_2) ─────────────── @@ -60,18 +51,15 @@ export interface StrangerStatus { */ export async function getStrangerStatus(bridge: Bridge, uin: number): Promise { try { - const resp = await runOidb<{ data?: { status?: { value?: bigint | number } } }>(bridge, { - cmd: 'OidbSvcTrpcTcp.0xfe1_2', - oidbCmd: 0xFE1, subCmd: 2, - request: { - schema: OidbStrangerStatusReqSchema, - value: { uin, key: [{ key: 27372 }] }, - // Same UIN-form flag fetchUserProfile sets — without it newer - // QQ NT rejects with `[oidb] one of uid/openid is invaild`. - isUid: true, - }, - response: { schema: OidbStrangerStatusRespSchema }, - }); + const env = makeOidbEnvelope( + 0xFE1, 2, + { uin, key: [{ key: 27372 }] } as any, + // Same UIN-form flag fetchUserProfile sets — without it newer + // QQ NT rejects with `[oidb] one of uid/openid is invaild`. + true, + ); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xfe1_2', encodeOidbEnv(env)); + const resp = decodeOidbEnv(respBytes).body; const raw = resp?.data?.status?.value; if (raw === undefined || raw === null) return null; const extBig = typeof raw === 'bigint' ? raw : BigInt(raw); @@ -110,13 +98,10 @@ export async function fetchAiVoiceList( groupId: number, chatType: AiVoiceChatType, ): Promise { - const resp = await runOidb<{ content?: AiVoiceCategory[] }>(bridge, { - cmd: 'OidbSvcTrpcTcp.0x929d_0', - oidbCmd: 0x929D, subCmd: 0, - request: { schema: OidbAiVoiceListReqSchema, value: { groupUin: groupId, chatType } }, - response: { schema: OidbAiVoiceListRespSchema }, - }); - return resp?.content ?? []; + const env = makeOidbEnvelope(0x929D, 0, { groupUin: groupId, chatType }); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x929d_0', encodeOidbEnv(env)); + const resp = decodeOidbEnv(respBytes).body; + return (resp?.content as AiVoiceCategory[] | undefined) ?? []; } /** @@ -139,19 +124,13 @@ export async function fetchAiVoice( // Random 32-bit session id — server uses this to deduplicate polls. const sessionId = Math.floor(Math.random() * 0xFFFFFFFF) >>> 0; for (let i = 0; i < maxRetries; i++) { - const resp = await runOidb<{ - statusCode?: number; - msgInfo?: { msgInfoBody?: Array<{ index?: MediaIndexNode }> }; - }>(bridge, { - cmd: 'OidbSvcTrpcTcp.0x929b_0', - oidbCmd: 0x929B, subCmd: 0, - request: { - schema: OidbAiVoiceReqSchema, - value: { groupUin: groupId, voiceId, text, chatType, session: { sessionId } }, - }, - response: { schema: OidbAiVoiceRespSchema }, - }); - const node = resp?.msgInfo?.msgInfoBody?.[0]?.index; + const env = makeOidbEnvelope( + 0x929B, 0, + { groupUin: groupId, voiceId, text, chatType, session: { sessionId } }, + ); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x929b_0', encodeOidbEnv(env)); + const resp = decodeOidbEnv(respBytes).body; + const node = resp?.msgInfo?.msgInfoBody?.[0]?.index as MediaIndexNode | undefined; if (node) return node; } throw new Error(`AI voice synthesis did not complete after ${maxRetries} polls`); diff --git a/packages/core/src/bridge/actions/friend.ts b/packages/core/src/bridge/actions/friend.ts index 4670ecf6..c4ff1510 100644 --- a/packages/core/src/bridge/actions/friend.ts +++ b/packages/core/src/bridge/actions/friend.ts @@ -3,50 +3,41 @@ // protocol uses opaque UIDs rather than QQ uin numbers. import type { Bridge } from '../bridge'; -import { runOidb } from '../bridge-oidb'; -import { - OidbDeleteFriendSchema, - OidbFriendRequestActionSchema, - OidbSetFriendRemarkSchema, -} from '../proto/oidb-action'; +import { runOidb, makeOidbEnvelope, encodeOidbEnv } from '../bridge-oidb'; +import type { + OidbDeleteFriend, + OidbFriendRequestAction, + OidbSetFriendRemark, +} from '../proto/proton/oidb-action'; export async function setFriendAddRequest(bridge: Bridge, uidOrFlag: string, approve: boolean): Promise { let targetUid = uidOrFlag; if (/^\d+$/.test(uidOrFlag)) { targetUid = await bridge.resolveUserUid(parseInt(uidOrFlag, 10)); } - await runOidb(bridge, { - cmd: 'OidbSvcTrpcTcp.0xb5d_44', - oidbCmd: 0xB5D, subCmd: 44, - request: { schema: OidbFriendRequestActionSchema, value: { accept: approve ? 3 : 5, targetUid } }, - }); + const env = makeOidbEnvelope(0xB5D, 44, { accept: approve ? 3 : 5, targetUid }); + await runOidb(bridge, 'OidbSvcTrpcTcp.0xb5d_44', encodeOidbEnv(env)); } export async function deleteFriend(bridge: Bridge, userId: number, block = false): Promise { const targetUid = await bridge.resolveUserUid(userId); - await runOidb(bridge, { - cmd: 'OidbSvcTrpcTcp.0x126b_0', - oidbCmd: 0x126B, subCmd: 0, - request: { - schema: OidbDeleteFriendSchema, - value: { - field1: { - targetUid, - field2: { - field1: 130, - field2: 109, - field3: { - field1: 8, - field2: 8, - field3: 50, - }, - }, - block, - field4: false, + const env = makeOidbEnvelope(0x126B, 0, { + field1: { + targetUid, + field2: { + field1: 130, + field2: 109, + field3: { + field1: 8, + field2: 8, + field3: 50, }, }, + block, + field4: false, }, }); + await runOidb(bridge, 'OidbSvcTrpcTcp.0x126b_0', encodeOidbEnv(env)); // Refresh friend cache after deletion so subsequent reads don't // surface a ghost entry. Best-effort: a transient OIDB hiccup here @@ -56,9 +47,6 @@ export async function deleteFriend(bridge: Bridge, userId: number, block = false export async function setFriendRemark(bridge: Bridge, userId: number, remark: string): Promise { const uid = await bridge.resolveUserUid(userId); - await runOidb(bridge, { - cmd: 'OidbSvcTrpcTcp.0xb6e_2', - oidbCmd: 0xB6E, subCmd: 2, - request: { schema: OidbSetFriendRemarkSchema, value: { targetUid: uid, remark } }, - }); + const env = makeOidbEnvelope(0xB6E, 2, { targetUid: uid, remark }); + await runOidb(bridge, 'OidbSvcTrpcTcp.0xb6e_2', encodeOidbEnv(env)); } diff --git a/packages/core/src/bridge/actions/group-admin.ts b/packages/core/src/bridge/actions/group-admin.ts index ef59e9a1..25b2eafd 100644 --- a/packages/core/src/bridge/actions/group-admin.ts +++ b/packages/core/src/bridge/actions/group-admin.ts @@ -4,72 +4,56 @@ // so callers can grep across the two layers. import type { Bridge } from '../bridge'; -import { runOidb } from '../bridge-oidb'; -import { - Oidb0x89a_0AddOptionSchema, - Oidb0x89a_0SearchSchema, - Oidb0x8a0ReqSchema, - Oidb0x8a7ReqSchema, - Oidb0x8a7RespSchema, - OidbGroupRequestActionSchema, - OidbKickMemberSchema, - OidbLeaveGroupSchema, - OidbMuteAllSchema, - OidbMuteMemberSchema, - OidbRenameGroupSchema, - OidbRenameMemberSchema, - OidbSetAdminSchema, - OidbSpecialTitleSchema, - Oidb0xf16ReqSchema, -} from '../proto/oidb-action'; +import { runOidb, makeOidbEnvelope, encodeOidbEnv, decodeOidbEnv } from '../bridge-oidb'; +import type { + Oidb0x89a_0AddOption, + Oidb0x89a_0Search, + Oidb0x8a0Req, + Oidb0x8a7Req, + Oidb0x8a7Resp, + Oidb0xf16Req, + OidbGroupRequestAction, + OidbKickMember, + OidbLeaveGroup, + OidbMuteAll, + OidbMuteMember, + OidbRenameGroup, + OidbRenameMember, + OidbSetAdmin, + OidbSpecialTitle, +} from '../proto/proton/oidb-action'; // ─────────────── mute / un-mute ─────────────── export async function muteGroupMember(bridge: Bridge, groupId: number, userId: number, duration: number): Promise { const uid = await bridge.resolveUserUid(userId, groupId); - await runOidb(bridge, { - cmd: 'OidbSvcTrpcTcp.0x1253_1', - oidbCmd: 0x1253, subCmd: 1, - request: { - schema: OidbMuteMemberSchema, - value: { groupUin: groupId, type: 1, body: { targetUid: uid, duration } }, - }, + const env = makeOidbEnvelope(0x1253, 1, { + groupUin: groupId, type: 1, body: { targetUid: uid, duration }, }); + await runOidb(bridge, 'OidbSvcTrpcTcp.0x1253_1', encodeOidbEnv(env)); } export async function muteGroupAll(bridge: Bridge, groupId: number, enable: boolean): Promise { - await runOidb(bridge, { - cmd: 'OidbSvcTrpcTcp.0x89a_0', - oidbCmd: 0x89A, subCmd: 0, - request: { - schema: OidbMuteAllSchema, - value: { groupUin: groupId, muteState: { state: enable ? 0xFFFFFFFF : 0 } }, - }, + const env = makeOidbEnvelope(0x89A, 0, { + groupUin: groupId, muteState: { state: enable ? 0xFFFFFFFF : 0 }, }); + await runOidb(bridge, 'OidbSvcTrpcTcp.0x89a_0', encodeOidbEnv(env)); } // ─────────────── join-policy ─────────────── export async function setGroupAddOption(bridge: Bridge, groupId: number, addType: number): Promise { - await runOidb(bridge, { - cmd: 'OidbSvcTrpcTcp.0x89a_0', - oidbCmd: 0x89A, subCmd: 0, - request: { - schema: Oidb0x89a_0AddOptionSchema, - value: { groupUin: BigInt(groupId), settings: { addType }, field12: 0 }, - }, + const env = makeOidbEnvelope(0x89A, 0, { + groupUin: BigInt(groupId), settings: { addType }, field12: 0, }); + await runOidb(bridge, 'OidbSvcTrpcTcp.0x89a_0', encodeOidbEnv(env)); } export async function setGroupSearch(bridge: Bridge, groupId: number): Promise { - await runOidb(bridge, { - cmd: 'OidbSvcTrpcTcp.0x89a_0', - oidbCmd: 0x89A, subCmd: 0, - request: { - schema: Oidb0x89a_0SearchSchema, - value: { groupUin: BigInt(groupId), settings: new Uint8Array(0), field12: 0 }, - }, + const env = makeOidbEnvelope(0x89A, 0, { + groupUin: BigInt(groupId), settings: new Uint8Array(0), field12: 0, }); + await runOidb(bridge, 'OidbSvcTrpcTcp.0x89a_0', encodeOidbEnv(env)); } export async function setGroupAddRequest( @@ -78,92 +62,64 @@ export async function setGroupAddRequest( ): Promise { const subCmd = filtered ? 2 : 1; const cmd = filtered ? 'OidbSvcTrpcTcp.0x10c8_2' : 'OidbSvcTrpcTcp.0x10c8_1'; - await runOidb(bridge, { - cmd, - oidbCmd: 0x10C8, subCmd, - request: { - schema: OidbGroupRequestActionSchema, - value: { accept: approve ? 1 : 2, body: { sequence: BigInt(sequence), eventType, groupUin: groupId, message: reason } }, - isUid: true, - }, - }); + const env = makeOidbEnvelope( + 0x10C8, subCmd, + { accept: approve ? 1 : 2, body: { sequence: BigInt(sequence), eventType, groupUin: groupId, message: reason } }, + true, + ); + await runOidb(bridge, cmd, encodeOidbEnv(env)); } // ─────────────── kick / leave ─────────────── export async function kickGroupMember(bridge: Bridge, groupId: number, userId: number, reject: boolean, reason = ''): Promise { const uid = await bridge.resolveUserUid(userId, groupId); - await runOidb(bridge, { - cmd: 'OidbSvcTrpcTcp.0x8a0_1', - oidbCmd: 0x8A0, subCmd: 1, - request: { - schema: OidbKickMemberSchema, - value: { groupUin: groupId, targetUid: uid, rejectAddRequest: reject, reason }, - }, + const env = makeOidbEnvelope(0x8A0, 1, { + groupUin: groupId, targetUid: uid, rejectAddRequest: reject, reason, }); + await runOidb(bridge, 'OidbSvcTrpcTcp.0x8a0_1', encodeOidbEnv(env)); } export async function kickGroupMembers(bridge: Bridge, groupId: number, userIds: number[], reject: boolean): Promise { const targetUids = await Promise.all(userIds.map(userId => bridge.resolveUserUid(userId, groupId))); - await runOidb(bridge, { - cmd: 'OidbSvcTrpcTcp.0x8a0_1', - oidbCmd: 0x8A0, subCmd: 1, - request: { - schema: Oidb0x8a0ReqSchema, - value: { groupId: BigInt(groupId), targetUids, rejectAddRequest: reject ? 1 : 0, kickReason: new Uint8Array(0), field12: 0 }, - }, + const env = makeOidbEnvelope(0x8A0, 1, { + groupId: BigInt(groupId), targetUids, rejectAddRequest: reject ? 1 : 0, kickReason: new Uint8Array(0), field12: 0, }); + await runOidb(bridge, 'OidbSvcTrpcTcp.0x8a0_1', encodeOidbEnv(env)); } export async function leaveGroup(bridge: Bridge, groupId: number): Promise { - await runOidb(bridge, { - cmd: 'OidbSvcTrpcTcp.0x1097_1', - oidbCmd: 0x1097, subCmd: 1, - request: { schema: OidbLeaveGroupSchema, value: { groupUin: groupId } }, - }); + const env = makeOidbEnvelope(0x1097, 1, { groupUin: groupId }); + await runOidb(bridge, 'OidbSvcTrpcTcp.0x1097_1', encodeOidbEnv(env)); } // ─────────────── role / display name ─────────────── export async function setGroupAdmin(bridge: Bridge, groupId: number, userId: number, enable: boolean): Promise { const uid = await bridge.resolveUserUid(userId, groupId); - await runOidb(bridge, { - cmd: 'OidbSvcTrpcTcp.0x1096_1', - oidbCmd: 0x1096, subCmd: 1, - request: { schema: OidbSetAdminSchema, value: { groupUin: groupId, uid, isAdmin: enable } }, - }); + const env = makeOidbEnvelope(0x1096, 1, { groupUin: groupId, uid, isAdmin: enable }); + await runOidb(bridge, 'OidbSvcTrpcTcp.0x1096_1', encodeOidbEnv(env)); } export async function setGroupCard(bridge: Bridge, groupId: number, userId: number, card: string): Promise { const uid = await bridge.resolveUserUid(userId, groupId); - await runOidb(bridge, { - cmd: 'OidbSvcTrpcTcp.0x8fc_3', - oidbCmd: 0x8FC, subCmd: 3, - request: { - schema: OidbRenameMemberSchema, - value: { groupUin: groupId, body: { targetUid: uid, targetName: card } }, - }, + const env = makeOidbEnvelope(0x8FC, 3, { + groupUin: groupId, body: { targetUid: uid, targetName: card }, }); + await runOidb(bridge, 'OidbSvcTrpcTcp.0x8fc_3', encodeOidbEnv(env)); } export async function setGroupName(bridge: Bridge, groupId: number, name: string): Promise { - await runOidb(bridge, { - cmd: 'OidbSvcTrpcTcp.0x89a_15', - oidbCmd: 0x89A, subCmd: 15, - request: { schema: OidbRenameGroupSchema, value: { groupUin: groupId, body: { targetName: name } } }, - }); + const env = makeOidbEnvelope(0x89A, 15, { groupUin: groupId, body: { targetName: name } }); + await runOidb(bridge, 'OidbSvcTrpcTcp.0x89a_15', encodeOidbEnv(env)); } export async function setGroupSpecialTitle(bridge: Bridge, groupId: number, userId: number, title: string): Promise { const uid = await bridge.resolveUserUid(userId, groupId); - await runOidb(bridge, { - cmd: 'OidbSvcTrpcTcp.0x8fc_2', - oidbCmd: 0x8FC, subCmd: 2, - request: { - schema: OidbSpecialTitleSchema, - value: { groupUin: groupId, body: { targetUid: uid, specialTitle: title, expireTime: -1 } }, - }, + const env = makeOidbEnvelope(0x8FC, 2, { + groupUin: groupId, body: { targetUid: uid, specialTitle: title, expireTime: -1 }, }); + await runOidb(bridge, 'OidbSvcTrpcTcp.0x8fc_2', encodeOidbEnv(env)); } // ─────────────── personal-side metadata ─────────────── @@ -172,11 +128,8 @@ export async function setGroupSpecialTitle(bridge: Bridge, groupId: number, user // here rather than in friend.ts because the semantic is "operate on a // group" rather than "operate on a contact list". export async function setGroupRemark(bridge: Bridge, groupId: number, remark: string): Promise { - await runOidb(bridge, { - cmd: 'OidbSvcTrpcTcp.0xf16_1', - oidbCmd: 0xF16, subCmd: 1, - request: { schema: Oidb0xf16ReqSchema, value: { inner: { groupId: BigInt(groupId), remark }, field12: 0 } }, - }); + const env = makeOidbEnvelope(0xF16, 1, { inner: { groupId: BigInt(groupId), remark }, field12: 0 }); + await runOidb(bridge, 'OidbSvcTrpcTcp.0xf16_1', encodeOidbEnv(env)); } // ─────────────── group-level quota query ─────────────── @@ -194,12 +147,9 @@ export async function getGroupAtAllRemain( type: 0, }; - const result = await runOidb(bridge, { - cmd: 'OidbSvcTrpcTcp.0x8a7_0', - oidbCmd: 0x8A7, subCmd: 0, - request: { schema: Oidb0x8a7ReqSchema, value: req }, - response: { schema: Oidb0x8a7RespSchema }, - }); + const env = makeOidbEnvelope(0x8A7, 0, req); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x8a7_0', encodeOidbEnv(env)); + const result = decodeOidbEnv(respBytes).body; if (!result) { throw new Error('get group at all remain result empty'); @@ -213,4 +163,3 @@ export async function getGroupAtAllRemain( remain_at_all_count_for_uin: Number(result.uinRemain || 0), }; } - diff --git a/packages/core/src/bridge/actions/group-file.ts b/packages/core/src/bridge/actions/group-file.ts index 1db541e4..2408904a 100644 --- a/packages/core/src/bridge/actions/group-file.ts +++ b/packages/core/src/bridge/actions/group-file.ts @@ -7,25 +7,25 @@ import type { Bridge } from '../bridge'; import { protobuf_encode } from '@snowluma/proton'; -import { runOidb } from '../bridge-oidb'; +import { runOidb, makeOidbEnvelope, encodeOidbEnv, decodeOidbEnv } from '../bridge-oidb'; import { fetchHighwaySession, uploadHighwayHttp } from '../highway/highway-client'; import { computeHashes, computeMd5, FILE_UPLOAD_MAX_BYTES, loadBinarySource } from '../highway/utils'; -import { - OidbGroupFileCountViewReqSchema, - OidbGroupFileCountViewRespSchema, - OidbGroupFileFolderReqSchema, - OidbGroupFileFolderRespSchema, - OidbGroupFileReqSchema, - OidbGroupFileRespSchema, - OidbGroupFileViewReqSchema, - OidbGroupFileViewRespSchema, - OidbPrivateFileDownloadReqSchema, - OidbPrivateFileDownloadRespSchema, - OidbPrivateFileUploadReqSchema, - OidbPrivateFileUploadRespSchema, - NTV2RichMediaReqSchema, - NTV2RichMediaRespSchema, -} from '../proto/oidb-action'; +import type { + OidbGroupFileCountViewReq, + OidbGroupFileCountViewResp, + OidbGroupFileFolderReq, + OidbGroupFileFolderResp, + OidbGroupFileReq, + OidbGroupFileResp, + OidbGroupFileViewReq, + OidbGroupFileViewResp, + OidbPrivateFileDownloadReq, + OidbPrivateFileDownloadResp, + OidbPrivateFileUploadReq, + OidbPrivateFileUploadResp, + NTV2RichMediaReq, + NTV2RichMediaResp, +} from '../proto/proton/oidb-action'; import type { FileUploadExt } from '../proto/proton/highway'; import { toHexUpper } from '../../utils/hex'; import { ensureRetCodeZero, resolveSelfUid, toInt, type MediaIndexNode } from './shared'; @@ -242,12 +242,9 @@ async function fetchNtv2DownloadUrl( oidbCmd: number, payload: Record, ): Promise { - const resp = await runOidb(bridge, { - cmd: serviceCmd, - oidbCmd, subCmd: 200, - request: { schema: NTV2RichMediaReqSchema, value: payload, isUid: true }, - response: { schema: NTV2RichMediaRespSchema }, - }); + const env = makeOidbEnvelope(oidbCmd, 200, payload as any, true); + const respBytes = await runOidb(bridge, serviceCmd, encodeOidbEnv(env)); + const resp = decodeOidbEnv(respBytes).body; ensureRetCodeZero('ntv2 download', resp?.respHead?.retCode, resp?.respHead?.message, undefined); const domain = typeof resp?.download?.info?.domain === 'string' ? resp.download.info.domain : ''; @@ -263,15 +260,12 @@ async function fetchNtv2DownloadUrl( // ─────────────── file count ─────────────── export async function fetchGroupFileCount(bridge: Bridge, groupId: number): Promise<{ fileCount: number; maxCount: number }> { - const resp = await runOidb(bridge, { - cmd: 'OidbSvcTrpcTcp.0x6d8_3', - oidbCmd: 0x6D8, subCmd: 3, - request: { - schema: OidbGroupFileCountViewReqSchema, - value: { count: { groupUin: groupId, appId: 7, busId: 0 } }, - }, - response: { schema: OidbGroupFileCountViewRespSchema }, - }); + const env = makeOidbEnvelope( + 0x6D8, 3, + { count: { groupUin: groupId, appId: 7, busId: 0 } }, + ); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d8_3', encodeOidbEnv(env)); + const resp = decodeOidbEnv(respBytes).body; return { fileCount: toInt(resp?.count?.fileCount ?? 0), maxCount: toInt(resp?.count?.maxCount ?? 10000), @@ -296,31 +290,28 @@ export async function uploadGroupFile( const fileName = normalizeUploadFileName(name, loaded.fileName); const hashes = computeHashes(loaded.bytes); - const resp = await runOidb(bridge, { - cmd: 'OidbSvcTrpcTcp.0x6d6_0', - oidbCmd: 0x6D6, subCmd: 0, - request: { - schema: OidbGroupFileReqSchema, - value: { - file: { - groupUin: groupId, - appId: 4, - busId: 102, - entrance: 6, - targetDirectory: normalizeDirectory(folderId), - fileName, - localDirectory: `/${fileName}`, - fileSize: BigInt(loaded.bytes.length), - fileSha1: hashes.sha1, - fileSha3: new Uint8Array(0), - fileMd5: hashes.md5, - field15: true, - }, + const env = makeOidbEnvelope( + 0x6D6, 0, + { + file: { + groupUin: groupId, + appId: 4, + busId: 102, + entrance: 6, + targetDirectory: normalizeDirectory(folderId), + fileName, + localDirectory: `/${fileName}`, + fileSize: BigInt(loaded.bytes.length), + fileSha1: hashes.sha1, + fileSha3: new Uint8Array(0), + fileMd5: hashes.md5, + field15: true, }, - isUid: true, }, - response: { schema: OidbGroupFileRespSchema }, - }); + true, + ); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d6_0', encodeOidbEnv(env)); + const resp = decodeOidbEnv(respBytes).body; const upload = resp?.upload; if (!upload) throw new Error('group file upload response missing'); @@ -389,32 +380,26 @@ export async function uploadPrivateFile( const fileName = normalizeUploadFileName(name, loaded.fileName); const hashes = computeHashes(loaded.bytes); - const resp = await runOidb(bridge, { - cmd: 'OidbSvcTrpcTcp.0xe37_1700', - oidbCmd: 0xE37, subCmd: 1700, - request: { - schema: OidbPrivateFileUploadReqSchema, - value: { - command: 1700, - seq: 0, - upload: { - senderUid: selfUid, - receiverUid: targetUid, - fileSize: loaded.bytes.length, - fileName, - md510MCheckSum: md5First10MB(loaded.bytes), - sha1CheckSum: hashes.sha1, - localPath: '/', - md5CheckSum: hashes.md5, - sha3CheckSum: new Uint8Array(0), - }, - businessId: 3, - clientType: 1, - flagSupportMediaPlatform: 1, - }, + const env = makeOidbEnvelope(0xE37, 1700, { + command: 1700, + seq: 0, + upload: { + senderUid: selfUid, + receiverUid: targetUid, + fileSize: loaded.bytes.length, + fileName, + md510MCheckSum: md5First10MB(loaded.bytes), + sha1CheckSum: hashes.sha1, + localPath: '/', + md5CheckSum: hashes.md5, + sha3CheckSum: new Uint8Array(0), }, - response: { schema: OidbPrivateFileUploadRespSchema }, + businessId: 3, + clientType: 1, + flagSupportMediaPlatform: 1, }); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xe37_1700', encodeOidbEnv(env)); + const resp = decodeOidbEnv(respBytes).body; const upload = resp?.upload; if (!upload) throw new Error('private file upload response missing'); @@ -463,27 +448,24 @@ export async function fetchGroupFiles(bridge: Bridge, groupId: number, folderId const pageSize = 20; let startIndex = 0; for (let page = 0; page < 200; page++) { - const resp = await runOidb(bridge, { - cmd: 'OidbSvcTrpcTcp.0x6d8_1', - oidbCmd: 0x6D8, subCmd: 1, - request: { - schema: OidbGroupFileViewReqSchema, - value: { - list: { - groupUin: groupId, - appId: 7, - targetDirectory, - fileCount: pageSize, - sortBy: 1, - startIndex, - field17: 2, - field18: 0, - }, + const env = makeOidbEnvelope( + 0x6D8, 1, + { + list: { + groupUin: groupId, + appId: 7, + targetDirectory, + fileCount: pageSize, + sortBy: 1, + startIndex, + field17: 2, + field18: 0, }, - isUid: true, }, - response: { schema: OidbGroupFileViewRespSchema }, - }); + true, + ); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d8_1', encodeOidbEnv(env)); + const resp = decodeOidbEnv(respBytes).body; const list = resp?.list; if (!list) break; @@ -538,23 +520,20 @@ export async function fetchGroupFiles(bridge: Bridge, groupId: number, folderId // ─────────────── url fetch (group / private files) ─────────────── export async function fetchGroupFileUrl(bridge: Bridge, groupId: number, fileId: string, busId = 102): Promise { - const resp = await runOidb(bridge, { - cmd: 'OidbSvcTrpcTcp.0x6d6_2', - oidbCmd: 0x6D6, subCmd: 2, - request: { - schema: OidbGroupFileReqSchema, - value: { - download: { - groupUin: groupId, - appId: 7, - busId, - fileId, - }, + const env = makeOidbEnvelope( + 0x6D6, 2, + { + download: { + groupUin: groupId, + appId: 7, + busId, + fileId, }, - isUid: true, }, - response: { schema: OidbGroupFileRespSchema }, - }); + true, + ); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d6_2', encodeOidbEnv(env)); + const resp = decodeOidbEnv(respBytes).body; const download = resp?.download; if (!download) throw new Error('group file url response missing'); @@ -574,29 +553,23 @@ export async function fetchGroupFileUrl(bridge: Bridge, groupId: number, fileId: export async function fetchPrivateFileUrl(bridge: Bridge, userId: number, fileId: string, fileHash: string): Promise { const uid = await bridge.resolveUserUid(userId); - const resp = await runOidb(bridge, { - cmd: 'OidbSvcTrpcTcp.0xe37_1200', - oidbCmd: 0xE37, subCmd: 1200, - request: { - schema: OidbPrivateFileDownloadReqSchema, - value: { - subCommand: 1200, - field2: 1, - body: { - receiverUid: uid, - fileUuid: fileId, - type: 2, - fileHash, - t2: 0, - }, - field101: 3, - field102: 103, - field200: 1, - field99999: new Uint8Array([0xC0, 0x85, 0x2C, 0x01]), - }, + const env = makeOidbEnvelope(0xE37, 1200, { + subCommand: 1200, + field2: 1, + body: { + receiverUid: uid, + fileUuid: fileId, + type: 2, + fileHash, + t2: 0, }, - response: { schema: OidbPrivateFileDownloadRespSchema }, + field101: 3, + field102: 103, + field200: 1, + field99999: new Uint8Array([0xC0, 0x85, 0x2C, 0x01]), }); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xe37_1200', encodeOidbEnv(env)); + const resp = decodeOidbEnv(respBytes).body; const result = resp?.body?.result; const server = typeof result?.server === 'string' ? result.server : ''; @@ -611,22 +584,19 @@ export async function fetchPrivateFileUrl(bridge: Bridge, userId: number, fileId // ─────────────── delete / move ─────────────── export async function deleteGroupFile(bridge: Bridge, groupId: number, fileId: string): Promise { - const resp = await runOidb(bridge, { - cmd: 'OidbSvcTrpcTcp.0x6d6_3', - oidbCmd: 0x6D6, subCmd: 3, - request: { - schema: OidbGroupFileReqSchema, - value: { - delete: { - groupUin: groupId, - busId: 102, - fileId, - }, + const env = makeOidbEnvelope( + 0x6D6, 3, + { + delete: { + groupUin: groupId, + busId: 102, + fileId, }, - isUid: true, }, - response: { schema: OidbGroupFileRespSchema }, - }); + true, + ); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d6_3', encodeOidbEnv(env)); + const resp = decodeOidbEnv(respBytes).body; const result = resp?.delete; if (!result) throw new Error('group file delete response missing'); @@ -640,25 +610,22 @@ export async function moveGroupFile( parentDirectory: string, targetDirectory: string, ): Promise { - const resp = await runOidb(bridge, { - cmd: 'OidbSvcTrpcTcp.0x6d6_5', - oidbCmd: 0x6D6, subCmd: 5, - request: { - schema: OidbGroupFileReqSchema, - value: { - move: { - groupUin: groupId, - appId: 7, - busId: 102, - fileId, - parentDirectory, - targetDirectory, - }, + const env = makeOidbEnvelope( + 0x6D6, 5, + { + move: { + groupUin: groupId, + appId: 7, + busId: 102, + fileId, + parentDirectory, + targetDirectory, }, - isUid: true, }, - response: { schema: OidbGroupFileRespSchema }, - }); + true, + ); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d6_5', encodeOidbEnv(env)); + const resp = decodeOidbEnv(respBytes).body; const result = resp?.move; if (!result) throw new Error('group file move response missing'); @@ -668,22 +635,19 @@ export async function moveGroupFile( // ─────────────── folders ─────────────── export async function createGroupFileFolder(bridge: Bridge, groupId: number, name: string, parentId = '/'): Promise { - const resp = await runOidb(bridge, { - cmd: 'OidbSvcTrpcTcp.0x6d7_0', - oidbCmd: 0x6D7, subCmd: 0, - request: { - schema: OidbGroupFileFolderReqSchema, - value: { - create: { - groupUin: groupId, - rootDirectory: normalizeDirectory(parentId), - folderName: name, - }, + const env = makeOidbEnvelope( + 0x6D7, 0, + { + create: { + groupUin: groupId, + rootDirectory: normalizeDirectory(parentId), + folderName: name, }, - isUid: true, }, - response: { schema: OidbGroupFileFolderRespSchema }, - }); + true, + ); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d7_0', encodeOidbEnv(env)); + const resp = decodeOidbEnv(respBytes).body; const result = resp?.create; if (!result) throw new Error('group folder create response missing'); @@ -691,21 +655,18 @@ export async function createGroupFileFolder(bridge: Bridge, groupId: number, nam } export async function deleteGroupFileFolder(bridge: Bridge, groupId: number, folderId: string): Promise { - const resp = await runOidb(bridge, { - cmd: 'OidbSvcTrpcTcp.0x6d7_1', - oidbCmd: 0x6D7, subCmd: 1, - request: { - schema: OidbGroupFileFolderReqSchema, - value: { - delete: { - groupUin: groupId, - folderId, - }, + const env = makeOidbEnvelope( + 0x6D7, 1, + { + delete: { + groupUin: groupId, + folderId, }, - isUid: true, }, - response: { schema: OidbGroupFileFolderRespSchema }, - }); + true, + ); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d7_1', encodeOidbEnv(env)); + const resp = decodeOidbEnv(respBytes).body; const result = resp?.delete; if (!result) throw new Error('group folder delete response missing'); @@ -713,22 +674,19 @@ export async function deleteGroupFileFolder(bridge: Bridge, groupId: number, fol } export async function renameGroupFileFolder(bridge: Bridge, groupId: number, folderId: string, newFolderName: string): Promise { - const resp = await runOidb(bridge, { - cmd: 'OidbSvcTrpcTcp.0x6d7_2', - oidbCmd: 0x6D7, subCmd: 2, - request: { - schema: OidbGroupFileFolderReqSchema, - value: { - rename: { - groupUin: groupId, - folderId, - newFolderName, - }, + const env = makeOidbEnvelope( + 0x6D7, 2, + { + rename: { + groupUin: groupId, + folderId, + newFolderName, }, - isUid: true, }, - response: { schema: OidbGroupFileFolderRespSchema }, - }); + true, + ); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d7_2', encodeOidbEnv(env)); + const resp = decodeOidbEnv(respBytes).body; const result = resp?.rename; if (!result) throw new Error('group folder rename response missing'); diff --git a/packages/core/src/bridge/actions/group-message.ts b/packages/core/src/bridge/actions/group-message.ts index 7419e244..13da8dc2 100644 --- a/packages/core/src/bridge/actions/group-message.ts +++ b/packages/core/src/bridge/actions/group-message.ts @@ -5,13 +5,13 @@ import type { Bridge } from '../bridge'; import { protoEncode } from '../../protobuf/decode'; -import { runOidb } from '../bridge-oidb'; +import { runOidb, makeOidbEnvelope, encodeOidbEnv } from '../bridge-oidb'; import { C2CRecallRequestSchema, GroupRecallRequestSchema, - OidbEssenceSchema, SsoReadedReportReqSchema, } from '../proto/oidb-action'; +import type { OidbEssence } from '../proto/proton/oidb-action'; export async function recallGroupMessage(bridge: Bridge, groupId: number, sequence: number): Promise { const request = protoEncode({ @@ -96,9 +96,6 @@ export async function markGroupMessageRead( export async function setGroupEssence(bridge: Bridge, groupId: number, sequence: number, random: number, enable: boolean): Promise { const subCmd = enable ? 1 : 2; const cmd = enable ? 'OidbSvcTrpcTcp.0xeac_1' : 'OidbSvcTrpcTcp.0xeac_2'; - await runOidb(bridge, { - cmd, - oidbCmd: 0xEAC, subCmd, - request: { schema: OidbEssenceSchema, value: { groupUin: groupId, sequence, random } }, - }); + const env = makeOidbEnvelope(0xEAC, subCmd, { groupUin: groupId, sequence, random }); + await runOidb(bridge, cmd, encodeOidbEnv(env)); } diff --git a/packages/core/src/bridge/actions/interaction.ts b/packages/core/src/bridge/actions/interaction.ts index 5d1faf4a..17279e00 100644 --- a/packages/core/src/bridge/actions/interaction.ts +++ b/packages/core/src/bridge/actions/interaction.ts @@ -3,37 +3,28 @@ // edit message content — they're purely social signals. import type { Bridge } from '../bridge'; -import { runOidb } from '../bridge-oidb'; -import { - Oidb0x9083ReqSchema, - Oidb0x9083RespSchema, - OidbGroupReactionSchema, - OidbLikeSchema, - OidbPokeSchema, -} from '../proto/oidb-action'; +import { runOidb, makeOidbEnvelope, encodeOidbEnv, decodeOidbEnv } from '../bridge-oidb'; +import type { + Oidb0x9083Req, + Oidb0x9083Resp, + OidbGroupReaction, + OidbLike, + OidbPoke, +} from '../proto/proton/oidb-action'; export async function sendPoke(bridge: Bridge, isGroup: boolean, peerUin: number, targetUin?: number): Promise { - await runOidb(bridge, { - cmd: 'OidbSvcTrpcTcp.0xed3_1', - oidbCmd: 0xED3, subCmd: 1, - request: { - schema: OidbPokeSchema, - value: { - uin: targetUin ?? peerUin, - groupUin: isGroup ? peerUin : 0, - friendUin: isGroup ? 0 : peerUin, - ext: 0, - }, - }, + const env = makeOidbEnvelope(0xED3, 1, { + uin: targetUin ?? peerUin, + groupUin: isGroup ? peerUin : 0, + friendUin: isGroup ? 0 : peerUin, + ext: 0, }); + await runOidb(bridge, 'OidbSvcTrpcTcp.0xed3_1', encodeOidbEnv(env)); } export async function sendLike(bridge: Bridge, userId: number, count: number): Promise { - await runOidb(bridge, { - cmd: 'OidbSvcTrpcTcp.0x7e5_104', - oidbCmd: 0x7E5, subCmd: 104, - request: { schema: OidbLikeSchema, value: { targetUin: userId, count } }, - }); + const env = makeOidbEnvelope(0x7E5, 104, { targetUin: userId, count }); + await runOidb(bridge, 'OidbSvcTrpcTcp.0x7e5_104', encodeOidbEnv(env)); } export async function setGroupReaction(bridge: Bridge, groupId: number, sequence: number, code: string, isSet: boolean): Promise { @@ -44,14 +35,8 @@ export async function setGroupReaction(bridge: Bridge, groupId: number, sequence // type field to pick the right resolution table; omitting it makes // unicode reactions silently fail. const type = code.length > 3 ? 2 : 1; - await runOidb(bridge, { - cmd, - oidbCmd: 0x9082, subCmd, - request: { - schema: OidbGroupReactionSchema, - value: { groupUin: groupId, sequence, code, type }, - }, - }); + const env = makeOidbEnvelope(0x9082, subCmd, { groupUin: groupId, sequence, code, type }); + await runOidb(bridge, cmd, encodeOidbEnv(env)); } export async function getEmojiLikes( @@ -63,7 +48,7 @@ export async function getEmojiLikes( count: number = 10, cookie: string = '', ): Promise<{ users: Array<{ uin: number }>, cookie: string, isLast: boolean }> { - const req = { + const req: any = { groupId: BigInt(groupId), sequence, emojiType, @@ -73,12 +58,9 @@ export async function getEmojiLikes( count, field12: 1, }; - const resp = await runOidb(bridge, { - cmd: 'OidbSvcTrpcTcp.0x9083_1', - oidbCmd: 0x9083, subCmd: 1, - request: { schema: Oidb0x9083ReqSchema, value: req }, - response: { schema: Oidb0x9083RespSchema }, - }); + const env = makeOidbEnvelope(0x9083, 1, req); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x9083_1', encodeOidbEnv(env)); + const resp = decodeOidbEnv(respBytes).body; const uin = resp?.inner?.userInfo?.uin; const users = uin ? [{ uin: Number(uin) }] : []; const respCookie = resp?.cookie ? Buffer.from(resp.cookie).toString('base64') : ''; diff --git a/packages/core/src/bridge/actions/misc.ts b/packages/core/src/bridge/actions/misc.ts index 3e0e98dd..b3b06f98 100644 --- a/packages/core/src/bridge/actions/misc.ts +++ b/packages/core/src/bridge/actions/misc.ts @@ -4,17 +4,19 @@ import type { Bridge } from '../bridge'; import { protoDecode, protoEncode } from '../../protobuf/decode'; -import { runOidb } from '../bridge-oidb'; +import { runOidb, makeOidbEnvelope, encodeOidbEnv, decodeOidbEnv } from '../bridge-oidb'; import { MiniAppShareReqSchema, MiniAppShareRespSchema, - Oidb0x112eReqSchema, - Oidb0x112eRespSchema, - Oidb0x990ReqSchema, - Oidb0x990RespSchema, - Oidb0xeb7ReqSchema, - Oidb0xeb7RespSchema, } from '../proto/oidb-action'; +import type { + Oidb0x112eReq, + Oidb0x112eResp, + Oidb0x990Req, + Oidb0x990Resp, + Oidb0xeb7Req, + Oidb0xeb7Resp, +} from '../proto/proton/oidb-action'; export async function translateEn2Zh( bridge: Bridge, @@ -30,12 +32,9 @@ export async function translateEn2Zh( tag12: 1, }; - const result = await runOidb(bridge, { - cmd: 'OidbSvcTrpcTcp.0x990_2', - oidbCmd: 0x990, subCmd: 2, - request: { schema: Oidb0x990ReqSchema, value: req }, - response: { schema: Oidb0x990RespSchema }, - }); + const env = makeOidbEnvelope(0x990, 2, req); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x990_2', encodeOidbEnv(env)); + const result = decodeOidbEnv(respBytes).body; const resp = result?.translateResp; if (!resp) { @@ -122,12 +121,9 @@ export async function clickInlineKeyboardButton( unknown9: 1, }; - const result = await runOidb(bridge, { - cmd: 'OidbSvcTrpcTcp.0x112e_1', - oidbCmd: 0x112E, subCmd: 1, - request: { schema: Oidb0x112eReqSchema, value: req }, - response: { schema: Oidb0x112eRespSchema }, - }); + const env = makeOidbEnvelope(0x112E, 1, req); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x112e_1', encodeOidbEnv(env)); + const result = decodeOidbEnv(respBytes).body; if (!result) { throw new Error('click inline keyboard button result empty'); @@ -155,10 +151,8 @@ export async function sendGroupSign( }, }; - await runOidb(bridge, { - cmd: 'OidbSvcTrpcTcp.0xEB7_1', - oidbCmd: 0xEB7, subCmd: 1, - request: { schema: Oidb0xeb7ReqSchema, value: req }, - response: { schema: Oidb0xeb7RespSchema }, - }); + const env = makeOidbEnvelope(0xEB7, 1, req); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xEB7_1', encodeOidbEnv(env)); + // Decode just to maintain the original behaviour of "consume the response". + decodeOidbEnv(respBytes); } diff --git a/packages/core/src/bridge/actions/profile.ts b/packages/core/src/bridge/actions/profile.ts index 849e6fb6..b0284428 100644 --- a/packages/core/src/bridge/actions/profile.ts +++ b/packages/core/src/bridge/actions/profile.ts @@ -4,25 +4,27 @@ import type { Bridge } from '../bridge'; import { protoDecode, protoEncode } from '../../protobuf/decode'; -import { runOidb } from '../bridge-oidb'; +import { runOidb, makeOidbEnvelope, encodeOidbEnv, decodeOidbEnv } from '../bridge-oidb'; import { fetchHighwaySession, uploadHighwayHttp } from '../highway/highway-client'; import { computeHashes, loadBinarySource } from '../highway/utils'; import { FaceroamOpReqSchema, FaceroamOpRespSchema, GroupAvatarExtraSchema, - Oidb0x112aReqSchema, - Oidb0x112aRespSchema, - Oidb0x7edReqSchema, - Oidb0x7edRespSchema, - Oidb0xcd4ReqSchema, - Oidb0xcd4RespSchema, - Oidb0xe17ReqSchema, - Oidb0xe17RespSchema, - OidbSetProfileSchema, SetStatusReqSchema, SetStatusRespSchema, } from '../proto/oidb-action'; +import type { + Oidb0x112aReq, + Oidb0x112aResp, + Oidb0x7edReq, + Oidb0x7edResp, + Oidb0xcd4Req, + Oidb0xcd4Resp, + Oidb0xe17Req, + Oidb0xe17Resp, + OidbSetProfile, +} from '../proto/proton/oidb-action'; import { resolveSelfUid } from './shared'; // ─────────────── status / profile setters ─────────────── @@ -110,11 +112,8 @@ export async function setProfile( stringProfiles, }; - await runOidb(bridge, { - cmd: 'OidbSvcTrpcTcp.0x112a_2', - oidbCmd: 0x112A, subCmd: 2, - request: { schema: OidbSetProfileSchema, value: req }, - }); + const env = makeOidbEnvelope(0x112A, 2, req); + await runOidb(bridge, 'OidbSvcTrpcTcp.0x112a_2', encodeOidbEnv(env)); } export async function setSelfLongNick( @@ -129,12 +128,10 @@ export async function setSelfLongNick( }, }; - await runOidb(bridge, { - cmd: 'OidbSvcTrpcTcp.0x112a_2', - oidbCmd: 0x112A, subCmd: 2, - request: { schema: Oidb0x112aReqSchema, value: req }, - response: { schema: Oidb0x112aRespSchema }, - }); + const env = makeOidbEnvelope(0x112A, 2, req); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x112a_2', encodeOidbEnv(env)); + // Decode just to maintain the original behaviour of "consume the response". + decodeOidbEnv(respBytes); } export async function setInputStatus( @@ -156,12 +153,10 @@ export async function setInputStatus( }, }; - await runOidb(bridge, { - cmd: 'OidbSvcTrpcTcp.0xcd4_1', - oidbCmd: 0xCD4, subCmd: 1, - request: { schema: Oidb0xcd4ReqSchema, value: req }, - response: { schema: Oidb0xcd4RespSchema }, - }); + const env = makeOidbEnvelope(0xCD4, 1, req); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xcd4_1', encodeOidbEnv(env)); + // Decode just to maintain the original behaviour of "consume the response". + decodeOidbEnv(respBytes); } export async function setAvatar( @@ -232,12 +227,9 @@ export async function getProfileLike( limit: limit, }; - const result = await runOidb(bridge, { - cmd: 'OidbSvcTrpcTcp.0x7ed_12', - oidbCmd: 0x7ED, subCmd: 12, - request: { schema: Oidb0x7edReqSchema, value: req }, - response: { schema: Oidb0x7edRespSchema }, - }); + const env = makeOidbEnvelope(0x7ED, 12, req); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x7ed_12', encodeOidbEnv(env)); + const result = decodeOidbEnv(respBytes).body; const data = result?.userLikeInfos?.[0]; if (!data) { @@ -277,12 +269,9 @@ export async function getUnidirectionalFriendList( jsonBody: JSON.stringify(reqObj), }; - const result = await runOidb(bridge, { - cmd: 'MQUpdateSvc_com_qq_ti.web.OidbSvc.0xe17_0', - oidbCmd: 0xE17, subCmd: 0, - request: { schema: Oidb0xe17ReqSchema, value: req }, - response: { schema: Oidb0xe17RespSchema }, - }); + const env = makeOidbEnvelope(0xE17, 0, req); + const respBytes = await runOidb(bridge, 'MQUpdateSvc_com_qq_ti.web.OidbSvc.0xe17_0', encodeOidbEnv(env)); + const result = decodeOidbEnv(respBytes).body; if (!result || !result.jsonBody) { throw new Error('get unidirectional friend list empty'); diff --git a/packages/core/src/bridge/bridge-contacts.ts b/packages/core/src/bridge/bridge-contacts.ts index 9e0fa6dc..54173dcf 100644 --- a/packages/core/src/bridge/bridge-contacts.ts +++ b/packages/core/src/bridge/bridge-contacts.ts @@ -4,24 +4,24 @@ import type { Bridge } from './bridge'; import type { DownloadRKeyInfo } from './bridge'; import type { FriendInfo, QQGroupInfo, GroupMemberInfo, UserProfileInfo, GroupRequestInfo } from './qq-info'; import { protoDecode } from '../protobuf/decode'; -import { runOidb } from './bridge-oidb'; -import { - OidbSvcTrpcTcp0xFD4_1ResponseSchema, - OidbSvcTrpcTcp0xFE5_2ResponseSchema, - OidbSvcTrpcTcp0xFE7_3ResponseSchema, - OidbSvcTrpcTcp0x10C0ResponseSchema, -} from './proto/oidb'; -import { - OidbFriendListRequestSchema, - OidbGroupListRequestSchema, - OidbGroupMemberListRequestSchema, - OidbUserInfoRequestSchema, - OidbUserInfoResponseSchema, - AvatarInfoSchema, - OidbGroupRequestListSchema, - NTV2RichMediaReqSchema, - NTV2RichMediaRespSchema, -} from './proto/oidb-action'; +import { runOidb, makeOidbEnvelope, encodeOidbEnv, decodeOidbEnv } from './bridge-oidb'; +import { AvatarInfoSchema } from './proto/oidb-action'; +import type { + OidbSvcTrpcTcp0xFD4_1Response, + OidbSvcTrpcTcp0xFE5_2Response, + OidbSvcTrpcTcp0xFE7_3Response, + OidbSvcTrpcTcp0x10C0Response, +} from './proto/proton/oidb'; +import type { + OidbFriendListRequest, + OidbGroupListRequest, + OidbGroupMemberListRequest, + OidbUserInfoRequest, + OidbUserInfoResponse, + OidbGroupRequestList, + NTV2RichMediaReq, + NTV2RichMediaResp, +} from './proto/proton/oidb-action'; // --------------------------------------------------------------------------- // Helpers @@ -71,12 +71,9 @@ export async function fetchFriendList(bridge: Bridge): Promise { body.nextUin = { uin: nextUin }; } - const resp = await runOidb(bridge, { - cmd: 'OidbSvcTrpcTcp.0xfd4_1', - oidbCmd: 0xFD4, subCmd: 1, - request: { schema: OidbFriendListRequestSchema, value: body }, - response: { schema: OidbSvcTrpcTcp0xFD4_1ResponseSchema }, - }); + const env = makeOidbEnvelope(0xFD4, 1, body); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xfd4_1', encodeOidbEnv(env)); + const resp = decodeOidbEnv(respBytes).body; if (resp?.friends) { for (const raw of resp.friends) { @@ -137,12 +134,9 @@ export async function fetchGroupList(bridge: Bridge): Promise { }, }; - const resp = await runOidb(bridge, { - cmd: 'OidbSvcTrpcTcp.0xfe5_2', - oidbCmd: 0xFE5, subCmd: 2, - request: { schema: OidbGroupListRequestSchema, value: body, isUid: true }, - response: { schema: OidbSvcTrpcTcp0xFE5_2ResponseSchema }, - }); + const env = makeOidbEnvelope(0xFE5, 2, body, true); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xfe5_2', encodeOidbEnv(env)); + const resp = decodeOidbEnv(respBytes).body; const groups: QQGroupInfo[] = []; if (resp?.groups) { @@ -184,12 +178,9 @@ export async function fetchGroupMemberList(bridge: Bridge, groupId: number): Pro }; if (token) body.token = token; - const resp = await runOidb(bridge, { - cmd: 'OidbSvcTrpcTcp.0xfe7_3', - oidbCmd: 0xFE7, subCmd: 3, - request: { schema: OidbGroupMemberListRequestSchema, value: body }, - response: { schema: OidbSvcTrpcTcp0xFE7_3ResponseSchema }, - }); + const env = makeOidbEnvelope(0xFE7, 3, body); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xfe7_3', encodeOidbEnv(env)); + const resp = decodeOidbEnv(respBytes).body; if (resp?.members) { for (const raw of resp.members) { @@ -234,12 +225,9 @@ export async function fetchUserProfile(bridge: Bridge, uin: number): Promise(bridge, { - cmd: 'OidbSvcTrpcTcp.0xfe1_2', - oidbCmd: 0xFE1, subCmd: 2, - request: { schema: OidbUserInfoRequestSchema, value: body, isUid: true }, - response: { schema: OidbUserInfoResponseSchema }, - }); + const env = makeOidbEnvelope(0xFE1, 2, body, true); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xfe1_2', encodeOidbEnv(env)); + const resp = decodeOidbEnv(respBytes).body; if (!resp?.body) throw new Error('user info response body missing'); @@ -291,12 +279,9 @@ export async function fetchUserProfile(bridge: Bridge, uin: number): Promise { const subCmd = filtered ? 2 : 1; const cmd = filtered ? 'OidbSvcTrpcTcp.0x10c0_2' : 'OidbSvcTrpcTcp.0x10c0_1'; - const resp = await runOidb(bridge, { - cmd, - oidbCmd: 0x10C0, subCmd, - request: { schema: OidbGroupRequestListSchema, value: { count: 20, field2: 0 } }, - response: { schema: OidbSvcTrpcTcp0x10C0ResponseSchema }, - }); + const env = makeOidbEnvelope(0x10C0, subCmd, { count: 20, field2: 0 }); + const respBytes = await runOidb(bridge, cmd, encodeOidbEnv(env)); + const resp = decodeOidbEnv(respBytes).body; const requests: GroupRequestInfo[] = []; for (const raw of resp?.requests ?? []) { @@ -343,12 +328,9 @@ export async function fetchDownloadRKeys(bridge: Bridge): Promise(bridge, { - cmd: 'OidbSvcTrpcTcp.0x9067_202', - oidbCmd: 0x9067, subCmd: 202, - request: { schema: NTV2RichMediaReqSchema, value: body, isUid: true }, - response: { schema: NTV2RichMediaRespSchema }, - }); + const env = makeOidbEnvelope(0x9067, 202, body, true); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x9067_202', encodeOidbEnv(env)); + const resp = decodeOidbEnv(respBytes).body; if (resp?.respHead?.retCode && resp.respHead.retCode !== 0) { throw new Error(resp.respHead.message ?? 'fetch download rkey failed'); diff --git a/packages/core/src/bridge/bridge-oidb.ts b/packages/core/src/bridge/bridge-oidb.ts index 23e71579..cdd5c76e 100644 --- a/packages/core/src/bridge/bridge-oidb.ts +++ b/packages/core/src/bridge/bridge-oidb.ts @@ -1,96 +1,101 @@ -// One deep entry point for a single OIDB round-trip: build the envelope, -// dispatch via Bridge.sendRawPacket, validate the response status, and -// optionally decode the body. Replaces the three positional helpers -// (makeOidbRequest / sendOidbAndCheck / sendOidbAndDecode) that used to -// scatter the same five-step pattern across every action file. +// One deep entry point for a single OIDB round-trip: dispatch a +// pre-encoded envelope via Bridge.sendRawPacket, validate the envelope +// retCode, and return the raw response bytes. +// +// History note. The legacy implementation used a runtime +// `makeOidbBaseSchema(InnerSchema)` factory and ran a runtime +// schema-walking encoder. Proton is compile-time, so the envelope is +// the generic interface `OidbBase` (proto/proton/oidb.ts). Proton's +// wrapper-binding requires *pass-through* wrappers (the wrapper's first +// arg must be forwarded unchanged to the inner codec — see +// proton/src/transform/replacer.ts), so this file exposes thin +// pass-through helpers (`encodeOidbEnv` / `decodeOidbEnv`) that +// proton monomorphizes at every call site. `runOidb` itself is +// non-generic — it just sends pre-encoded bytes and peeks at the +// envelope retCode via the non-generic `OidbBaseMeta` view. import type { Bridge } from './bridge'; -import type { ProtoSchema } from '../protobuf/decode'; -import { protoEncode, protoDecode } from '../protobuf/decode'; -import { makeOidbBaseSchema } from './proto/oidb'; +import { protobuf_encode, protobuf_decode } from '@snowluma/proton'; +import type { OidbBase, OidbBaseMeta } from './proto/proton/oidb'; -export interface OidbCall { - /** Service-cmd string sent on the wire, e.g. 'OidbSvcTrpcTcp.0x1253_1'. */ - cmd: string; - /** OIDB command number, e.g. 0x1253. */ - oidbCmd: number; - /** OIDB sub-command, e.g. 1. */ - subCmd: number; - request: { - schema: ProtoSchema; - value: any; - /** - * Sets the OIDB envelope `reserved` field to 1 when true. - * - * The name is historical and misleading: empirically (see Lagrange - * FetchStrangerByUin vs FetchStrangerByUid, fetchGroupList, our own - * highway uploads) the `reserved = 1` flag indicates the UIN-form - * variant of an OIDB call — it tells newer QQ NT to translate the - * UIN in the body to an internal UID rather than running the - * UID-form validator that expects a uid/openid string in the body. - * - * Omit (default false) for genuinely UID-keyed calls. - */ - isUid?: boolean; - }; - /** Omit to skip decoding the response body (fire-and-check). */ - response?: { - schema: ProtoSchema; +/** + * Build the OidbBase-shaped TS value. Pure helper, no protobuf + * encoding happens here — pair with `encodeOidbEnv` to produce the + * wire bytes. + * + * The `isUid` flag sets the envelope `reserved` field to 1; despite the + * name (kept for back-compat with the legacy API), `reserved = 1` + * empirically signals the UIN-form variant of an OIDB call. Omit + * (default false) for genuinely UID-keyed calls. + */ +export function makeOidbEnvelope( + oidbCmd: number, + subCmd: number, + body: T, + isUid: boolean = false, +): OidbBase { + return { + command: oidbCmd, + subCommand: subCmd, + errorCode: 0, + body, + errorMsg: '', + reserved: isUid ? 1 : 0, }; } /** - * Issue one OIDB request. Without `response`, returns void after - * verifying the envelope's retCode. With `response`, decodes the - * envelope, validates retCode, and returns the inner body. - * - * Throws on transport failure, missing response, decode failure, or any - * non-zero envelope retCode. Action modules layer their own retCode - * checks (on inner sub-replies like `upload.retCode`) on top of this. + * Pass-through encoder for the OIDB envelope. Single type param, body + * literally forwards its arg to `protobuf_encode>` — proton + * wrapper-binds this and replaces every `encodeOidbEnv(env)` call + * site with `protobuf_encode_OidbBase__MyReq(env)` at build time. */ -export function runOidb(bridge: Bridge, call: OidbCall & { response?: undefined }): Promise; -export function runOidb(bridge: Bridge, call: OidbCall & { response: { schema: ProtoSchema } }): Promise; -export async function runOidb(bridge: Bridge, call: OidbCall): Promise { - const envelope = encodeOidbEnvelope(call); - const result = await bridge.sendRawPacket(call.cmd, envelope); +export function encodeOidbEnv(env: OidbBase): Uint8Array { + return protobuf_encode>(env); +} + +/** + * Pass-through decoder for the OIDB envelope. Mirror of `encodeOidbEnv` + * — proton monomorphizes `OidbBase` per call site. + * + * Returns the full envelope; the caller usually wants `.body`. + */ +export function decodeOidbEnv(bytes: Uint8Array): OidbBase { + return protobuf_decode>(bytes); +} + +/** + * Issue one OIDB request and return the raw response bytes. + * + * Typical usage: + * const env = makeOidbEnvelope(0x1253, 1, value); + * const buf = await runOidb(bridge, cmd, encodeOidbEnv(env)); + * const resp = decodeOidbEnv(buf).body; + * + * Fire-and-check (no body decode): + * await runOidb(bridge, cmd, encodeOidbEnv(env)); + * + * Always peeks at the envelope errorCode via the non-generic + * `OidbBaseMeta` view so a server-side rejection cannot slip past + * silently. Returns the raw response bytes (empty `Uint8Array` if the + * packet carried no payload). + */ +export async function runOidb( + bridge: Bridge, + cmd: string, + envelopeBytes: Uint8Array, +): Promise { + const result = await bridge.sendRawPacket(cmd, envelopeBytes); if (!result.success) throw new Error(result.errorMessage || 'packet send failed'); - - if (call.response) { - if (!result.gotResponse || !result.responseData) { - throw new Error(result.errorMessage || 'no response'); - } - const baseSchema = makeOidbBaseSchema(call.response.schema); - const resp = protoDecode(result.responseData, baseSchema); - if (!resp) throw new Error('failed to decode OIDB response'); - throwIfOidbError(resp); - return (resp as any).body as TResp; - } - - // Fire-and-check: response data is optional, but if present we still - // peek at the envelope so a server-side retCode doesn't silently slip past. if (!result.gotResponse) throw new Error(result.errorMessage || 'no response'); - if (result.responseData && result.responseData.length > 0) { - const emptyBase = makeOidbBaseSchema({ _dummy: { field: 99, type: 'uint32' as const } }); - const resp = protoDecode(result.responseData, emptyBase); - if (resp) throwIfOidbError(resp); - } -} -function encodeOidbEnvelope(call: OidbCall): Uint8Array { - const baseSchema = makeOidbBaseSchema(call.request.schema); - return protoEncode({ - command: call.oidbCmd, - subCommand: call.subCmd, - errorCode: 0, - body: call.request.value, - errorMsg: '', - reserved: call.request.isUid ? 1 : 0, - }, baseSchema); -} - -function throwIfOidbError(resp: unknown): void { - const code = (resp as any).errorCode; - if (code && code !== 0) { - throw new Error(`OIDB error ${code}: ${(resp as any).errorMsg ?? ''}`); + const bytes = result.responseData ?? new Uint8Array(0); + if (bytes.length > 0) { + const meta = protobuf_decode(bytes); + const code = meta?.errorCode; + if (code && code !== 0) { + throw new Error(`OIDB error ${code}: ${meta?.errorMsg ?? ''}`); + } } + return bytes; } diff --git a/packages/core/src/bridge/highway/pipeline.ts b/packages/core/src/bridge/highway/pipeline.ts index b04b6b32..86b0be53 100644 --- a/packages/core/src/bridge/highway/pipeline.ts +++ b/packages/core/src/bridge/highway/pipeline.ts @@ -17,13 +17,13 @@ import crypto from 'crypto'; import type { Bridge } from '../bridge'; -import { protoDecode, protoEncode } from '../../protobuf/decode'; -import { makeOidbBaseSchema } from '../proto/oidb'; -import { - EncodableMediaMsgInfoSchema, - NTV2UploadRichMediaReqSchema, - NTV2UploadRichMediaRespSchema, -} from '../proto/highway'; +import { protobuf_encode } from '@snowluma/proton'; +import { makeOidbEnvelope, encodeOidbEnv, decodeOidbEnv } from '../bridge-oidb'; +import type { + EncodableMediaMsgInfo, + NTV2UploadRichMediaReq, + NTV2UploadRichMediaResp, +} from '../proto/proton/highway'; import { buildHighwayExtend, fetchHighwaySession, uploadHighwayHttp } from './highway-client'; import { createLogger } from '../../utils/logger'; @@ -159,24 +159,21 @@ export async function runNtv2Upload(params: NtV2UploadParams): Promise { }, }; - const baseSchema = makeOidbBaseSchema(NTV2UploadRichMediaReqSchema); - const request = protoEncode({ - command: oidbCmd, subCommand: 100, errorCode: 0, body, errorMsg: '', reserved: 1, - }, baseSchema); + const env = makeOidbEnvelope(oidbCmd, 100, body, true); + const requestBytes = encodeOidbEnv(env); - const result = await bridge.sendRawPacket(serviceCmd, request); + const result = await bridge.sendRawPacket(serviceCmd, requestBytes); if (!result.success || !result.gotResponse || !result.responseData) { throw new Error(result.errorMessage || `${label} upload request failed`); } - const respBaseSchema = makeOidbBaseSchema(NTV2UploadRichMediaRespSchema); - const resp: any = protoDecode(result.responseData, respBaseSchema); + const resp = decodeOidbEnv(result.responseData); if (!resp) throw new Error(`failed to decode ${label} upload response`); if (resp.errorCode && resp.errorCode !== 0) { throw new Error(`OIDB error ${resp.errorCode}: ${resp.errorMsg ?? ''}`); } - const uploadBody = resp.body; + const uploadBody: any = resp.body; if (!uploadBody) throw new Error(`${label} upload response body missing`); if (uploadBody.respHead?.retCode && uploadBody.respHead.retCode !== 0) { throw new Error(uploadBody.respHead.message ?? `${label} upload failed`); @@ -262,5 +259,5 @@ export function finalizeMediaMsgInfo( extBizInfo.busiType = upload.msgInfo.extBizInfo.busiType; } - return protoEncode({ msgInfoBody, extBizInfo }, EncodableMediaMsgInfoSchema); + return protobuf_encode({ msgInfoBody, extBizInfo }); } diff --git a/packages/core/src/bridge/web-actions/cookies.ts b/packages/core/src/bridge/web-actions/cookies.ts index 65bc37cf..fb398d79 100644 --- a/packages/core/src/bridge/web-actions/cookies.ts +++ b/packages/core/src/bridge/web-actions/cookies.ts @@ -4,22 +4,19 @@ // thread the cookies into a qun.qq.com REST endpoint. import type { Bridge } from '../bridge'; -import { runOidb } from '../bridge-oidb'; -import { - OidbClientKeyRespSchema, - OidbClientKeyReqSchema, - OidbGetPskeyReqSchema, - OidbGetPskeyRespSchema, -} from '../proto/oidb-action'; +import { runOidb, makeOidbEnvelope, encodeOidbEnv, decodeOidbEnv } from '../bridge-oidb'; +import type { + OidbClientKeyReq, + OidbClientKeyResp, + OidbGetPskeyReq, + OidbGetPskeyResp, +} from '../proto/proton/oidb-action'; import { RequestUtil } from '../web/request-util'; export async function forceFetchClientKey(bridge: Bridge) { - const resp = await runOidb(bridge, { - cmd: 'OidbSvcTrpcTcp.0x102a_1', - oidbCmd: 0x102A, subCmd: 1, - request: { schema: OidbClientKeyReqSchema, value: {} }, - response: { schema: OidbClientKeyRespSchema }, - }); + const env = makeOidbEnvelope(0x102A, 1, {}); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x102a_1', encodeOidbEnv(env)); + const resp = decodeOidbEnv(respBytes).body; const clientKey = resp?.clientKey || ''; // keyIndex falls back to "19" — origin unknown but the value is what @@ -34,12 +31,9 @@ export async function forceFetchClientKey(bridge: Bridge) { } export async function getPSkey(bridge: Bridge, domainList: string[]) { - const resp = await runOidb(bridge, { - cmd: 'OidbSvcTrpcTcp.0x102a_0', - oidbCmd: 0x102A, subCmd: 0, - request: { schema: OidbGetPskeyReqSchema, value: { domainList } }, - response: { schema: OidbGetPskeyRespSchema }, - }); + const env = makeOidbEnvelope(0x102A, 0, { domainList }); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x102a_0', encodeOidbEnv(env)); + const resp = decodeOidbEnv(respBytes).body; const domainPskeyMap = new Map(); diff --git a/packages/core/tests/actions/extras.test.ts b/packages/core/tests/actions/extras.test.ts index eca813a8..0278be45 100644 --- a/packages/core/tests/actions/extras.test.ts +++ b/packages/core/tests/actions/extras.test.ts @@ -1,19 +1,38 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '../../src/bridge/proto/proton/oidb'; +import type { + OidbStrangerStatusResp, + OidbAiVoiceListResp, + OidbAiVoiceResp, +} from '../../src/bridge/proto/proton/oidb-action'; -// Same stub-the-oidb-runner pattern as actions/group-admin.test.ts — -// we don't care about wire bytes, just that each function targets the -// right cmd / subCmd / schema. -vi.mock('../../src/bridge/bridge-oidb', () => ({ - runOidb: vi.fn(async () => ({})), -})); +// `encodeOidbEnv` / `decodeOidbEnv` are proton-bound pass-through wrappers +// that the plugin substitutes at the call site with the inlined codec, so +// mocking them on the module object is a no-op. The only mockable point +// is `runOidb` (non-generic, untouched by proton) returning real bytes +// that the production-side codec then decodes. `makeOidbEnvelope` is a +// pure TS helper, so its mock works for introspection. +vi.mock('../../src/bridge/bridge-oidb', async () => { + const actual = await vi.importActual( + '../../src/bridge/bridge-oidb', + ); + return { + ...actual, + runOidb: vi.fn(async () => new Uint8Array()), + makeOidbEnvelope: vi.fn((_oidbCmd, _subCmd, body) => ({ body })), + }; +}); import * as oidb from '../../src/bridge/bridge-oidb'; import * as extras from '../../src/bridge/actions/extras'; -import * as schemas from '../../src/bridge/proto/oidb-action'; import { mockBridge } from './_helpers'; describe('actions/extras / group todo (0xF90)', () => { - beforeEach(() => vi.mocked(oidb.runOidb).mockClear()); + beforeEach(() => { + vi.mocked(oidb.runOidb).mockClear(); + vi.mocked(oidb.makeOidbEnvelope).mockClear(); + }); it.each([ ['setGroupTodo', extras.setGroupTodo, 'OidbSvcTrpcTcp.0xf90_1', 1], @@ -22,32 +41,41 @@ describe('actions/extras / group todo (0xF90)', () => { ] as const)('%s dispatches the right subCmd with shared body', async (_name, fn, cmd, subCmd) => { const bridge = mockBridge(); await fn(bridge as any, 12345, 9876543210n); - const call = vi.mocked(oidb.runOidb).mock.calls[0]![1]; - expect(call.cmd).toBe(cmd); - expect(call.oidbCmd).toBe(0xF90); - expect(call.subCmd).toBe(subCmd); - expect(call.request.schema).toBe(schemas.OidbGroupTodoSchema); - expect(call.request.value).toEqual({ groupUin: 12345, msgSeq: 9876543210n }); + const [, runCmd] = vi.mocked(oidb.runOidb).mock.calls[0]!; + expect(runCmd).toBe(cmd); + const [oidbCmd, sub, body] = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]!; + expect(oidbCmd).toBe(0xF90); + expect(sub).toBe(subCmd); + expect(body).toEqual({ groupUin: 12345, msgSeq: 9876543210n }); }); }); describe('actions/extras / getStrangerStatus (0xFE1_2)', () => { - beforeEach(() => vi.mocked(oidb.runOidb).mockClear()); + beforeEach(() => { + vi.mocked(oidb.runOidb).mockReset(); + vi.mocked(oidb.runOidb).mockResolvedValue(new Uint8Array()); + vi.mocked(oidb.makeOidbEnvelope).mockClear(); + }); it('issues the FE1_2 query with key=27372', async () => { const bridge = mockBridge(); - vi.mocked(oidb.runOidb).mockResolvedValueOnce({ data: { status: { value: 5n } } } as any); + vi.mocked(oidb.runOidb).mockResolvedValueOnce( + protobuf_encode>({ body: { data: { status: { value: 5n } } } }), + ); await extras.getStrangerStatus(bridge as any, 100200); - const call = vi.mocked(oidb.runOidb).mock.calls[0]![1]; - expect(call.cmd).toBe('OidbSvcTrpcTcp.0xfe1_2'); - expect(call.oidbCmd).toBe(0xFE1); - expect(call.subCmd).toBe(2); - expect(call.request.value).toMatchObject({ uin: 100200, key: [{ key: 27372 }] }); + const [, runCmd] = vi.mocked(oidb.runOidb).mock.calls[0]!; + expect(runCmd).toBe('OidbSvcTrpcTcp.0xfe1_2'); + const [oidbCmd, sub, body] = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]!; + expect(oidbCmd).toBe(0xFE1); + expect(sub).toBe(2); + expect(body).toMatchObject({ uin: 100200, key: [{ key: 27372 }] }); }); it('low-band values (≤10) map to status*10 with ext_status=0', async () => { const bridge = mockBridge(); - vi.mocked(oidb.runOidb).mockResolvedValueOnce({ data: { status: { value: 7n } } } as any); + vi.mocked(oidb.runOidb).mockResolvedValueOnce( + protobuf_encode>({ body: { data: { status: { value: 7n } } } }), + ); expect(await extras.getStrangerStatus(bridge as any, 1)).toEqual({ status: 70, ext_status: 0 }); }); @@ -56,7 +84,9 @@ describe('actions/extras / getStrangerStatus (0xFE1_2)', () => { // value 0x42F100: bits 8-15 (the 0xff00 mask) = 0xF100; // bits 16-23 (>>16 & 0xff) = 0x42. // ext_status = 0xF100 + 0x42 = 0xF142. - vi.mocked(oidb.runOidb).mockResolvedValueOnce({ data: { status: { value: 0x42F100n } } } as any); + vi.mocked(oidb.runOidb).mockResolvedValueOnce( + protobuf_encode>({ body: { data: { status: { value: 0x42F100n } } } }), + ); const status = await extras.getStrangerStatus(bridge as any, 1); expect(status).toEqual({ status: 10, ext_status: 0xF142 }); }); @@ -69,58 +99,74 @@ describe('actions/extras / getStrangerStatus (0xFE1_2)', () => { it('returns null when the server omits the status field', async () => { const bridge = mockBridge(); - vi.mocked(oidb.runOidb).mockResolvedValueOnce({} as any); + vi.mocked(oidb.runOidb).mockResolvedValueOnce( + protobuf_encode>({ body: {} }), + ); expect(await extras.getStrangerStatus(bridge as any, 1)).toBeNull(); }); }); describe('actions/extras / AI voice (0x929D / 0x929B)', () => { - beforeEach(() => vi.mocked(oidb.runOidb).mockClear()); + beforeEach(() => { + vi.mocked(oidb.runOidb).mockReset(); + vi.mocked(oidb.runOidb).mockResolvedValue(new Uint8Array()); + vi.mocked(oidb.makeOidbEnvelope).mockClear(); + }); it('fetchAiVoiceList sends 0x929D_0 and returns server content verbatim', async () => { const bridge = mockBridge(); const fake = [ { category: 'cute', voices: [{ voiceId: 'v1', voiceDisplayName: 'V1', voiceExampleUrl: 'http://x' }] }, ]; - vi.mocked(oidb.runOidb).mockResolvedValueOnce({ content: fake } as any); + vi.mocked(oidb.runOidb).mockResolvedValueOnce( + protobuf_encode>({ body: { content: fake } } as any), + ); const out = await extras.fetchAiVoiceList(bridge as any, 4242, extras.AiVoiceChatType.Sound); expect(out).toEqual(fake); - const call = vi.mocked(oidb.runOidb).mock.calls[0]![1]; - expect(call.cmd).toBe('OidbSvcTrpcTcp.0x929d_0'); - expect(call.request.value).toEqual({ groupUin: 4242, chatType: 1 }); + const [, runCmd] = vi.mocked(oidb.runOidb).mock.calls[0]!; + expect(runCmd).toBe('OidbSvcTrpcTcp.0x929d_0'); + const body = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2]; + expect(body).toEqual({ groupUin: 4242, chatType: 1 }); }); it('fetchAiVoiceList returns [] when server replies with no content', async () => { const bridge = mockBridge(); - vi.mocked(oidb.runOidb).mockResolvedValueOnce({} as any); + vi.mocked(oidb.runOidb).mockResolvedValueOnce( + protobuf_encode>({ body: {} }), + ); const out = await extras.fetchAiVoiceList(bridge as any, 1, 1 as any); expect(out).toEqual([]); }); it('fetchAiVoice retries while msgInfo is empty, returns the first IndexNode it sees', async () => { const bridge = mockBridge(); - const node = { fileUuid: 'uuid-1', subType: 0 }; + // subType is non-zero so proto3 doesn't omit it from the wire (the + // re-decoded object must include the field for the matcher to spot it). + const node = { fileUuid: 'uuid-1', subType: 1 }; vi.mocked(oidb.runOidb) - .mockResolvedValueOnce({ statusCode: 2 } as any) - .mockResolvedValueOnce({ msgInfo: { msgInfoBody: [] } } as any) - .mockResolvedValueOnce({ msgInfo: { msgInfoBody: [{ index: node }] } } as any); + .mockResolvedValueOnce(protobuf_encode>({ body: { statusCode: 2 } })) + .mockResolvedValueOnce(protobuf_encode>({ body: { msgInfo: { msgInfoBody: [] } } as any })) + .mockResolvedValueOnce(protobuf_encode>({ body: { msgInfo: { msgInfoBody: [{ index: node }] } } as any })); const out = await extras.fetchAiVoice(bridge as any, 100, 'voice-id', 'hi', extras.AiVoiceChatType.Sound); - expect(out).toBe(node); + expect(out).toMatchObject(node); expect(vi.mocked(oidb.runOidb)).toHaveBeenCalledTimes(3); - const call = vi.mocked(oidb.runOidb).mock.calls[0]![1]; - expect(call.cmd).toBe('OidbSvcTrpcTcp.0x929b_0'); - expect(call.request.value).toMatchObject({ + const [, runCmd] = vi.mocked(oidb.runOidb).mock.calls[0]!; + expect(runCmd).toBe('OidbSvcTrpcTcp.0x929b_0'); + const body = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2] as any; + expect(body).toMatchObject({ groupUin: 100, voiceId: 'voice-id', text: 'hi', chatType: 1, }); // sessionId is randomized but must be a uint32. - expect((call.request.value as any).session.sessionId).toBeTypeOf('number'); - expect((call.request.value as any).session.sessionId).toBeGreaterThanOrEqual(0); - expect((call.request.value as any).session.sessionId).toBeLessThanOrEqual(0xFFFFFFFF); + expect(body.session.sessionId).toBeTypeOf('number'); + expect(body.session.sessionId).toBeGreaterThanOrEqual(0); + expect(body.session.sessionId).toBeLessThanOrEqual(0xFFFFFFFF); }); it('fetchAiVoice throws after exhausting the retry budget', async () => { const bridge = mockBridge(); - vi.mocked(oidb.runOidb).mockResolvedValue({ statusCode: 1 } as any); + vi.mocked(oidb.runOidb).mockResolvedValue( + protobuf_encode>({ body: { statusCode: 1 } }), + ); await expect(extras.fetchAiVoice(bridge as any, 1, 'v', 't', 1 as any, 3)).rejects.toThrow( /AI voice synthesis did not complete/, ); @@ -131,11 +177,11 @@ describe('actions/extras / AI voice (0x929D / 0x929B)', () => { const bridge = mockBridge(); const node = { fileUuid: 'uuid', subType: 0 }; vi.mocked(oidb.runOidb) - .mockResolvedValueOnce({} as any) - .mockResolvedValueOnce({ msgInfo: { msgInfoBody: [{ index: node }] } } as any); + .mockResolvedValueOnce(protobuf_encode>({ body: {} })) + .mockResolvedValueOnce(protobuf_encode>({ body: { msgInfo: { msgInfoBody: [{ index: node }] } } as any })); await extras.fetchAiVoice(bridge as any, 1, 'v', 't', 1 as any); - const first = (vi.mocked(oidb.runOidb).mock.calls[0]![1].request.value as any).session.sessionId; - const second = (vi.mocked(oidb.runOidb).mock.calls[1]![1].request.value as any).session.sessionId; + const first = (vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2] as any).session.sessionId; + const second = (vi.mocked(oidb.makeOidbEnvelope).mock.calls[1]![2] as any).session.sessionId; expect(first).toBe(second); }); }); diff --git a/packages/core/tests/actions/forward.test.ts b/packages/core/tests/actions/forward.test.ts index 72f82931..2e63e515 100644 --- a/packages/core/tests/actions/forward.test.ts +++ b/packages/core/tests/actions/forward.test.ts @@ -1,7 +1,10 @@ import { describe, it, expect, vi } from 'vitest'; vi.mock('../../src/bridge/bridge-oidb', () => ({ - runOidb: vi.fn(async () => ({})), + runOidb: vi.fn(async () => new Uint8Array()), + makeOidbEnvelope: vi.fn((_oidbCmd, _subCmd, body) => ({ body })), + encodeOidbEnv: vi.fn(() => new Uint8Array()), + decodeOidbEnv: vi.fn(() => ({ body: {} })), })); // element-builder reaches into protoEncode with element-specific schemas diff --git a/packages/core/tests/actions/friend.test.ts b/packages/core/tests/actions/friend.test.ts index a190096c..919cd5ae 100644 --- a/packages/core/tests/actions/friend.test.ts +++ b/packages/core/tests/actions/friend.test.ts @@ -1,7 +1,10 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'; vi.mock('../../src/bridge/bridge-oidb', () => ({ - runOidb: vi.fn(async () => ({})), + runOidb: vi.fn(async () => new Uint8Array()), + makeOidbEnvelope: vi.fn((_oidbCmd, _subCmd, body) => ({ body })), + encodeOidbEnv: vi.fn(() => new Uint8Array()), + decodeOidbEnv: vi.fn(() => ({ body: {} })), })); import * as oidb from '../../src/bridge/bridge-oidb'; @@ -11,31 +14,35 @@ import { mockBridge } from './_helpers'; describe('actions/friend', () => { beforeEach(() => { vi.mocked(oidb.runOidb).mockClear(); + vi.mocked(oidb.makeOidbEnvelope).mockClear(); + vi.mocked(oidb.encodeOidbEnv).mockClear(); + vi.mocked(oidb.decodeOidbEnv).mockClear(); }); it('setFriendAddRequest: numeric input is treated as UIN and resolved', async () => { const bridge = mockBridge(); await friend.setFriendAddRequest(bridge as any, '10001', true); expect(bridge.resolveUserUid).toHaveBeenCalledWith(10001); - const call = vi.mocked(oidb.runOidb).mock.calls[0]![1]; - expect(call.request.value).toMatchObject({ accept: 3, targetUid: 'resolved-uid' }); + const body = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2]; + expect(body).toMatchObject({ accept: 3, targetUid: 'resolved-uid' }); }); it('setFriendAddRequest: non-numeric flag is forwarded as-is', async () => { const bridge = mockBridge(); await friend.setFriendAddRequest(bridge as any, 'flag-abc', false); expect(bridge.resolveUserUid).not.toHaveBeenCalled(); - const call = vi.mocked(oidb.runOidb).mock.calls[0]![1]; - expect(call.request.value).toMatchObject({ accept: 5, targetUid: 'flag-abc' }); + const body = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2]; + expect(body).toMatchObject({ accept: 5, targetUid: 'flag-abc' }); }); it('deleteFriend resolves UID, calls 0x126b_0, and triggers a friend-list refresh', async () => { const bridge = mockBridge(); await friend.deleteFriend(bridge as any, 10001, true); expect(bridge.resolveUserUid).toHaveBeenCalledWith(10001); - const call = vi.mocked(oidb.runOidb).mock.calls[0]![1]; - expect(call.cmd).toBe('OidbSvcTrpcTcp.0x126b_0'); - expect((call.request.value as any).field1.block).toBe(true); + const [, cmd] = vi.mocked(oidb.runOidb).mock.calls[0]!; + expect(cmd).toBe('OidbSvcTrpcTcp.0x126b_0'); + const body = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2]; + expect((body as any).field1.block).toBe(true); expect(bridge.fetchFriendList).toHaveBeenCalled(); }); @@ -50,8 +57,9 @@ describe('actions/friend', () => { it('setFriendRemark resolves UID and sends 0xb6e_2', async () => { const bridge = mockBridge(); await friend.setFriendRemark(bridge as any, 10001, 'best-friend'); - const call = vi.mocked(oidb.runOidb).mock.calls[0]![1]; - expect(call.cmd).toBe('OidbSvcTrpcTcp.0xb6e_2'); - expect(call.request.value).toMatchObject({ targetUid: 'resolved-uid', remark: 'best-friend' }); + const [, cmd] = vi.mocked(oidb.runOidb).mock.calls[0]!; + expect(cmd).toBe('OidbSvcTrpcTcp.0xb6e_2'); + const body = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2]; + expect(body).toMatchObject({ targetUid: 'resolved-uid', remark: 'best-friend' }); }); }); diff --git a/packages/core/tests/actions/group-admin.test.ts b/packages/core/tests/actions/group-admin.test.ts index cc2f0cb2..a7e0c5c7 100644 --- a/packages/core/tests/actions/group-admin.test.ts +++ b/packages/core/tests/actions/group-admin.test.ts @@ -1,10 +1,24 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '../../src/bridge/proto/proton/oidb'; +import type { Oidb0x8a7Resp } from '../../src/bridge/proto/proton/oidb-action'; -// Stub the OIDB shim so we can assert WHICH command + payload each -// action constructs without booting a real Bridge / native pipe. -vi.mock('../../src/bridge/bridge-oidb', () => ({ - runOidb: vi.fn(async () => ({})), -})); +// `encodeOidbEnv` / `decodeOidbEnv` are proton-bound pass-through wrappers +// that the plugin substitutes at the call site with the inlined codec, so +// mocking them on the module object is a no-op. The only mockable point +// is `runOidb` (non-generic, untouched by proton) returning real bytes +// that the production-side codec then decodes. `makeOidbEnvelope` is a +// pure TS helper, so its mock works for introspection. +vi.mock('../../src/bridge/bridge-oidb', async () => { + const actual = await vi.importActual( + '../../src/bridge/bridge-oidb', + ); + return { + ...actual, + runOidb: vi.fn(async () => new Uint8Array()), + makeOidbEnvelope: vi.fn((_oidbCmd, _subCmd, body) => ({ body })), + }; +}); import * as oidb from '../../src/bridge/bridge-oidb'; import * as admin from '../../src/bridge/actions/group-admin'; @@ -12,7 +26,9 @@ import { mockBridge } from './_helpers'; describe('actions/group-admin', () => { beforeEach(() => { - vi.mocked(oidb.runOidb).mockClear(); + vi.mocked(oidb.runOidb).mockReset(); + vi.mocked(oidb.runOidb).mockResolvedValue(new Uint8Array()); + vi.mocked(oidb.makeOidbEnvelope).mockClear(); }); it('muteGroupMember resolves UID and dispatches 0x1253_1', async () => { @@ -20,11 +36,12 @@ describe('actions/group-admin', () => { await admin.muteGroupMember(bridge as any, 12345, 67890, 600); expect(bridge.resolveUserUid).toHaveBeenCalledWith(67890, 12345); expect(oidb.runOidb).toHaveBeenCalledOnce(); - const call = vi.mocked(oidb.runOidb).mock.calls[0]![1]; - expect(call.cmd).toBe('OidbSvcTrpcTcp.0x1253_1'); - expect(call.oidbCmd).toBe(0x1253); - expect(call.subCmd).toBe(1); - expect(call.request.value).toMatchObject({ + const [, cmd] = vi.mocked(oidb.runOidb).mock.calls[0]!; + expect(cmd).toBe('OidbSvcTrpcTcp.0x1253_1'); + const [oidbCmd, subCmd, body] = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]!; + expect(oidbCmd).toBe(0x1253); + expect(subCmd).toBe(1); + expect(body).toMatchObject({ groupUin: 12345, type: 1, body: { targetUid: 'resolved-uid', duration: 600 }, @@ -34,13 +51,13 @@ describe('actions/group-admin', () => { it('muteGroupAll flips the muteState flag based on enable', async () => { const bridge = mockBridge(); await admin.muteGroupAll(bridge as any, 12345, true); - expect(vi.mocked(oidb.runOidb).mock.calls[0]![1].request.value).toMatchObject({ + expect(vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2]).toMatchObject({ groupUin: 12345, muteState: { state: 0xFFFFFFFF }, }); await admin.muteGroupAll(bridge as any, 12345, false); - expect(vi.mocked(oidb.runOidb).mock.calls[1]![1].request.value).toMatchObject({ + expect(vi.mocked(oidb.makeOidbEnvelope).mock.calls[1]![2]).toMatchObject({ muteState: { state: 0 }, }); }); @@ -49,7 +66,7 @@ describe('actions/group-admin', () => { const bridge = mockBridge(); await admin.kickGroupMember(bridge as any, 12345, 67890, true, 'bad behaviour'); expect(bridge.resolveUserUid).toHaveBeenCalledWith(67890, 12345); - expect(vi.mocked(oidb.runOidb).mock.calls[0]![1].request.value).toMatchObject({ + expect(vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2]).toMatchObject({ groupUin: 12345, targetUid: 'resolved-uid', rejectAddRequest: true, @@ -65,7 +82,7 @@ describe('actions/group-admin', () => { await admin.kickGroupMembers(bridge as any, 12345, [11, 22], false); expect(bridge.resolveUserUid).toHaveBeenCalledTimes(2); - const payload: any = vi.mocked(oidb.runOidb).mock.calls[0]![1].request.value; + const payload: any = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2]; expect(payload.targetUids).toEqual(['uid-a', 'uid-b']); expect(payload.rejectAddRequest).toBe(0); }); @@ -73,15 +90,15 @@ describe('actions/group-admin', () => { it('leaveGroup sends 0x1097_1 with the groupUin', async () => { const bridge = mockBridge(); await admin.leaveGroup(bridge as any, 12345); - const call = vi.mocked(oidb.runOidb).mock.calls[0]![1]; - expect(call.cmd).toBe('OidbSvcTrpcTcp.0x1097_1'); - expect(call.request.value).toMatchObject({ groupUin: 12345 }); + const [, cmd] = vi.mocked(oidb.runOidb).mock.calls[0]!; + expect(cmd).toBe('OidbSvcTrpcTcp.0x1097_1'); + expect(vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2]).toMatchObject({ groupUin: 12345 }); }); it('setGroupAdmin resolves UID and sends 0x1096_1', async () => { const bridge = mockBridge(); await admin.setGroupAdmin(bridge as any, 12345, 67890, true); - expect(vi.mocked(oidb.runOidb).mock.calls[0]![1].request.value).toMatchObject({ + expect(vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2]).toMatchObject({ groupUin: 12345, uid: 'resolved-uid', isAdmin: true, }); }); @@ -95,7 +112,7 @@ describe('actions/group-admin', () => { await admin.setGroupAddOption(bridge as any, 1, 2); await admin.setGroupSearch(bridge as any, 1); - const cmds = vi.mocked(oidb.runOidb).mock.calls.map(call => call[1].cmd); + const cmds = vi.mocked(oidb.runOidb).mock.calls.map(call => call[1]); expect(cmds).toEqual([ 'OidbSvcTrpcTcp.0x8fc_3', 'OidbSvcTrpcTcp.0x89a_15', @@ -111,27 +128,27 @@ describe('actions/group-admin', () => { await admin.setGroupAddRequest(bridge as any, 12345, 5, 1, true, 'ok', false); await admin.setGroupAddRequest(bridge as any, 12345, 5, 1, false, 'no', true); - const cmds = vi.mocked(oidb.runOidb).mock.calls.map(call => call[1].cmd); + const cmds = vi.mocked(oidb.runOidb).mock.calls.map(call => call[1]); expect(cmds).toEqual([ 'OidbSvcTrpcTcp.0x10c8_1', 'OidbSvcTrpcTcp.0x10c8_2', ]); - const firstBody: any = vi.mocked(oidb.runOidb).mock.calls[0]![1].request.value; + const firstBody: any = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2]; expect(firstBody.accept).toBe(1); expect(firstBody.body.message).toBe('ok'); - const secondBody: any = vi.mocked(oidb.runOidb).mock.calls[1]![1].request.value; + const secondBody: any = vi.mocked(oidb.makeOidbEnvelope).mock.calls[1]![2]; expect(secondBody.accept).toBe(2); }); it('getGroupAtAllRemain decodes the response and converts BigInts', async () => { const bridge = mockBridge(); - vi.mocked(oidb.runOidb).mockResolvedValueOnce({ - canAtAll: 1, - groupRemain: 12n, - uinRemain: 5n, - }); + vi.mocked(oidb.runOidb).mockResolvedValueOnce( + protobuf_encode>({ + body: { canAtAll: true, groupRemain: 12, uinRemain: 5 } as any, + }), + ); const out = await admin.getGroupAtAllRemain(bridge as any, 12345); expect(out).toEqual({ can_at_all: true, @@ -142,7 +159,11 @@ describe('actions/group-admin', () => { it('getGroupAtAllRemain throws when the response is empty', async () => { const bridge = mockBridge(); - vi.mocked(oidb.runOidb).mockResolvedValueOnce(null); + // An empty OidbBase envelope (no body) — production code sees `body` + // undefined and throws the "empty" error. + vi.mocked(oidb.runOidb).mockResolvedValueOnce( + protobuf_encode>({}), + ); await expect(admin.getGroupAtAllRemain(bridge as any, 12345)).rejects.toThrow(/empty/); }); }); diff --git a/packages/core/tests/actions/group-file.test.ts b/packages/core/tests/actions/group-file.test.ts index 2f71bc76..2a10edd9 100644 --- a/packages/core/tests/actions/group-file.test.ts +++ b/packages/core/tests/actions/group-file.test.ts @@ -1,8 +1,30 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '../../src/bridge/proto/proton/oidb'; +import type { + OidbGroupFileCountViewResp, + OidbGroupFileResp, + OidbGroupFileViewResp, + OidbPrivateFileUploadResp, + OidbGroupFileFolderResp, + NTV2RichMediaResp, +} from '../../src/bridge/proto/proton/oidb-action'; -vi.mock('../../src/bridge/bridge-oidb', () => ({ - runOidb: vi.fn(async () => ({})), -})); +// `encodeOidbEnv` / `decodeOidbEnv` are proton-bound pass-through wrappers +// (substituted at the call site with the inlined codec). Mocking them on +// the module object is a no-op — proton has already inlined the call. +// We mock `runOidb` (non-generic, proton leaves it alone) to return real +// proton-encoded bytes, which the production-side codec then decodes. +vi.mock('../../src/bridge/bridge-oidb', async () => { + const actual = await vi.importActual( + '../../src/bridge/bridge-oidb', + ); + return { + ...actual, + runOidb: vi.fn(async () => new Uint8Array()), + makeOidbEnvelope: vi.fn((_oidbCmd, _subCmd, body) => ({ body })), + }; +}); vi.mock('../../src/bridge/highway/highway-client', () => ({ fetchHighwaySession: vi.fn(async () => ({})), @@ -27,36 +49,45 @@ import { mockBridge } from './_helpers'; describe('actions/group-file', () => { beforeEach(() => { vi.mocked(oidb.runOidb).mockReset(); - vi.mocked(oidb.runOidb).mockResolvedValue({}); + vi.mocked(oidb.runOidb).mockResolvedValue(new Uint8Array()); + vi.mocked(oidb.makeOidbEnvelope).mockClear(); vi.mocked(highwayClient.fetchHighwaySession).mockClear(); vi.mocked(highwayClient.uploadHighwayHttp).mockClear(); }); it('fetchGroupFileCount returns { fileCount, maxCount } from the OIDB response', async () => { const bridge = mockBridge(); - vi.mocked(oidb.runOidb).mockResolvedValueOnce({ - count: { fileCount: 42, maxCount: 1000 }, - }); + vi.mocked(oidb.runOidb).mockResolvedValueOnce( + protobuf_encode>({ + body: { count: { fileCount: 42, maxCount: 1000 } }, + }), + ); const out = await groupFile.fetchGroupFileCount(bridge as any, 12345); expect(out).toEqual({ fileCount: 42, maxCount: 1000 }); }); it('fetchGroupFileCount falls back to defaults on partial response', async () => { const bridge = mockBridge(); - vi.mocked(oidb.runOidb).mockResolvedValueOnce({ count: {} }); + vi.mocked(oidb.runOidb).mockResolvedValueOnce( + protobuf_encode>({ body: { count: {} } }), + ); const out = await groupFile.fetchGroupFileCount(bridge as any, 12345); expect(out).toEqual({ fileCount: 0, maxCount: 10000 }); }); it('uploadGroupFile skips highway when boolFileExist is true', async () => { const bridge = mockBridge(); - vi.mocked(oidb.runOidb).mockResolvedValueOnce({ - upload: { - retCode: 0, - fileId: 'fid-xyz', - boolFileExist: true, - }, - }); + vi.mocked(oidb.runOidb).mockResolvedValueOnce( + protobuf_encode>({ + body: { + upload: { + // retCode 0 omitted by proto3 — production only checks against nonzero + fileId: 'fid-xyz', + boolFileExist: true, + }, + } as any, + }), + ); const out = await groupFile.uploadGroupFile(bridge as any, 12345, '/path/file.bin'); expect(out).toEqual({ fileId: 'fid-xyz' }); expect(highwayClient.fetchHighwaySession).not.toHaveBeenCalled(); @@ -65,17 +96,21 @@ describe('actions/group-file', () => { it('uploadGroupFile runs highway PUT when boolFileExist is false', async () => { const bridge = mockBridge(); - vi.mocked(oidb.runOidb).mockResolvedValueOnce({ - upload: { - retCode: 0, - fileId: 'fid-xyz', - boolFileExist: false, - uploadIp: '1.2.3.4', - uploadPort: 8080, - fileKey: new Uint8Array([9]), - checkKey: new Uint8Array([8]), - }, - }); + vi.mocked(oidb.runOidb).mockResolvedValueOnce( + protobuf_encode>({ + body: { + upload: { + fileId: 'fid-xyz', + // boolFileExist is the proto3 default (false) — omit, production + // sees undefined which the helper treats as "must upload via highway". + uploadIp: '1.2.3.4', + uploadPort: 8080, + fileKey: new Uint8Array([9]), + checkKey: new Uint8Array([8]), + }, + } as any, + }), + ); await groupFile.uploadGroupFile(bridge as any, 12345, '/path/file.bin'); expect(highwayClient.fetchHighwaySession).toHaveBeenCalledOnce(); expect(highwayClient.uploadHighwayHttp).toHaveBeenCalledOnce(); @@ -83,16 +118,20 @@ describe('actions/group-file', () => { it('uploadGroupFile throws on missing upload response', async () => { const bridge = mockBridge(); - vi.mocked(oidb.runOidb).mockResolvedValueOnce({}); + vi.mocked(oidb.runOidb).mockResolvedValueOnce( + protobuf_encode>({ body: {} }), + ); await expect(groupFile.uploadGroupFile(bridge as any, 12345, '/path/file.bin')) .rejects.toThrow(/response missing/); }); it('uploadGroupFile bubbles up OIDB retCode errors', async () => { const bridge = mockBridge(); - vi.mocked(oidb.runOidb).mockResolvedValueOnce({ - upload: { retCode: 999, retMsg: 'quota exceeded' }, - }); + vi.mocked(oidb.runOidb).mockResolvedValueOnce( + protobuf_encode>({ + body: { upload: { retCode: 999, retMsg: 'quota exceeded' } as any }, + }), + ); await expect(groupFile.uploadGroupFile(bridge as any, 12345, '/path/file.bin')) .rejects.toThrow(/code=999/); }); @@ -111,9 +150,11 @@ describe('actions/group-file', () => { vi.mocked(bridge.resolveUserUid) .mockResolvedValueOnce('target-uid') // target user .mockResolvedValueOnce('self-uid-resolved'); // self fallback - vi.mocked(oidb.runOidb).mockResolvedValueOnce({ - upload: { retCode: 0, uuid: 'fid', fileAddon: 'hash', boolFileExist: true }, - }); + vi.mocked(oidb.runOidb).mockResolvedValueOnce( + protobuf_encode>({ + body: { upload: { uuid: 'fid', fileAddon: 'hash', boolFileExist: true } as any }, + }), + ); const out = await groupFile.uploadPrivateFile(bridge as any, 67890, '/path/file'); expect(out).toEqual({ fileId: 'fid', fileHash: 'hash' }); expect(bridge.resolveUserUid).toHaveBeenCalledTimes(2); @@ -121,16 +162,19 @@ describe('actions/group-file', () => { it('fetchGroupFiles paginates files + folders out of OIDB items', async () => { const bridge = mockBridge(); - vi.mocked(oidb.runOidb).mockResolvedValueOnce({ - list: { - retCode: 0, - isEnd: true, - items: [ - { type: 1, fileInfo: { fileId: 'f1', fileName: 'a.txt', uploaderUin: 1, uploaderName: 'alice' } }, - { type: 2, folderInfo: { folderId: 'd1', folderName: 'dir', creatorUin: 2, creatorName: 'bob' } }, - ], - }, - }); + vi.mocked(oidb.runOidb).mockResolvedValueOnce( + protobuf_encode>({ + body: { + list: { + isEnd: true, + items: [ + { type: 1, fileInfo: { fileId: 'f1', fileName: 'a.txt', uploaderUin: 1, uploaderName: 'alice' } }, + { type: 2, folderInfo: { folderId: 'd1', folderName: 'dir', creatorUin: 2, creatorName: 'bob' } }, + ], + } as any, + }, + }), + ); const out = await groupFile.fetchGroupFiles(bridge as any, 12345); expect(out.files).toHaveLength(1); expect(out.files[0]).toMatchObject({ fileId: 'f1', fileName: 'a.txt', uploader: 1, uploaderName: 'alice' }); @@ -140,22 +184,27 @@ describe('actions/group-file', () => { it('fetchGroupFileUrl builds the https URL from downloadDns + hex-encoded path', async () => { const bridge = mockBridge(); - vi.mocked(oidb.runOidb).mockResolvedValueOnce({ - download: { - retCode: 0, - downloadDns: 'cdn.example.com', - downloadUrl: new Uint8Array([0x01, 0x02]), - }, - }); + vi.mocked(oidb.runOidb).mockResolvedValueOnce( + protobuf_encode>({ + body: { + download: { + downloadDns: 'cdn.example.com', + downloadUrl: new Uint8Array([0x01, 0x02]), + } as any, + }, + }), + ); const url = await groupFile.fetchGroupFileUrl(bridge as any, 12345, 'fid-xyz'); expect(url).toBe('https://cdn.example.com/ftn_handler/0102/?fname=fid-xyz'); }); it('fetchGroupFileUrl throws when response is missing dns or url', async () => { const bridge = mockBridge(); - vi.mocked(oidb.runOidb).mockResolvedValueOnce({ - download: { retCode: 0 }, - }); + vi.mocked(oidb.runOidb).mockResolvedValueOnce( + protobuf_encode>({ + body: { download: {} as any }, + }), + ); await expect(groupFile.fetchGroupFileUrl(bridge as any, 12345, 'fid-xyz')) .rejects.toThrow(/invalid/); }); @@ -163,34 +212,38 @@ describe('actions/group-file', () => { it('deleteGroupFile / moveGroupFile dispatch the right sub-commands', async () => { const bridge = mockBridge(); vi.mocked(oidb.runOidb) - .mockResolvedValueOnce({ delete: { retCode: 0 } }) - .mockResolvedValueOnce({ move: { retCode: 0 } }); + .mockResolvedValueOnce(protobuf_encode>({ body: { delete: {} as any } })) + .mockResolvedValueOnce(protobuf_encode>({ body: { move: {} as any } })); await groupFile.deleteGroupFile(bridge as any, 12345, 'fid'); await groupFile.moveGroupFile(bridge as any, 12345, 'fid', '/a', '/b'); - expect(vi.mocked(oidb.runOidb).mock.calls.map(c => c[1].subCmd)).toEqual([3, 5]); + expect(vi.mocked(oidb.makeOidbEnvelope).mock.calls.map(c => c[1])).toEqual([3, 5]); }); it('createGroupFileFolder / deleteGroupFileFolder / renameGroupFileFolder dispatch 0x6d7 family', async () => { const bridge = mockBridge(); vi.mocked(oidb.runOidb) - .mockResolvedValueOnce({ create: { retcode: 0 } }) - .mockResolvedValueOnce({ delete: { retcode: 0 } }) - .mockResolvedValueOnce({ rename: { retcode: 0 } }); + .mockResolvedValueOnce(protobuf_encode>({ body: { create: {} as any } })) + .mockResolvedValueOnce(protobuf_encode>({ body: { delete: {} as any } })) + .mockResolvedValueOnce(protobuf_encode>({ body: { rename: {} as any } })); await groupFile.createGroupFileFolder(bridge as any, 1, 'folder'); await groupFile.deleteGroupFileFolder(bridge as any, 1, 'fid'); await groupFile.renameGroupFileFolder(bridge as any, 1, 'fid', 'newname'); - expect(vi.mocked(oidb.runOidb).mock.calls.map(c => c[1].oidbCmd)).toEqual([0x6D7, 0x6D7, 0x6D7]); + expect(vi.mocked(oidb.makeOidbEnvelope).mock.calls.map(c => c[0])).toEqual([0x6D7, 0x6D7, 0x6D7]); }); it('fetch*UrlByNode builds https://domain/path?rkey from the NTV2 response', async () => { const bridge = mockBridge(); - vi.mocked(oidb.runOidb).mockResolvedValue({ - respHead: { retCode: 0 }, - download: { - info: { domain: 'media.example.com', urlPath: '/path/x' }, - rKeyParam: '?rkey=abc', - }, - }); + vi.mocked(oidb.runOidb).mockResolvedValue( + protobuf_encode>({ + body: { + respHead: {}, + download: { + info: { domain: 'media.example.com', urlPath: '/path/x' }, + rKeyParam: '?rkey=abc', + } as any, + } as any, + }), + ); const url = await groupFile.fetchGroupVideoUrlByNode(bridge as any, 12345, { fileUuid: 'uuid' }); expect(url).toBe('https://media.example.com/path/x?rkey=abc'); }); diff --git a/packages/core/tests/actions/group-message.test.ts b/packages/core/tests/actions/group-message.test.ts index 5c50b90c..95281197 100644 --- a/packages/core/tests/actions/group-message.test.ts +++ b/packages/core/tests/actions/group-message.test.ts @@ -1,7 +1,10 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'; vi.mock('../../src/bridge/bridge-oidb', () => ({ - runOidb: vi.fn(async () => ({})), + runOidb: vi.fn(async () => new Uint8Array()), + makeOidbEnvelope: vi.fn((_oidbCmd, _subCmd, body) => ({ body })), + encodeOidbEnv: vi.fn(() => new Uint8Array()), + decodeOidbEnv: vi.fn(() => ({ body: {} })), })); import * as oidb from '../../src/bridge/bridge-oidb'; @@ -11,6 +14,9 @@ import { mockBridge } from './_helpers'; describe('actions/group-message', () => { beforeEach(() => { vi.mocked(oidb.runOidb).mockClear(); + vi.mocked(oidb.makeOidbEnvelope).mockClear(); + vi.mocked(oidb.encodeOidbEnv).mockClear(); + vi.mocked(oidb.decodeOidbEnv).mockClear(); }); it('recallGroupMessage sends to SsoGroupRecallMsg with the group sequence', async () => { @@ -59,7 +65,7 @@ describe('actions/group-message', () => { const bridge = mockBridge(); await msg.setGroupEssence(bridge as any, 12345, 5, 7, true); await msg.setGroupEssence(bridge as any, 12345, 5, 7, false); - const cmds = vi.mocked(oidb.runOidb).mock.calls.map(c => c[1].cmd); + const cmds = vi.mocked(oidb.runOidb).mock.calls.map(c => c[1]); expect(cmds).toEqual(['OidbSvcTrpcTcp.0xeac_1', 'OidbSvcTrpcTcp.0xeac_2']); }); }); diff --git a/packages/core/tests/actions/interaction.test.ts b/packages/core/tests/actions/interaction.test.ts index b12a89c5..feace71a 100644 --- a/packages/core/tests/actions/interaction.test.ts +++ b/packages/core/tests/actions/interaction.test.ts @@ -1,8 +1,25 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '../../src/bridge/proto/proton/oidb'; +import type { Oidb0x9083Resp } from '../../src/bridge/proto/proton/oidb-action'; -vi.mock('../../src/bridge/bridge-oidb', () => ({ - runOidb: vi.fn(async () => ({})), -})); +// `encodeOidbEnv` / `decodeOidbEnv` are proton-bound pass-through wrappers +// that the plugin substitutes at the call site for the inlined codec. +// That means production calls to them NEVER hit the imported function — +// mocking them on the module object is a no-op. The only mockable point +// is `runOidb` (non-generic, untouched by proton) returning real bytes +// that the production-side codec actually decodes. `makeOidbEnvelope` is +// a pure TS helper, so its mock works for introspection. +vi.mock('../../src/bridge/bridge-oidb', async () => { + const actual = await vi.importActual( + '../../src/bridge/bridge-oidb', + ); + return { + ...actual, + runOidb: vi.fn(async () => new Uint8Array()), + makeOidbEnvelope: vi.fn((_oidbCmd, _subCmd, body) => ({ body })), + }; +}); import * as oidb from '../../src/bridge/bridge-oidb'; import * as inter from '../../src/bridge/actions/interaction'; @@ -11,45 +28,51 @@ import { mockBridge } from './_helpers'; describe('actions/interaction', () => { beforeEach(() => { vi.mocked(oidb.runOidb).mockReset(); - vi.mocked(oidb.runOidb).mockResolvedValue({}); + vi.mocked(oidb.runOidb).mockResolvedValue(new Uint8Array()); + vi.mocked(oidb.makeOidbEnvelope).mockClear(); }); it('sendPoke group: groupUin set, friendUin=0', async () => { const bridge = mockBridge(); await inter.sendPoke(bridge as any, true, 12345, 67890); - const call = vi.mocked(oidb.runOidb).mock.calls[0]![1]; - expect(call.request.value).toMatchObject({ uin: 67890, groupUin: 12345, friendUin: 0 }); + const body = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2]; + expect(body).toMatchObject({ uin: 67890, groupUin: 12345, friendUin: 0 }); }); it('sendPoke friend: friendUin set, groupUin=0, targetUin defaults to peer', async () => { const bridge = mockBridge(); await inter.sendPoke(bridge as any, false, 67890); - const call = vi.mocked(oidb.runOidb).mock.calls[0]![1]; - expect(call.request.value).toMatchObject({ uin: 67890, groupUin: 0, friendUin: 67890 }); + const body = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2]; + expect(body).toMatchObject({ uin: 67890, groupUin: 0, friendUin: 67890 }); }); it('sendLike forwards target + count to 0x7e5_104', async () => { const bridge = mockBridge(); await inter.sendLike(bridge as any, 10001, 3); - const call = vi.mocked(oidb.runOidb).mock.calls[0]![1]; - expect(call.cmd).toBe('OidbSvcTrpcTcp.0x7e5_104'); - expect(call.request.value).toMatchObject({ targetUin: 10001, count: 3 }); + const [, cmd] = vi.mocked(oidb.runOidb).mock.calls[0]!; + expect(cmd).toBe('OidbSvcTrpcTcp.0x7e5_104'); + const body = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2]; + expect(body).toMatchObject({ targetUin: 10001, count: 3 }); }); it('setGroupReaction picks _1 for set and _2 for unset', async () => { const bridge = mockBridge(); await inter.setGroupReaction(bridge as any, 12345, 99, '128516', true); await inter.setGroupReaction(bridge as any, 12345, 99, '128516', false); - const cmds = vi.mocked(oidb.runOidb).mock.calls.map(c => c[1].cmd); + const cmds = vi.mocked(oidb.runOidb).mock.calls.map(c => c[1]); expect(cmds).toEqual(['OidbSvcTrpcTcp.0x9082_1', 'OidbSvcTrpcTcp.0x9082_2']); }); it('getEmojiLikes decodes user list, base64-encodes cookie, and reports isLast', async () => { const bridge = mockBridge(); - vi.mocked(oidb.runOidb).mockResolvedValueOnce({ - inner: { userInfo: { uin: 10001 } }, - cookie: new Uint8Array([0xCA, 0xFE]), - }); + vi.mocked(oidb.runOidb).mockResolvedValueOnce( + protobuf_encode>({ + body: { + inner: { userInfo: { uin: 10001n } }, + cookie: new Uint8Array([0xCA, 0xFE]), + } as any, + }), + ); const out = await inter.getEmojiLikes(bridge as any, 12345, 99, '128516'); expect(out.users).toEqual([{ uin: 10001 }]); expect(out.cookie).toBe(Buffer.from([0xCA, 0xFE]).toString('base64')); @@ -58,7 +81,9 @@ describe('actions/interaction', () => { it('getEmojiLikes reports isLast=true when no cookie comes back', async () => { const bridge = mockBridge(); - vi.mocked(oidb.runOidb).mockResolvedValueOnce({}); + vi.mocked(oidb.runOidb).mockResolvedValueOnce( + protobuf_encode>({ body: {} }), + ); const out = await inter.getEmojiLikes(bridge as any, 12345, 99, '128516'); expect(out.users).toEqual([]); expect(out.isLast).toBe(true); diff --git a/packages/core/tests/actions/misc.test.ts b/packages/core/tests/actions/misc.test.ts index 05a30962..09efd6e2 100644 --- a/packages/core/tests/actions/misc.test.ts +++ b/packages/core/tests/actions/misc.test.ts @@ -1,8 +1,26 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '../../src/bridge/proto/proton/oidb'; +import type { + Oidb0x990Resp, + Oidb0x112eResp, +} from '../../src/bridge/proto/proton/oidb-action'; -vi.mock('../../src/bridge/bridge-oidb', () => ({ - runOidb: vi.fn(async () => ({})), -})); +// `encodeOidbEnv` / `decodeOidbEnv` are proton-bound pass-through wrappers +// — the plugin substitutes them at the call site with the inlined codec, +// so mocking them on the module object is a no-op. We mock `runOidb` +// (non-generic, untouched by proton) to return real proton-encoded bytes +// that the production-side codec then actually decodes. +vi.mock('../../src/bridge/bridge-oidb', async () => { + const actual = await vi.importActual( + '../../src/bridge/bridge-oidb', + ); + return { + ...actual, + runOidb: vi.fn(async () => new Uint8Array()), + makeOidbEnvelope: vi.fn((_oidbCmd, _subCmd, body) => ({ body })), + }; +}); import * as oidb from '../../src/bridge/bridge-oidb'; import * as misc from '../../src/bridge/actions/misc'; @@ -11,21 +29,26 @@ import { mockBridge } from './_helpers'; describe('actions/misc', () => { beforeEach(() => { vi.mocked(oidb.runOidb).mockReset(); - vi.mocked(oidb.runOidb).mockResolvedValue({}); + vi.mocked(oidb.runOidb).mockResolvedValue(new Uint8Array()); + vi.mocked(oidb.makeOidbEnvelope).mockClear(); }); it('translateEn2Zh returns dstWords when present', async () => { const bridge = mockBridge(); - vi.mocked(oidb.runOidb).mockResolvedValueOnce({ - translateResp: { dstWords: ['你好', '世界'] }, - }); + vi.mocked(oidb.runOidb).mockResolvedValueOnce( + protobuf_encode>({ + body: { translateResp: { dstWords: ['你好', '世界'] } } as any, + }), + ); const out = await misc.translateEn2Zh(bridge as any, ['hello', 'world']); expect(out).toEqual(['你好', '世界']); }); it('translateEn2Zh throws on empty response', async () => { const bridge = mockBridge(); - vi.mocked(oidb.runOidb).mockResolvedValueOnce({}); + vi.mocked(oidb.runOidb).mockResolvedValueOnce( + protobuf_encode>({ body: {} }), + ); await expect(misc.translateEn2Zh(bridge as any, ['hello'])) .rejects.toThrow(/empty/); }); @@ -60,9 +83,11 @@ describe('actions/misc', () => { it('clickInlineKeyboardButton returns shaped result', async () => { const bridge = mockBridge(); - vi.mocked(oidb.runOidb).mockResolvedValueOnce({ - result: 1, errMsg: 'ok', promptText: 'hi', - }); + vi.mocked(oidb.runOidb).mockResolvedValueOnce( + protobuf_encode>({ + body: { result: 1, errMsg: 'ok', promptText: 'hi' } as any, + }), + ); const out = await misc.clickInlineKeyboardButton(bridge as any, 1, 2, 'btn', 'data', 100); expect(out).toMatchObject({ result: 1, errMsg: 'ok', promptText: 'hi', status: 0 }); }); @@ -70,7 +95,7 @@ describe('actions/misc', () => { it('sendGroupSign dispatches to 0xEB7_1', async () => { const bridge = mockBridge(); await misc.sendGroupSign(bridge as any, 12345); - const call = vi.mocked(oidb.runOidb).mock.calls[0]![1]; - expect(call.cmd).toBe('OidbSvcTrpcTcp.0xEB7_1'); + const [, cmd] = vi.mocked(oidb.runOidb).mock.calls[0]!; + expect(cmd).toBe('OidbSvcTrpcTcp.0xEB7_1'); }); }); diff --git a/packages/core/tests/actions/profile.test.ts b/packages/core/tests/actions/profile.test.ts index 52feb3f2..6ec45f46 100644 --- a/packages/core/tests/actions/profile.test.ts +++ b/packages/core/tests/actions/profile.test.ts @@ -1,8 +1,26 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '../../src/bridge/proto/proton/oidb'; +import type { + Oidb0x7edResp, + Oidb0xe17Resp, +} from '../../src/bridge/proto/proton/oidb-action'; -vi.mock('../../src/bridge/bridge-oidb', () => ({ - runOidb: vi.fn(async () => ({})), -})); +// `encodeOidbEnv` / `decodeOidbEnv` are proton-bound pass-through wrappers +// (substituted at the call site with the inlined codec). Mocking them on +// the module object is a no-op — proton has already inlined the call. +// We mock `runOidb` (non-generic) to return real proton-encoded bytes +// that the production-side codec actually decodes. +vi.mock('../../src/bridge/bridge-oidb', async () => { + const actual = await vi.importActual( + '../../src/bridge/bridge-oidb', + ); + return { + ...actual, + runOidb: vi.fn(async () => new Uint8Array()), + makeOidbEnvelope: vi.fn((_oidbCmd, _subCmd, body) => ({ body })), + }; +}); vi.mock('../../src/bridge/highway/highway-client', () => ({ fetchHighwaySession: vi.fn(async () => ({})), @@ -23,7 +41,8 @@ import { mockBridge } from './_helpers'; describe('actions/profile', () => { beforeEach(() => { vi.mocked(oidb.runOidb).mockReset(); - vi.mocked(oidb.runOidb).mockResolvedValue({}); + vi.mocked(oidb.runOidb).mockResolvedValue(new Uint8Array()); + vi.mocked(oidb.makeOidbEnvelope).mockClear(); vi.mocked(highwayClient.fetchHighwaySession).mockClear(); vi.mocked(highwayClient.uploadHighwayHttp).mockClear(); }); @@ -93,23 +112,23 @@ describe('actions/profile', () => { const bridge = mockBridge(); await profile.setProfile(bridge as any, 'New Nick'); expect(oidb.runOidb).toHaveBeenCalledOnce(); - const call = vi.mocked(oidb.runOidb).mock.calls[0]![1]; - expect((call.request.value as any).stringProfiles).toEqual([{ fieldId: 20002, value: 'New Nick' }]); + const body = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2]; + expect((body as any).stringProfiles).toEqual([{ fieldId: 20002, value: 'New Nick' }]); }); it('setSelfLongNick wraps the long nick in profile tag 102', async () => { const bridge = mockBridge(); await profile.setSelfLongNick(bridge as any, 'hello world'); - const call = vi.mocked(oidb.runOidb).mock.calls[0]![1]; - expect((call.request.value as any).profile).toEqual({ tag: 102, value: 'hello world' }); + const body = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2]; + expect((body as any).profile).toEqual({ tag: 102, value: 'hello world' }); }); it('setInputStatus resolves UID first and sends 0xcd4_1', async () => { const bridge = mockBridge(); await profile.setInputStatus(bridge as any, 10001, 1); expect(bridge.resolveUserUid).toHaveBeenCalledWith(10001); - const call = vi.mocked(oidb.runOidb).mock.calls[0]![1]; - expect(call.cmd).toBe('OidbSvcTrpcTcp.0xcd4_1'); + const [, cmd] = vi.mocked(oidb.runOidb).mock.calls[0]!; + expect(cmd).toBe('OidbSvcTrpcTcp.0xcd4_1'); }); it('setAvatar loads bytes and pushes through the highway upload path (cmd 90)', async () => { @@ -155,14 +174,18 @@ describe('actions/profile', () => { it('getProfileLike (self): resolves self UID, returns formatted favorite + vote info', async () => { const bridge = mockBridge(); - vi.mocked(oidb.runOidb).mockResolvedValueOnce({ - userLikeInfos: [{ - uid: 'u', - time: 1700000000n, - favoriteInfo: { totalCount: 5, lastTime: 1n, newCount: 1 }, - voteInfo: { totalCount: 7, newCount: 2, lastTime: 2n }, - }], - }); + vi.mocked(oidb.runOidb).mockResolvedValueOnce( + protobuf_encode>({ + body: { + userLikeInfos: [{ + uid: 'u', + time: 1700000000n, + favoriteInfo: { totalCount: 5, lastTime: 1n, newCount: 1 }, + voteInfo: { totalCount: 7, newCount: 2, lastTime: 2n }, + }], + } as any, + }), + ); const out = await profile.getProfileLike(bridge as any); expect(out.favoriteInfo.total_count).toBe(5); expect(out.voteInfo.total_count).toBe(7); @@ -170,15 +193,19 @@ describe('actions/profile', () => { it('getProfileLike throws on empty result', async () => { const bridge = mockBridge(); - vi.mocked(oidb.runOidb).mockResolvedValueOnce({ userLikeInfos: [] }); + vi.mocked(oidb.runOidb).mockResolvedValueOnce( + protobuf_encode>({ body: { userLikeInfos: [] } as any }), + ); await expect(profile.getProfileLike(bridge as any)).rejects.toThrow(/empty/); }); it('getUnidirectionalFriendList parses the embedded JSON body', async () => { const bridge = mockBridge(); - vi.mocked(oidb.runOidb).mockResolvedValueOnce({ - jsonBody: JSON.stringify({ rpt_block_list: [{ uin: 10001 }, { uin: 10002 }] }), - }); + vi.mocked(oidb.runOidb).mockResolvedValueOnce( + protobuf_encode>({ + body: { jsonBody: JSON.stringify({ rpt_block_list: [{ uin: 10001 }, { uin: 10002 }] }) } as any, + }), + ); const out = await profile.getUnidirectionalFriendList(bridge as any); expect(out).toEqual([{ uin: 10001 }, { uin: 10002 }]); }); diff --git a/packages/core/tests/proton-parity.test.ts b/packages/core/tests/proton-parity.test.ts index 85e966c2..a613d739 100644 --- a/packages/core/tests/proton-parity.test.ts +++ b/packages/core/tests/proton-parity.test.ts @@ -51,6 +51,7 @@ import { FileUploadExtSchema, } from '../src/bridge/proto/highway'; import { makeOidbBaseSchema, OidbSvcTrpcTcp0xFE5_2ResponseSchema } from '../src/bridge/proto/oidb'; +import { makeOidbEnvelope, encodeOidbEnv, decodeOidbEnv } from '../src/bridge/bridge-oidb'; import type { SendLongMsgResp, @@ -618,6 +619,24 @@ describe('proton ↔ legacy parity (longmsg subset)', () => { expect(hex(proton)).toBe(hex(legacy)); }); + it('encodeOidbEnv pass-through wrapper byte-equivalent to direct codec', () => { + // The bridge-oidb.ts module exposes encodeOidbEnv / decodeOidbEnv + // as pure pass-through wrappers around protobuf_encode/decode>. + // Proton wrapper-binds them and substitutes each call site with the + // monomorphized codec, so byte-output must match a direct call. + const body: OidbSvcTrpcTcp0xFE5_2Response = { + groups: [{ groupUin: 100, info: { groupName: 'G' } }], + }; + const env = makeOidbEnvelope(0xFE5, 2, body, false); + const viaWrapper = encodeOidbEnv(env); + const viaDirect = protobuf_encode>(env); + expect(hex(viaWrapper)).toBe(hex(viaDirect)); + + const back = decodeOidbEnv(viaWrapper); + expect(back.body?.groups?.[0]?.groupUin).toBe(100); + expect(back.body?.groups?.[0]?.info?.groupName).toBe('G'); + }); + it('round-trips OidbBase with non-trivial nested body', () => { const body: OidbSvcTrpcTcp0xFE5_2Response = { groups: [{ groupUin: 100, info: { groupName: 'G' } }], diff --git a/packages/core/tests/web-actions/cookies.test.ts b/packages/core/tests/web-actions/cookies.test.ts index e0ec6b56..fdf54624 100644 --- a/packages/core/tests/web-actions/cookies.test.ts +++ b/packages/core/tests/web-actions/cookies.test.ts @@ -1,10 +1,26 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '../../src/bridge/proto/proton/oidb'; +import type { + OidbClientKeyResp, + OidbGetPskeyResp, +} from '../../src/bridge/proto/proton/oidb-action'; -// Mock the OIDB shim so we can control what `forceFetchClientKey` and -// `getPSkey` see without standing up a Bridge. -vi.mock('../../src/bridge/bridge-oidb', () => ({ - runOidb: vi.fn(async () => ({})), -})); +// `encodeOidbEnv` / `decodeOidbEnv` are proton-bound pass-through wrappers +// — the plugin substitutes them at the call site with the inlined codec, +// so mocking them on the module object is a no-op. We mock `runOidb` +// (non-generic, untouched by proton) to return real proton-encoded bytes +// that the production-side codec then decodes. +vi.mock('../../src/bridge/bridge-oidb', async () => { + const actual = await vi.importActual( + '../../src/bridge/bridge-oidb', + ); + return { + ...actual, + runOidb: vi.fn(async () => new Uint8Array()), + makeOidbEnvelope: vi.fn((_oidbCmd, _subCmd, body) => ({ body })), + }; +}); // Mock the actual HTTP cookie fetch. vi.mock('../../src/bridge/web/request-util', () => ({ @@ -28,35 +44,54 @@ import { const bridge = { identity: { uin: '10001' } } as any; +function resetOidbMocks() { + vi.mocked(oidb.runOidb).mockReset(); + vi.mocked(oidb.runOidb).mockResolvedValue(new Uint8Array()); + vi.mocked(oidb.makeOidbEnvelope).mockClear(); +} + +// Bake the encoded OidbBase bytes a test wants `runOidb` to return. +// Keeping these inline as `protobuf_encode>({body: ...})` +// — proton substitutes them with the inlined codec at this file's +// transform time, just like for production code. + describe('cookies — forceFetchClientKey', () => { - beforeEach(() => { vi.mocked(oidb.runOidb).mockReset(); }); + beforeEach(() => { resetOidbMocks(); }); it('returns clientKey + keyIndex + expireTime from the OIDB response', async () => { - vi.mocked(oidb.runOidb).mockResolvedValueOnce({ - clientKey: 'ck-xyz', keyIndex: 42, expireTime: 3600, - }); + vi.mocked(oidb.runOidb).mockResolvedValueOnce( + protobuf_encode>({ + body: { clientKey: 'ck-xyz', keyIndex: 42, expireTime: 3600 } as any, + }), + ); const out = await forceFetchClientKey(bridge); expect(out).toEqual({ clientKey: 'ck-xyz', keyIndex: '42', expireTime: '3600' }); }); it('falls back to default keyIndex/expireTime when the response omits them', async () => { - vi.mocked(oidb.runOidb).mockResolvedValueOnce({ clientKey: 'ck' }); + vi.mocked(oidb.runOidb).mockResolvedValueOnce( + protobuf_encode>({ body: { clientKey: 'ck' } as any }), + ); const out = await forceFetchClientKey(bridge); expect(out).toEqual({ clientKey: 'ck', keyIndex: '19', expireTime: '1800' }); }); }); describe('cookies — getPSkey', () => { - beforeEach(() => { vi.mocked(oidb.runOidb).mockReset(); }); + beforeEach(() => { resetOidbMocks(); }); it('folds pskeyItems into a domain → pskey Map', async () => { - vi.mocked(oidb.runOidb).mockResolvedValueOnce({ - pskeyItems: [ - { domain: 'qun.qq.com', pskey: 'psk-a' }, - { domain: 'qzone.qq.com', pskey: 'psk-b' }, - { domain: 'corrupt', pskey: '' }, - ], - }); + vi.mocked(oidb.runOidb).mockResolvedValueOnce( + protobuf_encode>({ + body: { + pskeyItems: [ + { domain: 'qun.qq.com', pskey: 'psk-a' }, + { domain: 'qzone.qq.com', pskey: 'psk-b' }, + { domain: 'corrupt', pskey: '' }, + ], + } as any, + }), + ); const { domainPskeyMap } = await getPSkey(bridge, ['qun.qq.com', 'qzone.qq.com']); expect(domainPskeyMap.get('qun.qq.com')).toBe('psk-a'); expect(domainPskeyMap.get('qzone.qq.com')).toBe('psk-b'); @@ -66,12 +101,16 @@ describe('cookies — getPSkey', () => { describe('cookies — getCookies', () => { beforeEach(() => { - vi.mocked(oidb.runOidb).mockReset(); + resetOidbMocks(); vi.mocked(RequestUtil.HttpsGetCookies).mockReset(); }); it('builds the ptlogin2 jump URL with the right query params', async () => { - vi.mocked(oidb.runOidb).mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 }); + vi.mocked(oidb.runOidb).mockResolvedValueOnce( + protobuf_encode>({ + body: { clientKey: 'ck', keyIndex: 19 } as any, + }), + ); vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({ p_skey: 'psk', skey: 'sk', @@ -89,10 +128,14 @@ describe('cookies — getCookies', () => { it('falls back to getPSkey when p_skey is missing in the cookie response', async () => { vi.mocked(oidb.runOidb) - .mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 }) // forceFetchClientKey - .mockResolvedValueOnce({ // getPSkey - pskeyItems: [{ domain: 'qun.qq.com', pskey: 'psk-from-oidb' }], - }); + .mockResolvedValueOnce( + protobuf_encode>({ body: { clientKey: 'ck', keyIndex: 19 } as any }), + ) + .mockResolvedValueOnce( + protobuf_encode>({ + body: { pskeyItems: [{ domain: 'qun.qq.com', pskey: 'psk-from-oidb' }] } as any, + }), + ); vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({}); const out = await getCookies(bridge, 'qun.qq.com'); @@ -101,7 +144,9 @@ describe('cookies — getCookies', () => { it('returns whatever cookies it got if getPSkey fallback throws', async () => { vi.mocked(oidb.runOidb) - .mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 }) + .mockResolvedValueOnce( + protobuf_encode>({ body: { clientKey: 'ck', keyIndex: 19 } as any }), + ) .mockRejectedValueOnce(new Error('pskey unavailable')); vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({ skey: 'sk' }); @@ -112,29 +157,38 @@ describe('cookies — getCookies', () => { describe('cookies — getSKey', () => { beforeEach(() => { - vi.mocked(oidb.runOidb).mockReset(); + resetOidbMocks(); vi.mocked(RequestUtil.HttpsGetCookies).mockReset(); }); it('returns skey from the qzone-targeted ptlogin2 jump', async () => { - vi.mocked(oidb.runOidb).mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 }); + vi.mocked(oidb.runOidb).mockResolvedValueOnce( + protobuf_encode>({ body: { clientKey: 'ck', keyIndex: 19 } as any }), + ); vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({ skey: 'the-skey' }); expect(await getSKey(bridge)).toBe('the-skey'); }); it('throws when clientKey comes back empty', async () => { - vi.mocked(oidb.runOidb).mockResolvedValueOnce({ clientKey: '' }); + // Empty clientKey is the proto3 default; omit so it decodes back to ''. + vi.mocked(oidb.runOidb).mockResolvedValueOnce( + protobuf_encode>({ body: {} }), + ); await expect(getSKey(bridge)).rejects.toThrow(/clientKey is empty/); }); it('throws when the jump response omits skey', async () => { - vi.mocked(oidb.runOidb).mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 }); + vi.mocked(oidb.runOidb).mockResolvedValueOnce( + protobuf_encode>({ body: { clientKey: 'ck', keyIndex: 19 } as any }), + ); vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({}); await expect(getSKey(bridge)).rejects.toThrow(/SKey is Empty/); }); }); describe('cookies — pure helpers', () => { + beforeEach(() => { resetOidbMocks(); }); + it('getBknFromSKey: deterministic djb2 truncated to 31 bits', () => { // Two calls on the same input → same number; different input → different. const a = getBknFromSKey('hello'); @@ -147,21 +201,27 @@ describe('cookies — pure helpers', () => { }); it('getCookiesStr: joins cookies with "; "', async () => { - vi.mocked(oidb.runOidb).mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 }); + vi.mocked(oidb.runOidb).mockResolvedValueOnce( + protobuf_encode>({ body: { clientKey: 'ck', keyIndex: 19 } as any }), + ); vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({ p_skey: 'p', skey: 's' }); const out = await getCookiesStr(bridge, 'qun.qq.com'); expect(out).toBe('p_skey=p; skey=s'); }); it('getCsrfToken: combines getSKey + getBknFromSKey', async () => { - vi.mocked(oidb.runOidb).mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 }); + vi.mocked(oidb.runOidb).mockResolvedValueOnce( + protobuf_encode>({ body: { clientKey: 'ck', keyIndex: 19 } as any }), + ); vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({ skey: 'abc' }); const csrf = await getCsrfToken(bridge); expect(csrf).toBe(getBknFromSKey('abc')); }); it('getCredentials: returns { cookies, token, csrf_token } with bkn(p_skey)', async () => { - vi.mocked(oidb.runOidb).mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 }); + vi.mocked(oidb.runOidb).mockResolvedValueOnce( + protobuf_encode>({ body: { clientKey: 'ck', keyIndex: 19 } as any }), + ); vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({ p_skey: 'p', skey: 's' }); const out = await getCredentials(bridge, 'qun.qq.com'); @@ -172,7 +232,9 @@ describe('cookies — pure helpers', () => { it('getCredentials: token is 0 when no skey/p_skey available', async () => { vi.mocked(oidb.runOidb) - .mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 }) + .mockResolvedValueOnce( + protobuf_encode>({ body: { clientKey: 'ck', keyIndex: 19 } as any }), + ) .mockRejectedValueOnce(new Error('no pskey')); vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({}); diff --git a/packages/proton/src/ast/analyzer.ts b/packages/proton/src/ast/analyzer.ts index c7c1c61e..4041b0a7 100644 --- a/packages/proton/src/ast/analyzer.ts +++ b/packages/proton/src/ast/analyzer.ts @@ -107,58 +107,108 @@ export function analyze(code: string, filePath: string, imported?: ImportedDefin for (const [k, v] of imported.templates) templates.set(k, v); } + // Stack of generic-function type-param scopes. When visiting a + // `protobuf_encode/decode` call whose type arg references one of + // these (e.g. `protobuf_encode>(env)` inside + // `function encodeOidbEnv(...)`), we MUST skip monomorphization — + // the type arg only resolves once the wrapper itself is instantiated + // at a downstream call site, and that case is handled separately by + // the wrapper-binding path in `matchForwardedProtobufFn`. Without + // this skip, the analyzer would happily mint a literal `OidbBase__T` + // registry entry with a `body.typeName = 'T'` field, which the + // wire-type guard then trips on. + const enclosingTypeParamStack: Set[] = []; + function typeArgReferencesEnclosingParam(typeArg: ts.TypeNode): boolean { + if (enclosingTypeParamStack.length === 0) return false; + let found = false; + function check(n: ts.Node): void { + if (found) return; + if (ts.isTypeReferenceNode(n) && ts.isIdentifier(n.typeName)) { + const name = n.typeName.text; + for (const scope of enclosingTypeParamStack) { + if (scope.has(name)) { found = true; return; } + } + } + ts.forEachChild(n, check); + } + check(typeArg); + return found; + } + function nodeIntroducesTypeParams(n: ts.Node): readonly ts.TypeParameterDeclaration[] | undefined { + if (ts.isFunctionDeclaration(n)) return n.typeParameters; + if (ts.isFunctionExpression(n)) return n.typeParameters; + if (ts.isArrowFunction(n)) return n.typeParameters; + if (ts.isMethodDeclaration(n)) return n.typeParameters; + return undefined; + } + // ── single walk ───────────────────────────────────────────────────── ts.forEachChild(sf, function visit(node) { - if (ts.isInterfaceDeclaration(node)) { - if (node.typeParameters?.length) { - const tpl = collectGenericInterface(node, sf, resolveImportedTypeName); - if (tpl) templates.set(tpl.name, tpl); - } else { - const msg = collectInterface(node, sf, resolveImportedTypeName); - if (msg) concrete.push(msg); - // Queue any generic-instantiated type-args appearing as field types - // (e.g. `wrapped: pb<5, Wrapper>`) for monomorphization. - // The call-site queue only sees the outer concrete type, so without - // this the nested instantiation would never reach the registry. - for (const ta of collectConcreteFieldGenericTypeArgs(node, resolveImportedTypeName)) { - deferredTypeArgs.push(ta); - } - } + const introduced = nodeIntroducesTypeParams(node); + const pushedScope = !!(introduced && introduced.length); + if (pushedScope) { + enclosingTypeParamStack.push(new Set(introduced!.map(p => p.name.text))); } - if (ts.isCallExpression(node)) { - const cs = matchProtobufCallSite(node, sf, importBindings, { - allowLegacyUnboundCanonical: true, - }); - if (cs) { - deferredTypeArgs.push(cs.firstTypeArg); - callSites.push(cs); - } else if ( - node.typeArguments?.length && - getCallableName(node.expression) && - wrapperBindings.has(getCallableName(node.expression)!) - ) { - const binding = wrapperBindings.get(getCallableName(node.expression)!)!; - const firstTypeArg = instantiateWrapperTypePattern(binding, node.typeArguments, sf); - if (!firstTypeArg) { - ts.forEachChild(node, visit); - return; + try { + if (ts.isInterfaceDeclaration(node)) { + if (node.typeParameters?.length) { + const tpl = collectGenericInterface(node, sf, resolveImportedTypeName); + if (tpl) templates.set(tpl.name, tpl); + } else { + const msg = collectInterface(node, sf, resolveImportedTypeName); + if (msg) concrete.push(msg); + // Queue any generic-instantiated type-args appearing as field types + // (e.g. `wrapped: pb<5, Wrapper>`) for monomorphization. + // The call-site queue only sees the outer concrete type, so without + // this the nested instantiation would never reach the registry. + for (const ta of collectConcreteFieldGenericTypeArgs(node, resolveImportedTypeName)) { + deferredTypeArgs.push(ta); + } } - const exprStart = node.expression.getStart(sf); - const lc = sf.getLineAndCharacterOfPosition(exprStart); - deferredTypeArgs.push(firstTypeArg); - callSites.push({ - fnName: binding.fnName, - exprStart, - typeArgsEnd: node.typeArguments.end + 1, - firstTypeArg, - line: lc.line + 1, - column: lc.character + 1, + } + + if (ts.isCallExpression(node)) { + const cs = matchProtobufCallSite(node, sf, importBindings, { + allowLegacyUnboundCanonical: true, }); + if (cs) { + if (!typeArgReferencesEnclosingParam(cs.firstTypeArg)) { + deferredTypeArgs.push(cs.firstTypeArg); + callSites.push(cs); + } + // else: this call sits inside a generic wrapper definition; the + // wrapper-binding path will materialise concrete codecs at each + // downstream call site instead. + } else if ( + node.typeArguments?.length && + getCallableName(node.expression) && + wrapperBindings.has(getCallableName(node.expression)!) + ) { + const binding = wrapperBindings.get(getCallableName(node.expression)!)!; + const firstTypeArg = instantiateWrapperTypePattern(binding, node.typeArguments, sf); + if (!firstTypeArg) { + ts.forEachChild(node, visit); + return; + } + const exprStart = node.expression.getStart(sf); + const lc = sf.getLineAndCharacterOfPosition(exprStart); + deferredTypeArgs.push(firstTypeArg); + callSites.push({ + fnName: binding.fnName, + exprStart, + typeArgsEnd: node.typeArguments.end + 1, + firstTypeArg, + line: lc.line + 1, + column: lc.character + 1, + }); + } } - } - ts.forEachChild(node, visit); + ts.forEachChild(node, visit); + } finally { + if (pushedScope) enclosingTypeParamStack.pop(); + } }); // ── post-walk: monomorphize deferred type args ────────────────────── diff --git a/packages/proton/src/ast/collector.ts b/packages/proton/src/ast/collector.ts index 7bdc321c..f05deda6 100644 --- a/packages/proton/src/ast/collector.ts +++ b/packages/proton/src/ast/collector.ts @@ -46,7 +46,15 @@ export function collectInterface( const f = extractField(m, sf, resolveImportedTypeName); if (f) fields.push(f); } - return fields.length ? { name: node.name.text, fields } : null; + // Register interfaces that are EXPLICITLY empty (`interface X {}`) as + // zero-field proto messages — proto3 wire format allows them and + // downstream code routinely uses them for "this OIDB call has no + // meaningful response body" placeholders. Interfaces that have + // members but no pb-marked fields are NOT proto messages — they + // belong to regular TS types and must stay unregistered to avoid + // polluting the registry. + if (fields.length === 0 && node.members.length > 0) return null; + return { name: node.name.text, fields }; } /** Collect a generic interface template. */ From 76b87f6b27c52469d6a95482be5750abb9b89afe Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Tue, 19 May 2026 08:28:11 +0800 Subject: [PATCH 22/48] feat(proton): migrate group-album actions (PR #31) to proton codec MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PR #31 landed 4 TRPC group-album actions on the legacy runtime schema encoder. Migrate them to the compile-time codec, matching the pattern established by the OIDB migration: TS interfaces in `proto/proton/oidb-action.ts` are monomorphized at build time and each `protoEncode/Decode` call site now calls `protobuf_encode` / `protobuf_decode` directly. - Add 33 proton interfaces for the new TRPC envelopes (GetMediaList, DoQunComment, DoQunLike, DeleteMedias, plus all nested types) — inline anonymous schemas in legacy lifted to named interfaces. - Migrate `actions/group-album.ts` to the proton API; drop the `(resp as any)` casts now that decoded responses are typed. - Add 4 wire-byte parity tests for the new envelopes; non-default field values throughout so byte equivalence holds (proto3 omission of defaults is the documented divergence). - Drop dead `GroupAvatarUploadExtSchema` from `proto/highway.ts` and unused `import * as console from "node:console"` in `web/group-album.ts` — leftovers from the original PR review. core: 609/609 tests pass, typecheck clean. --- .../core/src/bridge/actions/group-album.ts | 99 ++++--- packages/core/src/bridge/proto/highway.ts | 15 +- .../src/bridge/proto/proton/oidb-action.ts | 280 ++++++++++++++++++ packages/core/src/bridge/web/group-album.ts | 1 - packages/core/tests/proton-parity.test.ts | 124 ++++++++ 5 files changed, 463 insertions(+), 56 deletions(-) diff --git a/packages/core/src/bridge/actions/group-album.ts b/packages/core/src/bridge/actions/group-album.ts index 2856905a..75c8e135 100644 --- a/packages/core/src/bridge/actions/group-album.ts +++ b/packages/core/src/bridge/actions/group-album.ts @@ -1,16 +1,23 @@ -// Group album actions via TRPC protocol +// Group album actions via TRPC protocol. +// +// Unlike the OIDB action family, these endpoints speak raw TRPC +// (service command `QunAlbum.trpc.qzone.webapp_qun_*`) without an +// `OidbBase` envelope. We hit `bridge.sendRawPacket` directly with +// proton-encoded bodies and decode the responses through proton's +// monomorphized codecs. import type { Bridge } from '../bridge'; -import { protoEncode, protoDecode } from '@/protobuf/decode'; -import { GetMediaListRequestSchema, - GetMediaListResponseSchema, - DoQunCommentRequestSchema, - DoQunCommentResponseSchema, - DoQunLikeRequestSchema, - DoQunLikeResponseSchema, - DeleteMediasRequestSchema, - DeleteMediasResponseSchema -} from '../proto/oidb-action'; +import { protobuf_encode, protobuf_decode } from '@snowluma/proton'; +import type { + GetMediaListRequest, + GetMediaListResponse, + DoQunCommentRequest, + DoQunCommentResponse, + DoQunLikeRequest, + DoQunLikeResponse, + DeleteMediasRequest, + DeleteMediasResponse, +} from '../proto/proton/oidb-action'; export interface GroupAlbumMediaResult { mediaList: any[]; @@ -47,7 +54,7 @@ export async function getGroupAlbumMediaList( ): Promise { const traceId = `_${Date.now()}_${Math.floor(Math.random() * 100000)}`; - const body = protoEncode({ + const body = protobuf_encode({ field1: 0, field2: new Uint8Array(0), field3: new Uint8Array(0), @@ -60,7 +67,7 @@ export async function getGroupAlbumMediaList( }, traceId: traceId, extMap: [{ key: 'fc-appid', value: '100' }], - }, GetMediaListRequestSchema); + }); const result = await bridge.sendRawPacket( 'QunAlbum.trpc.qzone.webapp_qun_media.QunMedia.GetMediaList', @@ -72,15 +79,15 @@ export async function getGroupAlbumMediaList( throw new Error(result.errorMessage || 'failed to get album media list'); } - const resp = protoDecode(result.responseData, GetMediaListResponseSchema); + const resp = protobuf_decode(result.responseData); - if (!resp || (resp as any).field1 !== 0) { - throw new Error(`fetch album media list error: retCode ${(resp as any)?.field1 || 'unknown'}`); + if (resp.field1 !== 0) { + throw new Error(`fetch album media list error: retCode ${resp.field1 ?? 'unknown'}`); } - const data = (resp as any).data || {}; - const mediaList = data.mediaList || []; - const nextAttachInfo = data.nextAttachInfo || ''; + const data = resp.data ?? {}; + const mediaList = data.mediaList ?? []; + const nextAttachInfo = data.nextAttachInfo ?? ''; return convertBigIntToString({ mediaList, @@ -101,7 +108,7 @@ export async function commentGroupAlbumMedia( const clientKey = Date.now().toString(); const uin = bridge.identity.uin; - const body = protoEncode({ + const body = protobuf_encode({ field1: 8527, field2: new Uint8Array(0), field3: new Uint8Array(0), @@ -137,7 +144,7 @@ export async function commentGroupAlbumMedia( }, traceId, extMap: [{ key: 'fc-appid', value: '100' }], - }, DoQunCommentRequestSchema); + }); const result = await bridge.sendRawPacket( 'QunAlbum.trpc.qzone.webapp_qun_operation.FeedsWriter.DoQunComment', @@ -149,21 +156,21 @@ export async function commentGroupAlbumMedia( throw new Error(result.errorMessage || 'failed to comment on album media'); } - const resp = protoDecode(result.responseData, DoQunCommentResponseSchema); + const resp = protobuf_decode(result.responseData); - const resCode = (resp as any)?.field1; - if (!resp || (resCode !== 0 && resCode !== 8527 && !(resp as any).comment)) { - throw new Error(`comment album media error: retCode ${resCode || 'unknown'}`); + const resCode = resp.field1; + if (resCode !== 0 && resCode !== 8527 && !resp.comment) { + throw new Error(`comment album media error: retCode ${resCode ?? 'unknown'}`); } - const commentData = (resp as any).comment?.data || {}; + const commentData = resp.comment?.data ?? {}; return convertBigIntToString({ - id: commentData.id || '', - user: { uin: commentData.user?.uin || '' }, - content: commentData.content || [], - time: commentData.time || '0', - clientKey: commentData.clientKey || '', + id: commentData.id ?? '', + user: { uin: commentData.user?.uin ?? '' }, + content: commentData.content ?? [], + time: commentData.time ?? '0', + clientKey: commentData.clientKey ?? '', }); } @@ -188,7 +195,7 @@ export async function likeGroupAlbumMedia( id = `421_1_0_${groupId}|${albumId}|${batchId}`; } - const body = protoEncode({ + const body = protobuf_encode({ field1: 5495, field2: "h5_test", field3: "h5_test", @@ -214,7 +221,7 @@ export async function likeGroupAlbumMedia( clientKey }, extMap: [{ key: 'fc-appid', value: '100' }], - }, DoQunLikeRequestSchema); + }); const result = await bridge.sendRawPacket( 'QunAlbum.trpc.qzone.webapp_qun_operation.FeedsWriter.DoQunLike', @@ -226,14 +233,14 @@ export async function likeGroupAlbumMedia( throw new Error(result.errorMessage || 'failed to like album media'); } - const resp = protoDecode(result.responseData, DoQunLikeResponseSchema); - const resCode = (resp as any)?.field1; + const resp = protobuf_decode(result.responseData); + const resCode = resp.field1; - if (!resp || resCode !== 5495) { - throw new Error(`like album media error: retCode ${resCode || 'unknown'}`); + if (resCode !== 5495) { + throw new Error(`like album media error: retCode ${resCode ?? 'unknown'}`); } - return (resp as any).body?.like || {}; + return convertBigIntToString(resp.body?.like ?? {}); } export async function deleteGroupAlbumMedia( @@ -245,7 +252,7 @@ export async function deleteGroupAlbumMedia( const uin = bridge.identity.uin; const clientKey = `${uin}_${Date.now()}_${Math.floor(Math.random() * 100000)}`; - const body = protoEncode({ + const body = protobuf_encode({ field1: 8694, field2: "h5_test", field3: "h5_test", @@ -256,7 +263,7 @@ export async function deleteGroupAlbumMedia( }, traceId: clientKey, extMap: [{ key: 'fc-appid', value: '100' }], - }, DeleteMediasRequestSchema); + }); const result = await bridge.sendRawPacket( 'QunAlbum.trpc.qzone.webapp_qun_media.QunMedia.DeleteMedias', @@ -268,13 +275,13 @@ export async function deleteGroupAlbumMedia( throw new Error(result.errorMessage || 'failed to delete album media'); } - const resp = protoDecode(result.responseData, DeleteMediasResponseSchema); - const resCode = (resp as any)?.field1; - const errCode = (resp as any)?.field2; - const errMsg = (resp as any)?.field3; + const resp = protobuf_decode(result.responseData); + const resCode = resp.field1; + const errCode = resp.field2; + const errMsg = resp.field3; - if (!resp || resCode !== 8694 || errCode) { - throw new Error(`delete album media error [${errCode || 'unknown'}]: ${errMsg || 'unknown'}`); + if (resCode !== 8694 || errCode) { + throw new Error(`delete album media error [${errCode ?? 'unknown'}]: ${errMsg ?? 'unknown'}`); } return { success: true }; diff --git a/packages/core/src/bridge/proto/highway.ts b/packages/core/src/bridge/proto/highway.ts index f61f30bf..11a583e7 100644 --- a/packages/core/src/bridge/proto/highway.ts +++ b/packages/core/src/bridge/proto/highway.ts @@ -335,12 +335,9 @@ export const NTV2UploadRichMediaRespSchema = { upload: { field: 2, type: 'message' as const, schema: NTV2UploadRespBodySchema }, } satisfies ProtoSchema; -// --- Group Avatar Upload Extend --- - -export const GroupAvatarUploadExtSchema = { - field1: { field: 1, type: 'uint32' as const }, - groupId: { field: 2, type: 'uint64' as const }, - field3: { field: 3, type: 'bytes' as const }, - field5: { field: 5, type: 'uint32' as const }, - field6: { field: 6, type: 'uint32' as const }, -} satisfies ProtoSchema; +// (The legacy `GroupAvatarUploadExtSchema` definition that briefly +// lived here in PR #31 was removed: it was a residual artifact of an +// alternative `setGroupAvatar` implementation that got dropped during +// review — the canonical Lagrange-derived `GroupAvatarExtraSchema` +// further up this file is the one `actions/profile.setGroupAvatar` +// actually uses.) diff --git a/packages/core/src/bridge/proto/proton/oidb-action.ts b/packages/core/src/bridge/proto/proton/oidb-action.ts index 3d8b00e7..1aede706 100644 --- a/packages/core/src/bridge/proto/proton/oidb-action.ts +++ b/packages/core/src/bridge/proto/proton/oidb-action.ts @@ -1277,3 +1277,283 @@ export interface GroupAvatarExtra { field5?: pb<5, uint_32>; // observed value: 3 field6?: pb<6, uint_32>; // observed value: 1 } + +// ── Group Album: TRPC envelopes ──────────────────────────────────── +// Raw TRPC packets (not OIDB-wrapped) for the qzone group-album +// service. Service commands look like +// `QunAlbum.trpc.qzone.webapp_qun_*`. Field naming follows the legacy +// schema's positional convention (`field1`/`field2`/...) where the +// reverse-engineered packet has no semantic name yet — keep it stable +// for the parity audit. + +// Common: `extMap` trace tag carried by every request envelope. +export interface ExtMapEntry { + key?: pb<1, string>; + value?: pb<2, string>; +} + +// ── GetMediaList: list media in a group album with pagination ────── + +export interface ReqInfo { + groupId?: pb<1, string>; + albumId?: pb<2, string>; + field3?: pb<3, int_32>; + attachInfo?: pb<4, string>; // 翻页 cursor — empty for the first page + field5?: pb<5, string>; +} + +export interface GetMediaListRequest { + field1?: pb<1, int_32>; + field2?: pb<2, bytes>; + field3?: pb<3, bytes>; + reqInfo?: pb<4, ReqInfo>; + traceId?: pb<5, string>; + extMap?: pb_repeated<10, ExtMapEntry>; +} + +export interface UrlInfo { + url?: pb<1, string>; + width?: pb<2, uint_32>; + height?: pb<3, uint_32>; +} + +export interface PhotoUrl { + spec?: pb<1, uint_32>; + url?: pb<2, UrlInfo>; +} + +export interface ImageInfo { + name?: pb<1, string>; + sloc?: pb<2, string>; + lloc?: pb<3, string>; + photoUrls?: pb_repeated<4, PhotoUrl>; + defaultUrl?: pb<5, UrlInfo>; + isGif?: pb<6, bool>; + hasRaw?: pb<7, bool>; +} + +export interface MediaInfo { + type?: pb<1, uint_32>; + image?: pb<2, ImageInfo>; + uploader?: pb<6, string>; + batchId?: pb<7, uint_64>; + uploadTime?: pb<8, uint_64>; +} + +// Inline-in-legacy: `GetMediaListRspDataSchema.albumInfo.schema`. +export interface GetMediaListAlbumInfo { + albumId?: pb<1, string>; + owner?: pb<2, string>; + name?: pb<3, string>; +} + +export interface GetMediaListRspData { + albumInfo?: pb<1, GetMediaListAlbumInfo>; + mediaList?: pb_repeated<3, MediaInfo>; + prevAttachInfo?: pb<4, string>; + nextAttachInfo?: pb<5, string>; +} + +export interface GetMediaListResponse { + field1?: pb<1, int_32>; + field2?: pb<2, bytes>; + field3?: pb<3, bytes>; + data?: pb<4, GetMediaListRspData>; +} + +// ── DoQunComment: post a comment on a media item ─────────────────── + +export interface CommentContentItem { + type?: pb<1, uint_32>; + content?: pb<2, string>; +} + +export interface CommentUser { + uin?: pb<13, string>; +} + +// Inline-in-legacy: `CommentReqContentSchema.field3.schema`. +export interface CommentReqContentMeta { + field1?: pb<1, uint_32>; + field2?: pb<2, string>; + field3?: pb<3, string>; + field4?: pb<4, string>; + field5?: pb<5, uint_32>; + field6?: pb<6, string>; +} + +export interface CommentReqContent { + field2?: pb<2, CommentUser>; + field3?: pb<3, CommentReqContentMeta>; + clientKey?: pb<7, string>; +} + +// Inline-in-legacy: `CommentReqPhotoInfoSchema.field1.schema.field2.schema`. +export interface CommentReqPhotoMeta { + field1?: pb<1, uint_32>; + field2?: pb<2, string>; + lloc?: pb<3, string>; + field4?: pb<4, string>; + field6?: pb<6, string>; + field7?: pb<7, uint_32>; + field8?: pb<8, uint_32>; + field9?: pb<9, uint_32>; + field14?: pb<14, uint_32>; + field15?: pb<15, uint_32>; + field17?: pb<17, uint_32>; +} + +// Inline-in-legacy: `CommentReqPhotoInfoSchema.field1.schema`. +export interface CommentReqPhotoWrap { + field2?: pb<2, CommentReqPhotoMeta>; +} + +export interface CommentReqPhotoInfo { + field1?: pb<1, CommentReqPhotoWrap>; + albumId?: pb<3, string>; + field5?: pb<5, uint_32>; +} + +// Inline-in-legacy: `CommentReqBodySchema.field1.schema`. +export interface CommentReqBodyHeader { + field3?: pb<3, uint_32>; + field4?: pb<4, string>; +} + +// Inline-in-legacy: `CommentReqBodySchema.field2.schema`. +export interface CommentReqBodyUserWrap { + field1?: pb<1, CommentUser>; +} + +export interface CommentReqBody { + field1?: pb<1, CommentReqBodyHeader>; + field2?: pb<2, CommentReqBodyUserWrap>; + field5?: pb<5, CommentReqPhotoInfo>; // 抓包证实评论文本在 field 5 +} + +// Inline-in-legacy: `DoQunCommentRequestSchema.body.schema`. +export interface DoQunCommentRequestBody { + groupId?: pb<2, string>; + field3?: pb<3, uint_32>; + reqBody?: pb<4, CommentReqBody>; + field5?: pb<5, CommentReqContent>; // 评论文本在外层 field 5 +} + +export interface DoQunCommentRequest { + field1?: pb<1, int_32>; + field2?: pb<2, bytes>; + field3?: pb<3, bytes>; + body?: pb<4, DoQunCommentRequestBody>; + traceId?: pb<5, string>; + extMap?: pb_repeated<10, ExtMapEntry>; +} + +export interface CommentRespUser { + uin?: pb<13, string>; +} + +export interface CommentRespContent { + type?: pb<1, uint_32>; + content?: pb<2, string>; +} + +export interface CommentRespData { + id?: pb<1, string>; + user?: pb<2, CommentRespUser>; + content?: pb_repeated<3, CommentRespContent>; + time?: pb<4, uint_64>; + clientKey?: pb<7, string>; +} + +// Inline-in-legacy: `DoQunCommentResponseSchema.comment.schema`. +export interface DoQunCommentResponseComment { + data?: pb<2, CommentRespData>; +} + +export interface DoQunCommentResponse { + field1?: pb<1, int_32>; + comment?: pb<4, DoQunCommentResponseComment>; +} + +// ── DoQunLike: like / unlike a media item ────────────────────────── + +export interface DoQunLikeReqLikeInfo { + id?: pb<1, string>; + status?: pb<3, uint_32>; +} + +export interface DoQunLikeReqCellCommon { + time?: pb<3, uint_64>; + feedId?: pb<4, string>; +} + +export interface DoQunLikeReqCellUser { + uin?: pb<13, string>; // 抓包证实 uin 是 field 13 +} + +export interface DoQunLikeReqCellUserInfo { + user?: pb<1, DoQunLikeReqCellUser>; +} + +export interface DoQunLikeReqCellQunInfo { + qunId?: pb<1, string>; +} + +export interface DoQunLikeReqCellMedia { + albumId?: pb<3, string>; + batchId?: pb<5, uint_64>; +} + +export interface DoQunLikeReqFeedPublish { + cellCommon?: pb<1, DoQunLikeReqCellCommon>; + cellUserInfo?: pb<2, DoQunLikeReqCellUserInfo>; + cellMedia?: pb<5, DoQunLikeReqCellMedia>; + cellQunInfo?: pb<12, DoQunLikeReqCellQunInfo>; +} + +export interface DoQunLikeReqBody { + type?: pb<2, uint_32>; + like?: pb<3, DoQunLikeReqLikeInfo>; + publish?: pb<4, DoQunLikeReqFeedPublish>; + clientKey?: pb<5, string>; +} + +export interface DoQunLikeRequest { + field1?: pb<1, int_32>; + field2?: pb<2, string>; + field3?: pb<3, string>; + body?: pb<4, DoQunLikeReqBody>; + extMap?: pb_repeated<10, ExtMapEntry>; +} + +export interface DoQunLikeRespBody { + like?: pb<2, DoQunLikeReqLikeInfo>; +} + +export interface DoQunLikeResponse { + field1?: pb<1, int_32>; + body?: pb<4, DoQunLikeRespBody>; +} + +// ── DeleteMedias: delete a media item from a group album ─────────── + +export interface DeleteMediasReqBody { + groupId?: pb<1, string>; + albumId?: pb<2, string>; + lloc?: pb<3, string>; +} + +export interface DeleteMediasRequest { + field1?: pb<1, int_32>; + field2?: pb<2, string>; + field3?: pb<3, string>; + body?: pb<4, DeleteMediasReqBody>; + traceId?: pb<5, string>; + extMap?: pb_repeated<10, ExtMapEntry>; +} + +export interface DeleteMediasResponse { + field1?: pb<1, int_32>; // expected 8694 for success + field2?: pb<2, int_32>; // error code (e.g. 10023) + field3?: pb<3, string>; // error message +} diff --git a/packages/core/src/bridge/web/group-album.ts b/packages/core/src/bridge/web/group-album.ts index 3ea71e19..321e9790 100644 --- a/packages/core/src/bridge/web/group-album.ts +++ b/packages/core/src/bridge/web/group-album.ts @@ -3,7 +3,6 @@ import { createHash } from 'crypto'; import { readFileSync, statSync, createReadStream, writeFileSync, unlinkSync } from 'fs'; import { basename, join } from 'path'; import { tmpdir } from 'os'; -import * as console from "node:console"; // 群相册信息 export interface GroupAlbumInfo { diff --git a/packages/core/tests/proton-parity.test.ts b/packages/core/tests/proton-parity.test.ts index a613d739..a6531434 100644 --- a/packages/core/tests/proton-parity.test.ts +++ b/packages/core/tests/proton-parity.test.ts @@ -52,6 +52,13 @@ import { } from '../src/bridge/proto/highway'; import { makeOidbBaseSchema, OidbSvcTrpcTcp0xFE5_2ResponseSchema } from '../src/bridge/proto/oidb'; import { makeOidbEnvelope, encodeOidbEnv, decodeOidbEnv } from '../src/bridge/bridge-oidb'; +import { + GetMediaListRequestSchema, + DoQunCommentRequestSchema, + DoQunLikeRequestSchema, + DeleteMediasRequestSchema, + DeleteMediasResponseSchema, +} from '../src/bridge/proto/oidb-action'; import type { SendLongMsgResp, @@ -100,6 +107,13 @@ import type { OidbBase, OidbSvcTrpcTcp0xFE5_2Response, } from '../src/bridge/proto/proton/oidb'; +import type { + GetMediaListRequest, + DoQunCommentRequest, + DoQunLikeRequest, + DeleteMediasRequest, + DeleteMediasResponse, +} from '../src/bridge/proto/proton/oidb-action'; function hex(buf: Uint8Array): string { return Buffer.from(buf).toString('hex'); @@ -688,4 +702,114 @@ describe('proton ↔ legacy parity (longmsg subset)', () => { const decoded = protobuf_decode(encoded); expect(decoded.result?.resId).toBe('rt-2'); }); + + // ── Group album TRPC envelopes (PR #31) ───────────────────────────── + // + // Raw TRPC packets — not OIDB-wrapped — that the group-album actions + // ship to `QunAlbum.trpc.qzone.webapp_qun_*`. Field names are mostly + // positional (`field1`/`field2`/...) because the upstream protocol + // doesn't expose semantic names; the byte-for-byte parity below is + // what guarantees the migration preserved every numbered field. + + // NOTE: every numeric/bytes field below is non-zero / non-empty — + // proton follows proto3 semantics and skips default-valued fields on + // the wire, while the legacy runtime encoder writes them all. Byte + // parity therefore only holds when no field equals its default. The + // actual production callers in `actions/group-album.ts` *do* pass + // some zero-valued fields (e.g. `field1: 0`), which means the + // post-migration packet drops a few leading zero tags — semantically + // equivalent to a proto3-conforming reader, see the explicit + // divergence test earlier in this file. + + it('encodes GetMediaListRequest (nested ReqInfo + extMap) identically', () => { + const data: GetMediaListRequest = { + field1: 1, // proto3 non-default + field2: new Uint8Array([0xab]), + field3: new Uint8Array([0xcd]), + reqInfo: { groupId: '555', albumId: 'alb-1', field3: 7, attachInfo: 'cursor', field5: 'tag' }, + traceId: '_1700000000_12345', + extMap: [{ key: 'fc-appid', value: '100' }], + }; + const legacy = protoEncode(data as any, GetMediaListRequestSchema); + const proton = protobuf_encode(data); + expect(hex(proton)).toBe(hex(legacy)); + }); + + it('encodes DoQunCommentRequest (deeply nested anonymous-in-legacy schemas) identically', () => { + const data: DoQunCommentRequest = { + field1: 8527, + field2: new Uint8Array([0x01]), + field3: new Uint8Array([0x02]), + body: { + groupId: '555', + field3: 2, + reqBody: { + field1: { field3: 3, field4: 'h' }, + field2: { field1: { uin: '10001' } }, + field5: { + field1: { + field2: { + field1: 1, field2: 'a', lloc: 'lloc-x', + field4: 'b', field6: 'c', field7: 1, field8: 1, field9: 1, + field14: 1, field15: 1, field17: 1, + }, + }, + albumId: 'alb-1', + field5: 1, + }, + }, + field5: { + field2: { uin: '10001' }, + field3: { field1: 1, field2: 'hello', field3: 'd', field4: 'e', field5: 1, field6: 'f' }, + clientKey: 'ck-1', + }, + }, + traceId: '_1700000000_12345', + extMap: [{ key: 'fc-appid', value: '100' }], + }; + const legacy = protoEncode(data as any, DoQunCommentRequestSchema); + const proton = protobuf_encode(data); + expect(hex(proton)).toBe(hex(legacy)); + }); + + it('encodes DoQunLikeRequest (with bigint time/batchId) identically', () => { + const data: DoQunLikeRequest = { + field1: 5495, + field2: 'h5_test', + field3: 'h5_test', + body: { + type: 2, + like: { id: '421_1_0_555|alb|42', status: 1 }, // non-default + publish: { + cellCommon: { time: 1700000000000n, feedId: '422_0_42' }, + cellUserInfo: { user: { uin: '10001' } }, + cellMedia: { albumId: 'alb', batchId: 42n }, + cellQunInfo: { qunId: '555' }, + }, + clientKey: 'ck', + }, + extMap: [{ key: 'fc-appid', value: '100' }], + }; + const legacy = protoEncode(data as any, DoQunLikeRequestSchema); + const proton = protobuf_encode(data); + expect(hex(proton)).toBe(hex(legacy)); + }); + + it('encodes DeleteMediasRequest + decodes DeleteMediasResponse identically', () => { + const req: DeleteMediasRequest = { + field1: 8694, field2: 'h5_test', field3: 'h5_test', + body: { groupId: '555', albumId: 'alb', lloc: 'lloc-x' }, + traceId: 'tr-1', + extMap: [{ key: 'fc-appid', value: '100' }], + }; + expect(hex(protobuf_encode(req))) + .toBe(hex(protoEncode(req as any, DeleteMediasRequestSchema))); + + // Response: encode with legacy, decode with proton, fields stay aligned. + const respBytes = protoEncode({ field1: 8694, field2: 10023, field3: 'no right delete' } as any, DeleteMediasResponseSchema); + const decoded = protobuf_decode(respBytes); + expect(decoded.field1).toBe(8694); + expect(decoded.field2).toBe(10023); + expect(decoded.field3).toBe('no right delete'); + }); }); From d8213369430eb46be9f47595445b9e0aa31f6673 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Tue, 19 May 2026 11:16:54 +0800 Subject: [PATCH 23/48] fix(onebot): hot-reload HTTP server accessToken without re-binding MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `HttpServerAdapter.startServer` baked `accessToken` into the `createServer` callback's closure, then relied on `bindingSignature` including the token to trigger a `close()`+`open()` round-trip on every change. Two problems: 1. The three sibling adapters (`ws-server`, `http-post`, `ws-client`) all read `this.config.accessToken` inline at the point of use, so the HTTP-server's closure-capture pattern was the odd one out. 2. `server.close()` is asynchronous; the immediately-following `server.listen()` on the same port can race with the OS releasing it. When it loses, the new listener fails with EADDRINUSE (logged via `server.on('error', …)` but not bubbled up), the old server is gone, and the operator's `reload` looks successful while the endpoint is actually broken — which lines up with the "token didn't hot-reload" reports. Drop the closure capture: `handleRequest` reads `this.config.path` and `this.config.accessToken` fresh per request (`reload()` already replaces `this.config` in place via `structuredClone(next)`). Remove `accessToken` from `bindingSignature` so a token change no longer triggers a port re-bind. `host`/`port`/`path` stay in the signature because Node's `Server.listen()` binds the socket on those. Four hot-reload tests pin the new contract: token swap, clearing to empty, setting from empty, and "token-only change returns `NetworkReloadType.Normal`" (no Reopened/Closed). All four hit a single OS-assigned port and verify the port is unchanged after reload — a re-bind would either land on a different port or fail. core: 613/613 tests pass (+4), typecheck clean. --- .../src/onebot/network/http-server-adapter.ts | 28 +++- .../core/tests/http-server-hot-reload.test.ts | 141 ++++++++++++++++++ 2 files changed, 162 insertions(+), 7 deletions(-) create mode 100644 packages/core/tests/http-server-hot-reload.test.ts diff --git a/packages/core/src/onebot/network/http-server-adapter.ts b/packages/core/src/onebot/network/http-server-adapter.ts index 1691e4c6..8291b24d 100644 --- a/packages/core/src/onebot/network/http-server-adapter.ts +++ b/packages/core/src/onebot/network/http-server-adapter.ts @@ -79,11 +79,8 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter onEvent(_event: JsonObject, _payload: DispatchPayload): void { /* no-op */ } private startServer(): void { - const expectedPath = normalizePath(this.config.path ?? '/'); - const accessToken = this.config.accessToken ?? ''; - const server = createServer((req, res) => { - void this.handleRequest(expectedPath, accessToken, req, res); + void this.handleRequest(req, res); }); this.server = server; @@ -93,7 +90,7 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter this.name, this.config.host ?? '0.0.0.0', this.config.port, - expectedPath, + normalizePath(this.config.path ?? '/'), ); }); server.on('error', (err) => { @@ -103,7 +100,15 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter server.listen(this.config.port, this.config.host ?? '0.0.0.0'); } - private async handleRequest(expectedPath: string, accessToken: string, req: IncomingMessage, res: ServerResponse): Promise { + private async handleRequest(req: IncomingMessage, res: ServerResponse): Promise { + // Read `path` + `accessToken` fresh from `this.config` on every + // request so config hot-reloads (`reload()` overwrites `this.config` + // in place) take effect on the very next request without + // re-binding the listener. Matches the ws-server / http-post / + // ws-client adapters, which all read `this.config.accessToken` + // inline at the point of use. + const expectedPath = normalizePath(this.config.path ?? '/'); + const accessToken = this.config.accessToken ?? ''; const parsedUrl = new URL(req.url ?? '/', 'http://127.0.0.1'); const incomingPath = parsedUrl.pathname; @@ -224,7 +229,16 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter } function bindingSignature(net: HttpServerNetwork): string { - return `${net.host ?? '0.0.0.0'}:${net.port}${normalizePath(net.path ?? '/')}#${net.accessToken ?? ''}`; + // `accessToken` deliberately omitted: it's read per-request from + // `this.config`, so a token change doesn't need to re-bind the + // listener. Including it here would cause a `close()` + `listen()` + // round trip on every token edit — a needless port-rebind that, on + // some hosts, races with the OS releasing the port and lands the + // server in a half-broken state where the old token still + // authenticates because the EADDRINUSE-failing new server never + // replaced the old one. `host`/`port`/`path` still gate a restart + // because Node's HTTP `Server.listen()` binds the socket on those. + return `${net.host ?? '0.0.0.0'}:${net.port}${normalizePath(net.path ?? '/')}`; } function readRequestBody(req: IncomingMessage, maxBytes = 2 * 1024 * 1024): Promise { diff --git a/packages/core/tests/http-server-hot-reload.test.ts b/packages/core/tests/http-server-hot-reload.test.ts new file mode 100644 index 00000000..9509541b --- /dev/null +++ b/packages/core/tests/http-server-hot-reload.test.ts @@ -0,0 +1,141 @@ +// Hot-reload tests for HttpServerAdapter — pins the contract that +// `reload({ accessToken: })` must take effect on the very next +// request without the listener being torn down. Earlier the adapter +// captured `accessToken` into a `startServer()` closure and relied on +// `bindingSignature` to trigger a `close()` + `open()` round-trip on +// token change; that race-prone path is gone and `handleRequest` now +// reads `this.config.accessToken` per request. + +import { describe, expect, it, vi, afterEach } from 'vitest'; +import http from 'http'; +import type { AddressInfo } from 'net'; +import { HttpServerAdapter } from '../src/onebot/network/http-server-adapter'; +import { NetworkReloadType, type NetworkAdapterContext } from '../src/onebot/network/adapter'; +import type { HttpServerNetwork } from '../src/onebot/types'; + +function fakeCtx(): NetworkAdapterContext { + return { + uin: '10001', + api: { + handle: vi.fn(async () => ({ status: 'ok', retcode: 0, data: { online: true } })), + } as any, + buildLifecycleEvent: vi.fn(() => ({})), + buildHeartbeatEvent: vi.fn(() => ({})), + }; +} + +function get(port: number, path: string, headers: Record = {}): Promise<{ status: number }> { + return new Promise((resolve, reject) => { + const req = http.request( + { hostname: '127.0.0.1', port, path, method: 'GET', headers }, + (res) => { + res.on('data', () => { /* drain */ }); + res.on('end', () => resolve({ status: res.statusCode! })); + }, + ); + req.on('error', reject); + req.end(); + }); +} + +// Wait until the underlying http.Server has bound its port; tests that +// hit the socket too early get ECONNREFUSED on slow CI hosts. +async function waitForListen(adapter: HttpServerAdapter): Promise { + for (let i = 0; i < 50; i++) { + const server = (adapter as any).server as http.Server | null; + const addr = server?.address() as AddressInfo | null | undefined; + if (addr && typeof addr === 'object') return addr.port; + await new Promise((r) => setTimeout(r, 20)); + } + throw new Error('http server never started listening'); +} + +describe('HttpServerAdapter — accessToken hot reload', () => { + let adapter: HttpServerAdapter | null = null; + + afterEach(() => { + adapter?.close(); + adapter = null; + }); + + it('a swapped accessToken authorizes the new token on the next request — no listener re-bind', async () => { + const ctx = fakeCtx(); + // port=0 → OS-assigned; the swap proves no re-bind happens because + // a re-bind would land on a different port and `waitForListen` + // would diverge from the original. + const config: HttpServerNetwork = { + name: 'hot', port: 0, enabled: true, accessToken: 'tok-1', + messageFormat: 'array', reportSelfMessage: false, + }; + adapter = new HttpServerAdapter('hot', config, ctx); + adapter.open(); + const portBefore = await waitForListen(adapter); + + // Sanity: old token authorizes, anything else 401s. + expect((await get(portBefore, '/', { authorization: 'Bearer tok-1' })).status).toBe(200); + expect((await get(portBefore, '/', { authorization: 'Bearer tok-2' })).status).toBe(401); + + // Hot-swap the token. + await adapter.reload({ ...config, accessToken: 'tok-2' }); + + // Same port (no re-bind) — and the new token must take effect on + // the very next request. + const portAfter = ((adapter as any).server as http.Server).address() as AddressInfo; + expect(portAfter.port).toBe(portBefore); + + expect((await get(portBefore, '/', { authorization: 'Bearer tok-1' })).status).toBe(401); + expect((await get(portBefore, '/', { authorization: 'Bearer tok-2' })).status).toBe(200); + }); + + it('clearing accessToken to empty disables auth on the next request', async () => { + const ctx = fakeCtx(); + const config: HttpServerNetwork = { + name: 'hot-clear', port: 0, enabled: true, accessToken: 'tok-1', + messageFormat: 'array', reportSelfMessage: false, + }; + adapter = new HttpServerAdapter('hot-clear', config, ctx); + adapter.open(); + const port = await waitForListen(adapter); + + expect((await get(port, '/')).status).toBe(401); // no token header → 401 + + await adapter.reload({ ...config, accessToken: '' }); + + expect((await get(port, '/')).status).toBe(200); // auth disabled + }); + + it('setting accessToken from empty enforces auth on the next request', async () => { + const ctx = fakeCtx(); + const config: HttpServerNetwork = { + name: 'hot-add', port: 0, enabled: true, + messageFormat: 'array', reportSelfMessage: false, + }; + adapter = new HttpServerAdapter('hot-add', config, ctx); + adapter.open(); + const port = await waitForListen(adapter); + + expect((await get(port, '/')).status).toBe(200); // no auth configured + + await adapter.reload({ ...config, accessToken: 'tok-new' }); + + expect((await get(port, '/')).status).toBe(401); // auth now required + expect((await get(port, '/', { authorization: 'Bearer tok-new' })).status).toBe(200); + }); + + it('changing only accessToken returns NetworkReloadType.Normal — no Reopened/Closed', async () => { + const ctx = fakeCtx(); + const config: HttpServerNetwork = { + name: 'hot-type', port: 0, enabled: true, accessToken: 'a', + messageFormat: 'array', reportSelfMessage: false, + }; + adapter = new HttpServerAdapter('hot-type', config, ctx); + adapter.open(); + await waitForListen(adapter); + + const reloadType = await adapter.reload({ ...config, accessToken: 'b' }); + // Without re-binding, the adapter reports `Normal` — anything but + // `Reopened` / `Closed` is acceptable; we mostly care that nothing + // touched the listener. + expect(reloadType).toBe(NetworkReloadType.Normal); + }); +}); From 70715763bd110f955c0351b3816e791105670953 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Tue, 19 May 2026 11:20:47 +0800 Subject: [PATCH 24/48] fix(core): wire @snowluma/proton vite plugin into the production build MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The proton plugin was only in `vitest.config.ts`, so tests and typecheck passed but the bundled `dist/index.mjs` shipped with the unsubstituted generic shells — every `protobuf_encode()` / `protobuf_decode()` call hit the runtime fallback and threw: "protobuf_encode() was not transformed by the @snowluma/proton Vite plugin. …" at every msg-push, rkey/friend/group/profile warmup, etc. on the Win/Linux releases. Add `protobufVitePlugin()` to the shared `BaseConfigPlugin` so the transform runs in both dev (`vite build --mode development`) and prod (`vite build`). Sanity-check on a fresh `vite build` shows the bundle now contains 481 distinct monomorphized codecs (704 encode + 511 decode call-site replacements), and the only remaining "was not transformed" string is the dead runtime fallback that no longer has a caller. --- packages/core/vite.config.ts | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/packages/core/vite.config.ts b/packages/core/vite.config.ts index 99b4d5af..79cefc18 100644 --- a/packages/core/vite.config.ts +++ b/packages/core/vite.config.ts @@ -4,6 +4,7 @@ import fs from 'fs'; import path from 'path'; import { builtinModules } from 'module'; import cp from 'vite-plugin-cp'; +import protobufVitePlugin from '@snowluma/proton/vite'; const __dirname = path.dirname(fileURLToPath(import.meta.url)); const repoRoot = path.resolve(__dirname, '..', '..'); @@ -76,6 +77,14 @@ if (missingNatives.length > 0) { } const BaseConfigPlugin: PluginOption[] = [ + // Proton substitutes every `protobuf_encode` / `protobuf_decode` + // call site with a monomorphized codec at build time. WITHOUT this + // plugin in the plugins array the runtime fallback in + // `@snowluma/proton/runtime.ts` throws on the first call (and the + // packaged Win/Linux release does exactly that). It MUST appear + // before `cp` so the transform runs on every source file Vite asks + // for, regardless of where `cp` later copies emitted assets. + protobufVitePlugin(), cp({ targets: [ ...runtimeDistFiles.map((file) => ({ From ecb8064ca9220900a2d42032b58780df7d813704 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Tue, 19 May 2026 11:48:41 +0800 Subject: [PATCH 25/48] perf(webui): code-split routes; cut initial JS from 606 kB to 284 kB MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `vite build` was emitting a single ~606 kB chunk for the whole SPA (Vite even printed its >500 kB warning). Every route — overview, config (with its full edit-dialog form surface), logs, settings — was eagerly imported in `router/index.tsx`, so users paid the full parse + execute cost before the login redirect even resolved. That's the most plausible cause of the "loading node config is somewhat slow" report. Switch each route to `lazyRouteComponent(() => import('…'), '')` so the page chunk is fetched on demand, and wrap `` in `AppLayout` with a `` boundary backed by a small skeleton fallback. `defaultPreload: 'intent'` is already set on the router, so hovering a sidebar link warms the next chunk before the click — navigation still feels instant after the first idle moment. Build now emits: index.js 606 kB → 284 kB (-53%) overview-page 15 kB config-page 25 kB logs-page 5.6 kB settings-page 5.8 kB button (shared primitives) 164 kB + smaller per-component chunks Vite shook out And the >500 kB warning is gone. Bonus: replace the per-render `list.filter(...).map(...).includes(item.name)` O(n²) duplicate-name check in `NetworkTabView` with a one-shot `Map` — matters every time the user types in the edit dialog and the tab underneath re-renders. --- .../src/components/pages/config-page.tsx | 17 ++++++++-- packages/webui/src/router/app-layout.tsx | 27 +++++++++++++-- packages/webui/src/router/index.tsx | 33 ++++++++++++++----- 3 files changed, 65 insertions(+), 12 deletions(-) diff --git a/packages/webui/src/components/pages/config-page.tsx b/packages/webui/src/components/pages/config-page.tsx index a9954fac..fa7594f4 100644 --- a/packages/webui/src/components/pages/config-page.tsx +++ b/packages/webui/src/components/pages/config-page.tsx @@ -353,6 +353,20 @@ function NetworkTabView({ // widening cast at the call site rather than ladder-of-ifs per tab. const summarize = tab.summarize as (it: typeof list[number]) => string; + // Tally name occurrences once instead of doing `list.filter(...).map(...).includes(...)` + // inside `.map()` (O(n²) per render). With this lookup, the duplicate + // check is O(1) per row — matters once the list grows past a few entries + // or when typing renames a node and the tab re-renders on every keystroke. + const nameCounts = useMemo(() => { + const counts = new Map(); + for (const item of list) { + const name = item.name; + if (!name) continue; + counts.set(name, (counts.get(name) ?? 0) + 1); + } + return counts; + }, [list]); + if (list.length === 0) { return (
@@ -369,8 +383,7 @@ function NetworkTabView({

{tab.description}

{list.map((item, idx) => { - const others = list.filter((_, i) => i !== idx).map((n) => n.name); - const duplicate = !!item.name && others.includes(item.name); + const duplicate = !!item.name && (nameCounts.get(item.name) ?? 0) > 1; return ( - + {/* Routes use `lazyRouteComponent` (router/index.tsx) for + code-splitting, which suspends until the chunk is fetched. + The chrome (sidebar / top bar) stays mounted across this + boundary so only the page surface flashes a skeleton. */} + }> + + ); } + +function PageFallback() { + // Generic page placeholder. Kept intentionally low-detail (just a + // header + a couple of card-shaped blocks) so it works for every + // route — overview's stat grid, config's tabbed editor, logs' list, + // and the settings page all converge on roughly this skeleton on + // their own loading states. + return ( +
+ + + + +
+ ); +} diff --git a/packages/webui/src/router/index.tsx b/packages/webui/src/router/index.tsx index 21e828b0..791dc490 100644 --- a/packages/webui/src/router/index.tsx +++ b/packages/webui/src/router/index.tsx @@ -2,14 +2,19 @@ import { createRootRoute, createRoute, createRouter, + lazyRouteComponent, Outlet, } from '@tanstack/react-router'; -import { OverviewPage } from '@/components/pages/overview-page'; -import { ConfigPage } from '@/components/pages/config-page'; -import { LogsPage } from '@/components/pages/logs-page'; -import { SettingsPage } from '@/components/pages/settings-page'; import { AppLayout } from './app-layout'; +// Page components are loaded on demand so the initial paint only ships +// the auth surface + layout shell. With `defaultPreload: 'intent'` set +// below, the router warms the next chunk on hover/focus, so navigation +// still feels instant after the first idle moment. Previously every +// page (overview / config / logs / settings) lived in the single +// ~600 kB bundle that Vite explicitly warned about — config-page edit +// dialog alone pulls in a large form surface that most users never +// touch on first visit. const rootRoute = createRootRoute({ component: () => , }); @@ -23,25 +28,37 @@ const appLayoutRoute = createRoute({ const overviewRoute = createRoute({ path: '/', getParentRoute: () => appLayoutRoute, - component: OverviewPage, + component: lazyRouteComponent( + () => import('@/components/pages/overview-page'), + 'OverviewPage', + ), }); const configRoute = createRoute({ path: '/config', getParentRoute: () => appLayoutRoute, - component: ConfigPage, + component: lazyRouteComponent( + () => import('@/components/pages/config-page'), + 'ConfigPage', + ), }); const logsRoute = createRoute({ path: '/logs', getParentRoute: () => appLayoutRoute, - component: LogsPage, + component: lazyRouteComponent( + () => import('@/components/pages/logs-page'), + 'LogsPage', + ), }); const settingsRoute = createRoute({ path: '/settings', getParentRoute: () => appLayoutRoute, - component: SettingsPage, + component: lazyRouteComponent( + () => import('@/components/pages/settings-page'), + 'SettingsPage', + ), }); const routeTree = rootRoute.addChildren([ From a50e038272dc27feefca4181106e92fe5673308f Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Tue, 19 May 2026 11:52:55 +0800 Subject: [PATCH 26/48] docs(readme): list @snowluma/proton in the workspace table Vendored in 6294e29, used by every protobuf call site in `core` since the OIDB migration landed (5b55f5b). Add a one-liner to the workspace table next to the other infrastructure packages. --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 739c313b..84a5db6b 100644 --- a/README.md +++ b/README.md @@ -68,6 +68,7 @@ WebUI 默认监听 `5099` 端口。首次启动会在控制台打印 `initial cr | [`@snowluma/sdk`](packages/sdk) | OneBot HTTP & WebSocket TypeScript SDK,发布到 npm。 | | [`@snowluma/ui`](packages/ui) | Tailwind 4 共享组件库(shadcn 风格),发布到 npm。 | | [`@snowluma/websocket`](packages/websocket) | OneBot WebSocket 适配器底层。 | +| [`@snowluma/proton`](packages/proton) | 编译期 protobuf 编/解码器生成器:TS interface 标注 `pb`,Vite 插件在构建时把 `protobuf_encode` / `protobuf_decode` 替换为内联 codec,零运行时反射。 | | [`@snowluma/runtime`](packages/runtime) | 运行时清单与发布包资源。 | | [`webui`](packages/webui) | Web 管理面板前端。 | From e6376478779dcf390cce5ee68479450ea9c56bf2 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Tue, 19 May 2026 12:31:05 +0800 Subject: [PATCH 27/48] fix(bridge): publish uploaded files as chat messages (the "empty message" bug) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `upload_group_file` / `upload_private_file` used to do only the upload half of the napcat-equivalent flow: OIDB 0x6D6_0 alloc → highway PUT → return fileId The fileId was real, the bytes were on QQ's CDN, the logs said "uploaded" — but the chat showed nothing because no message was ever sent referring to the upload. NapCat's `UploadGroupFile` action (`dev/napcatQQ/.../UploadGroupFile.ts:54-58`) does the upload AND immediately calls `MsgApi.sendMsg(peer, [fileElement])` in the same action; that second step is what makes the file visible in the chat. Add the missing send step. Two paths because the wire shape differs: - **Group files** ride on `Elem.transElem` (type 24) in the `RichText.elems` array. Add a `makeGroupFileElem()` helper + `case 'file':` in `element-builder.buildSendElems`, then `bridge.sendGroupMessage(groupId, [fileElement])` after a successful upload. The TransElem wraps a `GroupFileExtra` protobuf in `0x01 | BE16(len) | payload`, byte-symmetric with the receive-side decoder at `rich-body-decoder.ts:171-185`. - **C2C (private) files** live on `RichText.notOnlineFile` (field 3 on RichText, parallel to `elems`), so they can't go through `buildSendElems` at all. Add `Bridge.sendC2cFileMessage` that builds the `SendMessageRequest` with `notOnlineFile` directly and dispatches via `sendRawPacket`. The decoder side that lifts these back to `{type:'file'}` segments has lived at `rich-body-decoder.ts:425-433` the whole time. Behavioural detail: both upload paths call the chat-publish step *only* when `uploadFile=true` (the default). `uploadFile=false` keeps the upload-only semantics for callers that just want a fileId without dropping a message in the chat. If the chat post fails for any reason (server rejection / network), the action still returns the fileId with a warning log — the file is on QQ's side, callers can re-publish if they want. Regression coverage in `tests/actions/group-file.test.ts`: - publishes the file as `{type:'file'}` via sendGroupMessage on group upload - skips the post when uploadFile=false - returns success even when the chat post fails - same trio for private upload going through sendC2cFileMessage - and confirms private path does NOT route through the `sendPrivateMessage` elems[] pipeline core: 618/618 tests pass (+5), typecheck clean. Production build contains 8 substituted call sites for the new GroupFileExtra + SendMessageRequest paths under proton. --- .../core/src/bridge/actions/group-file.ts | 51 ++++++++++++ packages/core/src/bridge/bridge-interface.ts | 12 +++ packages/core/src/bridge/bridge.ts | 70 ++++++++++++++++ packages/core/src/bridge/element-builder.ts | 63 ++++++++++++++ packages/core/tests/actions/_helpers.ts | 10 +++ .../core/tests/actions/group-file.test.ts | 82 +++++++++++++++++++ 6 files changed, 288 insertions(+) diff --git a/packages/core/src/bridge/actions/group-file.ts b/packages/core/src/bridge/actions/group-file.ts index 2408904a..f56b408f 100644 --- a/packages/core/src/bridge/actions/group-file.ts +++ b/packages/core/src/bridge/actions/group-file.ts @@ -28,8 +28,11 @@ import type { } from '../proto/proton/oidb-action'; import type { FileUploadExt } from '../proto/proton/highway'; import { toHexUpper } from '../../utils/hex'; +import { createLogger } from '../../utils/logger'; import { ensureRetCodeZero, resolveSelfUid, toInt, type MediaIndexNode } from './shared'; +const log = createLogger('GroupFile'); + // ─────────────── public result types ─────────────── export interface GroupFileInfo { @@ -349,6 +352,33 @@ export async function uploadGroupFile( await uploadHighwayHttp(bridge, session, 71, loaded.bytes, hashes.md5, ext); } + // 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 — + // the chat shows nothing. NapCat does the same (upload + sendMsg + // atomically inside `upload_group_file`, see + // `dev/napcatQQ/.../UploadGroupFile.ts:54-58`). Only suppressed when + // the caller opts out via `uploadFile=false` (treat that as "I only + // wanted the slot allocated, hold the chat post"). + if (uploadFile) { + try { + await bridge.sendGroupMessage(groupId, [{ + type: 'file', + fileId, + fileName, + fileSize: loaded.bytes.length, + md5Hex: bytesToHexUpper(hashes.md5), + sha1Hex: bytesToHexUpper(hashes.sha1), + }]); + } catch (err) { + // The bytes are already on the server and the fileId is valid — + // fail loud but don't lose the upload result the action handler + // committed to returning. Callers can still resolve the file by + // id; they'll just have to re-publish it themselves. + log.warn('group file uploaded (fileId=%s) but chat post failed: %s', + fileId, err instanceof Error ? err.message : String(err)); + } + } + return { fileId }; } @@ -435,6 +465,27 @@ export async function uploadPrivateFile( await uploadHighwayHttp(bridge, session, 95, loaded.bytes, hashes.md5, ext); } + // Stage 3: publish the file as a c2c chat message. C2C files use + // `RichText.notOnlineFile` (parallel to `elems`), so we go through + // the dedicated `sendC2cFileMessage` instead of `sendPrivateMessage` + // which only knows about elems[]. NapCat does the same atomic + // upload+send dance — without it the file sits on the server and + // the recipient sees nothing. + if (uploadFile) { + try { + await bridge.sendC2cFileMessage(userId, targetUid, { + fileId, + fileName, + fileSize: loaded.bytes.length, + fileMd5: hashes.md5, + fileHash: fileHash ?? '', + }); + } catch (err) { + log.warn('private file uploaded (fileId=%s) but chat post failed: %s', + fileId, err instanceof Error ? err.message : String(err)); + } + } + return { fileId, fileHash }; } diff --git a/packages/core/src/bridge/bridge-interface.ts b/packages/core/src/bridge/bridge-interface.ts index ca50979c..225a8d0e 100644 --- a/packages/core/src/bridge/bridge-interface.ts +++ b/packages/core/src/bridge/bridge-interface.ts @@ -43,6 +43,18 @@ export interface BridgeInterface { // ─── Send (messages) ─── sendGroupMessage(groupId: number, elements: MessageElement[]): Promise; sendPrivateMessage(userUin: number, elements: MessageElement[]): Promise; + /** + * Send a c2c file as a chat message. Bypasses the regular elems[] + * pipeline because c2c files live on `RichText.notOnlineFile`, not + * inside the elems array. Group files go through `sendGroupMessage` + * with a `{type:'file', fileId, fileName, fileSize, md5Hex, sha1Hex}` + * element instead. + */ + sendC2cFileMessage( + userUin: number, + userUid: string, + info: { fileId: string; fileName: string; fileSize: number; fileMd5: Uint8Array; fileHash?: string }, + ): Promise; // ─── Fetch (contacts / profile / system) ─── fetchFriendList(): Promise; diff --git a/packages/core/src/bridge/bridge.ts b/packages/core/src/bridge/bridge.ts index 5f032774..aabd813f 100644 --- a/packages/core/src/bridge/bridge.ts +++ b/packages/core/src/bridge/bridge.ts @@ -398,6 +398,76 @@ export class Bridge implements BridgeInterface { }; } + /** + * Send a c2c file as a chat message. + * + * Unlike images / videos / records that ride on `RichText.elems` as + * regular Elem entries, c2c files use `RichText.notOnlineFile` + * (parallel to `elems`, see `proto/proton/message.ts:75`). The + * receive-side decoder strips this back to a `{type:'file'}` segment + * in `rich-body-decoder.ts:425-433`. There's no Elem you can stuff + * into `buildSendElems` for this, so this helper short-circuits the + * normal send pipeline. + */ + async sendC2cFileMessage( + userUin: number, + userUid: string, + info: { fileId: string; fileName: string; fileSize: number; fileMd5: Uint8Array; fileHash?: string }, + ): Promise { + const random = this.nextMessageRandom(); + const clientSeq = this.nextClientSequence(); + + const request = protobuf_encode({ + routingHead: { + c2c: { uin: userUin, uid: userUid }, + }, + contentHead: { + type: 1, + subType: 0, + c2cCmd: 11, + }, + messageBody: { + richText: { + notOnlineFile: { + fileType: 0, + fileUuid: info.fileId, + fileMd5: info.fileMd5, + fileName: info.fileName, + fileSize: BigInt(info.fileSize), + fileHash: info.fileHash ?? '', + }, + }, + } as any, + clientSequence: clientSeq, + random, + syncCookie: new Uint8Array(0), + via: 0, + dataStatist: 0, + ctrl: { + msgFlag: Math.floor(Date.now() / 1000), + }, + multiSendSeq: 0, + }); + + const result = await this.sendRawPacket(Bridge.SEND_MSG_CMD, request); + if (!result.success || !result.gotResponse || !result.responseData) { + throw new Error(`send c2c file message failed: ${result.errorMessage || 'no response'}`); + } + + const response = protobuf_decode(result.responseData); + if (!response) { + throw new Error('failed to decode SendMessageResponse'); + } + if (response.result !== undefined && response.result !== 0) { + throw new Error(`send c2c file message rejected: result=${response.result} err=${response.errMsg ?? ''}`); + } + + const seq = response.privateSequence ?? 0; + const messageId = (random & 0x7FFFFFFF) || seq; + const timestamp = response.timestamp1 ?? Math.floor(Date.now() / 1000); + return { messageId, sequence: seq, clientSequence: clientSeq, random, timestamp }; + } + // --- Delegated: OIDB helpers --- async resolveUserUid(uin: number, groupId?: number): Promise { diff --git a/packages/core/src/bridge/element-builder.ts b/packages/core/src/bridge/element-builder.ts index a2840292..cace04b2 100644 --- a/packages/core/src/bridge/element-builder.ts +++ b/packages/core/src/bridge/element-builder.ts @@ -13,9 +13,11 @@ import type { MentionExtraSend, MarkdownData, } from './proto/proton/action'; +import type { GroupFileExtra } from './proto/proton/element'; import { uploadImageMsgInfo } from './highway/image-upload'; import { uploadPttMsgInfo } from './highway/ptt-upload'; import { uploadVideoMsgInfo } from './highway/video-upload'; +import { hexToBytes } from './highway/pipeline'; type ProtoElem = Partial>; @@ -244,6 +246,55 @@ async function makePttElem(ctx: SendContext, element: MessageElement): Promise

({ + inner: { + info: { + busId: 102, + fileId: element.fileId, + fileSize: BigInt(fileSize), + fileName, + fileSha: sha1, + extInfoString: '', + fileMd5: md5, + }, + }, + }); + if (extraBytes.length > 0xFFFF) { + // The 16-bit length prefix caps the payload at 64 KiB; even the + // densest GroupFileExtra (fileId/name/two hashes) is well under. + // This is here so a future schema change can't silently truncate. + throw new Error(`group file extra too large (${extraBytes.length} > 65535)`); + } + const elemValue = new Uint8Array(3 + extraBytes.length); + elemValue[0] = 0x01; + elemValue[1] = (extraBytes.length >> 8) & 0xff; + elemValue[2] = extraBytes.length & 0xff; + elemValue.set(extraBytes, 3); + + return { + transElem: { + elemType: 24, + elemValue, + } as any, + }; +} + async function makeVideoElem(ctx: SendContext, element: MessageElement): Promise { const isGroup = ctx.groupId !== undefined; const targetIdOrUid = isGroup ? ctx.groupId! : (ctx.userUid ?? ''); @@ -331,6 +382,18 @@ export async function buildSendElems(elements: MessageElement[], ctx?: SendConte } break; + case 'file': + // The group `TransElem(24)` shape works for group chats only. + // C2C files live on `RichText.notOnlineFile` instead of in the + // elems array, so `sendPrivateMessage` short-circuits before it + // ever lands here — see `bridge.sendPrivateMessage`. + if (ctx?.groupId !== undefined) { + result.push(makeGroupFileElem(elem)); + } else { + console.warn('[ElemBuilder] file send via elems[] is group-only; use bridge.sendC2cFileMessage for c2c'); + } + break; + default: console.warn(`[ElemBuilder] unsupported element type for send: ${elem.type}`); break; diff --git a/packages/core/tests/actions/_helpers.ts b/packages/core/tests/actions/_helpers.ts index 638079e1..097cdcae 100644 --- a/packages/core/tests/actions/_helpers.ts +++ b/packages/core/tests/actions/_helpers.ts @@ -24,6 +24,13 @@ export interface MockBridge { fetchGroupMemberList: ReturnType; fetchUserProfile: ReturnType; resolveUserUid: ReturnType; + // High-level message senders. Default to no-op resolves so actions + // that fire off a follow-up chat message after their main work + // (e.g. `upload_group_file` → `sendGroupMessage` to publish the + // file in chat) don't crash test setups that don't care about it. + sendGroupMessage: ReturnType; + sendPrivateMessage: ReturnType; + sendC2cFileMessage: ReturnType; } export function mockBridge(overrides: Partial = {}): MockBridge { @@ -49,6 +56,9 @@ export function mockBridge(overrides: Partial = {}): MockBridge { fetchGroupMemberList: vi.fn(async () => []), fetchUserProfile: vi.fn(async () => ({ uid: 'profile-uid' })), resolveUserUid: vi.fn(async () => 'resolved-uid'), + sendGroupMessage: vi.fn(async () => ({ messageId: 1, sequence: 1, clientSequence: 0, random: 1, timestamp: 0 })), + sendPrivateMessage: vi.fn(async () => ({ messageId: 1, sequence: 1, clientSequence: 0, random: 1, timestamp: 0 })), + sendC2cFileMessage: vi.fn(async () => ({ messageId: 1, sequence: 1, clientSequence: 0, random: 1, timestamp: 0 })), ...overrides, }; } diff --git a/packages/core/tests/actions/group-file.test.ts b/packages/core/tests/actions/group-file.test.ts index 2a10edd9..54eb890a 100644 --- a/packages/core/tests/actions/group-file.test.ts +++ b/packages/core/tests/actions/group-file.test.ts @@ -136,6 +136,54 @@ describe('actions/group-file', () => { .rejects.toThrow(/code=999/); }); + it('uploadGroupFile publishes the file as a chat message 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 + // `sendGroupMessage` the file never appears in the chat. Asserts + // that `bridge.sendGroupMessage` is invoked with a single + // `{type:'file'}` element pointing at the uploaded fileId. + const bridge = mockBridge(); + vi.mocked(oidb.runOidb).mockResolvedValueOnce( + protobuf_encode>({ + body: { upload: { fileId: 'fid-pub', boolFileExist: true } as any }, + }), + ); + await groupFile.uploadGroupFile(bridge as any, 12345, '/path/some-file.bin', 'mynote.txt'); + expect(bridge.sendGroupMessage).toHaveBeenCalledOnce(); + const [groupId, elements] = bridge.sendGroupMessage.mock.calls[0]!; + expect(groupId).toBe(12345); + expect(elements).toHaveLength(1); + expect(elements[0]).toMatchObject({ + type: 'file', + fileId: 'fid-pub', + fileName: 'mynote.txt', + }); + }); + + it('uploadGroupFile skips the chat post when uploadFile=false', async () => { + const bridge = mockBridge(); + vi.mocked(oidb.runOidb).mockResolvedValueOnce( + protobuf_encode>({ + body: { upload: { fileId: 'fid-skip', boolFileExist: true } as any }, + }), + ); + await groupFile.uploadGroupFile(bridge as any, 12345, '/path/file.bin', '', '/', false); + expect(bridge.sendGroupMessage).not.toHaveBeenCalled(); + }); + + it('uploadGroupFile returns success even when the chat post fails (file is still uploaded)', async () => { + const bridge = mockBridge(); + vi.mocked(bridge.sendGroupMessage).mockRejectedValueOnce(new Error('message rejected')); + vi.mocked(oidb.runOidb).mockResolvedValueOnce( + protobuf_encode>({ + body: { upload: { fileId: 'fid-tolerant', boolFileExist: true } as any }, + }), + ); + const out = await groupFile.uploadGroupFile(bridge as any, 12345, '/path/file.bin'); + expect(out).toEqual({ fileId: 'fid-tolerant' }); + expect(bridge.sendGroupMessage).toHaveBeenCalledOnce(); + }); + it('uploadPrivateFile resolves both target + self UID before OIDB call', async () => { const bridge = mockBridge({ identity: { @@ -160,6 +208,40 @@ describe('actions/group-file', () => { expect(bridge.resolveUserUid).toHaveBeenCalledTimes(2); }); + it('uploadPrivateFile publishes the file via sendC2cFileMessage after upload', async () => { + // C2C files use `RichText.notOnlineFile` (not in the elems array), + // so `uploadPrivateFile` calls the dedicated `sendC2cFileMessage` + // path on the bridge rather than `sendPrivateMessage`. Same bug + // class as the group case — without this the recipient sees no + // message even though the bytes are on the server. + const bridge = mockBridge(); + vi.mocked(bridge.resolveUserUid).mockResolvedValueOnce('target-uid'); + vi.mocked(oidb.runOidb).mockResolvedValueOnce( + protobuf_encode>({ + body: { upload: { uuid: 'pfid', fileAddon: 'phash', boolFileExist: true } as any }, + }), + ); + await groupFile.uploadPrivateFile(bridge as any, 67890, '/path/private-file.bin', 'doc.pdf'); + expect(bridge.sendC2cFileMessage).toHaveBeenCalledOnce(); + const [userUin, userUid, info] = bridge.sendC2cFileMessage.mock.calls[0]!; + expect(userUin).toBe(67890); + expect(userUid).toBe('target-uid'); + expect(info).toMatchObject({ fileId: 'pfid', fileName: 'doc.pdf', fileHash: 'phash' }); + expect(bridge.sendPrivateMessage).not.toHaveBeenCalled(); + }); + + it('uploadPrivateFile skips the chat post when uploadFile=false', async () => { + const bridge = mockBridge(); + vi.mocked(bridge.resolveUserUid).mockResolvedValueOnce('target-uid'); + vi.mocked(oidb.runOidb).mockResolvedValueOnce( + protobuf_encode>({ + body: { upload: { uuid: 'pfid', fileAddon: 'phash', boolFileExist: true } as any }, + }), + ); + await groupFile.uploadPrivateFile(bridge as any, 67890, '/path/file', '', false); + expect(bridge.sendC2cFileMessage).not.toHaveBeenCalled(); + }); + it('fetchGroupFiles paginates files + folders out of OIDB items', async () => { const bridge = mockBridge(); vi.mocked(oidb.runOidb).mockResolvedValueOnce( From 10154cfbff9e25742dd7ce7fc3896cc2cc1a2725 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Tue, 19 May 2026 12:42:47 +0800 Subject: [PATCH 28/48] =?UTF-8?q?fix(onebot):=20parse=20`{type:'file',=20f?= =?UTF-8?q?ile=5Fid:'=E2=80=A6'}`=20segments=20instead=20of=20dropping=20t?= =?UTF-8?q?hem?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The companion to `e637647`. That commit fixed `upload_group_file` / `upload_private_file` to publish the file as a chat message atomically (matching napcat). This one fixes the OTHER half of the same bug: when a bot framework does send_msg([{type:'file', file_id:''}]) — attaching an already-uploaded file as a message segment — the parser used to fall through to its default warn-and-drop branch (`message-parser.ts:340`). The dropped segment then either: - became "message is empty" if it was the only segment, or - silently disappeared if it shared the payload with text, producing a chat bubble missing the file. Adds a `case 'file':` that maps the OneBot segment shape to the existing `MessageElement{type:'file', fileId, fileName, fileSize, md5Hex, sha1Hex}` that `element-builder` already knows how to emit as `TransElem(24)`. Accepts the common alias spellings (`file_id`/`fileId`, `name`/`filename`/`fileName`, `size`/`fileSize`, `md5`/`md5Hex`, `sha1`/`sha1Hex`). Deliberately rejects `{file: '/path'}` form — kicking off an upload from inside the synchronous parser would either swallow errors or restructure the whole parseMessage signature, neither worth it. Callers wanting upload-and-send should keep using `upload_group_file` / `upload_private_file`, which now does both atomically. core: 621/621 tests pass (+3), typecheck clean. --- packages/core/src/onebot/message-parser.ts | 25 ++++++++++++ packages/core/tests/message-parser.test.ts | 44 ++++++++++++++++++++++ 2 files changed, 69 insertions(+) diff --git a/packages/core/src/onebot/message-parser.ts b/packages/core/src/onebot/message-parser.ts index f971aa0f..159dc530 100644 --- a/packages/core/src/onebot/message-parser.ts +++ b/packages/core/src/onebot/message-parser.ts @@ -336,6 +336,31 @@ async function segmentToElement(type: string, data: Record, opt // Anonymous flag — ignored during send, the protocol handles anonymity return null; } + case 'file': { + // OneBot11 file segment referencing a previously-uploaded file + // (returned by `upload_group_file` / `upload_private_file`). + // We deliberately do NOT support `{file: '/path'}` here because + // the upload pipeline is async and lives behind the bridge — + // the element-builder runs synchronously over the parsed + // message. Callers that want upload-and-send should use the + // dedicated `upload_*` actions which now publish the file in + // chat atomically (`actions/group-file.ts`). + const fileId = String(data.file_id ?? data.fileId ?? '').trim(); + if (!fileId) { + log.warn('[MsgParser] file segment without file_id is unsupported (upload first via upload_group_file / upload_private_file)'); + return null; + } + const fileName = String(data.name ?? data.filename ?? data.fileName ?? '').trim(); + const fileSize = intOr(data.size ?? data.fileSize, 0); + const md5Hex = String(data.md5 ?? data.md5Hex ?? '').trim(); + const sha1Hex = String(data.sha1 ?? data.sha1Hex ?? '').trim(); + const elem: MessageElement = { type: 'file', fileId }; + if (fileName) elem.fileName = fileName; + if (fileSize > 0) elem.fileSize = fileSize; + if (md5Hex) elem.md5Hex = md5Hex; + if (sha1Hex) elem.sha1Hex = sha1Hex; + return elem; + } default: console.warn(`[MsgParser] unsupported segment type: ${type}`); return null; diff --git a/packages/core/tests/message-parser.test.ts b/packages/core/tests/message-parser.test.ts index a7835c3a..debc405b 100644 --- a/packages/core/tests/message-parser.test.ts +++ b/packages/core/tests/message-parser.test.ts @@ -437,4 +437,48 @@ describe('parseMessage', () => { expect(result).toEqual([]); }); }); + + describe('file segment', () => { + // Closes the parser-side of the "upload says ok but message is + // empty" bug. Before this, `{type:'file', file_id:'…'}` segments + // fell through to the default warn-and-drop branch — which made + // `send_msg([{type:'file', file_id:''}])` produce either + // a "message is empty" error or, when mixed with text, a message + // with the file segment quietly missing. + it('parses {type:"file", file_id:"x"} into a file MessageElement', async () => { + const result = await parseMessage( + [{ type: 'file', data: { file_id: 'fid-1', name: 'a.zip', size: 123 } } as any], + false, + ); + expect(result).toEqual([ + { type: 'file', fileId: 'fid-1', fileName: 'a.zip', fileSize: 123 }, + ]); + }); + + it('drops a file segment with no file_id (upload-first contract)', async () => { + // Path-only segments aren't supported here — callers must + // upload via `upload_group_file` / `upload_private_file` first + // to obtain a file_id. Dropping with a warning is preferable + // to silently kicking off an upload from inside the message + // parser, which can't fail loudly without changing call sites. + const result = await parseMessage( + [{ type: 'file', data: { file: '/local/path/a.bin' } } as any], + false, + ); + expect(result).toEqual([]); + }); + + it('accepts fileId / filename / fileName / md5 / sha1 aliases', async () => { + const result = await parseMessage( + [{ + type: 'file', + data: { fileId: 'fid-2', filename: 'b.zip', fileSize: 456, md5: 'AB', sha1: 'CD' }, + } as any], + false, + ); + expect(result).toEqual([ + { type: 'file', fileId: 'fid-2', fileName: 'b.zip', fileSize: 456, md5Hex: 'AB', sha1Hex: 'CD' }, + ]); + }); + }); }); From c758eb6569f4ad77b112cef66efb905d41b094f7 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Tue, 19 May 2026 12:53:24 +0800 Subject: [PATCH 29/48] fix(onebot): recursively parse nested forward chains (node-inside-node) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A custom forward node's `content` field can itself be a list of `{type:'node'}` entries — that's the nested-forward case where one forward bubble contains another. `parseForwardNodes` used to pass the whole `content` straight into `parseMessage`, which routed each inner `{type:'node'}` through `message-parser.ts:217 case 'node':` and turned them into opaque `MessageElement{type:'node', resId: JSON.stringify(content)}` placeholders. `element-builder.buildSendElems` then dropped those at its default branch — so the outer forward shipped with either zero elements (pure-nested → server rejects with "message is empty") or text-only elements (mixed content → silently truncated chat bubble). User-facing symptom: "嵌套转发解析后发不出去". Add depth-aware recursion to `parseForwardNodes`, modelled on NapCat's `SendMsg.uploadForwardedNodesPacket` (3-level cap): - When a node's `content` is *all* `{type:'node'}` entries, recurse: parse the inner chain into ForwardNodePayload[], upload it via `bridge.uploadForwardNodes` to mint an inner res_id, then embed a `{type:'forward', resId}` element in the outer node. The receive-side rendering pipeline already builds the ARK preview card for that element shape, so the QQ client renders a tap-to-expand nested bubble. - Mixed content (text + node siblings) deliberately stays on the flat path — the meaning is ambiguous, and forcing a recursion would silently drop the non-node siblings. - Hard cap at depth 3; deeper attempts throw "depth exceeds 3". Matches NapCat and prevents one slow inner upload from aborting an unreasonably deep tree. Threading: each forward send entry point passes its destination into the parser (`{groupId}` from group-send, `{userId}` from private-send) so the inner forward uploads against the same res_id namespace. Test coverage in `tests/onebot/forward-nested.test.ts`: - group: inner uploads first, outer wraps inner res_id in a forward element, both calls happen in order - private: c2c path threads userId (not groupId) into the inner uploadForwardNodes - depth cap rejects 4-level nesting with /depth/ - flat (non-nested) content still uploads exactly once - mixed content stays on the legacy parseMessage path core: 626/626 tests pass (+5), typecheck clean, prod build clean. --- .../src/onebot/modules/message-actions.ts | 77 +++++- .../core/tests/onebot/forward-nested.test.ts | 230 ++++++++++++++++++ 2 files changed, 303 insertions(+), 4 deletions(-) create mode 100644 packages/core/tests/onebot/forward-nested.test.ts diff --git a/packages/core/src/onebot/modules/message-actions.ts b/packages/core/src/onebot/modules/message-actions.ts index ffee4639..a7b171a3 100644 --- a/packages/core/src/onebot/modules/message-actions.ts +++ b/packages/core/src/onebot/modules/message-actions.ts @@ -215,7 +215,11 @@ export async function sendGroupForwardMessage( messages: JsonValue, meta?: ForwardPreviewMeta, ): Promise<{ messageId: number; forwardId: string }> { - const nodes = await parseForwardNodes(ref, messages); + // Thread `groupId` into the parser so any nested forward inside a + // node's content uploads its inner forward against the same group + // namespace — otherwise the ARK card's res_id won't be resolvable + // when the recipient taps to expand. + const nodes = await parseForwardNodes(ref, messages, { groupId }); const forwardId = await ref.bridge.uploadForwardNodes(nodes, groupId); const previewElement = buildForwardPreviewElement(forwardId, nodes, true, meta); const receipt = await ref.bridge.sendGroupMessage(groupId, [previewElement]); @@ -240,7 +244,7 @@ export async function sendPrivateForwardMessage( messages: JsonValue, meta?: ForwardPreviewMeta, ): Promise<{ messageId: number; forwardId: string }> { - const nodes = await parseForwardNodes(ref, messages); + const nodes = await parseForwardNodes(ref, messages, { userId }); // userId is plumbed through so inner image/record/video can be uploaded // under the recipient's scene (otherwise the OIDB private-image upload // has no target uid and the element builder bails). @@ -267,7 +271,7 @@ export async function uploadForwardMessage( messages: JsonValue, groupId?: number, ): Promise<{ forwardId: string }> { - const nodes = await parseForwardNodes(ref, messages); + const nodes = await parseForwardNodes(ref, messages, { groupId }); // groupId controls the resId namespace (group vs private). Without it, // a resId minted here is unusable when later sent into a group. const forwardId = await ref.bridge.uploadForwardNodes(nodes, groupId); @@ -535,10 +539,49 @@ function logSentMessage(isGroup: boolean, targetId: number, elements: MessageEle log.info(`${type} ${targetId} | 发送:${content}`); } +// Cap forward nesting at the same depth NapCat uses +// (`SendMsg.ts:225-228`). QQ NT itself renders only a few levels of +// nested forward bubbles before collapsing into "查看更多" — going +// deeper just wastes long-msg uploads and increases the odds of one +// inner upload timing out and aborting the whole tree. +const MAX_FORWARD_DEPTH = 3; + +interface ParseForwardOptions { + /** Destination group, when the parent forward is going to a group. */ + groupId?: number; + /** Destination user, when the parent forward is going to a c2c peer. */ + userId?: number; + /** Internal: current recursion depth. Callers should leave this 0. */ + depth?: number; +} + +/** + * Are all entries of this array `{type:'node'}` segments? Then `content` + * itself is a nested forward chain (vs a regular flat segment list). + * Mixed content (some nodes + some text/image) returns false: that's + * not a meaningful protocol shape, so we treat it as flat-segment and + * let the node entries fall through to parseMessage (which drops them + * with a warning). + */ +function isNestedNodeArray(value: JsonValue): boolean { + if (!Array.isArray(value) || value.length === 0) return false; + for (const item of value) { + const seg = asJsonObject(item); + if (!seg || String(seg.type ?? '') !== 'node') return false; + } + return true; +} + async function parseForwardNodes( ref: OneBotInstanceContext, messages: JsonValue, + options: ParseForwardOptions = {}, ): Promise { + const depth = options.depth ?? 0; + if (depth >= MAX_FORWARD_DEPTH) { + throw new Error(`forward nesting depth exceeds ${MAX_FORWARD_DEPTH}`); + } + if (!Array.isArray(messages)) { throw new Error('forward messages must be an array'); } @@ -590,7 +633,33 @@ async function parseForwardNodes( const nickname = String(nodeData.nickname ?? nodeData.name ?? userUin); const content = (nodeData.content ?? nodeData.message ?? '') as JsonValue; - const elements = await parseMessage(content, false); + + let elements: MessageElement[]; + if (isNestedNodeArray(content)) { + // Nested forward chain — `content` is itself a list of `{type:'node'}` + // segments. Recursively parse them into ForwardNodePayloads, upload + // that inner chain as its own forward, then embed an ARK preview + // card pointing at the inner res_id. The receiving QQ client renders + // it as a tap-to-expand nested forward bubble. Matches NapCat's + // `SendMsg.uploadForwardedNodesPacket` recursion contract. + // + // Without this, the inner `{type:'node'}` entries fell through to + // `parseMessage` which produced useless `MessageElement{type:'node'}` + // entries that `element-builder` silently drops — leaving the outer + // forward with an empty body that QQ refuses with "message is empty" + // (single-node case) or a node whose content is missing the inner + // forward (mixed case). + const innerNodes = await parseForwardNodes(ref, content, { + groupId: options.groupId, + userId: options.userId, + depth: depth + 1, + }); + const innerResId = await ref.bridge.uploadForwardNodes(innerNodes, options.groupId, options.userId); + const isGroup = options.groupId !== undefined; + elements = [buildForwardPreviewElement(innerResId, innerNodes, isGroup, undefined)]; + } else { + elements = await parseMessage(content, false); + } if (elements.length === 0) throw new Error(`forward node content is empty: ${userUin}`); nodes.push({ userUin, nickname, elements }); diff --git a/packages/core/tests/onebot/forward-nested.test.ts b/packages/core/tests/onebot/forward-nested.test.ts new file mode 100644 index 00000000..2aebd243 --- /dev/null +++ b/packages/core/tests/onebot/forward-nested.test.ts @@ -0,0 +1,230 @@ +// Regression coverage for nested forward (forward-inside-forward). +// +// Bug being pinned: when a custom forward node's `content` is itself +// a list of `{type:'node'}` entries (a forward chain inside a forward +// chain), the parser used to call `parseMessage(content, false)` +// which routes each inner node through `message-parser.ts:217 case +// 'node':`. That case JSON-stringifies `content` into the +// `resId` field of a `MessageElement{type:'node'}` placeholder — +// which `element-builder.buildSendElems` then silently drops at its +// default case. End result: the outer forward goes out with an empty +// (or text-only) body, the nested chain is lost. +// +// Fix:`parseForwardNodes` now detects an all-node content array, +// recursively builds the inner ForwardNodePayload[], uploads it as a +// separate forward to obtain a `res_id`, then embeds an ARK preview +// element (`{type:'forward', resId}`) in the outer node — which is +// exactly the shape `element-builder.makeForwardElem` already knows +// how to render. Matches NapCat's `uploadForwardedNodesPacket` +// recursion (capped at 3 levels deep). + +import { describe, expect, it, vi } from 'vitest'; +import type { BridgeInterface } from '../../src/bridge/bridge-interface'; +import type { OneBotInstanceContext } from '../../src/onebot/instance-context'; +import { + sendGroupForwardMessage, + sendPrivateForwardMessage, +} from '../../src/onebot/modules/message-actions'; + +function fakeBridge(overrides: Partial = {}): BridgeInterface { + return new Proxy(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`); + }, + }); +} + +function makeCtx(bridge: BridgeInterface): OneBotInstanceContext { + return { + uin: '10001', + bridge, + messageStore: { findEvent: () => null } as any, + cacheMessageMeta: vi.fn(), + mediaStore: {} as any, + musicSignUrl: '', + } as unknown as OneBotInstanceContext; +} + +describe('forward — nested {type:"node"} content', () => { + it('group: nested forward uploads inner chain first, outer embeds ARK preview pointing at it', async () => { + const uploadForwardNodes = vi.fn(async (nodes: any[]) => { + // Inner gets uploaded before outer; track the order by inspecting + // the elements shape. The inner chain's payload is a plain text + // node; the outer chain's only element is a `forward` ARK preview + // referencing the inner res_id we returned just before. + const innerNode = nodes[0]; + const onlyElem = innerNode.elements[0]; + if (onlyElem.type === 'text' && onlyElem.text === 'hello from inner') { + return 'INNER_RESID'; + } + if (onlyElem.type === 'forward' && onlyElem.resId === 'INNER_RESID') { + return 'OUTER_RESID'; + } + throw new Error(`unexpected upload payload: ${JSON.stringify(nodes)}`); + }); + const sendGroupMessage = vi.fn(async () => ({ + messageId: 1, sequence: 100, clientSequence: 0, random: 1, timestamp: 1700000000, + })); + + const bridge = fakeBridge({ uploadForwardNodes, sendGroupMessage } as any); + const ctx = makeCtx(bridge); + + const messages = [{ + type: 'node', + data: { + user_id: 111, nickname: 'outer', + content: [{ + type: 'node', + data: { + user_id: 222, nickname: 'inner', + content: [{ type: 'text', data: { text: 'hello from inner' } }], + }, + }], + }, + }]; + + const result = await sendGroupForwardMessage(ctx, 12345, messages as any); + + // Two uploads: inner first, then outer. + expect(uploadForwardNodes).toHaveBeenCalledTimes(2); + + // Inner upload: nodes[0] is the leaf node, scoped to the outer group. + const [innerNodes, innerGroupId] = uploadForwardNodes.mock.calls[0]!; + expect(innerGroupId).toBe(12345); + expect((innerNodes as any[])[0]!.userUin).toBe(222); + expect((innerNodes as any[])[0]!.elements).toEqual([{ type: 'text', text: 'hello from inner' }]); + + // Outer upload: the wrapper node carries a single `forward` ARK + // preview element that points at the inner res_id we minted above. + const [outerNodes, outerGroupId] = uploadForwardNodes.mock.calls[1]!; + expect(outerGroupId).toBe(12345); + expect((outerNodes as any[])[0]!.userUin).toBe(111); + expect((outerNodes as any[])[0]!.elements).toHaveLength(1); + expect((outerNodes as any[])[0]!.elements[0]).toMatchObject({ + type: 'forward', + resId: 'INNER_RESID', + }); + + expect(result.forwardId).toBe('OUTER_RESID'); + expect(sendGroupMessage).toHaveBeenCalledOnce(); + }); + + it('private: nested forward threads userId into inner uploadForwardNodes', async () => { + // Same shape but routed via sendPrivateForwardMessage. The c2c path + // passes `userId` instead of `groupId` so any inner image/record + // uploads can pick up the recipient's UID scene (otherwise the + // OIDB private-media upload has no target uid). + const uploadForwardNodes = vi.fn(async () => 'RESID'); + const sendPrivateMessage = vi.fn(async () => ({ + messageId: 1, sequence: 100, clientSequence: 0, random: 1, timestamp: 1700000000, + })); + + const bridge = fakeBridge({ uploadForwardNodes, sendPrivateMessage } as any); + const ctx = makeCtx(bridge); + + const messages = [{ + type: 'node', + data: { + user_id: 111, nickname: 'outer', + content: [{ + type: 'node', + data: { + user_id: 222, nickname: 'inner', + content: [{ type: 'text', data: { text: 'hi' } }], + }, + }], + }, + }]; + + await sendPrivateForwardMessage(ctx, 67890, messages as any); + + // Inner upload: groupId undefined, userId is the c2c recipient. + const innerCall = uploadForwardNodes.mock.calls[0]!; + expect(innerCall[1]).toBeUndefined(); + expect(innerCall[2]).toBe(67890); + }); + + it('rejects nesting deeper than 3 levels', async () => { + // Build a 4-level nested chain. NapCat caps at 3 too, going further + // wastes long-msg uploads and risks one inner upload timing out + // and aborting the whole tree. Better to fail loud here. + const uploadForwardNodes = vi.fn(async () => 'X'); + const sendGroupMessage = vi.fn(async () => ({ + messageId: 1, sequence: 100, clientSequence: 0, random: 1, timestamp: 0, + })); + const bridge = fakeBridge({ uploadForwardNodes, sendGroupMessage } as any); + const ctx = makeCtx(bridge); + + function wrap(content: any, depth: number): any { + if (depth === 0) return [{ type: 'text', data: { text: 'leaf' } }]; + return [{ + type: 'node', + data: { user_id: 100 + depth, nickname: `lvl-${depth}`, content: wrap(content, depth - 1) }, + }]; + } + + await expect( + sendGroupForwardMessage(ctx, 12345, wrap(null, 4) as any), + ).rejects.toThrow(/depth/); + }); + + it('flat content (no nesting) still goes through the unchanged path', async () => { + // Backwards-compat: a single-level forward with plain text nodes + // calls uploadForwardNodes exactly once and never touches the + // recursive branch. + const uploadForwardNodes = vi.fn(async () => 'RES'); + const sendGroupMessage = vi.fn(async () => ({ + messageId: 1, sequence: 100, clientSequence: 0, random: 1, timestamp: 0, + })); + const bridge = fakeBridge({ uploadForwardNodes, sendGroupMessage } as any); + const ctx = makeCtx(bridge); + + const messages = [ + { type: 'node', data: { user_id: 111, nickname: 'a', content: [{ type: 'text', data: { text: 'one' } }] } }, + { type: 'node', data: { user_id: 222, nickname: 'b', content: [{ type: 'text', data: { text: 'two' } }] } }, + ]; + + await sendGroupForwardMessage(ctx, 12345, messages as any); + expect(uploadForwardNodes).toHaveBeenCalledOnce(); + const [nodes] = uploadForwardNodes.mock.calls[0]!; + expect((nodes as any[])).toHaveLength(2); + expect((nodes as any[])[0]!.elements).toEqual([{ type: 'text', text: 'one' }]); + expect((nodes as any[])[1]!.elements).toEqual([{ type: 'text', text: 'two' }]); + }); + + it('mixed content (some {type:"node"} + non-node) falls back to flat parsing — does NOT recurse', async () => { + // Recursion only kicks in when *all* content entries are nodes — + // mixed content is ambiguous (do the non-node parts belong to the + // outer node or are they parallel siblings?), so we keep the legacy + // behaviour and let parseMessage handle it. Non-node parts come + // through, node parts get parsed via `case 'node':` and then + // dropped by element-builder. A user who wants nested forward + // should pass a pure node list. + const uploadForwardNodes = vi.fn(async () => 'RES'); + const sendGroupMessage = vi.fn(async () => ({ + messageId: 1, sequence: 100, clientSequence: 0, random: 1, timestamp: 0, + })); + const bridge = fakeBridge({ uploadForwardNodes, sendGroupMessage } as any); + const ctx = makeCtx(bridge); + + const messages = [{ + type: 'node', + data: { + user_id: 111, nickname: 'mixed', + content: [ + { type: 'text', data: { text: 'a sibling' } }, + { type: 'node', data: { user_id: 222, content: [{ type: 'text', data: { text: 'lost' } }] } }, + ], + }, + }]; + + await sendGroupForwardMessage(ctx, 12345, messages as any); + expect(uploadForwardNodes).toHaveBeenCalledOnce(); + // Only the text element survives — the legacy "node MessageElement" + // that parseMessage produces is opaque to the element-builder. + const [nodes] = uploadForwardNodes.mock.calls[0]!; + const elements = (nodes as any[])[0]!.elements; + expect(elements.some((e: any) => e.type === 'text' && e.text === 'a sibling')).toBe(true); + }); +}); From ff5fc651d09dcc9d63db24e6e5b283c901adcabb Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Tue, 19 May 2026 13:00:41 +0800 Subject: [PATCH 30/48] fix(tests): declare full vi.fn arg signatures so CI typecheck doesn't trip on tuple length MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CI's `tsc --noEmit` was rejecting `forward-nested.test.ts` because the `vi.fn(async () => 'RES')` mocks for `bridge.uploadForwardNodes` only inferred zero or one arg from the lambda — so `uploadForwardNodes.mock.calls[0]` came out typed as `[]` or `[nodes: any[]]`, and indexing `[1]` / `[2]` for groupId / userId hit `Tuple type ... has no element at index 'N'`. Local `tsc --noEmit` happened to be looser about this in my version, which is why the bad assertions slipped past `e637647`. Declare the full 3-arg signature on every `uploadForwardNodes` mock — `(_nodes, _groupId?, _userId?)` — matching the real `Bridge.uploadForwardNodes` contract. `mock.calls[i]` now types as a 3-tuple, the index accesses check out, and the assertions stay unchanged. No production code touched, no test behaviour change. 626/626 still passing, typecheck clean. --- packages/core/tests/onebot/forward-nested.test.ts | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/packages/core/tests/onebot/forward-nested.test.ts b/packages/core/tests/onebot/forward-nested.test.ts index 2aebd243..9e5979fd 100644 --- a/packages/core/tests/onebot/forward-nested.test.ts +++ b/packages/core/tests/onebot/forward-nested.test.ts @@ -48,7 +48,7 @@ function makeCtx(bridge: BridgeInterface): OneBotInstanceContext { describe('forward — nested {type:"node"} content', () => { it('group: nested forward uploads inner chain first, outer embeds ARK preview pointing at it', async () => { - const uploadForwardNodes = vi.fn(async (nodes: any[]) => { + const uploadForwardNodes = vi.fn(async (nodes: any[], _groupId?: number, _userId?: number) => { // Inner gets uploaded before outer; track the order by inspecting // the elements shape. The inner chain's payload is a plain text // node; the outer chain's only element is a `forward` ARK preview @@ -115,7 +115,7 @@ describe('forward — nested {type:"node"} content', () => { // passes `userId` instead of `groupId` so any inner image/record // uploads can pick up the recipient's UID scene (otherwise the // OIDB private-media upload has no target uid). - const uploadForwardNodes = vi.fn(async () => 'RESID'); + const uploadForwardNodes = vi.fn(async (_nodes: any[], _groupId?: number, _userId?: number) => 'RESID'); const sendPrivateMessage = vi.fn(async () => ({ messageId: 1, sequence: 100, clientSequence: 0, random: 1, timestamp: 1700000000, })); @@ -149,7 +149,7 @@ describe('forward — nested {type:"node"} content', () => { // Build a 4-level nested chain. NapCat caps at 3 too, going further // wastes long-msg uploads and risks one inner upload timing out // and aborting the whole tree. Better to fail loud here. - const uploadForwardNodes = vi.fn(async () => 'X'); + const uploadForwardNodes = vi.fn(async (_nodes: any[], _groupId?: number, _userId?: number) => 'X'); const sendGroupMessage = vi.fn(async () => ({ messageId: 1, sequence: 100, clientSequence: 0, random: 1, timestamp: 0, })); @@ -173,7 +173,7 @@ describe('forward — nested {type:"node"} content', () => { // Backwards-compat: a single-level forward with plain text nodes // calls uploadForwardNodes exactly once and never touches the // recursive branch. - const uploadForwardNodes = vi.fn(async () => 'RES'); + const uploadForwardNodes = vi.fn(async (_nodes: any[], _groupId?: number, _userId?: number) => 'RES'); const sendGroupMessage = vi.fn(async () => ({ messageId: 1, sequence: 100, clientSequence: 0, random: 1, timestamp: 0, })); @@ -201,7 +201,7 @@ describe('forward — nested {type:"node"} content', () => { // through, node parts get parsed via `case 'node':` and then // dropped by element-builder. A user who wants nested forward // should pass a pure node list. - const uploadForwardNodes = vi.fn(async () => 'RES'); + const uploadForwardNodes = vi.fn(async (_nodes: any[], _groupId?: number, _userId?: number) => 'RES'); const sendGroupMessage = vi.fn(async () => ({ messageId: 1, sequence: 100, clientSequence: 0, random: 1, timestamp: 0, })); From 604dbc3f64089fb809eb4fde76669b933c8fe089 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Tue, 19 May 2026 13:36:03 +0800 Subject: [PATCH 31/48] fix(msg-push): Event0x210 subType=38 is the troop-shortcut-bar push, not friend-related MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Earlier this commit acknowledged subType 38 as a placeholder "FriendGrayTipInfo" because none of the LagrangeDev-family projects (Lagrange V2 / lagrange-python / LagrangeGo / acidify) have a handler for it — they all just fall through with a generic "unknown subType" debug log. The "best guess" gray-tip framing was wrong. A contributor traced it through the decompiled stock QQ Android client to `com.tencent.imcore.message.ext.codec.decoder.msgType0x210 .SubType0x26` (tsuzcx/qq_apk @ afe46ef). The payload is `submsgtype0x26.MsgBody` dispatching on `uint32_sub_cmd`: - 0x1 → `UpdateAppUnreadNum`: a list of `{group_code, app_id, unread_num}` keeping group-internal "mini-app" badge counts (e.g. `appId=101846662` / `101896870` for the troop shortcut bar) in sync. - 0x3 → `UpdateDiscussAppInfo`: `{conf_uin, app_tip_notify.text}` discussion-group app tips, routed through `getGAudioHandler()`. - 0x4 → delegated to the troop online-push handler. None of these have a meaningful OneBot mapping — they're QQ-client-UI state pushes (badge counts, in-app tips), not conversation events. Rename the enum entry to `GroupAppStatePush` to reflect the actual semantics, cite the decompiled source inline, and keep the silent-drop behaviour from the previous attempt. Tests + decoder routing follow the rename. 628/628 tests pass (unchanged), typecheck clean. --- .../bridge/msg-push/decoders/event-0x210.ts | 5 ++ packages/core/src/bridge/msg-push/enums.ts | 25 ++++++++ packages/core/tests/msg-push-handler.test.ts | 63 +++++++++++++++++++ 3 files changed, 93 insertions(+) diff --git a/packages/core/src/bridge/msg-push/decoders/event-0x210.ts b/packages/core/src/bridge/msg-push/decoders/event-0x210.ts index 4cbc479f..fadc5dd5 100644 --- a/packages/core/src/bridge/msg-push/decoders/event-0x210.ts +++ b/packages/core/src/bridge/msg-push/decoders/event-0x210.ts @@ -25,6 +25,11 @@ export const decodeEvent0x210: MsgPushDecoder = (ctx) => { case Event0x210SubType.FriendRequestNotice: return decodeFriendRequest(ctx); case Event0x210SubType.FriendRecallNotice: return decodeFriendRecall(ctx); case Event0x210SubType.FriendPokeNotice: return decodeFriendPoke(ctx); + case Event0x210SubType.GroupAppStatePush: + // QQ-client-internal troop shortcut bar / discussion app state + // push — no OneBot-level event. See enum comment for the + // decompiled-source breakdown of the sub_cmd dispatch. + return []; } unknownLog.debug('Event0x210 unknown subType=%d', ctx.head.subType); return []; diff --git a/packages/core/src/bridge/msg-push/enums.ts b/packages/core/src/bridge/msg-push/enums.ts index 38561e87..12ba3f08 100644 --- a/packages/core/src/bridge/msg-push/enums.ts +++ b/packages/core/src/bridge/msg-push/enums.ts @@ -31,4 +31,29 @@ export enum Event0x210SubType { FriendRequestNotice = 35, FriendRecallNotice = 138, FriendPokeNotice = 290, + /** + * Group-app state push (troop shortcut bar / discussion app). + * + * Sourced from the decompiled stock QQ Android client decoder at + * `com.tencent.imcore.message.ext.codec.decoder.msgType0x210.SubType0x26` + * (tsuzcx/qq_apk @ afe46ef). The payload is `submsgtype0x26.MsgBody` + * dispatching on `uint32_sub_cmd`: + * + * - 0x1 → `UpdateAppUnreadNum`: a list of + * `{group_code, app_id, unread_num}` entries the QQ client uses + * to keep group-internal "mini-app" badges (e.g. `appId=101846662` + * / `101896870` for the shortcut bar) in sync. + * - 0x3 → `UpdateDiscussAppInfo`: `{conf_uin, app_tip_notify.text}` + * for discussion-group app tips, routed to `getGAudioHandler()`. + * - 0x4 → delegated to the troop online-push handler. + * + * None of these have a OneBot event mapping — they're QQ-client-UI + * state pushes (unread badges, in-app tips), not user-visible + * conversation events. Acknowledge the subType so it doesn't keep + * showing up as "unknown" in debug logs and drop it silently. + * Lagrange V2 / lagrange-python / LagrangeGo / acidify all also + * fall through on this one because they don't surface the shortcut + * bar either. + */ + GroupAppStatePush = 38, } diff --git a/packages/core/tests/msg-push-handler.test.ts b/packages/core/tests/msg-push-handler.test.ts index 554b5f10..2df80459 100644 --- a/packages/core/tests/msg-push-handler.test.ts +++ b/packages/core/tests/msg-push-handler.test.ts @@ -7,6 +7,7 @@ import { GroupChangeSchema, OperatorInfoSchema } from '../src/bridge/proto/notif import type { GroupMemberJoin } from '../src/bridge/events'; import type { PacketInfo } from '../src/protocol/types'; import { protoEncode } from '../src/protobuf/decode'; +import { subscribeLogs } from '../src/utils/logger'; const SELF_UIN = '10001'; const GROUP_ID = 123456789; @@ -98,3 +99,65 @@ describe('parseMsgPush group member increase', () => { expect(event.operatorUid).toBe(operator.uid); }); }); + +describe('parseMsgPush Event0x210 subType=38 (acknowledged-but-silent)', () => { + // Tracked back to the stock-QQ-android decompiled decoder + // `com.tencent.imcore.message.ext.codec.decoder.msgType0x210.SubType0x26` + // — it's the QQ-client-internal "troop shortcut bar" / discussion + // app state push (badge counts + in-app tips), not a chat event. + // We acknowledge it via `Event0x210SubType.GroupAppStatePush` and + // drop silently — no OneBot-level event, and — critically — + // **no** "unknown subType=38" fallback log spam anymore. + function makeEvent0x210Packet(subType: number, content = new Uint8Array(0)): PacketInfo { + const body = protoEncode({ + message: { + responseHead: { fromUin: 22222, type: 0, sigMap: 0 }, + // 528 = Event0x210 + contentHead: { msgType: 528, subType, timestamp: 1710000000 }, + body: { msgContent: content }, + }, + status: 0, + } as any, PushMsgSchema); + return { + pid: 1, uin: SELF_UIN, serviceCmd: MSG_PUSH_CMD, seqId: 1, + retCode: 0, fromClient: false, body, + }; + } + + it('returns [] for subType 38 without falling through to the MsgPush.Unknown log', () => { + const captured: string[] = []; + const unsubscribe = subscribeLogs((entry) => { + // Only care about the spam that the prior implementation produced + // ("MsgPush.Unknown" with subType=38). Other modules log freely + // during identity setup etc., we ignore them. + if (entry.scope === 'MsgPush.Unknown' && /subType=38/.test(entry.message)) { + captured.push(entry.message); + } + }); + try { + const events = parseMsgPush(makeEvent0x210Packet(38), makeIdentity()); + expect(events).toEqual([]); + expect(captured).toEqual([]); // no "unknown subType=38" debug log + } finally { + unsubscribe(); + } + }); + + it('still flags genuinely-unknown subTypes via MsgPush.Unknown (regression guard)', () => { + // Counterpart to the silent-on-38 case: anything we *haven't* + // claimed in the enum should still hit the fallback so it's + // visible to whoever's tailing debug logs. + const captured: string[] = []; + const unsubscribe = subscribeLogs((entry) => { + if (entry.scope === 'MsgPush.Unknown' && /subType=999/.test(entry.message)) { + captured.push(entry.message); + } + }); + try { + parseMsgPush(makeEvent0x210Packet(999), makeIdentity()); + expect(captured.length).toBeGreaterThan(0); + } finally { + unsubscribe(); + } + }); +}); From 898898a5076e208ec8dec7b554ed67d5b8f03c93 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Tue, 19 May 2026 14:51:48 +0800 Subject: [PATCH 32/48] feat(msg-push): handle three friend-related events we used to drop on the floor MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Close three coverage gaps surfaced by the cross-Lagrange-family audit (Lagrange V2 / LagrangeGo / acidify / lagrange-python): - **0x210 subType 179 + 226 (NewFriend)** — mutual-accept friend notice. 179 fires when bot sent a request and the other side accepted; 226 fires for the opposite direction. Both decode through the same wire shape. LagrangeGo handles the pair via a `case 226: case 179:` fallthrough in `client/listener.go:248`. We surface them as `kind: 'friend_add'`, which the existing converter routes straight to OneBot `notice.friend_add` — bot frameworks that wait for "auto-add a friend after they accept" were previously stuck because nothing arrived. - **0x210 subType 139 (self-recall)** — bot recalled its own message sent to a friend. Same `FriendRecall` wire shape as 138 but the peer is on `toUid` instead of `fromUid` — acidify's `parseFriendRecall:380` splits exactly this way. Without 139, self-recalls disappeared and downstream `notice.friend_recall` handlers thought the bot had never recalled anything. - **PkgType 85 (bot self-joined a group)** — fires on the bot's session once `set_group_add_request` is approved or an invite is accepted, ported from lagrange-python's `server_push/msg.py:108`. PkgType 33 (GroupMemberIncreaseNotice) only fires for *other* members joining, so without 85 the bot never received its own `notice.group_increase` until the first message arrived. We decode `SelfJoinInGroup` and emit `kind: 'group_member_join'` with `userUin = selfUin`; the existing converter picks `sub_type: 'approve' | 'invite'` from the operator/user equality so consumers see the standard OneBot shape. While wiring 139, also fix a *pre-existing* prod bug spotted via proton call-site analysis on the resulting bundle: `event-0x210.ts` imported `FriendRecall` from both `proto/proton/notify` (as `FriendRecallNotify`) *and* `events` (as the event interface). Proton's import-resolver registers `importedTypeSources` keyed on the *imported* name (last-write-wins), so the events.ts import shadowed the proto one — `protobuf_decode(...)` lost its codec, fell through to the runtime fallback throw, and was silently swallowed by `MsgPushRegistry.decode`'s catch. Verified by the substituted codec list in `dist/index.mjs`: pre-fix it had `FriendRequest` / `GeneralGrayTipInfo` but no `FriendRecall`; post-fix `FriendRecall` / `NewFriend` / `SelfJoinInGroup` are all emitted as expected. Side-step the collision by importing the proto types unaliased and re-deriving the colliding event type via `Extract`. New proto interfaces in `proto/proton/notify.ts`: - `NewFriend` + `NewFriendInfo` (uid/time/message/nickName fields, fields 1-9; ported from `LagrangeGo/.../notify.proto:25 NewFriend`) - `SelfJoinInGroup` (groupUin / operatorUid + a few placeholder fields; ported from `lagrange-python/pb/status/group.py:170 PBSelfJoinInGroup`) Regression coverage in `tests/msg-push-handler.test.ts`: - subType 179/226 both produce identical friend_add events - falls back to `routingHead.fromUin` when the new friend's uid isn't in the local cache (matches LagrangeGo's "emit-then-resolve" pattern) - subType 138 keeps fromUid as the peer (other recalled their own msg to us); subType 139 picks toUid (we recalled ours sent to them) - PkgType 85 emits group_member_join with userUin == selfUin, operator resolved through identity when known core: 635/635 tests pass (+7), typecheck clean. Production bundle now contains substituted codecs for FriendRecall, NewFriend, SelfJoinInGroup (cross-checked via `grep protobuf_decode_X` on `dist/index.mjs`). --- .../bridge/msg-push/decoders/event-0x210.ts | 66 +++++- .../msg-push/decoders/group-member-change.ts | 46 ++++- packages/core/src/bridge/msg-push/enums.ts | 32 +++ packages/core/src/bridge/msg-push/index.ts | 3 +- .../core/src/bridge/proto/proton/notify.ts | 39 ++++ packages/core/tests/msg-push-handler.test.ts | 190 +++++++++++++++++- 6 files changed, 361 insertions(+), 15 deletions(-) diff --git a/packages/core/src/bridge/msg-push/decoders/event-0x210.ts b/packages/core/src/bridge/msg-push/decoders/event-0x210.ts index fadc5dd5..eafe1fb1 100644 --- a/packages/core/src/bridge/msg-push/decoders/event-0x210.ts +++ b/packages/core/src/bridge/msg-push/decoders/event-0x210.ts @@ -1,15 +1,29 @@ // Handles Event0x210 wrapper (528). Internal switch on subType dispatches -// to FriendRequest (35) / FriendRecall (138) / FriendPoke (290). +// to FriendRequest (35) / FriendRecall (138, 139) / NewFriend +// (179, 226) / FriendPoke (290). import { protobuf_decode } from '@snowluma/proton'; +// Proto types imported unaliased — proton's import-resolver registers +// `importedTypeSources` keyed on the *imported* name. If we also did +// `import type { FriendRecall } from '../../events'` it would shadow +// the proto-side mapping (last-write-wins), point the resolver at the +// event-side file which has no `pb<>` schema, and the codec would +// never get generated — `protobuf_decode(...)` then +// falls through to the runtime fallback and throws (silently caught +// by `MsgPushRegistry.decode`). The event-side colliding names are +// re-derived from `QQEventVariant` below via `Extract` instead. import type { - FriendRequest as FriendRequestNotify, - FriendRecall as FriendRecallNotify, + FriendRequest, + FriendRecall, GeneralGrayTipInfo, + NewFriend, } from '../../proto/proton/notify'; import type { - FriendRequestEvent, FriendRecall, FriendPokeEvent, QQEventVariant, + FriendRequestEvent, FriendPokeEvent, + FriendAddEvent, QQEventVariant, } from '../../events'; + +type FriendRecallEvent = Extract; import type { MsgPushDecoder } from '../registry'; import type { MsgPushContext } from '../context'; import { Event0x210SubType } from '../enums'; @@ -23,8 +37,17 @@ const unknownLog = createLogger('MsgPush.Unknown'); export const decodeEvent0x210: MsgPushDecoder = (ctx) => { switch (ctx.head.subType as Event0x210SubType) { case Event0x210SubType.FriendRequestNotice: return decodeFriendRequest(ctx); - case Event0x210SubType.FriendRecallNotice: return decodeFriendRecall(ctx); + // 138 (other-recalled) and 139 (self-recalled) share the same + // FriendRecall wire shape; the helper picks the right uid side + // based on the subType. + case Event0x210SubType.FriendRecallNotice: + case Event0x210SubType.FriendRecallSelfNotice: + return decodeFriendRecall(ctx); case Event0x210SubType.FriendPokeNotice: return decodeFriendPoke(ctx); + // 179 + 226 both carry the NewFriend payload — see enum comment. + case Event0x210SubType.NewFriendNotice: + case Event0x210SubType.NewFriendNoticeAlt: + return decodeNewFriend(ctx); case Event0x210SubType.GroupAppStatePush: // QQ-client-internal troop shortcut bar / discussion app state // push — no OneBot-level event. See enum comment for the @@ -36,7 +59,7 @@ export const decodeEvent0x210: MsgPushDecoder = (ctx) => { }; function decodeFriendRequest(ctx: MsgPushContext): QQEventVariant[] { - const request = protobuf_decode(ctx.content); + const request = protobuf_decode(ctx.content); if (!request?.info) return []; const sourceUid = request.info.newSource || request.info.sourceUid || ''; const ev: FriendRequestEvent = { @@ -52,18 +75,43 @@ function decodeFriendRequest(ctx: MsgPushContext): QQEventVariant[] { } function decodeFriendRecall(ctx: MsgPushContext): QQEventVariant[] { - const recall = protobuf_decode(ctx.content); + const recall = protobuf_decode(ctx.content); if (!recall?.info) return []; - const ev: FriendRecall = { + // 138 = friend recalled their own message sent to bot (peer = fromUid). + // 139 = bot recalled own message sent to friend (peer = toUid). Same + // ambiguity acidify handles in `parseFriendRecall:380`. Without this + // split, self-recall events surface `userUin` as the bot itself which + // confuses downstream OneBot consumers that key off `user_id`. + const isSelfRecall = ctx.head.subType === Event0x210SubType.FriendRecallSelfNotice; + const peerUid = (isSelfRecall ? recall.info.toUid : recall.info.fromUid) ?? ''; + const ev: FriendRecallEvent = { kind: 'friend_recall', time: recall.info.time ?? ctx.head.timestamp, selfUin: ctx.selfUin, - userUin: resolveUidToUin(ctx.identity, 0, recall.info.fromUid ?? '', ctx.fromUin), + userUin: resolveUidToUin(ctx.identity, 0, peerUid, ctx.fromUin), msgSeq: recall.info.clientSequence ?? 0, }; return [ev]; } +function decodeNewFriend(ctx: MsgPushContext): QQEventVariant[] { + const nf = protobuf_decode(ctx.content); + if (!nf?.info) return []; + const newFriendUid = nf.info.uid ?? ''; + const newFriendUin = resolveUidToUin(ctx.identity, 0, newFriendUid, ctx.fromUin); + if (newFriendUin <= 0) return []; // can't surface a `user_id`-less friend_add to OneBot + const ev: FriendAddEvent = { + kind: 'friend_add', + // proto field is `fixed32 Time` — already uint32 seconds epoch. + // Fall back to head.timestamp if the field is missing (some + // captures have it as 0). + time: nf.info.time && nf.info.time > 0 ? nf.info.time : ctx.head.timestamp, + selfUin: ctx.selfUin, + userUin: newFriendUin, + }; + return [ev]; +} + function decodeFriendPoke(ctx: MsgPushContext): QQEventVariant[] { const grayTip = protobuf_decode(ctx.content); if (!grayTip || (grayTip.busiType ?? 0n) !== 12n) return []; diff --git a/packages/core/src/bridge/msg-push/decoders/group-member-change.ts b/packages/core/src/bridge/msg-push/decoders/group-member-change.ts index 53386dfc..4d371620 100644 --- a/packages/core/src/bridge/msg-push/decoders/group-member-change.ts +++ b/packages/core/src/bridge/msg-push/decoders/group-member-change.ts @@ -1,9 +1,21 @@ -// Handles GroupMemberIncreaseNotice (33) + GroupMemberDecreaseNotice (34). -// Both share GroupChangeSchema; the decreaseType field distinguishes kick vs -// voluntary leave (dt != 0 && dt != 130 means kicked). +// Handles GroupMemberIncreaseNotice (33) + GroupMemberDecreaseNotice (34) + +// GroupSelfJoinedNotice (85, bot-self admittance). +// +// 33/34 share GroupChangeSchema; the decreaseType field distinguishes +// kick vs voluntary leave (dt != 0 && dt != 130 means kicked). +// +// 85 carries a different wire shape (`SelfJoinInGroup`) — without it +// the bot has no signal that its own `set_group_add_request` was +// approved (33 fires only for *other* members joining). We surface +// 85 as a regular GroupMemberJoin with `userUin = selfUin` so the +// existing OneBot converter naturally produces +// `notice.group_increase` with `sub_type: 'approve' | 'invite'` +// (the converter compares operator == user to pick the sub_type; +// for self-join the operator is the admin/inviter, so 'invite' is +// emitted — matching go-cqhttp / NapCat semantics). import { protobuf_decode } from '@snowluma/proton'; -import type { GroupChange } from '../../proto/proton/notify'; +import type { GroupChange, SelfJoinInGroup } from '../../proto/proton/notify'; import type { GroupMemberJoin, GroupMemberLeave } from '../../events'; import type { MsgPushDecoder } from '../registry'; import { decodeOperatorUid, resolveUidToUin } from '../helpers'; @@ -47,3 +59,29 @@ export const decodeGroupMemberLeave: MsgPushDecoder = (ctx) => { }; return [ev]; }; + +export const decodeGroupSelfJoined: MsgPushDecoder = (ctx) => { + const joined = protobuf_decode(ctx.content); + if (!joined) return []; + // groupUin is uint_64 on the wire (bigint). Real group IDs fit in + // uint32 (≤ 10 digits in practice), so Number() conversion is safe + // — saturate to 0 on the unlikely overflow rather than letting + // BigInt propagate downstream where consumers expect a number. + const groupUinBig = joined.groupUin ?? 0n; + const groupId = groupUinBig > 0n && groupUinBig <= 0x7FFFFFFFn ? Number(groupUinBig) : 0; + const operatorUid = joined.operatorUid ?? ''; + // We're the one joining — surface the bot's own identity as userUin + // so the existing converter's `notice.group_increase` shape works + // unchanged. + const ev: GroupMemberJoin = { + kind: 'group_member_join', + time: ctx.head.timestamp, + selfUin: ctx.selfUin, + groupId, + userUin: ctx.selfUin, + userUid: ctx.identity.selfUid ?? '', + operatorUin: resolveUidToUin(ctx.identity, groupId, operatorUid, 0), + operatorUid, + }; + return [ev]; +}; diff --git a/packages/core/src/bridge/msg-push/enums.ts b/packages/core/src/bridge/msg-push/enums.ts index 12ba3f08..19a98eb1 100644 --- a/packages/core/src/bridge/msg-push/enums.ts +++ b/packages/core/src/bridge/msg-push/enums.ts @@ -13,6 +13,17 @@ export enum PkgType { PrivateFileMessage = 529, GroupRequestInvitationNotice = 525, GroupRequestJoinNotice = 84, + /** + * Self-join admittance — fires on the bot's session right after an + * admin approves its `set_group_add_request` or an invite-accept + * goes through. Ported from `lagrange-python`'s + * `server_push/msg.py:108 case 85`. Maps to OneBot11 + * `notice.group_increase` with the bot itself as `user_id` — + * existing 33 (GroupMemberIncreaseNotice) doesn't fire for the + * bot's own join, so without this case the bot never knows it + * just entered a group until the first message arrives. + */ + GroupSelfJoinedNotice = 85, GroupInviteNotice = 87, GroupAdminChangedNotice = 44, GroupMemberIncreaseNotice = 33, @@ -29,8 +40,29 @@ export enum Event0x2DCSubType { export enum Event0x210SubType { FriendRequestNotice = 35, + /** + * Outgoing friend-message recall — bot recalled its own message that + * was sent to a friend. Same `FriendRecall` wire shape as 138; the + * difference is direction (138 = friend recalled their own message + * sent to bot, 139 = bot recalled own message sent to friend). + * Cross-referenced against Lagrange V2 (`FriendRecallMessageProcessor` + * registered for both 138 and 139) + acidify (`138, 139 -> + * parseFriendRecall`). The decoder uses the subType to figure out + * which UID side ends up as `userUin` on the emitted event. + */ + FriendRecallSelfNotice = 139, FriendRecallNotice = 138, FriendPokeNotice = 290, + /** + * Mutual-accept friend notice — 179 fires when bot sent a friend + * request and the other side accepted; 226 fires for the opposite + * direction. Both decode through the same `NewFriend` wire shape + * (LagrangeGo registers them via a `case 226: case 179:` fallthrough + * in `client/listener.go:248-258`). Maps to OneBot11 + * `notice.friend_add`. + */ + NewFriendNotice = 179, + NewFriendNoticeAlt = 226, /** * Group-app state push (troop shortcut bar / discussion app). * diff --git a/packages/core/src/bridge/msg-push/index.ts b/packages/core/src/bridge/msg-push/index.ts index 536c4c6f..71766e90 100644 --- a/packages/core/src/bridge/msg-push/index.ts +++ b/packages/core/src/bridge/msg-push/index.ts @@ -9,7 +9,7 @@ import { buildContext } from './context'; import { MsgPushRegistry } from './registry'; import { PkgType } from './enums'; import { - decodeGroupMemberJoin, decodeGroupMemberLeave, + decodeGroupMemberJoin, decodeGroupMemberLeave, decodeGroupSelfJoined, } from './decoders/group-member-change'; import { decodeGroupAdmin } from './decoders/group-admin'; import { @@ -26,6 +26,7 @@ export const MSG_PUSH_CMD = 'trpc.msg.olpush.OlPushService.MsgPush'; const registry = new MsgPushRegistry(); registry.register(PkgType.GroupMemberIncreaseNotice, decodeGroupMemberJoin); registry.register(PkgType.GroupMemberDecreaseNotice, decodeGroupMemberLeave); +registry.register(PkgType.GroupSelfJoinedNotice, decodeGroupSelfJoined); registry.register(PkgType.GroupAdminChangedNotice, decodeGroupAdmin); registry.register(PkgType.GroupRequestJoinNotice, decodeGroupJoinRequest); registry.register(PkgType.GroupRequestInvitationNotice, decodeGroupInvitation); diff --git a/packages/core/src/bridge/proto/proton/notify.ts b/packages/core/src/bridge/proto/proton/notify.ts index 2640dcca..4a916290 100644 --- a/packages/core/src/bridge/proto/proton/notify.ts +++ b/packages/core/src/bridge/proto/proton/notify.ts @@ -122,6 +122,45 @@ export interface FriendRecall { reserved?: pb<5, bytes>; } +// ── NewFriend (0x210 subType 179 + 226) ─────────────────────────── +// +// Mutual-accept friend notice. Fires when: +// - bot sent a friend request and the other side accepted (179), or +// - the other side sent a request and bot accepted it (226). +// Both subTypes share this wire shape; field semantics follow +// `LagrangeDev/LagrangeGo` client/packets/pb/message/notify.proto. + +export interface NewFriendInfo { + uid?: pb<1, string>; + field2?: pb<2, uint_32>; + time?: pb<3, uint_32>; // fixed32 on wire; uint_32 decoded value is the unix epoch + message?: pb<4, string>; + nickName?: pb<5, string>; + field6?: pb<6, uint_32>; + field7?: pb<7, uint_32>; + toUid?: pb<9, string>; +} + +export interface NewFriend { + field1?: pb<1, uint_32>; + info?: pb<2, NewFriendInfo>; +} + +// ── SelfJoinInGroup (PkgType 85) ────────────────────────────────── +// +// Fired when the bot itself was admitted into a group — typically the +// completion of an admin-approved join request or an accepted invite. +// Ported from `lagrange-python/pb/status/group.py:170 PBSelfJoinInGroup`. + +export interface SelfJoinInGroup { + groupUin?: pb<1, uint_64>; + field2?: pb<2, uint_32>; + operatorUid?: pb<3, string>; + field4?: pb<4, uint_32>; + field6?: pb<6, uint_32>; + field7?: pb<7, string>; +} + export interface GroupMuteState { targetUid?: pb<1, string>; duration?: pb<2, uint_32>; diff --git a/packages/core/tests/msg-push-handler.test.ts b/packages/core/tests/msg-push-handler.test.ts index 2df80459..c40ca4c8 100644 --- a/packages/core/tests/msg-push-handler.test.ts +++ b/packages/core/tests/msg-push-handler.test.ts @@ -1,10 +1,30 @@ import { describe, expect, it } from 'vitest'; +import { protobuf_encode } from '@snowluma/proton'; import { parseMsgPush, MSG_PUSH_CMD } from '../src/bridge/msg-push'; import { IdentityService } from '../src/bridge/identity-service'; import type { GroupMemberInfo, QQGroupInfo } from '../src/bridge/qq-info'; import { PushMsgSchema } from '../src/bridge/proto/message'; import { GroupChangeSchema, OperatorInfoSchema } from '../src/bridge/proto/notify'; -import type { GroupMemberJoin } from '../src/bridge/events'; +// Proton's call-site analyzer keys off the literal type identifier +// printed in `protobuf_encode` — it walks imports by *original* +// name (not alias). If both `import { X } from 'proto/notify'` and +// `import { X as Y } from 'events'` appear, the analyzer's import +// resolver picks up the second one and the proton-side definition +// loses, so call sites referencing `X` go un-replaced. Side-step by +// re-aliasing the event-side type's *source* (not just the local +// name) — we don't need to import it directly since assertions can +// inline-extract the kind. +import type { + NewFriend, FriendRecall, SelfJoinInGroup, +} from '../src/bridge/proto/proton/notify'; +import type { + GroupMemberJoin, FriendAddEvent, QQEventVariant, +} from '../src/bridge/events'; + +// Local alias for the event-side recall type — derived via Extract so +// we avoid an `import { FriendRecall as X }` that collides with the +// proton import above. +type FriendRecallEvent = Extract; import type { PacketInfo } from '../src/protocol/types'; import { protoEncode } from '../src/protobuf/decode'; import { subscribeLogs } from '../src/utils/logger'; @@ -161,3 +181,171 @@ describe('parseMsgPush Event0x210 subType=38 (acknowledged-but-silent)', () => { } }); }); + +// ── P1 coverage extension: subTypes confirmed by LagrangeGo / acidify +// that we were previously dropping into the "unknown" fallback. ── + +function makeEvent0x210PacketAny(subType: number, content: Uint8Array): PacketInfo { + const body = protoEncode({ + message: { + responseHead: { fromUin: 22222, type: 0, sigMap: 0 }, + contentHead: { msgType: 528, subType, timestamp: 1710000000 }, + body: { msgContent: content }, + }, + status: 0, + } as any, PushMsgSchema); + return { + pid: 1, uin: SELF_UIN, serviceCmd: MSG_PUSH_CMD, seqId: 1, + retCode: 0, fromClient: false, body, + }; +} + +describe('parseMsgPush Event0x210 subType=179/226 (NewFriend → friend_add)', () => { + // 179 fires when bot sent a request and other side accepted; 226 + // when bot accepted other side's request. Both share the + // `NewFriend` wire shape (LagrangeGo registers both via + // case-fallthrough in `client/listener.go:248`). We surface them + // identically as `kind: 'friend_add'`. + + function makeNewFriendPacket(subType: 179 | 226, friendUid: string, time = 1710000000): PacketInfo { + const content = protobuf_encode({ + field1: 0, + info: { uid: friendUid, time, message: 'hello', nickName: 'Alice' }, + }); + return makeEvent0x210PacketAny(subType, content); + } + + it('emits friend_add for subType 179', () => { + const member = makeGroupMember(99999, 'u_new_friend'); + const [event] = parseMsgPush( + makeNewFriendPacket(179, member.uid), + makeIdentity([member]), + ) as FriendAddEvent[]; + + expect(event.kind).toBe('friend_add'); + expect(event.userUin).toBe(99999); + expect(event.time).toBe(1710000000); + }); + + it('emits friend_add for subType 226 (same wire shape, different surface)', () => { + const member = makeGroupMember(88888, 'u_other_friend'); + const [event] = parseMsgPush( + makeNewFriendPacket(226, member.uid), + makeIdentity([member]), + ) as FriendAddEvent[]; + + expect(event.kind).toBe('friend_add'); + expect(event.userUin).toBe(88888); + }); + + it('falls back to the packet routingHead.fromUin when the uid is not in the local cache', () => { + // No member registered for `u_unknown_uid`, but the packet itself + // carries the new friend's uin on `fromUin` (22222 in + // makeEvent0x210PacketAny). That's the wire-level convention + // (LagrangeGo emits unconditionally then calls `ResolveUin` post + // hoc, see `client/listener.go:259`). Without the fallback the + // event would either drop or surface `user_id: 0`, both of which + // confuse OneBot consumers. + const [event] = parseMsgPush( + makeNewFriendPacket(179, 'u_unknown_uid'), + makeIdentity(), + ) as FriendAddEvent[]; + expect(event.kind).toBe('friend_add'); + expect(event.userUin).toBe(22222); // the packet's fromUin + }); +}); + +describe('parseMsgPush Event0x210 subType=139 (self-recall direction)', () => { + // 138 = friend recalled their own message sent to bot + // (peer in friend_recall event = fromUid) + // 139 = bot recalled own message sent to friend + // (peer in friend_recall event = toUid) + // Same wire shape; the subType is the direction discriminator. + // Acidify makes the same split in `parseFriendRecall:380`. Without + // 139, self-recalls used to fall through and disappear. + + function makeFriendRecallPacket(subType: 138 | 139, fromUid: string, toUid: string): PacketInfo { + const content = protobuf_encode({ + info: { + fromUid, toUid, clientSequence: 4242, newId: 0n, + time: 1710000000, random: 0, pkgNum: 1, pkgIndex: 0, divSeq: 1, + }, + }); + return makeEvent0x210PacketAny(subType, content); + } + + it('subType 138 keeps fromUid as the resolved peer (other recalled their own msg to us)', () => { + const friend = makeGroupMember(77777, 'u_friend'); + const [event] = parseMsgPush( + makeFriendRecallPacket(138, friend.uid, 'u_self'), + makeIdentity([friend]), + ) as FriendRecallEvent[]; + + expect(event.kind).toBe('friend_recall'); + expect(event.userUin).toBe(77777); + expect(event.msgSeq).toBe(4242); + }); + + it('subType 139 picks toUid as the peer (we recalled our msg sent to friend)', () => { + const friend = makeGroupMember(77777, 'u_friend'); + const [event] = parseMsgPush( + makeFriendRecallPacket(139, 'u_self', friend.uid), + makeIdentity([friend]), + ) as FriendRecallEvent[]; + + expect(event.kind).toBe('friend_recall'); + expect(event.userUin).toBe(77777); // resolved from toUid (the friend), not fromUid (us) + }); +}); + +describe('parseMsgPush PkgType 85 (bot self-joined a group)', () => { + // PkgType 33 (GroupMemberIncreaseNotice) fires for *other* members + // joining; the bot's own join after `set_group_add_request` approval + // / invite-accept arrives at 85 instead. We surface it as + // `group_member_join` with `userUin = selfUin` so the OneBot + // converter naturally produces `notice.group_increase`. + function makeSelfJoinPacket(groupId: number, operatorUid = ''): PacketInfo { + const content = protobuf_encode({ + groupUin: BigInt(groupId), + field2: 1, + operatorUid, + field4: 0, + field6: 48, + field7: '', + }); + const body = protoEncode({ + message: { + responseHead: { fromUin: groupId, type: 0, sigMap: 0 }, + contentHead: { msgType: 85, subType: 0, timestamp: 1710000000 }, + body: { msgContent: content }, + }, + status: 0, + } as any, PushMsgSchema); + return { + pid: 1, uin: SELF_UIN, serviceCmd: MSG_PUSH_CMD, seqId: 1, + retCode: 0, fromClient: false, body, + }; + } + + it('emits group_member_join with userUin == selfUin', () => { + const [event] = parseMsgPush( + makeSelfJoinPacket(GROUP_ID), + makeIdentity(), + ) as GroupMemberJoin[]; + + expect(event.kind).toBe('group_member_join'); + expect(event.groupId).toBe(GROUP_ID); + expect(event.userUin).toBe(Number(SELF_UIN)); + }); + + it('resolves operator uid through identity when present', () => { + const admin = makeGroupMember(11111, 'u_admin'); + const [event] = parseMsgPush( + makeSelfJoinPacket(GROUP_ID, admin.uid), + makeIdentity([admin]), + ) as GroupMemberJoin[]; + + expect(event.operatorUin).toBe(admin.uin); + expect(event.operatorUid).toBe(admin.uid); + }); +}); From 1daf6f6218774704e319a8ba33a053262a23fd28 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=89=8B=E7=93=9C=E4=B8=80=E5=8D=81=E9=9B=AA?= Date: Tue, 19 May 2026 15:30:41 +0800 Subject: [PATCH 33/48] Remove runtime dependency bundling step Delete the "Bundle runtime dependencies" step from .github/workflows/dev-build.yml. The removed step changed to working-directory: dist and ran npm install --omit=dev, so CI will no longer install runtime deps into dist during the dev build, reducing build time and avoiding bundling node modules into the dev artifacts. --- .github/workflows/dev-build.yml | 4 ---- 1 file changed, 4 deletions(-) diff --git a/.github/workflows/dev-build.yml b/.github/workflows/dev-build.yml index bb6d630f..a4379937 100644 --- a/.github/workflows/dev-build.yml +++ b/.github/workflows/dev-build.yml @@ -110,10 +110,6 @@ jobs: SNOWLUMA_TARGET: ${{ matrix.target }} run: pnpm run build:all - - name: Bundle runtime dependencies - working-directory: dist - run: npm install --omit=dev - # Naming convention: # SnowLuma-dev-.zip|tar.gz – zero-install (node bundled) # SnowLuma-dev--lite.zip|tar.gz – user provides Node >= 22 From 87ac6ffedbcd32418b9404eb424cdc61522df9d2 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Tue, 19 May 2026 21:18:08 +0800 Subject: [PATCH 34/48] fix(file-upload): fall back through parallel host fields when uploadIp is empty MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit User report: `upload_private_file` was failing with "private file upload host is invalid" on a fresh upload (boolFileExist=false). The OIDB call succeeded but `uploadIp` (field 60) came back empty, and we treated that single field as the only source of truth. Cross-referenced LagrangeGo's `OidbSvcTrpcTcp0xE37_800.proto` + NapCat's `Oidb.0XE37_800.ts`: the server has six parallel host slots on this response (uploadIp / uploadDomain / uploadIpList[0] / uploadHttpsDomain / uploadDns / uploadLanip). LagrangeGo + Lagrange.Core only read field 60 and would hit the same dead-end — we walk the chain instead. Also log the full slot set when we genuinely can't find a host so future reports can name which field the server actually populated. Adds two regression tests: one proves the fallback to `uploadDomain` goes to highway successfully, one proves we still throw when every slot is empty. --- .../core/src/bridge/actions/group-file.ts | 34 +++++++++++++- .../src/bridge/proto/proton/oidb-action.ts | 16 +++++++ .../core/tests/actions/group-file.test.ts | 45 +++++++++++++++++++ 3 files changed, 94 insertions(+), 1 deletion(-) diff --git a/packages/core/src/bridge/actions/group-file.ts b/packages/core/src/bridge/actions/group-file.ts index f56b408f..ef12dbd3 100644 --- a/packages/core/src/bridge/actions/group-file.ts +++ b/packages/core/src/bridge/actions/group-file.ts @@ -440,10 +440,42 @@ export async function uploadPrivateFile( if (!fileId) throw new Error('private file upload response missing file_id'); if (!upload.boolFileExist && uploadFile) { + // The server normally returns the highway host in `uploadIp` (field + // 60). LagrangeGo / Lagrange.Core both read that field directly with + // no fallback. We've seen real captures where the server picks one + // of the parallel host fields (uploadDomain / uploadIpList[0] / + // uploadHttpsDomain / uploadDns) instead — likely a rollout + // difference. Walk them in order rather than die with "upload host + // is invalid" when the server gives us a perfectly usable host + // through a different slot. The highway client uses HTTP PUT so we + // can pair any of these with the regular `uploadPort`; we only fall + // back to `uploadHttpsPort` if we picked the HTTPS-flavored host. + const ipListFirst = (Array.isArray(upload.uploadIpList) && upload.uploadIpList[0]) + ? upload.uploadIpList[0] : ''; const uploadHost = (typeof upload.uploadIp === 'string' && upload.uploadIp) + || (typeof upload.uploadDomain === 'string' && upload.uploadDomain) + || (ipListFirst) + || (typeof upload.uploadHttpsDomain === 'string' && upload.uploadHttpsDomain) + || (typeof upload.uploadDns === 'string' && upload.uploadDns) || ''; - const uploadPort = toInt(upload.uploadPort); + const httpsHostUsed = !upload.uploadIp && !upload.uploadDomain && !ipListFirst + && typeof upload.uploadHttpsDomain === 'string' && !!upload.uploadHttpsDomain; + const uploadPort = httpsHostUsed && toInt(upload.uploadHttpsPort) > 0 + ? toInt(upload.uploadHttpsPort) + : toInt(upload.uploadPort); if (!uploadHost || uploadPort <= 0) { + // Surface every host-bearing field we know about so a user + // hitting this can show us exactly which slot the server filled + // (or whether it returned nothing at all — which would point at + // a request mismatch rather than a missing decoder). + log.warn( + 'private file upload host missing — ip=%s domain=%s ipList=%s httpsDomain=%s dns=%s lanip=%s port=%s httpsPort=%s', + upload.uploadIp ?? '', upload.uploadDomain ?? '', + JSON.stringify(upload.uploadIpList ?? []), + upload.uploadHttpsDomain ?? '', upload.uploadDns ?? '', + upload.uploadLanip ?? '', upload.uploadPort ?? 0, + upload.uploadHttpsPort ?? 0, + ); throw new Error('private file upload host is invalid'); } diff --git a/packages/core/src/bridge/proto/proton/oidb-action.ts b/packages/core/src/bridge/proto/proton/oidb-action.ts index 1aede706..19ea7e4b 100644 --- a/packages/core/src/bridge/proto/proton/oidb-action.ts +++ b/packages/core/src/bridge/proto/proton/oidb-action.ts @@ -646,11 +646,27 @@ export interface OidbPrivateFileUploadReq { export interface OidbPrivateFileUploadRespBody { retCode?: pb<10, int_32>; retMsg?: pb<20, string>; + // 30/40/50 (totalSpace/usedSpace/uploadedSize int64) intentionally + // omitted — proton only needs fields we actually consume, and the + // quota numbers don't drive any code path. uploadIp?: pb<60, string>; + // Cross-checked against LagrangeGo `OidbSvcTrpcTcp0xE37_800.proto` + // (fields 60-170 enumerated below) + NapCat `Oidb.0XE37_800.ts`. + // Real server has been observed to leave `uploadIp` empty while + // populating `uploadDomain` / `uploadIpList[0]` instead (likely a + // server-side rollout difference). Decoding all of these lets us + // fall through in the consumer rather than die with "upload host + // is invalid" when the server picks a different field. + uploadDomain?: pb<70, string>; uploadPort?: pb<80, uint_32>; uuid?: pb<90, string>; uploadKey?: pb<100, bytes>; boolFileExist?: pb<110, bool>; + uploadIpList?: pb_repeated<130, string>; + uploadHttpsPort?: pb<140, int_32>; + uploadHttpsDomain?: pb<150, string>; + uploadDns?: pb<160, string>; + uploadLanip?: pb<170, string>; fileAddon?: pb<200, string>; mediaPlatformUploadKey?: pb<220, bytes>; } diff --git a/packages/core/tests/actions/group-file.test.ts b/packages/core/tests/actions/group-file.test.ts index 54eb890a..a5148277 100644 --- a/packages/core/tests/actions/group-file.test.ts +++ b/packages/core/tests/actions/group-file.test.ts @@ -242,6 +242,51 @@ describe('actions/group-file', () => { expect(bridge.sendC2cFileMessage).not.toHaveBeenCalled(); }); + it('uploadPrivateFile falls back to uploadDomain when uploadIp is empty', async () => { + // Regression: the server has been observed in the wild returning the + // highway host in `uploadDomain` (field 70) instead of `uploadIp` + // (field 60), causing "private file upload host is invalid". The + // helper should walk the parallel host fields rather than dying on + // a single missing slot. Cross-referenced against napcat's proto + // (`Oidb.0XE37_800.ts` ApplyUploadRespV3) — fields 60/70/130/150/160 + // all carry plausible host values from the same server endpoint. + const bridge = mockBridge(); + vi.mocked(bridge.resolveUserUid).mockResolvedValueOnce('target-uid'); + vi.mocked(oidb.runOidb).mockResolvedValueOnce( + protobuf_encode>({ + body: { + upload: { + uuid: 'pfid', + fileAddon: 'phash', + // boolFileExist defaults to false (proto3) — forces the + // highway path where the host fields actually matter. + uploadDomain: 'upload.qpic.cn', + uploadPort: 8080, + mediaPlatformUploadKey: new Uint8Array([1, 2, 3]), + } as any, + }, + }), + ); + await groupFile.uploadPrivateFile(bridge as any, 67890, '/path/file.bin'); + expect(highwayClient.uploadHighwayHttp).toHaveBeenCalledOnce(); + }); + + it('uploadPrivateFile throws "host is invalid" only when every host field is empty', async () => { + // The diagnostic warn-log lists every host slot to help users + // report which one the server actually populated; this test just + // asserts that the throw still fires when none of them carry a + // value (boolFileExist=false + no usable host). + const bridge = mockBridge(); + vi.mocked(bridge.resolveUserUid).mockResolvedValueOnce('target-uid'); + vi.mocked(oidb.runOidb).mockResolvedValueOnce( + protobuf_encode>({ + body: { upload: { uuid: 'pfid', fileAddon: 'phash', uploadPort: 8080 } as any }, + }), + ); + await expect(groupFile.uploadPrivateFile(bridge as any, 67890, '/path/file.bin')) + .rejects.toThrow(/upload host is invalid/); + }); + it('fetchGroupFiles paginates files + folders out of OIDB items', async () => { const bridge = mockBridge(); vi.mocked(oidb.runOidb).mockResolvedValueOnce( From 3c65df668caf1722dfda40a17f8906026621817b Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Tue, 19 May 2026 21:21:12 +0800 Subject: [PATCH 35/48] fix(msg-push): silently acknowledge Event0x210 subType=380 (unmapped client state) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Surveyed Lagrange.Core (PushMessageService.cs), LagrangeGo (client/listener.go), lagrange-python (server_push/msg.py), mania (push_msg.rs), and the tsuzcx/qq_apk decompile — zero handlers for 380 / 0x17C across the lot. Pattern matches subType=38 (also a QQ-client-internal state push with no OneBot mapping); drop it through the same silent-acknowledge path so we stop spamming `MsgPush.Unknown` at debug level on every push. --- .../bridge/msg-push/decoders/event-0x210.ts | 9 ++++++++ packages/core/src/bridge/msg-push/enums.ts | 21 +++++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/packages/core/src/bridge/msg-push/decoders/event-0x210.ts b/packages/core/src/bridge/msg-push/decoders/event-0x210.ts index eafe1fb1..9c3ebd1e 100644 --- a/packages/core/src/bridge/msg-push/decoders/event-0x210.ts +++ b/packages/core/src/bridge/msg-push/decoders/event-0x210.ts @@ -53,6 +53,15 @@ export const decodeEvent0x210: MsgPushDecoder = (ctx) => { // push — no OneBot-level event. See enum comment for the // decompiled-source breakdown of the sub_cmd dispatch. return []; + case Event0x210SubType.UnmappedClientState380: + // QQ-NT-era subType with no reference handler: the legacy QQ + // Android decompile (tsuzcx/qq_apk) only enumerates SubType0x26 + // through SubType0x146 under msgType0x210/, so 380 / 0x17C is + // an NT-era addition. None of the NT clients (Lagrange.Core, + // LagrangeGo, lagrange-python, mania) handle it either. See the + // enum comment for the full investigation; acknowledge silently + // until someone maps the schema. + return []; } unknownLog.debug('Event0x210 unknown subType=%d', ctx.head.subType); return []; diff --git a/packages/core/src/bridge/msg-push/enums.ts b/packages/core/src/bridge/msg-push/enums.ts index 19a98eb1..30f28279 100644 --- a/packages/core/src/bridge/msg-push/enums.ts +++ b/packages/core/src/bridge/msg-push/enums.ts @@ -88,4 +88,25 @@ export enum Event0x210SubType { * bar either. */ GroupAppStatePush = 38, + /** + * Unmapped QQ-NT-internal subType — first seen as a recurring + * "Event0x210 unknown subType=380" debug log in production captures. + * + * The tsuzcx/qq_apk decompile of the legacy QQ Android client only + * enumerates SubType0x26 (38) through SubType0x146 (326) under + * `com.tencent.imcore.message.ext.codec.decoder.msgType0x210/` — + * `SubType0x17c.java` (380) literally doesn't exist in that tree, so + * 380 is a QQ-NT-era addition rather than a missed legacy subType. + * + * The NT-era reference clients also don't handle it: Lagrange.Core + * (`PushMessageService.cs`), LagrangeGo (`client/listener.go`), + * lagrange-python (`server_push/msg.py`), and mania (`push_msg.rs`) + * each enumerate explicit 0x210 subtypes and none include 380 / 0x17C. + * + * Most likely a QQ-NT-client-UI state push (similar to 38) that + * doesn't map to any OneBot event. Acknowledge silently to keep the + * unknown log clean; if a real OneBot event ends up depending on it, + * revisit with whichever NT-era project finally maps the schema. + */ + UnmappedClientState380 = 380, } From 04a905460b249feedbd14f1fc6c06e6422a5e425 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Tue, 19 May 2026 21:45:40 +0800 Subject: [PATCH 36/48] fix(file-upload): read upload host from rtpMediaPlatformUploadAddress (NT 2026 rollout) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The 2026 QQ-NT server has stopped populating *every* legacy host field (uploadIp / uploadDomain / uploadIpList / uploadHttpsDomain / uploadDns). The host now arrives in the new field 210 `rtpMediaPlatformUploadAddress` — a repeated `IPv4` message carrying `inIP`/`inPort` (LAN) and `outIP`/`outPort` (WAN). Coworker's debugging hint "host 好像是 fix64" was the 8-12-byte length-delimited IPv4 message looking like a fixed-width field on the wire. Cross-referenced acidify (https://github.com/LagrangeDev/acidify) — the only NT-protocol fork that's tracked this change (refactored in their 2026-04 protobuf rewrite). They read `inIP`+`inPort` exclusively because that's the address the highway PUT actually needs to reach (same DC as the OIDB endpoint). LagrangeGo / Lagrange.Core / NapCat still ship the old schema and would fail the same way against this server build. Changes: - Proton schema: add `IPv4` message (fields 1-5: outIP/outPort/inIP/ inPort/iPType, all int32 varint) + field 210 on the upload response - Consumer: prefer `rtpMediaPlatformUploadAddress[0].inIP`+`inPort` before falling back through the legacy host chain - New helper `int32ToIpv4Dotted` reverses acidify's `Int.toIpString()` (little-endian byte order, `>>>` for unsigned shift so high-bit IPs don't render as negative octets) - Diagnostic warn-log now dumps the rtp address array too - Regression test: 192.168.1.1 (LE-packed 0x0101A8C0 = 16885952) + inPort=8080 should reach highway PUT --- .../core/src/bridge/actions/group-file.ts | 73 +++++++++++++++---- .../src/bridge/proto/proton/oidb-action.ts | 39 ++++++++-- .../core/tests/actions/group-file.test.ts | 29 ++++++++ 3 files changed, 119 insertions(+), 22 deletions(-) diff --git a/packages/core/src/bridge/actions/group-file.ts b/packages/core/src/bridge/actions/group-file.ts index ef12dbd3..6131ef10 100644 --- a/packages/core/src/bridge/actions/group-file.ts +++ b/packages/core/src/bridge/actions/group-file.ts @@ -83,6 +83,19 @@ function bytesToHexUpper(data: unknown): string { return toHexUpper(data); } +// Reverses acidify's `Int.toIpString()`: the 32-bit IP arrives +// little-endian-packed (byte0 = first dotted octet) and we unpack it the +// same way. Force-unsigned the shift to keep negative ints (high bit set) +// rendering correctly — JS `>>` is arithmetic and would turn 0xFF000000 +// into a negative number. +function int32ToIpv4Dotted(value: number): string { + const b1 = value & 0xFF; + const b2 = (value >>> 8) & 0xFF; + const b3 = (value >>> 16) & 0xFF; + const b4 = (value >>> 24) & 0xFF; + return `${b1}.${b2}.${b3}.${b4}`; +} + function normalizeUploadFileName(name: string, fallback: string): string { const trimmed = name.trim(); if (trimmed) return trimmed; @@ -440,36 +453,64 @@ export async function uploadPrivateFile( if (!fileId) throw new Error('private file upload response missing file_id'); if (!upload.boolFileExist && uploadFile) { - // The server normally returns the highway host in `uploadIp` (field - // 60). LagrangeGo / Lagrange.Core both read that field directly with - // no fallback. We've seen real captures where the server picks one - // of the parallel host fields (uploadDomain / uploadIpList[0] / - // uploadHttpsDomain / uploadDns) instead — likely a rollout - // difference. Walk them in order rather than die with "upload host - // is invalid" when the server gives us a perfectly usable host - // through a different slot. The highway client uses HTTP PUT so we - // can pair any of these with the regular `uploadPort`; we only fall - // back to `uploadHttpsPort` if we picked the HTTPS-flavored host. + // Host selection. + // + // Current QQ-NT server rollout has stopped populating the legacy + // `uploadIp` (field 60) entirely. The host now arrives as the first + // entry of `rtpMediaPlatformUploadAddress` (field 210, repeated + // IPv4 message) — same place acidify reads it from since their + // 2026-04 protobuf refactor. Each IPv4 has paired `inIP`/`inPort` + // (LAN, same DC as the OIDB endpoint) and `outIP`/`outPort` (WAN); + // acidify uses `inIP`/`inPort` exclusively and so do we, because + // that's the address the highway PUT actually needs to reach. + // + // The 32-bit IPs are little-endian-packed (byte0 = first octet) + // per acidify's `Int.toIpString()`. Cross-checked the byte order + // by inspecting their highway flow — there's no separate htonl + // step, so the integer is already in network-octet-first order. + // + // Older server versions still populate the legacy string fields + // (uploadIp / uploadDomain / uploadIpList[0] / uploadHttpsDomain / + // uploadDns), so we fall through to those after rtpMediaPlatform. + // Pair an HTTPS-flavored host with `uploadHttpsPort` if that's + // what we picked. + const rtpFirst = (Array.isArray(upload.rtpMediaPlatformUploadAddress) + && upload.rtpMediaPlatformUploadAddress[0]) + ? upload.rtpMediaPlatformUploadAddress[0] : null; + const rtpInIP = rtpFirst && typeof rtpFirst.inIP === 'number' && rtpFirst.inIP !== 0 + ? int32ToIpv4Dotted(rtpFirst.inIP) : ''; + const rtpInPort = rtpFirst && typeof rtpFirst.inPort === 'number' + ? rtpFirst.inPort : 0; const ipListFirst = (Array.isArray(upload.uploadIpList) && upload.uploadIpList[0]) ? upload.uploadIpList[0] : ''; - const uploadHost = (typeof upload.uploadIp === 'string' && upload.uploadIp) + const uploadHost = (rtpInIP) + || (typeof upload.uploadIp === 'string' && upload.uploadIp) || (typeof upload.uploadDomain === 'string' && upload.uploadDomain) || (ipListFirst) || (typeof upload.uploadHttpsDomain === 'string' && upload.uploadHttpsDomain) || (typeof upload.uploadDns === 'string' && upload.uploadDns) || ''; - const httpsHostUsed = !upload.uploadIp && !upload.uploadDomain && !ipListFirst + const httpsHostUsed = !rtpInIP && !upload.uploadIp && !upload.uploadDomain && !ipListFirst && typeof upload.uploadHttpsDomain === 'string' && !!upload.uploadHttpsDomain; - const uploadPort = httpsHostUsed && toInt(upload.uploadHttpsPort) > 0 - ? toInt(upload.uploadHttpsPort) - : toInt(upload.uploadPort); + const uploadPort = rtpInIP && rtpInPort > 0 + ? rtpInPort + : httpsHostUsed && toInt(upload.uploadHttpsPort) > 0 + ? toInt(upload.uploadHttpsPort) + : toInt(upload.uploadPort); if (!uploadHost || uploadPort <= 0) { // Surface every host-bearing field we know about so a user // hitting this can show us exactly which slot the server filled // (or whether it returned nothing at all — which would point at // a request mismatch rather than a missing decoder). + const rtpDump = Array.isArray(upload.rtpMediaPlatformUploadAddress) + ? JSON.stringify(upload.rtpMediaPlatformUploadAddress.map((e) => ({ + outIP: e.outIP, outPort: e.outPort, inIP: e.inIP, inPort: e.inPort, + iPType: e.iPType, + }))) + : '[]'; log.warn( - 'private file upload host missing — ip=%s domain=%s ipList=%s httpsDomain=%s dns=%s lanip=%s port=%s httpsPort=%s', + 'private file upload host missing — rtp=%s ip=%s domain=%s ipList=%s httpsDomain=%s dns=%s lanip=%s port=%s httpsPort=%s', + rtpDump, upload.uploadIp ?? '', upload.uploadDomain ?? '', JSON.stringify(upload.uploadIpList ?? []), upload.uploadHttpsDomain ?? '', upload.uploadDns ?? '', diff --git a/packages/core/src/bridge/proto/proton/oidb-action.ts b/packages/core/src/bridge/proto/proton/oidb-action.ts index 19ea7e4b..bb051888 100644 --- a/packages/core/src/bridge/proto/proton/oidb-action.ts +++ b/packages/core/src/bridge/proto/proton/oidb-action.ts @@ -643,6 +643,21 @@ export interface OidbPrivateFileUploadReq { flagSupportMediaPlatform?: pb<200, int_32>; } +// IPv4 wire message used inside ApplyUploadRespV3.rtpMediaPlatformUploadAddress +// (field 210). Sourced from acidify's `IPv4` class — outIP/inIP are +// little-endian-packed 32-bit IPv4 addresses (byte order: low byte = first +// octet), decoded via the standard `(ip & 0xFF).(ip>>8 & 0xFF)....` recipe. +// outPort/inPort are the matching port for each leg (out = WAN, in = LAN). +// iPType is the address family hint (1 = IPv4, etc — acidify treats it +// purely as metadata, no behavior). +export interface IPv4 { + outIP?: pb<1, int_32>; + outPort?: pb<2, int_32>; + inIP?: pb<3, int_32>; + inPort?: pb<4, int_32>; + iPType?: pb<5, int_32>; +} + export interface OidbPrivateFileUploadRespBody { retCode?: pb<10, int_32>; retMsg?: pb<20, string>; @@ -651,12 +666,13 @@ export interface OidbPrivateFileUploadRespBody { // quota numbers don't drive any code path. uploadIp?: pb<60, string>; // Cross-checked against LagrangeGo `OidbSvcTrpcTcp0xE37_800.proto` - // (fields 60-170 enumerated below) + NapCat `Oidb.0XE37_800.ts`. - // Real server has been observed to leave `uploadIp` empty while - // populating `uploadDomain` / `uploadIpList[0]` instead (likely a - // server-side rollout difference). Decoding all of these lets us - // fall through in the consumer rather than die with "upload host - // is invalid" when the server picks a different field. + // (fields 60-170 enumerated below) + NapCat `Oidb.0XE37_800.ts` + + // acidify (most recent NT-protocol fork, 2026-04). Real server in + // 2026 has been observed to leave the legacy host fields empty and + // put the host into the new field 210 (`rtpMediaPlatformUploadAddress`, + // repeated IPv4 messages) instead — the consumer walks them in that + // order. Decoding the legacy fields too means we keep working against + // older server rollouts. uploadDomain?: pb<70, string>; uploadPort?: pb<80, uint_32>; uuid?: pb<90, string>; @@ -667,7 +683,18 @@ export interface OidbPrivateFileUploadRespBody { uploadHttpsDomain?: pb<150, string>; uploadDns?: pb<160, string>; uploadLanip?: pb<170, string>; + // Field 200 — acidify renamed this to `fileIdCrc` in their 2026-04 + // refactor; we keep `fileAddon` because the wire bytes are identical + // and our callers already read `fileAddon` as the file-hash blob (it's + // a hex string in practice). Worth renaming if a consumer ever needs + // the new semantic. fileAddon?: pb<200, string>; + // Field 210 — the new "host carrier" the NT server actually populates + // in current rollouts. Each IPv4 entry has `inIP`/`inPort` (LAN) + + // `outIP`/`outPort` (WAN). acidify reads `inIP`+`inPort` exclusively; + // we follow suit because that's what the highway HTTP PUT needs to + // reach (same datacenter as the OIDB endpoint that returned this). + rtpMediaPlatformUploadAddress?: pb_repeated<210, IPv4>; mediaPlatformUploadKey?: pb<220, bytes>; } diff --git a/packages/core/tests/actions/group-file.test.ts b/packages/core/tests/actions/group-file.test.ts index a5148277..73bd9ae8 100644 --- a/packages/core/tests/actions/group-file.test.ts +++ b/packages/core/tests/actions/group-file.test.ts @@ -242,6 +242,35 @@ describe('actions/group-file', () => { expect(bridge.sendC2cFileMessage).not.toHaveBeenCalled(); }); + it('uploadPrivateFile reads host from rtpMediaPlatformUploadAddress[0].inIP when populated', async () => { + // The 2026 QQ-NT server rollout moved the upload host out of the + // legacy `uploadIp` (field 60) string into the new + // `rtpMediaPlatformUploadAddress` (field 210, repeated IPv4 message). + // Mirrors acidify's `UploadPrivateFile.kt` consumer logic — read + // `inIP` (LAN, same DC as the OIDB endpoint) and pair with `inPort`. + // The int is little-endian-packed: 0x0101A8C0 → 192.168.1.1. + const bridge = mockBridge(); + vi.mocked(bridge.resolveUserUid).mockResolvedValueOnce('target-uid'); + vi.mocked(oidb.runOidb).mockResolvedValueOnce( + protobuf_encode>({ + body: { + upload: { + uuid: 'pfid', + fileAddon: 'phash', + // boolFileExist defaults to false — forces highway path + // 192.168.1.1 little-endian packed = (1 << 24) | (1 << 16) | (168 << 8) | 192 = 16885952 + rtpMediaPlatformUploadAddress: [ + { outIP: 0, outPort: 0, inIP: 16885952, inPort: 8080, iPType: 1 }, + ], + mediaPlatformUploadKey: new Uint8Array([1, 2, 3]), + } as any, + }, + }), + ); + await groupFile.uploadPrivateFile(bridge as any, 67890, '/path/file.bin'); + expect(highwayClient.uploadHighwayHttp).toHaveBeenCalledOnce(); + }); + it('uploadPrivateFile falls back to uploadDomain when uploadIp is empty', async () => { // Regression: the server has been observed in the wild returning the // highway host in `uploadDomain` (field 70) instead of `uploadIp` From 8f839f4f302d5f0f196fead8800b63c031cb2727 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Tue, 19 May 2026 21:51:35 +0800 Subject: [PATCH 37/48] =?UTF-8?q?fix(group-file):=20correct=20GroupFileExt?= =?UTF-8?q?ra=20wire=20shape=20=E2=80=94=20server=20was=20rejecting=20with?= =?UTF-8?q?=20result=3D79?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two off-by-one bugs in the group-file chat-post element that combined to make the QQ-NT server reject every group file send with result=79 (visible as "group file uploaded but chat post failed" in the logs): 1. Inner GroupFileInfo fields were shifted one tag left: - fileSha was field 5, should be field 6 - extInfo was field 6, should be field 7 - fileMd5 was field 7, should be field 8 Field 5 is actually a uint32 placeholder (`field5` in both NapCat and acidify). With the bug, our fileSha bytes were landing where the server expected a varint and the rest of the message got skipped as garbage. 2. Outer GroupFileExtra was missing the magic field1=6 + fileName slots that NapCat's encoder writes (`packet/message/element.ts:589`). Acidify's schema also models them as required even though it serialises with defaults. The current server build rejects sends without these slots populated. Cross-referenced: - NapCat `GroupFileExtraInfo` (component.ts:146-155) — matches our new field numbers exactly - acidify `GroupFileExtra.Inner.Info` (proto/message/extra/GroupFileExtra.kt) — same field numbers; their schema uses generic `field5`/`field7` names but the wire layout is identical Changes: - Proton + legacy schemas: shift inner fields, add outer field1/ fileName/display - `makeGroupFileElem`: write field1=6 + fileName on the outer wrapper - Regression test asserts each inner tag lands at 50/58/66 (not the old 42/50/58) and verifies the new outer field1 + fileName bytes are present --- packages/core/src/bridge/element-builder.ts | 9 ++++ packages/core/src/bridge/proto/element.ts | 16 ++++-- .../core/src/bridge/proto/proton/element.ts | 28 ++++++++-- packages/core/tests/element-builder.test.ts | 54 +++++++++++++++++++ 4 files changed, 100 insertions(+), 7 deletions(-) diff --git a/packages/core/src/bridge/element-builder.ts b/packages/core/src/bridge/element-builder.ts index cace04b2..367f881e 100644 --- a/packages/core/src/bridge/element-builder.ts +++ b/packages/core/src/bridge/element-builder.ts @@ -262,7 +262,16 @@ function makeGroupFileElem(element: MessageElement): ProtoElem { const md5 = element.md5Hex ? hexToBytes(element.md5Hex) : new Uint8Array(0); const sha1 = element.sha1Hex ? hexToBytes(element.sha1Hex) : new Uint8Array(0); + // Outer field1 is hardcoded to 6 in NapCat's encoder + // (`packet/message/element.ts:589`). It's a magic tag the server + // expects on send (acidify ships the same shape via their generic + // `field1: Int` default but their consumer writes it too). Without + // these outer fields the current QQ-NT server rejects the message + // with `result=79`. Inner field5 is the uint32 placeholder both + // NapCat and acidify leave at 0 — we follow suit. const extraBytes = protobuf_encode({ + field1: 6, + fileName, inner: { info: { busId: 102, diff --git a/packages/core/src/bridge/proto/element.ts b/packages/core/src/bridge/proto/element.ts index 7ce06cb8..94f78dce 100644 --- a/packages/core/src/bridge/proto/element.ts +++ b/packages/core/src/bridge/proto/element.ts @@ -390,14 +390,21 @@ export const MsgInfoSchema = { // --- GroupFileExtra (TransElem type=24) --- +// Field numbers cross-checked against NapCat (component.ts:146) + +// acidify (GroupFileExtra.kt:Inner.Info). Old schema had fileSha at 5 +// / extInfoString at 6 / fileMd5 at 7 which mismatched the real wire +// shape — the server rejected the chat post with `result=79` because +// fileSha bytes were landing where it expected a uint32 (field 5). +// See proton/element.ts for the WHY comment. export const GroupFileInfoSchema = { busId: { field: 1, type: 'uint32' as const }, fileId: { field: 2, type: 'string' as const }, fileSize: { field: 3, type: 'uint64' as const }, fileName: { field: 4, type: 'string' as const }, - fileSha: { field: 5, type: 'bytes' as const }, - extInfoString: { field: 6, type: 'string' as const }, - fileMd5: { field: 7, type: 'bytes' as const }, + field5: { field: 5, type: 'uint32' as const }, + fileSha: { field: 6, type: 'bytes' as const }, + extInfoString: { field: 7, type: 'string' as const }, + fileMd5: { field: 8, type: 'bytes' as const }, } satisfies ProtoSchema; export const GroupFileExtraInnerSchema = { @@ -405,6 +412,9 @@ export const GroupFileExtraInnerSchema = { } satisfies ProtoSchema; export const GroupFileExtraSchema = { + field1: { field: 1, type: 'uint32' as const }, + fileName: { field: 2, type: 'string' as const }, + display: { field: 3, type: 'string' as const }, inner: { field: 7, type: 'message' as const, schema: GroupFileExtraInnerSchema }, } satisfies ProtoSchema; diff --git a/packages/core/src/bridge/proto/proton/element.ts b/packages/core/src/bridge/proto/proton/element.ts index 3da2ac6f..304cd08e 100644 --- a/packages/core/src/bridge/proto/proton/element.ts +++ b/packages/core/src/bridge/proto/proton/element.ts @@ -392,23 +392,43 @@ export interface MsgInfo { } // ── GroupFileExtra (TransElem type=24) ────────────────────────────── +// +// Sourced from NapCat's `GroupFileExtraInfo` (component.ts:146-155) +// cross-checked against acidify's `GroupFileExtra.Inner.Info` +// (proto/message/extra/GroupFileExtra.kt). Field numbers had been +// shifted by one in the previous schema (fileSha at 5, ext at 6, +// fileMd5 at 7) which caused the server to reject group-file chat +// posts with `result=79` — the server saw fileSha bytes where it +// expected a uint32 placeholder (field 5) and silently dropped the +// rest. Field 5 is a uint32 placeholder both refs label `field5`; +// fileSha is at 6, extInfoString at 7, fileMd5 at 8. export interface GroupFileInfo { busId?: pb<1, uint_32>; fileId?: pb<2, string>; fileSize?: pb<3, uint_64>; fileName?: pb<4, string>; - fileSha?: pb<5, bytes>; - extInfoString?: pb<6, string>; - fileMd5?: pb<7, bytes>; + field5?: pb<5, uint_32>; + fileSha?: pb<6, bytes>; + extInfoString?: pb<7, string>; + fileMd5?: pb<8, bytes>; } export interface GroupFileExtraInner { info?: pb<2, GroupFileInfo>; } +// Outer wrapper carries three additional fields the server expects: +// field1 (uint32, NapCat hardcodes to 6 — "magic op tag"), fileName +// (string mirror of the inner info.fileName), display (optional UI +// preview string, NapCat leaves empty but writes the slot). Without +// these the server still recognized the message in older builds but +// rejects it in the current rollout. export interface GroupFileExtra { - inner?: pb<7, GroupFileExtraInner>; + field1?: pb<1, uint_32>; + fileName?: pb<2, string>; + display?: pb<3, string>; + inner?: pb<7, GroupFileExtraInner>; } // ── Preserve (for message receipt info) ───────────────────────────── diff --git a/packages/core/tests/element-builder.test.ts b/packages/core/tests/element-builder.test.ts index ebe4e639..a4893110 100644 --- a/packages/core/tests/element-builder.test.ts +++ b/packages/core/tests/element-builder.test.ts @@ -92,3 +92,57 @@ describe('element-builder / commonElem.businessType per scene', () => { }); }); }); + +describe('element-builder / group file element wire shape', () => { + // Regression for the same `result=79` class: the GroupFileExtra outer + // wrapper was missing the magic `field1=6` + `fileName` slots and the + // inner GroupFileInfo had fileSha/extInfoString/fileMd5 shifted one + // tag to the left (5/6/7 instead of the correct 6/7/8). Both + // mistakes made the current QQ-NT server reject the chat post. This + // test decodes the element back through the proton-generated codec + // and asserts each field lands at the right tag. + it('encodes outer field1=6 + fileName, and inner fields at tags 6/7/8', async () => { + const [elem] = await buildSendElems( + [{ + type: 'file', + fileId: 'fid-abc', + fileName: 'doc.txt', + fileSize: 123, + md5Hex: 'aabbccddeeff00112233445566778899', + sha1Hex: '0102030405060708090a0b0c0d0e0f1011121314', + } as any], + { bridge: fakeBridge, groupId: 12345 }, + ); + const transElem = (elem as any).transElem as { elemType: number; elemValue: Uint8Array }; + expect(transElem.elemType).toBe(24); + // 0x01 prefix + BE16 length + payload + expect(transElem.elemValue[0]).toBe(0x01); + const len = (transElem.elemValue[1] << 8) | transElem.elemValue[2]; + const payload = transElem.elemValue.subarray(3, 3 + len); + + // Hand-walk the wire bytes to verify each tag lands where the + // server expects. Each varint tag = (field << 3) | wire_type: + // outer field1=6 → tag 8 (wire 0 / varint), value 6 + // outer fileName → tag 18 (wire 2 / length-delimited), 'doc.txt' + // outer inner → tag 58 (field 7 wire 2) + // inner.info → tag 18 (field 2 wire 2) + // info.busId → tag 8 (field 1 wire 0), value 102 + // info.fileId → tag 18 (field 2 wire 2) + // info.fileSize → tag 24 (field 3 wire 0), value 123 + // info.fileName → tag 34 (field 4 wire 2) + // info.fileSha → tag 50 (field 6 wire 2) ← was 42 (field 5) + // info.extInfoString → tag 58 (field 7 wire 2) ← was 50 (field 6) + // info.fileMd5 → tag 66 (field 8 wire 2) ← was 58 (field 7) + const tagAt = (i: number) => payload[i]; + expect(tagAt(0)).toBe(8); // outer field1 tag — regression: missing entirely before + expect(payload[1]).toBe(6); // value of field1 (NapCat hardcodes 6) + expect(tagAt(2)).toBe(18); // outer fileName tag — regression: missing + // Locate the inner GroupFileExtraInfo by scanning for tag 50 (was 42 + // in the bug). A naive scan for `0x32` is enough because no string + // field happens to contain that byte in this test fixture. + expect(payload.includes(50)).toBe(true); // fileSha at tag 50 (field 6) + expect(payload.includes(58)).toBe(true); // extInfoString at tag 58 (field 7) + expect(payload.includes(66)).toBe(true); // fileMd5 at tag 66 (field 8) + expect(payload.includes(42)).toBe(false); // sanity: nothing at the old (wrong) tag for fileSha + }); +}); From 0b8dc1f7af083a3aa0588e89bd7951b55e578b8a Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Tue, 19 May 2026 22:20:38 +0800 Subject: [PATCH 38/48] fix(video): populate NTV2 fileInfo.time with the real duration (receiver was rendering 00:00) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The NTV2 upload request for video carried `time: 0` on the main mp4 sub-file, mirroring NapCat's transformer. But NapCat lives on top of the desktop QQ-NT client's IPC layer, which patches the duration into the resulting MsgInfo before the wire send — we don't have that layer, so the `time: 0` we passed in ended up baked into the `VideoFile. fileTime` field of every video the bot sent. Receivers then rendered every video bubble as "00:00". Cross-checked acidify's `RichMediaUpload.kt::buildVideoUploadInfoList` (2026-04 refactor) — they're a protocol-direct client too and write `time = payload.videoDuration` for exactly this reason. We already have `video.duration` from `loadVideo` (probed via ffprobe), so it's a one-liner. Width/height kept at 0 deliberately — acidify fills them, NapCat zeros them, and our earlier comment recorded "QQ NT server treats non-zero values here as schema mismatch on c2c sends". Out of scope for this fix; revisit if a c2c regression surfaces. Test asserts `fileInfo.time === 10` for the main sub-file (matches FINGERPRINT.duration) and stays 0 on the thumb. --- .../core/src/bridge/highway/video-upload.ts | 20 ++++++++++++++----- .../core/tests/highway/video-upload.test.ts | 15 ++++++++++++++ 2 files changed, 30 insertions(+), 5 deletions(-) diff --git a/packages/core/src/bridge/highway/video-upload.ts b/packages/core/src/bridge/highway/video-upload.ts index 96191ad3..bc7568a6 100644 --- a/packages/core/src/bridge/highway/video-upload.ts +++ b/packages/core/src/bridge/highway/video-upload.ts @@ -480,14 +480,24 @@ export async function uploadVideoMsgInfo( fileHash: video.md5Hex, fileSha1: video.sha1Hex, fileName: 'nya.mp4', - // NapCat sends type.videoFormat=0 and width/height/time=0 - // for the main video sub-file (only the thumb carries - // dimensions). The QQ NT server treats non-zero values - // here as a schema mismatch on c2c sends. type: { type: 2, picFormat: 0, videoFormat: 0, voiceFormat: 0 }, + // Width/height kept at 0 — NapCat does the same and the QQ-NT + // server has been observed to reject non-zero dimensions + // here on c2c sends with a schema-mismatch error. acidify + // *does* fill them (`payload.videoWidth/Height`) but we + // leave that alone until c2c regression coverage exists. height: 0, width: 0, - time: 0, + // `time` MUST be the real duration in seconds, otherwise + // every receiving client renders "00:00" on the video. + // NapCat ships `time: 0` because it sits on top of QQ-NT's + // IPC layer, which the desktop client patches up before + // the wire message goes out. We're a protocol-direct + // client (same position as acidify), so we own this field. + // acidify writes `payload.videoDuration` here for the same + // reason — verified against `RichMediaUpload.kt:: + // buildVideoUploadInfoList` (2026-04 refactor). + time: video.duration, original: 0, }, subFileType: 0, diff --git a/packages/core/tests/highway/video-upload.test.ts b/packages/core/tests/highway/video-upload.test.ts index 00837a7f..0d352d31 100644 --- a/packages/core/tests/highway/video-upload.test.ts +++ b/packages/core/tests/highway/video-upload.test.ts @@ -90,6 +90,21 @@ describe('video-upload', () => { expect((uploadInfo[1] as any).fileInfo.type.type).toBe(1); // pic (thumb) }); + it('main video carries the real `time` (duration in seconds) — regression: was 0', async () => { + // NTV2 server bakes the `time` field into the resulting MsgInfo + // bytes that ride along as `commonElem.pbElem`; the receiver + // reads it back via `VideoFile.fileTime` and renders it as the + // playable duration. NapCat ships `time: 0` only because it sits + // on top of QQ-NT's IPC layer which patches the value in before + // the wire send; we're a protocol-direct client (same position + // as acidify) and must populate it ourselves. Without this the + // receiver shows "00:00" on every video the bot sends. + await uploadVideoMsgInfo({} as any, true, 12345, FINGERPRINT); + const uploadInfo = vi.mocked(pipeline.runNtv2Upload).mock.calls[0]![0].uploadInfo; + expect((uploadInfo[0] as any).fileInfo.time).toBe(10); // matches FINGERPRINT.duration + expect((uploadInfo[1] as any).fileInfo.time).toBe(0); // thumb stays at 0 (matches acidify) + }); + it('thumb falls back to a synthesized 1x1 PNG with real bytes', async () => { await uploadVideoMsgInfo({} as any, true, 12345, FINGERPRINT); const uploads = vi.mocked(pipeline.runNtv2Upload).mock.calls[0]![0].uploads; From cec38b4c1bf6b389a107120a554dd9bc804caddf Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Tue, 19 May 2026 23:29:59 +0800 Subject: [PATCH 39/48] fix(forward): piggyback every nested level onto the outermost long-msg upload (NapCat model) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Cross-referenced `dev/NapCatQQ/.../SendMsg.uploadForwardedNodesPacket` (208-347): every layer of a nested forward attaches its own msgBody to the *outer* long-msg upload under a uuid `actionCommand` slot. Receiver walks the whole tree from one server fetch instead of resolving each layer's res_id separately. `dev/Lagrange.Core` (V2 branch on `linwenxuan04/v2`, `MultiMsgUploadService.cs:23-31`) only writes a single MultiMsg action — that's why NapCat-style receivers couldn't follow our previous nested-forward sends past the first level. Refactor: 1. `ForwardNodePayload` gets an optional `innerForward?: ForwardNodePayload[]` field. `parseForwardNodes` no longer eagerly uploads inner chains — it just attaches them here. 2. `uploadForwardNodes` now drives the whole recursion. The new `uploadForwardNodesRecursive`: - walks each node, recursively uploads any `innerForward` first - replaces that node's `elements` with a real `{type:'forward'}` preview pointing at the inner res_id - piggybacks the inner level's `{uuid, msgBody}` + every deeper level it surfaced into this level's `myInnerActions` - encodes the long-msg payload as `[{MultiMsg, ownMsgBody}, ...innerActions.map(uuid+msgBody)]` - returns `{resId, msgBody, uuid, innerActions}` so an outer call can keep climbing Top-level public signature unchanged: `Promise`. 3. New `deriveInnerSource` / `previewLinesFromNodes` / `previewFromElements` helpers synthesise the ARK preview metadata the inner bubble shows before the user taps to expand. They handle text/image/record/video/file/forward/face element previews. 4. `parseForwardNodes`: when `content` is an all-node array, attach the parsed inner chain to `node.innerForward` and let the upload pipeline take over. `elements = []` placeholder is replaced by `uploadForwardNodes` once it has the real res_id. Tests: - `actions/forward.test.ts`: - `uploadForwardNodes recursively uploads nested innerForward chains (NapCat piggyback model)` — asserts two SsoSendLongMsg roundtrips (inner first, then outer) and the outer res_id propagates up - `flat sends still take a single roundtrip` — backwards-compat - `onebot/forward-nested.test.ts`: rewritten — mock now sees exactly one `uploadForwardNodes` call with `innerForward` attached, instead of two sequential calls; depth-limit + mixed-content tests unchanged. --- packages/core/src/bridge/actions/forward.ts | 173 ++++++++++++++++-- packages/core/src/bridge/events.ts | 12 ++ .../src/onebot/modules/message-actions.ts | 42 +++-- packages/core/tests/actions/forward.test.ts | 46 +++++ .../core/tests/onebot/forward-nested.test.ts | 102 +++++------ 5 files changed, 289 insertions(+), 86 deletions(-) diff --git a/packages/core/src/bridge/actions/forward.ts b/packages/core/src/bridge/actions/forward.ts index 8a85336a..07c1db36 100644 --- a/packages/core/src/bridge/actions/forward.ts +++ b/packages/core/src/bridge/actions/forward.ts @@ -5,10 +5,11 @@ import type { Bridge } from '../bridge'; import { gunzipSync, gzipSync } from 'zlib'; +import { randomUUID } from 'crypto'; import { protobuf_encode, protobuf_decode } from '@snowluma/proton'; import { buildSendElems } from '../element-builder'; import { parseMsgPush } from '../msg-push'; -import type { ForwardNodePayload } from '../events'; +import type { ForwardNodePayload, MessageElement } from '../events'; import type { PacketInfo } from '../../protocol/types'; import type { LongMsgResult, @@ -73,12 +74,60 @@ async function buildForwardPushBody( }; } +// Per-layer piggyback entry. Each level of a nested forward attaches +// its own msgBody under a uuid `actionCommand`, so when the receiver +// fetches the outermost res_id it gets every layer in one shot +// (modelled on NapCat's `uploadForwardedNodesPacket` — see +// `dev/NapCatQQ/.../SendMsg.ts:208-347`). Lagrange.Core master + V2 +// both ship a single-action model and silently break when the +// recipient is a NapCat instance trying to walk the tree. +interface ForwardInnerAction { + uuid: string; + msgBody: PushMsgBody[]; +} + +interface ForwardUploadResult { + resId: string; + // The current level's msgBody + uuid — what an outer caller would + // piggyback to expose this layer through the tree. + msgBody: PushMsgBody[]; + uuid: string; + // All accumulated piggyback entries from deeper levels. Outer + // callers concatenate these to their own actions list so the + // outermost upload carries the full tree. + innerActions: ForwardInnerAction[]; +} + export async function uploadForwardNodes( bridge: Bridge, nodes: ForwardNodePayload[], groupId?: number, userId?: number, ): Promise { + const { resId } = await uploadForwardNodesRecursive(bridge, nodes, groupId, userId); + return resId; +} + +/** + * Recursive upload with NapCat-style piggyback. Each invocation: + * 1. Walks `nodes`. For any node whose `innerForward` is set, + * recursively uploads that inner chain first (which itself runs + * this same recursion). + * 2. Replaces the node's `elements` with an ARK preview pointing at + * the inner res_id (and inner uuid for receiver-side walking). + * 3. Accumulates the inner level's `{uuid, msgBody}` plus all of + * ITS accumulated `innerActions` into this level's piggyback list. + * 4. Encodes this level's long-msg payload as + * `[MultiMsg + thisMsgBody, ...innerActions]`, uploads it, + * returns `{resId, msgBody, uuid, innerActions}` so an outer + * caller can keep piggybacking up the tree. + */ +async function uploadForwardNodesRecursive( + bridge: Bridge, + nodes: ForwardNodePayload[], + groupId?: number, + userId?: number, +): Promise { if (!Array.isArray(nodes) || nodes.length === 0) { throw new Error('forward nodes are required'); } @@ -86,25 +135,77 @@ export async function uploadForwardNodes( // For a private forward to `userId`, any image/record/video inside a node // needs the recipient's uid as upload scene. Resolve it once up-front, // and only when at least one node actually contains media (saves an RPC - // for text-only forwards). + // for text-only forwards). Also need it when a node is itself a nested + // forward — the inner upload uses the same scene. let userUid: string | undefined; if (groupId === undefined && userId !== undefined && userId > 0) { - const hasMedia = nodes.some(node => node.elements.some( - e => e.type === 'image' || e.type === 'record' || e.type === 'video', - )); - if (hasMedia) { + const needsUid = nodes.some(node => !!node.innerForward + || node.elements.some(e => e.type === 'image' || e.type === 'record' || e.type === 'video')); + if (needsUid) { const resolved = await bridge.resolveUserUid(userId); if (resolved) userUid = resolved; } } - const msgBody = await Promise.all(nodes.map(node => buildForwardPushBody(bridge, node, groupId, userUid))); + // Walk nodes and resolve nested forwards first (so we know their + // res_id / uuid before encoding the outer ARK previews). Build + // `processedNodes` with elements rewritten for nested layers, + // and collect every inner level's piggyback in `myInnerActions`. + const myInnerActions: ForwardInnerAction[] = []; + const processedNodes: ForwardNodePayload[] = []; + const isGroup = groupId !== undefined; + for (const node of nodes) { + if (node.innerForward && node.innerForward.length > 0) { + const inner = await uploadForwardNodesRecursive(bridge, node.innerForward, groupId, userId); + // NapCat piggybacks `{uuid: inner.uuid, packetMsg: inner.packetMsg}` + // + the entire `inner.innerPacketMsg` array up to its caller. We + // mirror that — `inner.uuid` indexes the inner level itself, + // and `inner.innerActions` already contains deeper layers. + myInnerActions.push({ uuid: inner.uuid, msgBody: inner.msgBody }); + myInnerActions.push(...inner.innerActions); + // Replace the inner placeholder element with a forward preview + // pointing at the inner res_id. The wire-side element builder + // turns this into the same XML m_resid blob it already produced + // for top-level forwards — see `makeForwardElem` in + // element-builder.ts:153. + const previewElement: MessageElement = { + type: 'forward', + resId: inner.resId, + forwardSource: deriveInnerSource(node.innerForward, isGroup), + forwardSummary: `查看${node.innerForward.length}条转发消息`, + forwardPrompt: '[聊天记录]', + forwardNews: previewLinesFromNodes(node.innerForward), + forwardTSum: node.innerForward.length, + }; + processedNodes.push({ + userUin: node.userUin, + nickname: node.nickname, + elements: [previewElement], + time: node.time, + msgId: node.msgId, + msgSeq: node.msgSeq, + groupId: node.groupId, + senderCard: node.senderCard, + messageType: node.messageType, + }); + } else { + processedNodes.push(node); + } + } + + // Encode this level's msgBody. + const msgBody = await Promise.all(processedNodes.map( + node => buildForwardPushBody(bridge, node, groupId, userUid), + )); + + // Compose the action list: own MultiMsg + piggybacked inner actions. const longMsgResult = protobuf_encode({ action: [ - { - actionCommand: 'MultiMsg', - actionData: { msgBody }, - }, + { actionCommand: 'MultiMsg', actionData: { msgBody } }, + ...myInnerActions.map(a => ({ + actionCommand: a.uuid, + actionData: { msgBody: a.msgBody }, + })), ], }); @@ -137,7 +238,7 @@ export async function uploadForwardNodes( throw new Error('upload forward message response missing res_id'); } - forwardResCache.set(resId, nodes.map(node => ({ + forwardResCache.set(resId, processedNodes.map(node => ({ userUin: node.userUin, nickname: node.nickname, elements: [...node.elements], @@ -149,7 +250,53 @@ export async function uploadForwardNodes( messageType: node.messageType ?? (groupId ? 'group' : 'private'), }))); - return resId; + return { + resId, + msgBody, + uuid: randomUUID(), + innerActions: myInnerActions, + }; +} + +// Inner forward preview metadata — kept minimal here (the OneBot +// `parseForwardNodes` caller can override these on the top-level +// node by passing custom forwardSource/forwardSummary on the +// non-nested send path; nested levels just get sensible defaults +// since they're synthesised by us and never reach OneBot input). +function deriveInnerSource(innerNodes: ForwardNodePayload[], isGroup: boolean): string { + const nicks: string[] = []; + const seen = new Set(); + for (const node of innerNodes) { + const name = (node.nickname ?? '').trim(); + if (name && !seen.has(name)) { + seen.add(name); + nicks.push(name); + } + if (nicks.length >= 4) break; + } + if (nicks.length === 0) return isGroup ? '群聊的聊天记录' : '聊天记录'; + return `${nicks.join('和')}的聊天记录`; +} + +function previewLinesFromNodes(innerNodes: ForwardNodePayload[]): Array<{ text: string }> { + return innerNodes.slice(0, 4).map(node => { + const name = (node.nickname ?? '').trim() || String(node.userUin || 'QQ用户'); + const previewText = previewFromElements(node.elements); + return { text: previewText ? `${name}: ${previewText}` : name }; + }); +} + +function previewFromElements(elements: MessageElement[]): string { + for (const elem of elements) { + if (elem.type === 'text' && elem.text) return elem.text.slice(0, 30); + if (elem.type === 'image') return '[图片]'; + if (elem.type === 'record') return '[语音]'; + if (elem.type === 'video') return '[视频]'; + if (elem.type === 'file') return '[文件]'; + if (elem.type === 'forward') return '[聊天记录]'; + if (elem.type === 'face') return '[表情]'; + } + return ''; } export async function fetchForwardNodes(bridge: Bridge, resId: string): Promise { diff --git a/packages/core/src/bridge/events.ts b/packages/core/src/bridge/events.ts index e2665791..dcfe20ac 100644 --- a/packages/core/src/bridge/events.ts +++ b/packages/core/src/bridge/events.ts @@ -83,6 +83,18 @@ export interface ForwardNodePayload { groupId?: number; senderCard?: string; messageType?: 'group' | 'private'; + // When set, this node's `content` is a nested forward chain. The + // upload pipeline (see `actions/forward.ts::uploadForwardNodes`) + // recursively uploads the inner chain and replaces this node's + // `elements` with an ARK preview element pointing at the inner + // res_id. We also piggyback the inner chain's msgBody onto the + // outer long-msg upload as an extra `actionCommand` slot so the + // NapCat-compatible receiver can walk the whole tree from one + // server fetch without resolving each layer's res_id separately + // (modelled after `dev/NapCatQQ/.../SendMsg.uploadForwardedNodesPacket`). + // Caller never sets this on top-level OneBot input — `parseForward + // Nodes` synthesises it when it detects a nested-node array. + innerForward?: ForwardNodePayload[]; } export interface QQEvent { diff --git a/packages/core/src/onebot/modules/message-actions.ts b/packages/core/src/onebot/modules/message-actions.ts index a7b171a3..911b1bc7 100644 --- a/packages/core/src/onebot/modules/message-actions.ts +++ b/packages/core/src/onebot/modules/message-actions.ts @@ -635,34 +635,42 @@ async function parseForwardNodes( const content = (nodeData.content ?? nodeData.message ?? '') as JsonValue; let elements: MessageElement[]; + let innerForward: ForwardNodePayload[] | undefined; if (isNestedNodeArray(content)) { // Nested forward chain — `content` is itself a list of `{type:'node'}` - // segments. Recursively parse them into ForwardNodePayloads, upload - // that inner chain as its own forward, then embed an ARK preview - // card pointing at the inner res_id. The receiving QQ client renders - // it as a tap-to-expand nested forward bubble. Matches NapCat's - // `SendMsg.uploadForwardedNodesPacket` recursion contract. + // segments. We recursively parse them into a sibling + // `ForwardNodePayload[]` and attach it to this node as `innerForward`. + // `uploadForwardNodes` then drives the recursive upload + ARK-preview + // generation + msgBody piggyback in one pass over the whole tree. // - // Without this, the inner `{type:'node'}` entries fell through to - // `parseMessage` which produced useless `MessageElement{type:'node'}` - // entries that `element-builder` silently drops — leaving the outer - // forward with an empty body that QQ refuses with "message is empty" - // (single-node case) or a node whose content is missing the inner - // forward (mixed case). - const innerNodes = await parseForwardNodes(ref, content, { + // Why hand it off instead of uploading here: NapCat (`dev/NapCatQQ/ + // .../SendMsg.uploadForwardedNodesPacket`) carries every inner level's + // packetMsg up to the outermost long-msg upload as extra + // `actionCommand` slots, so the receiver gets the whole tree from one + // server fetch. That cross-layer piggyback needs the upload pipeline + // to own the recursion — doing it in `parseForwardNodes` would force + // each level to do its own independent long-msg upload, which is what + // the previous implementation did and what a NapCat-compatible + // receiver couldn't walk. + innerForward = await parseForwardNodes(ref, content, { groupId: options.groupId, userId: options.userId, depth: depth + 1, }); - const innerResId = await ref.bridge.uploadForwardNodes(innerNodes, options.groupId, options.userId); - const isGroup = options.groupId !== undefined; - elements = [buildForwardPreviewElement(innerResId, innerNodes, isGroup, undefined)]; + // Placeholder — `uploadForwardNodes` replaces these with a real + // forward-preview MessageElement once it has the inner res_id + + // uuid in hand. + elements = []; } else { elements = await parseMessage(content, false); } - if (elements.length === 0) throw new Error(`forward node content is empty: ${userUin}`); + if (!innerForward && elements.length === 0) { + throw new Error(`forward node content is empty: ${userUin}`); + } - nodes.push({ userUin, nickname, elements }); + const node: ForwardNodePayload = { userUin, nickname, elements }; + if (innerForward) node.innerForward = innerForward; + nodes.push(node); } if (nodes.length === 0) { diff --git a/packages/core/tests/actions/forward.test.ts b/packages/core/tests/actions/forward.test.ts index 2e63e515..8226118c 100644 --- a/packages/core/tests/actions/forward.test.ts +++ b/packages/core/tests/actions/forward.test.ts @@ -104,4 +104,50 @@ describe('actions/forward', () => { await expect(forward.fetchForwardNodes(bridge as any, 'cold-cache-miss')) .rejects.toThrow(/download forward message failed|down/); }); + + it('uploadForwardNodes recursively uploads nested innerForward chains (NapCat piggyback model)', async () => { + // Regression: nested forward needs the inner chain to be uploaded + // first (so we have its res_id for the outer ARK preview), AND + // the inner level's msgBody to be carried up to the outermost + // long-msg upload as an extra `actionCommand` slot keyed on a + // uuid. Matches `dev/NapCatQQ/.../SendMsg.uploadForwardedNodesPacket` + // — the receiver gets the whole tree from a single fetch instead + // of resolving each layer's res_id separately. + const responses = ['inner-res', 'outer-res']; + const sendRawPacket = vi.fn(async () => uploadResponseWithResId(responses.shift()!)) as any; + const bridge = mockBridge({ sendRawPacket }); + + const resId = await forward.uploadForwardNodes(bridge as any, [ + { + userUin: 111, + nickname: 'outer', + elements: [], + innerForward: [ + { userUin: 222, nickname: 'inner', elements: [{ type: 'text', text: 'hi' }] }, + ], + }, + ]); + + // Two server roundtrips: one for the inner chain, then one for + // the outer (which piggybacks the inner msgBody onto its actions + // array). The outer res_id is what the caller gets back. + expect(resId).toBe('outer-res'); + expect(sendRawPacket).toHaveBeenCalledTimes(2); + }); + + it('uploadForwardNodes leaves flat (non-nested) sends at a single roundtrip', async () => { + // Backwards-compat: the common case (no inner forward) must still + // be one SsoSendLongMsg call. Without this we'd double upload + // every regular forward send. + const sendRawPacket = vi.fn(async () => uploadResponseWithResId('flat-res')) as any; + const bridge = mockBridge({ sendRawPacket }); + + const resId = await forward.uploadForwardNodes(bridge as any, [ + { userUin: 10001, nickname: 'a', elements: [{ type: 'text', text: 'hello' }] }, + { userUin: 10002, nickname: 'b', elements: [{ type: 'text', text: 'world' }] }, + ]); + + expect(resId).toBe('flat-res'); + expect(sendRawPacket).toHaveBeenCalledOnce(); + }); }); diff --git a/packages/core/tests/onebot/forward-nested.test.ts b/packages/core/tests/onebot/forward-nested.test.ts index 9e5979fd..39863dd5 100644 --- a/packages/core/tests/onebot/forward-nested.test.ts +++ b/packages/core/tests/onebot/forward-nested.test.ts @@ -1,22 +1,17 @@ // Regression coverage for nested forward (forward-inside-forward). // -// Bug being pinned: when a custom forward node's `content` is itself -// a list of `{type:'node'}` entries (a forward chain inside a forward -// chain), the parser used to call `parseMessage(content, false)` -// which routes each inner node through `message-parser.ts:217 case -// 'node':`. That case JSON-stringifies `content` into the -// `resId` field of a `MessageElement{type:'node'}` placeholder — -// which `element-builder.buildSendElems` then silently drops at its -// default case. End result: the outer forward goes out with an empty -// (or text-only) body, the nested chain is lost. +// `parseForwardNodes` detects an all-`{type:'node'}` content array, +// recursively builds the inner `ForwardNodePayload[]`, and attaches it +// to the outer node as `innerForward`. `uploadForwardNodes` then drives +// the recursive long-msg upload + ARK-preview generation + msgBody +// piggyback in one pass over the tree — modelled on NapCat's +// `uploadForwardedNodesPacket` (`dev/NapCatQQ/.../SendMsg.ts:208`). // -// Fix:`parseForwardNodes` now detects an all-node content array, -// recursively builds the inner ForwardNodePayload[], uploads it as a -// separate forward to obtain a `res_id`, then embeds an ARK preview -// element (`{type:'forward', resId}`) in the outer node — which is -// exactly the shape `element-builder.makeForwardElem` already knows -// how to render. Matches NapCat's `uploadForwardedNodesPacket` -// recursion (capped at 3 levels deep). +// These tests stub `bridge.uploadForwardNodes` so we can inspect the +// payload that the upload pipeline receives: outer nodes carry an +// `innerForward` field holding the parsed inner chain, and the +// upload helper is invoked exactly ONCE (the recursive walk happens +// inside the real implementation; mocks see only the top call). import { describe, expect, it, vi } from 'vitest'; import type { BridgeInterface } from '../../src/bridge/bridge-interface'; @@ -47,22 +42,13 @@ function makeCtx(bridge: BridgeInterface): OneBotInstanceContext { } describe('forward — nested {type:"node"} content', () => { - it('group: nested forward uploads inner chain first, outer embeds ARK preview pointing at it', async () => { - const uploadForwardNodes = vi.fn(async (nodes: any[], _groupId?: number, _userId?: number) => { - // Inner gets uploaded before outer; track the order by inspecting - // the elements shape. The inner chain's payload is a plain text - // node; the outer chain's only element is a `forward` ARK preview - // referencing the inner res_id we returned just before. - const innerNode = nodes[0]; - const onlyElem = innerNode.elements[0]; - if (onlyElem.type === 'text' && onlyElem.text === 'hello from inner') { - return 'INNER_RESID'; - } - if (onlyElem.type === 'forward' && onlyElem.resId === 'INNER_RESID') { - return 'OUTER_RESID'; - } - throw new Error(`unexpected upload payload: ${JSON.stringify(nodes)}`); - }); + it('group: nested forward attaches inner chain to outer node via `innerForward`', async () => { + // Single upload call, but the outer payload now carries an + // `innerForward` field with the recursively-parsed inner chain. + // The real `uploadForwardNodes` (the production module) walks + // that tree and does the recursive long-msg uploads with NapCat + // piggyback — we're just testing the parse-side handoff here. + const uploadForwardNodes = vi.fn(async (_nodes: any[], _groupId?: number, _userId?: number) => 'OUTER_RESID'); const sendGroupMessage = vi.fn(async () => ({ messageId: 1, sequence: 100, clientSequence: 0, random: 1, timestamp: 1700000000, })); @@ -86,35 +72,34 @@ describe('forward — nested {type:"node"} content', () => { const result = await sendGroupForwardMessage(ctx, 12345, messages as any); - // Two uploads: inner first, then outer. - expect(uploadForwardNodes).toHaveBeenCalledTimes(2); + // Exactly one upload call: the production-side recursive walker + // owns the inner upload, the OneBot parser just hands off the tree. + expect(uploadForwardNodes).toHaveBeenCalledOnce(); - // Inner upload: nodes[0] is the leaf node, scoped to the outer group. - const [innerNodes, innerGroupId] = uploadForwardNodes.mock.calls[0]!; - expect(innerGroupId).toBe(12345); - expect((innerNodes as any[])[0]!.userUin).toBe(222); - expect((innerNodes as any[])[0]!.elements).toEqual([{ type: 'text', text: 'hello from inner' }]); - - // Outer upload: the wrapper node carries a single `forward` ARK - // preview element that points at the inner res_id we minted above. - const [outerNodes, outerGroupId] = uploadForwardNodes.mock.calls[1]!; + const [outerNodes, outerGroupId] = uploadForwardNodes.mock.calls[0]!; expect(outerGroupId).toBe(12345); - expect((outerNodes as any[])[0]!.userUin).toBe(111); - expect((outerNodes as any[])[0]!.elements).toHaveLength(1); - expect((outerNodes as any[])[0]!.elements[0]).toMatchObject({ - type: 'forward', - resId: 'INNER_RESID', + const outerNode = (outerNodes as any[])[0]!; + expect(outerNode.userUin).toBe(111); + // Outer node's `elements` is empty — the upload pipeline replaces + // it with the real ARK preview once it has the inner res_id. + expect(outerNode.elements).toEqual([]); + // The inner chain rides along as `innerForward`. + expect(Array.isArray(outerNode.innerForward)).toBe(true); + expect(outerNode.innerForward).toHaveLength(1); + expect(outerNode.innerForward[0]).toMatchObject({ + userUin: 222, + nickname: 'inner', + elements: [{ type: 'text', text: 'hello from inner' }], }); expect(result.forwardId).toBe('OUTER_RESID'); expect(sendGroupMessage).toHaveBeenCalledOnce(); }); - it('private: nested forward threads userId into inner uploadForwardNodes', async () => { + it('private: nested forward threads userId into uploadForwardNodes', async () => { // Same shape but routed via sendPrivateForwardMessage. The c2c path - // passes `userId` instead of `groupId` so any inner image/record - // uploads can pick up the recipient's UID scene (otherwise the - // OIDB private-media upload has no target uid). + // passes `userId` instead of `groupId` so the upload pipeline can + // pick up the recipient's UID scene for any inner media element. const uploadForwardNodes = vi.fn(async (_nodes: any[], _groupId?: number, _userId?: number) => 'RESID'); const sendPrivateMessage = vi.fn(async () => ({ messageId: 1, sequence: 100, clientSequence: 0, random: 1, timestamp: 1700000000, @@ -139,10 +124,15 @@ describe('forward — nested {type:"node"} content', () => { await sendPrivateForwardMessage(ctx, 67890, messages as any); - // Inner upload: groupId undefined, userId is the c2c recipient. - const innerCall = uploadForwardNodes.mock.calls[0]!; - expect(innerCall[1]).toBeUndefined(); - expect(innerCall[2]).toBe(67890); + // Single call, c2c-scoped (groupId undefined, userId = recipient). + expect(uploadForwardNodes).toHaveBeenCalledOnce(); + const call = uploadForwardNodes.mock.calls[0]!; + expect(call[1]).toBeUndefined(); + expect(call[2]).toBe(67890); + // Inner chain attached via `innerForward`. + const outerNode = (call[0] as any[])[0]!; + expect(outerNode.innerForward).toHaveLength(1); + expect(outerNode.innerForward[0]!.userUin).toBe(222); }); it('rejects nesting deeper than 3 levels', async () => { From f65fe959bb4f06eb0d67978eaa435c441ec7705a Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Tue, 19 May 2026 23:36:12 +0800 Subject: [PATCH 40/48] =?UTF-8?q?fix(send-private):=20split=20c2c=20file?= =?UTF-8?q?=20segments=20out=20to=20sendC2cFileMessage=20(was=20shipping?= =?UTF-8?q?=20"[=E7=A9=BA=E6=B6=88=E6=81=AF]")?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit User report: `send_private_msg` with a `{type:'file', file_id}` segment fired `[ElemBuilder] file send via elems[] is group-only; use bridge. sendC2cFileMessage for c2c` and the message went out as "[空消息]". Root cause: c2c files live on `RichText.notOnlineFile` (parallel to the elems array, see proto/proton/message.ts), not inside `elems[]`. The element-builder explicitly drops c2c `{type:'file'}` elements with a warning. `sendPrivateMessage` was passing the file straight to `bridge.sendPrivateMessage(userId, [fileElement])` which then ran through `buildSendElems`, lost the file at the drop, and shipped a 0-element wire send — rendered as "[空消息]" by every receiver. Fix: split at the OneBot layer in `sendPrivateMessage`. Pull file elements out of the batch and dispatch each via `bridge.sendC2cFileMessage`; route the rest through the regular elems[] path. Matches NapCat's `dev/NapCatQQ/.../SendMsg.ts:404-415` where FILE / VIDEO / ARK / PTT each get their own sendMsg call and never mix with the regular elems[] batch. - File-only message: only the c2c file API is called (single roundtrip) - Mixed text + file: two sends, text first then file - File without file_id: dropped with a warn (was silently shipping empty messages) - UID resolution failure: surfaced as throw instead of empty send Also rewrote the element-builder fallback warn from "use sendC2cFileMessage for c2c" (now stale advice) to "BUG: c2c file reached element-builder — should be split out at the OneBot layer". Tests: 4 new regression cases under `tests/onebot/send-private-c2c-file.test.ts`. 646/646 pass. --- packages/core/src/bridge/element-builder.ts | 13 +- .../src/onebot/modules/message-actions.ts | 59 ++++++- .../onebot/send-private-c2c-file.test.ts | 153 ++++++++++++++++++ 3 files changed, 214 insertions(+), 11 deletions(-) create mode 100644 packages/core/tests/onebot/send-private-c2c-file.test.ts diff --git a/packages/core/src/bridge/element-builder.ts b/packages/core/src/bridge/element-builder.ts index 367f881e..e51414a2 100644 --- a/packages/core/src/bridge/element-builder.ts +++ b/packages/core/src/bridge/element-builder.ts @@ -393,13 +393,18 @@ export async function buildSendElems(elements: MessageElement[], ctx?: SendConte case 'file': // The group `TransElem(24)` shape works for group chats only. - // C2C files live on `RichText.notOnlineFile` instead of in the - // elems array, so `sendPrivateMessage` short-circuits before it - // ever lands here — see `bridge.sendPrivateMessage`. + // C2C files live on `RichText.notOnlineFile` (parallel to elems, + // see proto/proton/message.ts:notOnlineFile) and are routed + // out at the OneBot layer in `sendPrivateMessage` — split off + // from elems[] and dispatched via `bridge.sendC2cFileMessage`. + // If a c2c file segment still reaches us here, the caller + // forgot to route — log loudly and drop, otherwise the message + // ships as "[空消息]" (only-file case) or quietly loses the + // file (mixed case). if (ctx?.groupId !== undefined) { result.push(makeGroupFileElem(elem)); } else { - console.warn('[ElemBuilder] file send via elems[] is group-only; use bridge.sendC2cFileMessage for c2c'); + console.warn('[ElemBuilder] BUG: c2c {type:"file"} reached element-builder — should be split out at the OneBot layer (see modules/message-actions.ts::sendPrivateMessage)'); } break; diff --git a/packages/core/src/onebot/modules/message-actions.ts b/packages/core/src/onebot/modules/message-actions.ts index 911b1bc7..a47a2ac2 100644 --- a/packages/core/src/onebot/modules/message-actions.ts +++ b/packages/core/src/onebot/modules/message-actions.ts @@ -136,19 +136,64 @@ export async function sendPrivateMessage( }); if (elements.length === 0) throw new Error('message is empty'); - const receipt = await ref.bridge.sendPrivateMessage(userId, elements); - const messageId = hashMessageIdInt32(receipt.sequence, userId, PRIVATE_MESSAGE_EVENT); + // C2C `{type:'file'}` segments can't ride on the elems[] pipeline — + // c2c files live on `RichText.notOnlineFile`, parallel to elems + // (see `proto/proton/message.ts:notOnlineFile`). The element-builder + // explicitly drops them with a warn ("file send via elems[] is + // group-only"), so a private message that bundled a file alongside + // anything else used to either ship as "[空消息]" (only-file case, + // 0 elements after drop) or silently lose the file (mixed case). + // + // NapCat splits the same way (`dev/NapCatQQ/.../SendMsg.ts:404-415`): + // FILE / VIDEO / ARK / PTT each go in their own sendMsg call, + // never mixed with the regular elements. We only need it for file + // here — video/ARK/ptt already go through commonElem so the + // element-builder handles them inline. + const fileElements = elements.filter(e => e.type === 'file' && e.fileId); + const nonFileElements = elements.filter(e => e.type !== 'file'); + if (fileElements.length !== elements.filter(e => e.type === 'file').length) { + log.warn('[OneBot] private file segment without file_id — skipped (upload first via upload_private_file)'); + } - logSentMessage(false, userId, elements); + let lastReceipt: Awaited> | undefined; + if (nonFileElements.length > 0) { + lastReceipt = await ref.bridge.sendPrivateMessage(userId, nonFileElements); + logSentMessage(false, userId, nonFileElements); + } + if (fileElements.length > 0) { + // C2C file send needs the recipient's UID — resolve once and reuse. + const userUid = await ref.bridge.resolveUserUid(userId); + if (!userUid) { + throw new Error(`c2c file send: could not resolve uid for user ${userId}`); + } + for (const fileEl of fileElements) { + const fileMd5 = fileEl.md5Hex + ? Buffer.from(fileEl.md5Hex, 'hex') + : new Uint8Array(0); + lastReceipt = await ref.bridge.sendC2cFileMessage(userId, userUid, { + fileId: fileEl.fileId!, + // Fall back to a generic name — the QQ server resolves the + // file by fileUuid, not name, so a missing name only affects + // the chat bubble display. + fileName: fileEl.fileName ?? 'file', + fileSize: fileEl.fileSize ?? 0, + fileMd5, + fileHash: fileEl.fileHash, + }); + logSentMessage(false, userId, [fileEl]); + } + } + if (!lastReceipt) throw new Error('message is empty'); + const messageId = hashMessageIdInt32(lastReceipt.sequence, userId, PRIVATE_MESSAGE_EVENT); ref.cacheMessageMeta(messageId, { isGroup: false, targetId: userId, - sequence: receipt.sequence, + sequence: lastReceipt.sequence, eventName: PRIVATE_MESSAGE_EVENT, - clientSequence: receipt.clientSequence, - random: receipt.random, - timestamp: receipt.timestamp, + clientSequence: lastReceipt.clientSequence, + random: lastReceipt.random, + timestamp: lastReceipt.timestamp, }); return { messageId }; diff --git a/packages/core/tests/onebot/send-private-c2c-file.test.ts b/packages/core/tests/onebot/send-private-c2c-file.test.ts new file mode 100644 index 00000000..c9c80ed8 --- /dev/null +++ b/packages/core/tests/onebot/send-private-c2c-file.test.ts @@ -0,0 +1,153 @@ +// Regression coverage for the c2c-file-in-send_private_msg bug. +// +// Symptom in the wild: bot called `send_private_msg` with a +// `{type:'file', file_id}` segment; the OneBot module passed it +// straight to `bridge.sendPrivateMessage(userId, [fileElement])`; +// `buildSendElems` warned ("file send via elems[] is group-only") +// and dropped it; the resulting wire send had 0 elems and the chat +// rendered "[空消息]". +// +// Fix: c2c file segments are split out at the OneBot layer in +// `sendPrivateMessage` and dispatched through `bridge.sendC2cFileMessage` +// (which writes `RichText.notOnlineFile`, the correct wire slot for +// c2c files). Matches NapCat's `SendMsg.ts:404-415` which splits +// FILE / VIDEO / ARK / PTT into their own sendMsg calls and never +// mixes them with the regular elems[] batch. + +import { describe, expect, it, vi } from 'vitest'; +import type { BridgeInterface } from '../../src/bridge/bridge-interface'; +import type { OneBotInstanceContext } from '../../src/onebot/instance-context'; +import { sendPrivateMessage } from '../../src/onebot/modules/message-actions'; + +function fakeBridge(overrides: Partial = {}): BridgeInterface { + return new Proxy(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`); + }, + }); +} + +function makeCtx(bridge: BridgeInterface): OneBotInstanceContext { + return { + uin: '10001', + bridge, + messageStore: { findEvent: () => null } as any, + cacheMessageMeta: vi.fn(), + mediaStore: {} as any, + musicSignUrl: '', + } as unknown as OneBotInstanceContext; +} + +const goodReceipt = { + messageId: 1, sequence: 100, clientSequence: 0, random: 1, timestamp: 1700000000, +}; + +describe('send_private_msg with {type:"file"} segment', () => { + it('file-only message routes through sendC2cFileMessage (not sendPrivateMessage)', async () => { + // Pure-file case — the elems[] path would have dropped this entirely + // and shipped "[空消息]". The c2c file route must take over. + const sendPrivateMessage_bridge = vi.fn(); + const sendC2cFileMessage = vi.fn(async () => goodReceipt); + const resolveUserUid = vi.fn(async () => 'u_peer'); + const bridge = fakeBridge({ + sendPrivateMessage: sendPrivateMessage_bridge, + sendC2cFileMessage, + resolveUserUid, + } as any); + const ctx = makeCtx(bridge); + + await sendPrivateMessage(ctx, 67890, [{ + type: 'file', + data: { file_id: 'uuid-abc', name: 'doc.txt', size: 123, md5: '00112233' }, + }] as any, false); + + expect(sendC2cFileMessage).toHaveBeenCalledOnce(); + expect(sendPrivateMessage_bridge).not.toHaveBeenCalled(); + + const [uin, uid, info] = sendC2cFileMessage.mock.calls[0]!; + expect(uin).toBe(67890); + expect(uid).toBe('u_peer'); + expect(info).toMatchObject({ + fileId: 'uuid-abc', + fileName: 'doc.txt', + fileSize: 123, + }); + // md5 decoded from hex (4 bytes for '00112233') + expect(info.fileMd5).toEqual(Buffer.from('00112233', 'hex')); + }); + + it('mixed file + text splits across two sends (text first, file second)', async () => { + const sendPrivateMessage_bridge = vi.fn(async () => goodReceipt); + const sendC2cFileMessage = vi.fn(async () => goodReceipt); + const resolveUserUid = vi.fn(async () => 'u_peer'); + const bridge = fakeBridge({ + sendPrivateMessage: sendPrivateMessage_bridge, + sendC2cFileMessage, + resolveUserUid, + } as any); + const ctx = makeCtx(bridge); + + await sendPrivateMessage(ctx, 67890, [ + { type: 'text', data: { text: 'here is the file:' } }, + { type: 'file', data: { file_id: 'uuid-xyz', name: 'pkg.zip' } }, + ] as any, false); + + expect(sendPrivateMessage_bridge).toHaveBeenCalledOnce(); + expect(sendC2cFileMessage).toHaveBeenCalledOnce(); + + // Text goes via the elems[] pipeline. + const [textUin, textElements] = sendPrivateMessage_bridge.mock.calls[0]!; + expect(textUin).toBe(67890); + expect(textElements).toEqual([{ type: 'text', text: 'here is the file:' }]); + + // File goes via the dedicated c2c-file API. + const [fileUin, fileUid, fileInfo] = sendC2cFileMessage.mock.calls[0]!; + expect(fileUin).toBe(67890); + expect(fileUid).toBe('u_peer'); + expect(fileInfo).toMatchObject({ fileId: 'uuid-xyz', fileName: 'pkg.zip' }); + }); + + it('file segment without file_id is skipped (with a warn-level log)', async () => { + // OneBot11 file segments are upload-by-reference — without a + // file_id there's nothing to send. Previously these slipped + // through to the elems[] path and shipped empty messages. + const sendPrivateMessage_bridge = vi.fn(async () => goodReceipt); + const sendC2cFileMessage = vi.fn(); + const bridge = fakeBridge({ + sendPrivateMessage: sendPrivateMessage_bridge, + sendC2cFileMessage, + resolveUserUid: vi.fn(), + } as any); + const ctx = makeCtx(bridge); + + await sendPrivateMessage(ctx, 67890, [ + { type: 'text', data: { text: 'with bad file segment' } }, + { type: 'file', data: {} }, // no file_id + ] as any, false); + + // Text still went out, file dropped (no c2c file call). + expect(sendPrivateMessage_bridge).toHaveBeenCalledOnce(); + expect(sendC2cFileMessage).not.toHaveBeenCalled(); + }); + + it('throws when uid cannot be resolved for a file-only message', async () => { + // C2C file send requires the recipient's UID for the RichText. + // notOnlineFile routing. If lookup fails we can't proceed — + // surfacing the error is better than shipping a c2c send with + // an empty uid. + const sendC2cFileMessage = vi.fn(); + const bridge = fakeBridge({ + sendPrivateMessage: vi.fn(), + sendC2cFileMessage, + resolveUserUid: vi.fn(async () => ''), // intentional empty + } as any); + const ctx = makeCtx(bridge); + + await expect(sendPrivateMessage(ctx, 67890, [ + { type: 'file', data: { file_id: 'uuid-orphan', name: 'x.txt' } }, + ] as any, false)).rejects.toThrow(/could not resolve uid/); + + expect(sendC2cFileMessage).not.toHaveBeenCalled(); + }); +}); From 1db287d8ccb723a2eae22ba3474a5fc96e5368d3 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Tue, 19 May 2026 23:45:40 +0800 Subject: [PATCH 41/48] fix(c2c-file): rewrite sendC2cFileMessage wire shape per Lagrange.Core V2 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The c2c file send path was wrong on three independent axes — every c2c file the bot tried to deliver was getting rejected by the QQ-NT server. Aligned to `dev/Lagrange.Core` (V2 branch) which is the only direct-protocol reference for c2c files; NapCat goes through QQ-NT IPC and never builds this packet itself. Three wire-shape fixes: 1. **Routing**: `routingHead.c2c { uin, uid }` → `routingHead.trans0x211 { ccCmd: 4, uid }`. RoutingHead field 15 is the c2c-file scene's slot. `MessagePacker.BuildPacketBase` makes this conditional on `chain.HasTypeOf()`: when a file is present, C2C goes nil and Trans0X211 carries the routing. 2. **File payload location**: `messageBody.richText.notOnlineFile {...}` → `messageBody.msgContent = serialize(FileExtra{file: NotOnlineFile})`. The server doesn't read c2c file metadata from `richText` at all — `MessageBody.cs:12` even has the comment "Offline file is now put here(?". Confirmed by `FileEntity.PackElement()` returning empty and `PackMessageContent()` returning the FileExtra wrapper. 3. **contentHead.c2cCmd**: `11` → `0` (default/omitted). `11` was a stale go-cqhttp value the QQ-NT server doesn't recognise on the c2c-file dispatcher. Lagrange leaves it at the C# default (0). Schema fixes (proton + legacy, both directions): - `RoutingHead` gains `trans0x211?: pb<15, RoutingTrans0x211>`. The new message has `toUin@1`, `ccCmd@2`, `uid@8`. - `SendMessageBody` gains `msgContent?: pb<2, bytes>` (the receive-side `MessageBody` already had it). - `FileExtraInfo` deleted — was wrong on every tag (fileSize=1, fileName=2, fileMd5=3, fileUuid=4, fileHash=5, none of which match the wire). `FileExtra { file: pb<1, NotOnlineFile> }` now wraps the same `NotOnlineFile` used on the receive path. This is why c2c file PUSHES were also silently failing the four-field truthy check in `extractMsgContent` — the schema couldn't decode anything. - `NotOnlineFile` gains the three intake-validator fields the server requires on send: `subcmd@9 = 1`, `dangerEvel@50 = 0`, `expireTime@55` = now+7d. Receive side (`rich-body-decoder.ts::extractMsgContent`): drop the "all four fields must be truthy" guard (it was a workaround for the broken schema) and accept any payload that decodes a fileUuid. Tests: - `bridge-private-routing.test.ts`: new regression that round-trips `sendC2cFileMessage` through `protoDecode` and asserts trans0x211 routing, msgContent FileExtra wrapper, NotOnlineFile field tags, c2cCmd=0. Catches each of the three wire-shape regressions independently. - `send-private-c2c-file.test.ts`: vi.fn arg signatures explicit for CI typecheck. 647/647 tests pass. --- packages/core/src/bridge/bridge.ts | 80 ++++++++++++++----- .../src/bridge/msg-push/rich-body-decoder.ts | 24 ++++-- packages/core/src/bridge/proto/action.ts | 20 ++++- packages/core/src/bridge/proto/message.ts | 37 +++++---- .../core/src/bridge/proto/proton/action.ts | 26 +++++- .../core/src/bridge/proto/proton/message.ts | 43 ++++++---- .../core/tests/bridge-private-routing.test.ts | 78 ++++++++++++++++++ .../onebot/send-private-c2c-file.test.ts | 8 +- 8 files changed, 248 insertions(+), 68 deletions(-) diff --git a/packages/core/src/bridge/bridge.ts b/packages/core/src/bridge/bridge.ts index aabd813f..3f3c59a3 100644 --- a/packages/core/src/bridge/bridge.ts +++ b/packages/core/src/bridge/bridge.ts @@ -17,6 +17,7 @@ import type { SendMessageRequest, SendMessageResponse, } from './proto/proton/action'; +import type { FileExtra } from './proto/proton/message'; // Delegated modules import { @@ -401,13 +402,27 @@ export class Bridge implements BridgeInterface { /** * Send a c2c file as a chat message. * - * Unlike images / videos / records that ride on `RichText.elems` as - * regular Elem entries, c2c files use `RichText.notOnlineFile` - * (parallel to `elems`, see `proto/proton/message.ts:75`). The - * receive-side decoder strips this back to a `{type:'file'}` segment - * in `rich-body-decoder.ts:425-433`. There's no Elem you can stuff - * into `buildSendElems` for this, so this helper short-circuits the - * normal send pipeline. + * The wire shape isn't the same as a regular c2c message — the c2c + * file path uses three slots that differ from a normal text/image + * send (verified against `dev/Lagrange.Core/.../MessagePacker.cs: + * BuildPacketBase` + `FileEntity.PackMessageContent`): + * + * 1. `routingHead.trans0x211 { ccCmd: 4, uid: peer }` instead of + * `routingHead.c2c { uin, uid }`. The server rejects c2c file + * messages routed through the regular c2c slot. + * 2. `messageBody.msgContent` carries the serialised + * `FileExtra { file: NotOnlineFile }` bytes. NOT + * `richText.notOnlineFile` — the receiver doesn't read that + * slot for file metadata. + * 3. `contentHead.c2cCmd` left at 0 (Lagrange's default). The + * previous `c2cCmd: 11` was a stale go-cqhttp value the QQ-NT + * server doesn't recognise. + * + * NotOnlineFile carries three required-on-send fields the receiver + * itself ignores but the server's intake validator checks: + * - `subcmd: 1` — c2c file send command code + * - `dangerEvel: 0` — virus-scan severity, always 0 client-side + * - `expireTime` — 7 days from now (Lagrange convention) */ async sendC2cFileMessage( userUin: number, @@ -417,38 +432,61 @@ export class Bridge implements BridgeInterface { const random = this.nextMessageRandom(); const clientSeq = this.nextClientSequence(); + const nowSec = Math.floor(Date.now() / 1000); + const sevenDaysSec = 7 * 24 * 60 * 60; + // Serialise `FileExtra { file: NotOnlineFile }` for `msgContent`. + // The NotOnlineFile field tags (1/3/4/5/6/9/50/55/57) are shared + // between send and receive — the schema is symmetric. + const fileExtraBytes = protobuf_encode({ + file: { + fileType: 0, + fileUuid: info.fileId, + fileMd5: info.fileMd5, + fileName: info.fileName, + fileSize: BigInt(info.fileSize), + subcmd: 1, + dangerEvel: 0, + expireTime: nowSec + sevenDaysSec, + fileHash: info.fileHash ?? '', + }, + }); + const request = protobuf_encode({ routingHead: { - c2c: { uin: userUin, uid: userUid }, + // c2c-file scene: route through `trans0x211` (field 15) with + // ccCmd=4. The regular `c2c { uin, uid }` routing slot causes + // the server to reject this with a routing-mismatch error. + trans0x211: { ccCmd: 4, uid: userUid }, }, contentHead: { type: 1, subType: 0, - c2cCmd: 11, + // c2cCmd intentionally omitted (defaults to 0). Was `11`, + // which produced an unknown-command error in the QQ-NT + // server's c2c file handler. `userUin` is unused on this path + // (routing carries the uid only) but kept in the function + // signature for symmetry with the OneBot caller. }, messageBody: { - richText: { - notOnlineFile: { - fileType: 0, - fileUuid: info.fileId, - fileMd5: info.fileMd5, - fileName: info.fileName, - fileSize: BigInt(info.fileSize), - fileHash: info.fileHash ?? '', - }, - }, - } as any, + // No elems — the file metadata lives in msgContent below. + msgContent: fileExtraBytes, + }, clientSequence: clientSeq, random, syncCookie: new Uint8Array(0), via: 0, dataStatist: 0, ctrl: { - msgFlag: Math.floor(Date.now() / 1000), + msgFlag: nowSec, }, multiSendSeq: 0, }); + // Silence the unused-parameter lint — `userUin` is part of our + // BridgeInterface contract (the OneBot layer threads it through) + // but the wire shape only needs the uid. + void userUin; + const result = await this.sendRawPacket(Bridge.SEND_MSG_CMD, request); if (!result.success || !result.gotResponse || !result.responseData) { throw new Error(`send c2c file message failed: ${result.errorMessage || 'no response'}`); diff --git a/packages/core/src/bridge/msg-push/rich-body-decoder.ts b/packages/core/src/bridge/msg-push/rich-body-decoder.ts index 118a26b4..c980d23b 100644 --- a/packages/core/src/bridge/msg-push/rich-body-decoder.ts +++ b/packages/core/src/bridge/msg-push/rich-body-decoder.ts @@ -434,14 +434,24 @@ function extractRichtextExtras( } function extractMsgContent(msgContent: Uint8Array, elements: MessageElement[]): void { + // `MessageBody.msgContent` is where the QQ-NT server actually puts + // c2c file metadata — serialised `FileExtra { file: NotOnlineFile }` + // bytes. The previous schema (`FileExtraInfoSchema` with fileSize=1/ + // fileName=2/fileMd5=3/fileUuid=4/fileHash=5) didn't match the wire + // shape — every field landed at the wrong tag, so the four-field + // truthiness check below filtered out every real c2c file push as + // "incomplete metadata". After consolidating FileExtra to wrap + // `NotOnlineFile` (Lagrange.Core's `FileExtra { File: NotOnlineFile }`), + // this reads the right tags. const extra = protoDecode(msgContent, FileExtraSchema); if (!extra?.file) return; const f = extra.file; - if (f.fileSize !== undefined && f.fileName && f.fileMd5 && f.fileUuid && f.fileHash) { - elements.push({ - type: 'file', fileName: f.fileName, fileId: f.fileUuid, - fileSize: f.fileSize !== undefined ? Number(f.fileSize) : 0, - fileHash: f.fileHash, - }); - } + if (!f.fileUuid) return; + elements.push({ + type: 'file', + fileId: f.fileUuid, + fileName: f.fileName ?? '', + fileSize: f.fileSize !== undefined ? Number(f.fileSize) : 0, + fileHash: f.fileHash ?? '', + }); } diff --git a/packages/core/src/bridge/proto/action.ts b/packages/core/src/bridge/proto/action.ts index 7974c008..bf56540e 100644 --- a/packages/core/src/bridge/proto/action.ts +++ b/packages/core/src/bridge/proto/action.ts @@ -15,9 +15,20 @@ export const RoutingGroupSchema = { groupCode: { field: 1, type: 'uint64' as const }, } satisfies ProtoSchema; +// `Trans0x211` is the c2c-file scene's routing header (Lagrange.Core +// `Routing/Trans0X211.cs`). See proton/action.ts:RoutingTrans0x211 +// for the rationale — c2c file sends *must* route through this slot, +// not `c2c`, or the server rejects them. +export const RoutingTrans0x211Schema = { + toUin: { field: 1, type: 'uint64' as const }, + ccCmd: { field: 2, type: 'uint32' as const }, + uid: { field: 8, type: 'string' as const }, +} satisfies ProtoSchema; + export const RoutingHeadSchema = { - c2c: { field: 1, type: 'message' as const, schema: RoutingC2CSchema }, - grp: { field: 2, type: 'message' as const, schema: RoutingGroupSchema }, + c2c: { field: 1, type: 'message' as const, schema: RoutingC2CSchema }, + grp: { field: 2, type: 'message' as const, schema: RoutingGroupSchema }, + trans0x211: { field: 15, type: 'message' as const, schema: RoutingTrans0x211Schema }, } satisfies ProtoSchema; // --- Content Head (for send) --- @@ -43,7 +54,10 @@ export const SendRichTextSchema = { // --- MessageBody (for send) --- export const SendMessageBodySchema = { - richText: { field: 1, type: 'message' as const, schema: SendRichTextSchema }, + richText: { field: 1, type: 'message' as const, schema: SendRichTextSchema }, + // C2C file payload — serialised `FileExtra { file: NotOnlineFile }` + // bytes. See proton/action.ts:SendMessageBody for the WHY. + msgContent: { field: 2, type: 'bytes' as const }, } satisfies ProtoSchema; // --- SendMessageRequest --- diff --git a/packages/core/src/bridge/proto/message.ts b/packages/core/src/bridge/proto/message.ts index e8f0f345..6b51a157 100644 --- a/packages/core/src/bridge/proto/message.ts +++ b/packages/core/src/bridge/proto/message.ts @@ -59,13 +59,20 @@ export const PttSchema = { // --- NotOnlineFile (C2C file) --- +// Field numbers per `dev/Lagrange.Core/.../Component/NotOnlineFile.cs`. +// fields 9 (subcmd), 50 (dangerEvel), 55 (expireTime) are required +// on c2c file SEND (the receiver ignores them); the identification +// fields (1/3/4/5/6/57) are read both directions. export const NotOnlineFileSchema = { - fileType: { field: 1, type: 'uint32' as const }, - fileUuid: { field: 3, type: 'string' as const }, - fileMd5: { field: 4, type: 'bytes' as const }, - fileName: { field: 5, type: 'string' as const }, - fileSize: { field: 6, type: 'uint64' as const }, - fileHash: { field: 57, type: 'string' as const }, + fileType: { field: 1, type: 'uint32' as const }, + fileUuid: { field: 3, type: 'string' as const }, + fileMd5: { field: 4, type: 'bytes' as const }, + fileName: { field: 5, type: 'string' as const }, + fileSize: { field: 6, type: 'uint64' as const }, + subcmd: { field: 9, type: 'uint32' as const }, + dangerEvel: { field: 50, type: 'uint32' as const }, + expireTime: { field: 55, type: 'uint32' as const }, + fileHash: { field: 57, type: 'string' as const }, } satisfies ProtoSchema; // --- RichText --- @@ -84,17 +91,17 @@ export const MessageBodySchema = { } satisfies ProtoSchema; // --- FileExtra (for C2C file in msg_content) --- - -export const FileExtraInfoSchema = { - fileSize: { field: 1, type: 'uint64' as const }, - fileName: { field: 2, type: 'string' as const }, - fileMd5: { field: 3, type: 'bytes' as const }, - fileUuid: { field: 4, type: 'string' as const }, - fileHash: { field: 5, type: 'string' as const }, -} satisfies ProtoSchema; +// +// `FileExtra { file: NotOnlineFile }` is the wrapper QQ-NT actually +// uses at `MessageBody.msgContent` for c2c file sends. The previous +// `FileExtraInfoSchema` had fileSize=1, fileName=2, fileMd5=3, +// fileUuid=4, fileHash=5 — every field at the wrong tag, so received +// c2c-file payloads silently failed to parse. Consolidated to the +// shared `NotOnlineFileSchema` (Lagrange.Core's `FileExtra.cs` does +// the same — `[ProtoMember(1)] public NotOnlineFile? File`). export const FileExtraSchema = { - file: { field: 1, type: 'message' as const, schema: FileExtraInfoSchema }, + file: { field: 1, type: 'message' as const, schema: NotOnlineFileSchema }, } satisfies ProtoSchema; // --- PushMsgBody --- diff --git a/packages/core/src/bridge/proto/proton/action.ts b/packages/core/src/bridge/proto/proton/action.ts index b500f60e..0a44d8b8 100644 --- a/packages/core/src/bridge/proto/proton/action.ts +++ b/packages/core/src/bridge/proto/proton/action.ts @@ -15,9 +15,24 @@ export interface RoutingGroup { groupCode?: pb<1, uint_64>; } +// `Trans0x211` is the c2c-file scene's routing header. The server +// rejects c2c file messages routed through `RoutingC2C` — instead it +// expects `trans0x211 { ccCmd: 4, uid: }`. Confirmed against +// `dev/Lagrange.Core/Lagrange.Core/Internal/Packets/Message/ +// Routing/Trans0X211.cs` + `RoutingHead.cs` (Trans0X211 sits at +// field 15) + `MessagePacker.BuildPacketBase` (`Trans0X211 = +// !chain.HasTypeOf() ? null : new Trans0X211 { CcCmd = 4, +// Uid = chain.Uid }`). +export interface RoutingTrans0x211 { + toUin?: pb<1, uint_64>; + ccCmd?: pb<2, uint_32>; + uid?: pb<8, string>; +} + export interface RoutingHead { - c2c?: pb<1, RoutingC2C>; - grp?: pb<2, RoutingGroup>; + c2c?: pb<1, RoutingC2C>; + grp?: pb<2, RoutingGroup>; + trans0x211?: pb<15, RoutingTrans0x211>; } // ── Content Head (for send) ───────────────────────────────────────── @@ -43,7 +58,12 @@ export interface SendRichText { // ── MessageBody (for send) ────────────────────────────────────────── export interface SendMessageBody { - richText?: pb<1, SendRichText>; + richText?: pb<1, SendRichText>; + // C2C file payload — serialised `FileExtra { file: NotOnlineFile }` + // bytes. The server reads c2c file metadata from this slot, NOT + // from `richText.notOnlineFile`. Confirmed against `dev/Lagrange.Core/ + // .../MessageBody.cs:12` (commented "Offline file is now put here"). + msgContent?: pb<2, bytes>; } // ── SendMessageRequest ────────────────────────────────────────────── diff --git a/packages/core/src/bridge/proto/proton/message.ts b/packages/core/src/bridge/proto/proton/message.ts index 1727c90a..8f31ab6b 100644 --- a/packages/core/src/bridge/proto/proton/message.ts +++ b/packages/core/src/bridge/proto/proton/message.ts @@ -58,14 +58,24 @@ export interface Ptt { } // ── NotOnlineFile (C2C file) ──────────────────────────────────────── +// +// Field numbers cross-checked against `dev/Lagrange.Core/.../Component/ +// NotOnlineFile.cs`. This same shape is what gets serialised inside +// `FileExtra` (below) and ridden as `MessageBody.msgContent` for c2c +// file sends — fields 9/50/55 are required on send (subcmd=1, +// dangerEvel=0, expireTime=now+7d), the receiver only reads the +// identification slots. export interface NotOnlineFile { - fileType?: pb<1, uint_32>; - fileUuid?: pb<3, string>; - fileMd5?: pb<4, bytes>; - fileName?: pb<5, string>; - fileSize?: pb<6, uint_64>; - fileHash?: pb<57, string>; + fileType?: pb<1, uint_32>; + fileUuid?: pb<3, string>; + fileMd5?: pb<4, bytes>; + fileName?: pb<5, string>; + fileSize?: pb<6, uint_64>; + subcmd?: pb<9, uint_32>; + dangerEvel?: pb<50, uint_32>; + expireTime?: pb<55, uint_32>; + fileHash?: pb<57, string>; } // ── RichText ──────────────────────────────────────────────────────── @@ -84,17 +94,20 @@ export interface MessageBody { } // ── FileExtra (for C2C file in msg_content) ───────────────────────── - -export interface FileExtraInfo { - fileSize?: pb<1, uint_64>; - fileName?: pb<2, string>; - fileMd5?: pb<3, bytes>; - fileUuid?: pb<4, string>; - fileHash?: pb<5, string>; -} +// +// `FileExtra { file: NotOnlineFile }` is the wrapper the server expects +// at `MessageBody.msgContent` (per `dev/Lagrange.Core/.../FileExtra.cs`). +// Old code had a parallel `FileExtraInfo` with fileSize=1, fileName=2, +// fileMd5=3, fileUuid=4, fileHash=5 — that schema didn't match the +// wire shape at all (every field was at the wrong tag), which is why +// c2c file messages we received via msgContent silently failed to +// parse, and c2c file messages we sent through `richText.notOnlineFile` +// (also wrong — see SendMessageBody) shipped a payload the recipient +// couldn't render. Consolidating to a single shared `NotOnlineFile` +// (identification fields 1/3/4/5/6/57) fixes both directions. export interface FileExtra { - file?: pb<1, FileExtraInfo>; + file?: pb<1, NotOnlineFile>; } // ── PushMsgBody ───────────────────────────────────────────────────── diff --git a/packages/core/tests/bridge-private-routing.test.ts b/packages/core/tests/bridge-private-routing.test.ts index 5c93e761..443ce172 100644 --- a/packages/core/tests/bridge-private-routing.test.ts +++ b/packages/core/tests/bridge-private-routing.test.ts @@ -2,6 +2,7 @@ import { describe, expect, it, vi } from 'vitest'; import type { SendPacketResult } from '../src/protocol/packet-sender'; import { protoDecode, protoEncode } from '../src/protobuf/decode'; import { SendMessageRequestSchema, SendMessageResponseSchema } from '../src/bridge/proto/action'; +import { FileExtraSchema } from '../src/bridge/proto/message'; vi.mock('../src/bridge/element-builder', () => ({ buildSendElems: vi.fn(async () => [{ text: { str: 'stub media elem' } }]), @@ -47,4 +48,81 @@ describe('Bridge private media routing', () => { uid: 'u_peer_12345', }); }); + + it('sendC2cFileMessage uses trans0x211 routing + msgContent FileExtra (NOT richText.notOnlineFile)', async () => { + // Regression: c2c file messages route through `trans0x211 { ccCmd: + // 4, uid }` (RoutingHead field 15), not `c2c { uin, uid }`. The + // file metadata lives in `MessageBody.msgContent` (a serialised + // `FileExtra { file: NotOnlineFile }`), not in `richText.notOnlineFile`. + // Confirmed against `dev/Lagrange.Core/.../MessagePacker.cs: + // BuildPacketBase` + `FileEntity.PackMessageContent`. Previous + // implementation wrote c2c routing + richText.notOnlineFile + + // c2cCmd=11 — the QQ-NT server rejected every c2c file send. + const { Bridge } = await import('../src/bridge/bridge'); + const { IdentityService } = await import('../src/bridge/identity-service'); + + class TestBridge extends Bridge { + capturedBody: Uint8Array | null = null; + override async sendRawPacket(_cmd: string, body: Uint8Array): Promise { + this.capturedBody = body; + return { + success: true, gotResponse: true, errorCode: 0, errorMessage: '', + responseData: Buffer.from(protoEncode({ + result: 0, privateSequence: 88, timestamp1: 1710000000, + }, SendMessageResponseSchema)), + }; + } + } + const bridge = new TestBridge(IdentityService.memory('10000')); + + const fileMd5 = new Uint8Array([0xde, 0xad, 0xbe, 0xef]); + await bridge.sendC2cFileMessage(67890, 'u_peer_xyz', { + fileId: 'uuid-abc-123', + fileName: 'doc.txt', + fileSize: 1024, + fileMd5, + fileHash: 'hash-xyz', + }); + + const request = protoDecode(bridge.capturedBody as Uint8Array, SendMessageRequestSchema); + + // Routing: must be trans0x211 with ccCmd=4 + uid, no c2c slot. + expect(request?.routingHead?.trans0x211).toMatchObject({ + ccCmd: 4, + uid: 'u_peer_xyz', + }); + expect(request?.routingHead?.c2c).toBeUndefined(); + + // Body: msgContent carries the FileExtra; richText is absent (no + // elems, no notOnlineFile slot — both lived on the wrong place). + expect(request?.messageBody?.msgContent).toBeInstanceOf(Uint8Array); + expect(request?.messageBody?.richText).toBeUndefined(); + + // Decode the msgContent and verify the NotOnlineFile fields land + // at the correct tags (Lagrange's NotOnlineFile schema, not the + // dead FileExtraInfo one). + const fileExtra = protoDecode( + request!.messageBody!.msgContent as Uint8Array, + FileExtraSchema, + ); + expect(fileExtra?.file).toMatchObject({ + fileUuid: 'uuid-abc-123', + fileName: 'doc.txt', + fileSize: 1024n, + fileHash: 'hash-xyz', + subcmd: 1, // server-required intake validator field + // dangerEvel and fileType are 0 — proto3 omits zero values on + // the wire, so they're not asserted here (matches Lagrange's + // behaviour: it sets `DangerEvel = 0` but protobuf-net also + // skips serialising default ints). + }); + expect(fileExtra?.file?.fileMd5).toEqual(fileMd5); + // expireTime is now+7d; just sanity-check it landed (non-zero, plausible) + expect(fileExtra?.file?.expireTime).toBeGreaterThan(Math.floor(Date.now() / 1000)); + + // c2cCmd is left at 0 / undefined — the old `c2cCmd=11` was a + // stale go-cqhttp value the QQ-NT server doesn't recognise on the + // c2c-file path. + expect(request?.contentHead?.c2cCmd ?? 0).toBe(0); + }); }); diff --git a/packages/core/tests/onebot/send-private-c2c-file.test.ts b/packages/core/tests/onebot/send-private-c2c-file.test.ts index c9c80ed8..4b46d6b6 100644 --- a/packages/core/tests/onebot/send-private-c2c-file.test.ts +++ b/packages/core/tests/onebot/send-private-c2c-file.test.ts @@ -48,7 +48,7 @@ describe('send_private_msg with {type:"file"} segment', () => { // Pure-file case — the elems[] path would have dropped this entirely // and shipped "[空消息]". The c2c file route must take over. const sendPrivateMessage_bridge = vi.fn(); - const sendC2cFileMessage = vi.fn(async () => goodReceipt); + const sendC2cFileMessage = vi.fn(async (_uin: number, _uid: string, _info: any) => goodReceipt); const resolveUserUid = vi.fn(async () => 'u_peer'); const bridge = fakeBridge({ sendPrivateMessage: sendPrivateMessage_bridge, @@ -78,8 +78,8 @@ describe('send_private_msg with {type:"file"} segment', () => { }); it('mixed file + text splits across two sends (text first, file second)', async () => { - const sendPrivateMessage_bridge = vi.fn(async () => goodReceipt); - const sendC2cFileMessage = vi.fn(async () => goodReceipt); + const sendPrivateMessage_bridge = vi.fn(async (_uin: number, _elements: any[]) => goodReceipt); + const sendC2cFileMessage = vi.fn(async (_uin: number, _uid: string, _info: any) => goodReceipt); const resolveUserUid = vi.fn(async () => 'u_peer'); const bridge = fakeBridge({ sendPrivateMessage: sendPrivateMessage_bridge, @@ -112,7 +112,7 @@ describe('send_private_msg with {type:"file"} segment', () => { // OneBot11 file segments are upload-by-reference — without a // file_id there's nothing to send. Previously these slipped // through to the elems[] path and shipped empty messages. - const sendPrivateMessage_bridge = vi.fn(async () => goodReceipt); + const sendPrivateMessage_bridge = vi.fn(async (_uin: number, _elements: any[]) => goodReceipt); const sendC2cFileMessage = vi.fn(); const bridge = fakeBridge({ sendPrivateMessage: sendPrivateMessage_bridge, From 312df29b5faa0a961a280c48f5e92b854af0adb4 Mon Sep 17 00:00:00 2001 From: H3CoF6 <1707889225@qq.com> Date: Wed, 20 May 2026 10:29:41 +0800 Subject: [PATCH 42/48] =?UTF-8?q?feat:=20=E6=B7=BB=E5=8A=A0=E6=B3=A8?= =?UTF-8?q?=E5=85=A5=E5=89=8D=E6=8E=A2=E6=B5=8B=20QQ=20=E7=99=BB=E5=BD=95?= =?UTF-8?q?=E7=8A=B6=E6=80=81=E5=8A=9F=E8=83=BD=20(#56)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 通过扫描 QQ 进程开放的 9210-9219 端口,在注入 DLL 前即可获取登录状态和账号信息。 - 新增端口探测模块 (qq-port-probe.ts) - 前端添加"探测登录"按钮和状态显示对话框 - 兼容 Windows 和 Linux 平台 - 修复端口查询逻辑,正确识别每个 PID 开放的端口 Co-authored-by: Claude Sonnet 4.6 --- .gitignore | 1 + packages/core/src/hook/hook-manager.ts | 7 + packages/core/src/hook/qq-port-probe.ts | 168 ++++++++++++++++++ packages/core/src/webui/server.ts | 15 ++ .../src/components/pages/overview-page.tsx | 20 +++ .../src/components/process-probe-dialog.tsx | 140 +++++++++++++++ packages/webui/src/lib/api/client.ts | 1 + packages/webui/src/lib/api/types.ts | 1 + 8 files changed, 353 insertions(+) create mode 100644 packages/core/src/hook/qq-port-probe.ts create mode 100644 packages/webui/src/components/process-probe-dialog.tsx diff --git a/.gitignore b/.gitignore index d72959a4..0e235bec 100644 --- a/.gitignore +++ b/.gitignore @@ -11,6 +11,7 @@ dist/ /config/ /data/ +logs/ # macOS metadata .DS_Store diff --git a/packages/core/src/hook/hook-manager.ts b/packages/core/src/hook/hook-manager.ts index b03a07b3..18728c54 100644 --- a/packages/core/src/hook/hook-manager.ts +++ b/packages/core/src/hook/hook-manager.ts @@ -12,9 +12,11 @@ import { HookSession, type HookSessionDeps } from './hook-session'; import { PipeWatcher } from './pipe-watcher'; import { QqHookClient } from './qq-hook-client'; import type { HookProcessInfo } from './types'; +import { probeQqLoginInfo, type QqPortLoginInfo } from './qq-port-probe'; export type { HookProcessInfo, HookProcessStatus } from './types'; export type { HookProcessBaseInfo } from './injector'; +export type { QqPortLoginInfo } from './qq-port-probe'; export type HookManagerDeps = { bridgeManager: BridgeManager; @@ -147,6 +149,11 @@ export class HookManager { return session.refresh(); } + async probeProcessLoginInfo(pid: number): Promise { + this.assertValidPid(pid); + return probeQqLoginInfo(pid); + } + dispose(): void { if (this.disposed) return; this.disposed = true; diff --git a/packages/core/src/hook/qq-port-probe.ts b/packages/core/src/hook/qq-port-probe.ts new file mode 100644 index 00000000..b9bde522 --- /dev/null +++ b/packages/core/src/hook/qq-port-probe.ts @@ -0,0 +1,168 @@ +import net from 'net'; +import { exec } from 'child_process'; +import { promisify } from 'util'; + +const execAsync = promisify(exec); + +const PORT_RANGE_START = 9210; +const PORT_RANGE_END = 9219; +const PROBE_TIMEOUT_MS = 1000; +const CONNECTION_TIMEOUT_MS = 500; + +export interface QqPortLoginInfo { + port: number; + uin: string; + uid?: string; + nickName?: string; + loggedIn: boolean; +} + +interface JwtPayload { + errCode: number; + errMsg: string; + port: number; + uin?: string; + uid?: string; + nickName?: string; + data?: { + uin?: string; + url?: string; + }; + iat: number; +} + +function decodeJwt(token: string): JwtPayload | null { + try { + const parts = token.split('.'); + if (parts.length !== 3) return null; + const payload = Buffer.from(parts[1], 'base64').toString('utf8'); + return JSON.parse(payload); + } catch { + return null; + } +} + +async function probePort(port: number): Promise { + return new Promise((resolve) => { + const client = new net.Socket(); + const link = 'tencent://'; + const payload = `POST /tencent HTTP/1.1\r\nHost: 127.0.0.1:${port}\r\nConnection: close\r\nContent-Length: ${link.length}\r\n\r\n${link}`; + + let responseData = ''; + let timer: NodeJS.Timeout; + + const cleanup = () => { + clearTimeout(timer); + client.removeAllListeners(); + client.destroy(); + }; + + timer = setTimeout(() => { + cleanup(); + resolve(null); + }, PROBE_TIMEOUT_MS); + + client.setTimeout(CONNECTION_TIMEOUT_MS); + + client.connect(port, '127.0.0.1', () => { + client.write(payload); + }); + + client.on('data', (data) => { + responseData += data.toString(); + }); + + client.on('close', () => { + cleanup(); + const jwtMatch = responseData.match(/eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/); + if (!jwtMatch) { + resolve(null); + return; + } + + const decoded = decodeJwt(jwtMatch[0]); + if (!decoded || decoded.errCode !== 0) { + resolve(null); + return; + } + + const uin = decoded.uin || decoded.data?.uin || ''; + resolve({ + port, + uin, + uid: decoded.uid, + nickName: decoded.nickName, + loggedIn: uin.length > 0, + }); + }); + + client.on('error', () => { + cleanup(); + resolve(null); + }); + + client.on('timeout', () => { + cleanup(); + resolve(null); + }); + }); +} + +async function getProcessPorts(pid: number): Promise { + try { + if (process.platform === 'win32') { + const { stdout } = await execAsync(`netstat -ano | findstr ${pid}`); + const ports = new Set(); + const lines = stdout.split('\n'); + for (const line of lines) { + const parts = line.trim().split(/\s+/); + if (parts.length < 5) continue; + const owningPid = parts[parts.length - 1]; + if (owningPid !== String(pid)) continue; + const localAddr = parts[1]; + const portMatch = localAddr.match(/:(\d+)$/); + if (!portMatch) continue; + const port = Number(portMatch[1]); + if (port >= PORT_RANGE_START && port <= PORT_RANGE_END) { + ports.add(port); + } + } + return Array.from(ports); + } else { + const { stdout } = await execAsync(`ss -tlnp | grep pid=${pid}`); + const ports = new Set(); + const lines = stdout.split('\n'); + for (const line of lines) { + const match = line.match(/:(\d+)\s/); + if (match) { + const port = Number(match[1]); + if (port >= PORT_RANGE_START && port <= PORT_RANGE_END) { + ports.add(port); + } + } + } + return Array.from(ports); + } + } catch { + return []; + } +} + +export async function probeQqLoginInfo(pid: number): Promise { + const ports = await getProcessPorts(pid); + + if (ports.length === 0) { + for (let port = PORT_RANGE_START; port <= PORT_RANGE_END; port++) { + const info = await probePort(port); + if (info) return info; + } + return null; + } + + for (const port of ports) { + const info = await probePort(port); + if (info) return info; + } + + return null; +} diff --git a/packages/core/src/webui/server.ts b/packages/core/src/webui/server.ts index 1848eb0a..87cfa31d 100644 --- a/packages/core/src/webui/server.ts +++ b/packages/core/src/webui/server.ts @@ -450,6 +450,21 @@ export async function initWebUI( app.post('/api/processes/:pid/unload', processAction('unload', (pid) => hookManager!.unloadProcess(pid))); app.post('/api/processes/:pid/refresh', processAction('refresh', (pid) => hookManager!.refreshProcess(pid))); + app.get('/api/processes/:pid/probe-login', async (c) => { + if (!hookManager) return c.json({ info: null, message: 'hook manager is not available' }, 503); + const pid = Number(c.req.param('pid')); + if (!Number.isInteger(pid) || pid <= 0 || pid > MAX_PID) { + return c.json({ info: null, message: 'invalid pid' }, 400); + } + try { + const info = await hookManager.probeProcessLoginInfo(pid); + return c.json({ info }); + } catch (err) { + log.warn('probe-login pid=%d failed: %s', pid, err instanceof Error ? err.message : String(err)); + return c.json({ info: null, message: '探测失败' }, 500); + } + }); + app.get('/api/config/:uin', (c) => { const uin = c.req.param('uin'); if (!UIN_REGEX.test(uin)) return c.json({ message: 'invalid uin' }, 400); diff --git a/packages/webui/src/components/pages/overview-page.tsx b/packages/webui/src/components/pages/overview-page.tsx index 54b8e2cc..096d1db2 100644 --- a/packages/webui/src/components/pages/overview-page.tsx +++ b/packages/webui/src/components/pages/overview-page.tsx @@ -5,6 +5,7 @@ import { AlertCircle, CheckCircle2, Cpu, + Eye, Loader2, MemoryStick, MonitorCog, @@ -21,6 +22,7 @@ import { ScrollArea } from '@/components/ui/scroll-area'; import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'; import { Skeleton } from '@/components/ui/skeleton'; import { ConfirmDialog } from '@/components/confirm-dialog'; +import { ProcessProbeDialog } from '@/components/process-probe-dialog'; import { cn, formatBytes, formatUptime } from '@/lib/utils'; import type { HookProcessInfo } from '@/types'; import { useAppState } from '@/contexts/AppStateContext'; @@ -91,6 +93,7 @@ export function OverviewPage() { | { kind: 'load' | 'unload'; pid: number; name: string } | null >(null); + const [probeDialog, setProbeDialog] = useState<{ pid: number; name: string } | null>(null); // Lightweight tick to refresh "uptime" pretty-print every 30s const [, force] = useState(0); @@ -325,6 +328,14 @@ export function OverviewPage() { )}

+ {showRefresh && (
); } diff --git a/packages/webui/src/components/process-probe-dialog.tsx b/packages/webui/src/components/process-probe-dialog.tsx new file mode 100644 index 00000000..bbd221ba --- /dev/null +++ b/packages/webui/src/components/process-probe-dialog.tsx @@ -0,0 +1,140 @@ +import { useEffect, useState } from 'react'; +import { Eye, Loader2, User, UserX } from 'lucide-react'; +import { Button } from '@/components/ui/button'; +import { + Dialog, + DialogContent, + DialogDescription, + DialogHeader, + DialogTitle, +} from '@/components/ui/dialog'; +import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'; +import { Badge } from '@/components/ui/badge'; +import { useApi } from '@/lib/api'; + +interface QqPortLoginInfo { + port: number; + uin: string; + uid?: string; + nickName?: string; + loggedIn: boolean; +} + +interface ProcessProbeDialogProps { + pid: number; + processName: string; + open: boolean; + onOpenChange: (open: boolean) => void; +} + +function qqAvatarUrl(uin: string) { + return `/avatar/${encodeURIComponent(uin)}`; +} + +export function ProcessProbeDialog({ pid, processName, open, onOpenChange }: ProcessProbeDialogProps) { + const api = useApi(); + const [loading, setLoading] = useState(false); + const [info, setInfo] = useState(null); + const [error, setError] = useState(null); + + const probe = async () => { + setLoading(true); + setError(null); + setInfo(null); + try { + const result = await api.processes.probeLoginInfo(pid); + setInfo(result as QqPortLoginInfo | null); + if (!result) { + setError('未检测到登录信息(端口 9210-9219 无响应)'); + } + } catch (err) { + setError(err instanceof Error ? err.message : '探测失败'); + } finally { + setLoading(false); + } + }; + + useEffect(() => { + if (open) { + probe(); + } else { + setInfo(null); + setError(null); + } + }, [open]); + + return ( + + + + 查看登录状态 + + {processName} (PID {pid}) + + + +
+ {loading && ( +
+ +
+ )} + + {!loading && error && ( +
+ +

{error}

+
+ )} + + {!loading && info && ( +
+ {info.loggedIn ? ( +
+ + + + + + +
+
+ {info.nickName || info.uin} + 已登录 +
+
UIN: {info.uin}
+ {info.uid && ( +
+ UID: {info.uid} +
+ )} +
端口: {info.port}
+
+
+ ) : ( +
+ +
+

等待登录

+

端口 {info.port} 已响应,但未检测到登录账号

+
+
+ )} +
+ )} + +
+ + {!loading && ( + + )} +
+
+
+
+ ); +} diff --git a/packages/webui/src/lib/api/client.ts b/packages/webui/src/lib/api/client.ts index b732727c..617de321 100644 --- a/packages/webui/src/lib/api/client.ts +++ b/packages/webui/src/lib/api/client.ts @@ -53,6 +53,7 @@ class HttpApiClient implements ApiClient { load: (pid) => this.postJson(`/api/processes/${pid}/load`), unload: (pid) => this.postJson(`/api/processes/${pid}/unload`), refresh: (pid) => this.postJson(`/api/processes/${pid}/refresh`), + probeLoginInfo: (pid) => this.getJson<{ info: unknown }>(`/api/processes/${pid}/probe-login`).then((d) => d.info ?? null), }; this.config = { diff --git a/packages/webui/src/lib/api/types.ts b/packages/webui/src/lib/api/types.ts index 01153200..83beb3a0 100644 --- a/packages/webui/src/lib/api/types.ts +++ b/packages/webui/src/lib/api/types.ts @@ -57,6 +57,7 @@ export interface ApiClient { load(pid: number): Promise; unload(pid: number): Promise; refresh(pid: number): Promise; + probeLoginInfo(pid: number): Promise; }; // ---- OneBotInstance per-UIN config ---- From 6de2e071be5a1075d7ecc28e57e3f96f236d0b49 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=89=8B=E7=93=9C=E4=B8=80=E5=8D=81=E9=9B=AA?= Date: Wed, 20 May 2026 10:52:43 +0800 Subject: [PATCH 43/48] Forward image sub_type and summary fields Include optional element.subType and element.summary in the image segment payload (mapped to sub_type and summary) so custom emoji/sticker metadata is preserved. Adds a unit test to verify these fields are forwarded. --- .../src/onebot/event-converter/to-segment.ts | 2 ++ packages/core/tests/event-converter.test.ts | 21 +++++++++++++++++++ 2 files changed, 23 insertions(+) diff --git a/packages/core/src/onebot/event-converter/to-segment.ts b/packages/core/src/onebot/event-converter/to-segment.ts index e60587f5..fd926fae 100644 --- a/packages/core/src/onebot/event-converter/to-segment.ts +++ b/packages/core/src/onebot/event-converter/to-segment.ts @@ -54,6 +54,8 @@ async function elementToSegment( const data: JsonObject = { url, file: element.fileId ?? '', + sub_type: element.subType ?? 0, + summary: element.summary ?? '', }; if (mediaSegmentSink) mediaSegmentSink('image', element, data, isGroup, sessionId); return { type: 'image', data }; diff --git a/packages/core/tests/event-converter.test.ts b/packages/core/tests/event-converter.test.ts index c298619a..1887d067 100644 --- a/packages/core/tests/event-converter.test.ts +++ b/packages/core/tests/event-converter.test.ts @@ -343,6 +343,8 @@ describe('convertEvent — message elements (13 segment types)', () => { expect(seg.type).toBe('image'); expect((seg.data as Record).url).toBe('http://resolved'); expect((seg.data as Record).file).toBe('fid'); + expect((seg.data as Record).sub_type).toBe(0); + expect((seg.data as Record).summary).toBe(''); }); it('image without resolver uses element.imageUrl', async () => { @@ -350,6 +352,25 @@ describe('convertEvent — message elements (13 segment types)', () => { expect((seg.data as Record).url).toBe('http://x'); }); + it('image: forwards optional sub_type and summary for custom emoji/stickers', async () => { + const seg = await segment({ + type: 'image', + fileId: 'fid', + imageUrl: 'http://x', + subType: 1, + summary: '[动画表情]', + }); + expect(seg).toEqual({ + type: 'image', + data: { + url: 'http://x', + file: 'fid', + sub_type: 1, + summary: '[动画表情]', + }, + }); + }); + it('at: targetUin -> qq string', async () => { const seg = await segment({ type: 'at', targetUin: PEER_UIN }); expect(seg).toEqual({ type: 'at', data: { qq: String(PEER_UIN) } }); From c83c333e733ce75143aa1a3b81c52194be9ba93e Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Wed, 20 May 2026 13:30:13 +0800 Subject: [PATCH 44/48] fix(file): route group publish through OIDB 0x6d9_4 and cache upload meta for c2c resend MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The chat-publish step after upload_group_file used to ship a PbSendMsg with a transElem(elemType=24) — but that wire shape is RECEIVE-side only, and current QQ-NT rejects it on send with `result=79`. Lagrange. Core V2 uses a dedicated `OidbSvcTrpcTcp.0x6d9_4` for the publish (`GroupSendFileService.cs`); mirror that. Send_group_msg with a `{type:'file', file_id}` segment now routes through the same path after the OneBot layer splits file segments out (matching the c2c file split pattern). Separately, send_private_msg with just `{file_id}` was shipping a 0 B file because the wire packet for c2c file send needs fileSize/fileMd5/ fileName/fileHash but the OneBot caller only echoes the file_id from upload_private_file. Add a bounded (1024-entry, FIFO) bridge cache populated at upload time so the send-message path can rehydrate the full tuple; inline segment fields still take precedence so callers that track the metadata themselves can bypass the cache. Parser now also accepts `file_hash`/`fileHash` on file segments. Also: file segments no longer get a `[空消息]` log line — the format string now shows `[文件:]`. --- .../core/src/bridge/actions/group-file.ts | 101 +++++++++++++-- packages/core/src/bridge/bridge-interface.ts | 11 ++ packages/core/src/bridge/bridge.ts | 76 +++++++++++ packages/core/src/bridge/element-builder.ts | 98 ++++---------- .../src/bridge/proto/proton/oidb-action.ts | 35 +++++ packages/core/src/onebot/message-parser.ts | 6 + .../src/onebot/modules/message-actions.ts | 92 ++++++++++++-- packages/core/tests/actions/_helpers.ts | 11 +- .../core/tests/actions/group-file.test.ts | 105 ++++++++++++--- packages/core/tests/element-builder.test.ts | 54 ++------ .../core/tests/onebot/send-group-file.test.ts | 120 ++++++++++++++++++ .../onebot/send-private-c2c-file.test.ts | 83 ++++++++++++ 12 files changed, 634 insertions(+), 158 deletions(-) create mode 100644 packages/core/tests/onebot/send-group-file.test.ts diff --git a/packages/core/src/bridge/actions/group-file.ts b/packages/core/src/bridge/actions/group-file.ts index 6131ef10..4d3aab82 100644 --- a/packages/core/src/bridge/actions/group-file.ts +++ b/packages/core/src/bridge/actions/group-file.ts @@ -19,6 +19,7 @@ import type { OidbGroupFileResp, OidbGroupFileViewReq, OidbGroupFileViewResp, + OidbGroupSendFileReq, OidbPrivateFileDownloadReq, OidbPrivateFileDownloadResp, OidbPrivateFileUploadReq, @@ -273,6 +274,48 @@ async function fetchNtv2DownloadUrl( return `https://${domain}${path}${rKeyParam}`; } +// ─────────────── publish (group file → chat) ─────────────── + +/** + * Publish a previously-uploaded group file as a chat message. + * + * Wire is OIDB `OidbSvcTrpcTcp.0x6d9_4` — NOT `MessageSvc.PbSendMsg`. + * Lagrange.Core V2 splits these two roles: the file UPLOAD path goes + * via 0x6D6_0 + highway PUT, then a SECOND OIDB hop (this one) tells + * the QQ server "now publish that staged blob as a chat message" so + * everyone in the group can see the file bubble. + * + * The old approach — wrap the file as `TransElem(elemType=24)` inside + * `richText.elems[]` and ship it via PbSendMsg — works for INCOMING + * messages (the receive decoder unpacks transElem(24) into a + * FileEntity) but the QQ-NT server REJECTS it on outgoing with + * `result=79` ("invalid element on send-side"). Mirror Lagrange's + * dedicated GroupSendFileService instead. + * + * The unused `field4` slot and the `field3=random` value match + * Lagrange's send-side defaults (`OidbSvcTrpcTcp0x6D9_4.cs` + the + * `Random.Shared.Next()` call in `GroupSendFileService.cs`). Field 5 + * is the `Field5=true` flag the receiver's deserializer expects. + */ +export async function sendGroupFileMessage(bridge: Bridge, groupId: number, fileId: string): Promise { + if (!fileId) throw new Error('sendGroupFileMessage requires fileId'); + const env = makeOidbEnvelope(0x6D9, 4, { + body: { + groupUin: groupId, + type: 2, + info: { + busiType: 102, + fileId, + field3: Math.floor(Math.random() * 0x7fffffff) >>> 0, + field5: true, + }, + }, + }); + // The envelope-level errorCode peek inside `runOidb` covers the + // happy-path validation; failures surface as a thrown OIDB error. + await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d9_4', encodeOidbEnv(env)); +} + // ─────────────── file count ─────────────── export async function fetchGroupFileCount(bridge: Bridge, groupId: number): Promise<{ fileCount: number; maxCount: number }> { @@ -336,6 +379,23 @@ export async function uploadGroupFile( const fileId = typeof upload.fileId === 'string' && upload.fileId ? upload.fileId : null; if (!fileId) 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 `sendGroupFileMessage` 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 + // `uploadPrivateFile` is where the cache is actually load-bearing. + bridge.rememberUploadedFile({ + fileId, + scope: 'group', + groupId, + fileName, + fileSize: loaded.bytes.length, + fileMd5: hashes.md5, + fileSha1: hashes.sha1, + rememberedAt: Date.now(), + }); + if (!upload.boolFileExist && uploadFile) { const senderUin = toInt(bridge.identity.uin); if (senderUin <= 0) throw new Error('invalid self uin for group file upload'); @@ -366,22 +426,20 @@ export async function uploadGroupFile( } // 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 — - // the chat shows nothing. NapCat does the same (upload + sendMsg - // atomically inside `upload_group_file`, see - // `dev/napcatQQ/.../UploadGroupFile.ts:54-58`). Only suppressed when - // the caller opts out via `uploadFile=false` (treat that as "I only - // wanted the slot allocated, hold the chat post"). + // the chat shows nothing. The publish step goes via a dedicated OIDB + // call (0x6D9_4), NOT via `MessageSvc.PbSendMsg` with a transElem(24) + // payload — the QQ-NT server rejects that with `result=79`. Mirrors + // Lagrange.Core V2's `GroupSendFileService.cs`. Suppressed when the + // caller opts out via `uploadFile=false` (treat that as "I only + // wanted the slot allocated, hold the chat post"). Routes through + // the public bridge method (rather than the local `sendGroupFileMessage`) + // so tests can mock at the bridge boundary, matching the pattern + // `uploadPrivateFile` uses with `bridge.sendC2cFileMessage`. if (uploadFile) { try { - await bridge.sendGroupMessage(groupId, [{ - type: 'file', - fileId, - fileName, - fileSize: loaded.bytes.length, - md5Hex: bytesToHexUpper(hashes.md5), - sha1Hex: bytesToHexUpper(hashes.sha1), - }]); + await bridge.sendGroupFileMessage(groupId, fileId); } catch (err) { // The bytes are already on the server and the fileId is valid — // fail loud but don't lose the upload result the action handler @@ -452,6 +510,23 @@ export async function uploadPrivateFile( const fileHash = typeof upload.fileAddon === 'string' && upload.fileAddon ? upload.fileAddon : null; if (!fileId) throw new Error('private file upload response missing file_id'); + // Cache the metadata so a later `send_private_msg` carrying just + // `{type:'file', file_id}` can resurrect the full c2c-file packet + // (NotOnlineFile { fileSize, fileMd5, fileName, fileHash }). Without + // this the recipient sees a 0-byte file because the OneBot send path + // has no way to recover those fields from the file_id alone. + bridge.rememberUploadedFile({ + fileId, + scope: 'private', + userId, + fileName, + fileSize: loaded.bytes.length, + fileMd5: hashes.md5, + fileSha1: hashes.sha1, + fileHash: fileHash ?? '', + rememberedAt: Date.now(), + }); + if (!upload.boolFileExist && uploadFile) { // Host selection. // diff --git a/packages/core/src/bridge/bridge-interface.ts b/packages/core/src/bridge/bridge-interface.ts index 225a8d0e..43a55aa4 100644 --- a/packages/core/src/bridge/bridge-interface.ts +++ b/packages/core/src/bridge/bridge-interface.ts @@ -22,6 +22,7 @@ import type { SendMessageReceipt, DownloadRKeyInfo, ClientKeyInfo, + UploadedFileMeta, } from './bridge'; import type { SendPacketResult } from '../protocol/packet-sender'; @@ -89,6 +90,16 @@ export interface BridgeInterface { // ─── Files ─── uploadGroupFile(groupId: number, file: string, name?: string, folderId?: string, uploadFile?: boolean): Promise<{ fileId: string | null }>; uploadPrivateFile(userId: number, file: string, name?: string, uploadFile?: boolean): Promise<{ fileId: string | null }>; + /** + * Publish a previously-uploaded group file as a chat message via + * `OidbSvcTrpcTcp.0x6d9_4`. The atomic upload+publish flow inside + * `uploadGroupFile` already does this, but the OneBot send-message + * path needs it too for {type:'file', file_id} segments. + */ + sendGroupFileMessage(groupId: number, fileId: string): Promise; + /** Cache file metadata so a later send_msg with just `file_id` can rehydrate it. */ + rememberUploadedFile(meta: UploadedFileMeta): void; + recallUploadedFile(fileId: string): UploadedFileMeta | undefined; fetchGroupFiles(groupId: number, folderId?: string): Promise; fetchGroupFileUrl(groupId: number, fileId: string, busId?: number): Promise; fetchPrivateFileUrl(userId: number, fileId: string, fileHash: string): Promise; diff --git a/packages/core/src/bridge/bridge.ts b/packages/core/src/bridge/bridge.ts index 3f3c59a3..74b945c4 100644 --- a/packages/core/src/bridge/bridge.ts +++ b/packages/core/src/bridge/bridge.ts @@ -48,6 +48,7 @@ import { import { uploadGroupFile as uploadGroupFile_, uploadPrivateFile as uploadPrivateFile_, + sendGroupFileMessage as sendGroupFileMessage_, fetchGroupFiles as fetchGroupFiles_, fetchGroupFileUrl as fetchGroupFileUrl_, fetchPrivateFileUrl as fetchPrivateFileUrl_, @@ -147,6 +148,29 @@ export interface SendMessageReceipt { timestamp: number; } +/** + * Metadata remembered after `upload_group_file` / `upload_private_file` + * succeeds. Lets the OneBot send-message path reconstruct the full + * payload when the caller only echoes the `file_id` back later. See + * `Bridge.rememberUploadedFile` / `recallUploadedFile`. + */ +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; @@ -186,6 +210,24 @@ export class Bridge implements BridgeInterface { private memberListInflight_ = new Map>(); private memberListLastFetch_ = new Map(); + // ── Uploaded-file metadata cache ──────────────────────────────────── + // + // After a file goes through `upload_group_file` / `upload_private_file` + // we remember the (fileName, fileSize, fileMd5, fileHash) tuple keyed + // by the returned file_id. The OneBot send-message paths consult this + // when the caller later passes `{type:'file', file_id:'xxx'}` without + // the rest of the metadata — c2c file send needs the size/md5/name + // for the wire packet (server-side rejection / "0 byte file" otherwise), + // and the group send path falls back to the name for the log line. + // + // Bounded at ~1024 entries with simple FIFO eviction. Files older + // than 7 days expire on QQ's side anyway, so this isn't load-bearing + // for correctness — just a UX convenience cache so the OneBot caller + // doesn't have to thread the metadata themselves between upload and + // send_msg. + private static readonly UPLOADED_FILE_CACHE_MAX = 1024; + private uploadedFileMeta_ = new Map(); + // Sequence and random generators for outgoing messages private clientSeq_ = 100000000 + (Date.now() % 1000000000); private msgRandom_ = (Date.now() & 0xFFFFFFFF) >>> 0; @@ -252,6 +294,37 @@ export class Bridge implements BridgeInterface { return true; } + // --- Uploaded-file metadata cache --- + + /** + * Remember a freshly-uploaded file so a later `send_*_msg` carrying + * just the file_id can reconstruct the full c2c-file packet (fileName + * / fileSize / fileMd5 are required by the QQ NT server's c2c file + * intake, even if only the uuid is needed for the OIDB lookup + * internally — without them the file shows as 0 B in the recipient's + * chat or is silently rejected). Insertion is FIFO; oldest entry is + * evicted when the cache hits `UPLOADED_FILE_CACHE_MAX`. + */ + rememberUploadedFile(meta: UploadedFileMeta): void { + if (!meta.fileId) return; + if (this.uploadedFileMeta_.size >= Bridge.UPLOADED_FILE_CACHE_MAX) { + // Map iteration order is insertion order — drop the oldest. + const oldest = this.uploadedFileMeta_.keys().next().value; + if (oldest !== undefined) this.uploadedFileMeta_.delete(oldest); + } + this.uploadedFileMeta_.set(meta.fileId, meta); + } + + /** + * Recall metadata for a previously-uploaded file. Returns `undefined` + * if the file_id was never uploaded through this bridge instance, or + * if it's been evicted from the cache. + */ + recallUploadedFile(fileId: string): UploadedFileMeta | undefined { + if (!fileId) return undefined; + return this.uploadedFileMeta_.get(fileId); + } + // --- Sequence / random generators --- private nextClientSequence(): number { @@ -562,6 +635,9 @@ export class Bridge implements BridgeInterface { async uploadPrivateFile(userId: number, file: string, name = '', uploadFile = true): Promise<{ fileId: string | null }> { return uploadPrivateFile_(this, userId, file, name, uploadFile); } + async sendGroupFileMessage(groupId: number, fileId: string): Promise { + return sendGroupFileMessage_(this, groupId, fileId); + } async fetchGroupFiles(groupId: number, folderId = '/'): Promise { return fetchGroupFiles_(this, groupId, folderId); } async fetchGroupFileUrl(groupId: number, fileId: string, busId = 102): Promise { return fetchGroupFileUrl_(this, groupId, fileId, busId); } async fetchPrivateFileUrl(userId: number, fileId: string, fileHash: string): Promise { return fetchPrivateFileUrl_(this, userId, fileId, fileHash); } diff --git a/packages/core/src/bridge/element-builder.ts b/packages/core/src/bridge/element-builder.ts index e51414a2..d3530c40 100644 --- a/packages/core/src/bridge/element-builder.ts +++ b/packages/core/src/bridge/element-builder.ts @@ -13,11 +13,12 @@ import type { MentionExtraSend, MarkdownData, } from './proto/proton/action'; -import type { GroupFileExtra } from './proto/proton/element'; +// `GroupFileExtra` + `hexToBytes` used to support `makeGroupFileElem` +// (removed — see comment above the former call site). The receive-side +// decoder in `msg-push/rich-body-decoder.ts` still pulls those in. import { uploadImageMsgInfo } from './highway/image-upload'; import { uploadPttMsgInfo } from './highway/ptt-upload'; import { uploadVideoMsgInfo } from './highway/video-upload'; -import { hexToBytes } from './highway/pipeline'; type ProtoElem = Partial>; @@ -246,63 +247,12 @@ async function makePttElem(ctx: SendContext, element: MessageElement): Promise

({ - field1: 6, - fileName, - inner: { - info: { - busId: 102, - fileId: element.fileId, - fileSize: BigInt(fileSize), - fileName, - fileSha: sha1, - extInfoString: '', - fileMd5: md5, - }, - }, - }); - if (extraBytes.length > 0xFFFF) { - // The 16-bit length prefix caps the payload at 64 KiB; even the - // densest GroupFileExtra (fileId/name/two hashes) is well under. - // This is here so a future schema change can't silently truncate. - throw new Error(`group file extra too large (${extraBytes.length} > 65535)`); - } - const elemValue = new Uint8Array(3 + extraBytes.length); - elemValue[0] = 0x01; - elemValue[1] = (extraBytes.length >> 8) & 0xff; - elemValue[2] = extraBytes.length & 0xff; - elemValue.set(extraBytes, 3); - - return { - transElem: { - elemType: 24, - elemValue, - } as any, - }; -} +// (formerly `makeGroupFileElem` — removed. The `transElem(24)` shape it +// produced was a RECEIVE-side encoding only. The QQ-NT server rejects +// outgoing PbSendMsg with that element with `result=79`; group files +// publish through `OidbSvcTrpcTcp.0x6d9_4` instead, called from the +// OneBot layer at `modules/message-actions.ts::sendGroupMessage` after +// the file segment is split off.) async function makeVideoElem(ctx: SendContext, element: MessageElement): Promise { const isGroup = ctx.groupId !== undefined; @@ -392,20 +342,22 @@ export async function buildSendElems(elements: MessageElement[], ctx?: SendConte break; case 'file': - // The group `TransElem(24)` shape works for group chats only. - // C2C files live on `RichText.notOnlineFile` (parallel to elems, - // see proto/proton/message.ts:notOnlineFile) and are routed - // out at the OneBot layer in `sendPrivateMessage` — split off - // from elems[] and dispatched via `bridge.sendC2cFileMessage`. - // If a c2c file segment still reaches us here, the caller - // forgot to route — log loudly and drop, otherwise the message - // ships as "[空消息]" (only-file case) or quietly loses the - // file (mixed case). - if (ctx?.groupId !== undefined) { - result.push(makeGroupFileElem(elem)); - } else { - console.warn('[ElemBuilder] BUG: c2c {type:"file"} reached element-builder — should be split out at the OneBot layer (see modules/message-actions.ts::sendPrivateMessage)'); - } + // Files NEVER ride on the elems[] pipeline anymore — both flavors + // route at the OneBot layer: + // * c2c (private): split off and dispatched via + // `bridge.sendC2cFileMessage` (uses routingHead.trans0x211 + + // msgContent FileExtra; see bridge.ts::sendC2cFileMessage). + // * group: split off and dispatched via + // `bridge.sendGroupFileMessage` (uses OIDB 0x6d9_4; see + // actions/group-file.ts::sendGroupFileMessage). + // + // The old transElem(24) shape DOES work for receive-side decode + // (rich-body-decoder unpacks it into a FileEntity), but the + // QQ-NT server rejects it on outgoing with result=79. If a file + // segment still reaches us here the caller forgot to route at + // the OneBot layer — drop with a loud warn so it doesn't silently + // ship as "[空消息]" or a 0-byte stub. + console.warn('[ElemBuilder] BUG: {type:"file"} reached element-builder — must be split out at the OneBot layer (see modules/message-actions.ts::sendPrivateMessage / ::sendGroupMessage)'); break; default: diff --git a/packages/core/src/bridge/proto/proton/oidb-action.ts b/packages/core/src/bridge/proto/proton/oidb-action.ts index bb051888..40e2bc4a 100644 --- a/packages/core/src/bridge/proto/proton/oidb-action.ts +++ b/packages/core/src/bridge/proto/proton/oidb-action.ts @@ -548,6 +548,41 @@ export interface OidbGroupFileResp { move?: pb<6, OidbGroupFileRetResp>; } +// --- 0x6D9_4: Group file PUBLISH-AS-CHAT-MESSAGE --- +// +// Posts an already-uploaded group file (via 0x6D6_0 + highway) as a +// chat message in the group. This is a separate OIDB endpoint from +// the file upload — NOT a `MessageSvc.PbSendMsg` with a `TransElem` +// payload (sending the file as a transElem(24) is a RECEIVE-side +// decoding shape, and the QQ-NT server rejects it on send with +// `result=79`). +// +// Wire shape (mirrors Lagrange.Core V2's nesting): +// OidbBase.body (envelope field 4) +// → OidbGroupSendFileReq.body (field 5) ← the nested wrapper +// → OidbGroupSendFileBody { groupUin, type, info } +// +// Ports `dev/Lagrange.Core/.../Internal/Service/Message/GroupSendFileService.cs` +// + `Internal/Packets/Service/Oidb/Request/OidbSvcTrpcTcp0x6D9_4.cs`. + +export interface OidbGroupSendFileInfo { + busiType?: pb<1, uint_32>; // hardcoded 102 + fileId?: pb<2, string>; // uuid from 0x6D6_0 upload response + field3?: pb<3, uint_32>; // random uint32 (msg id seed) + field4?: pb<4, string>; // null/empty on send + field5?: pb<5, bool>; // hardcoded true +} + +export interface OidbGroupSendFileBody { + groupUin?: pb<1, uint_32>; + type?: pb<2, uint_32>; // hardcoded 2 (= chat post) + info?: pb<3, OidbGroupSendFileInfo>; +} + +export interface OidbGroupSendFileReq { + body?: pb<5, OidbGroupSendFileBody>; +} + // --- 0x6D7_0 / 0x6D7_1 / 0x6D7_2: Group file folder ops --- export interface OidbGroupFileCreateFolderReq { diff --git a/packages/core/src/onebot/message-parser.ts b/packages/core/src/onebot/message-parser.ts index 159dc530..dea16d07 100644 --- a/packages/core/src/onebot/message-parser.ts +++ b/packages/core/src/onebot/message-parser.ts @@ -354,11 +354,17 @@ async function segmentToElement(type: string, data: Record, opt const fileSize = intOr(data.size ?? data.fileSize, 0); const md5Hex = String(data.md5 ?? data.md5Hex ?? '').trim(); const sha1Hex = String(data.sha1 ?? data.sha1Hex ?? '').trim(); + // file_hash is the c2c-file server-issued addon string — needed + // on the wire when re-sending a previously-uploaded c2c file. + // get_private_file_url callers already pass it through, so honour + // the same field naming here. + const fileHash = String(data.file_hash ?? data.fileHash ?? '').trim(); const elem: MessageElement = { type: 'file', fileId }; if (fileName) elem.fileName = fileName; if (fileSize > 0) elem.fileSize = fileSize; if (md5Hex) elem.md5Hex = md5Hex; if (sha1Hex) elem.sha1Hex = sha1Hex; + if (fileHash) elem.fileHash = fileHash; return elem; } default: diff --git a/packages/core/src/onebot/modules/message-actions.ts b/packages/core/src/onebot/modules/message-actions.ts index a47a2ac2..c2589e79 100644 --- a/packages/core/src/onebot/modules/message-actions.ts +++ b/packages/core/src/onebot/modules/message-actions.ts @@ -167,18 +167,34 @@ export async function sendPrivateMessage( throw new Error(`c2c file send: could not resolve uid for user ${userId}`); } for (const fileEl of fileElements) { + // C2C file send requires fileSize/fileMd5/fileName to ride on the + // wire (NotOnlineFile inside msgContent). The OneBot caller + // usually only echoes the file_id from a previous + // `upload_private_file`, so look up the rest from the upload + // cache. Inline segment fields (md5/size/name) take precedence so + // a caller that already knows everything can bypass the cache. + const cached = ref.bridge.recallUploadedFile(fileEl.fileId!); const fileMd5 = fileEl.md5Hex ? Buffer.from(fileEl.md5Hex, 'hex') - : new Uint8Array(0); + : (cached?.fileMd5 ?? new Uint8Array(0)); + const fileSize = fileEl.fileSize ?? cached?.fileSize ?? 0; + // Fall back to a generic name — the QQ server resolves the + // file by fileUuid, not name, so a missing name only affects + // the chat bubble display. + const fileName = fileEl.fileName ?? cached?.fileName ?? 'file'; + const fileHash = fileEl.fileHash ?? cached?.fileHash; + if (fileSize === 0 && !cached) { + log.warn( + '[OneBot] c2c file_id=%s sent without fileSize and no upload cache — recipient may see 0 B', + fileEl.fileId, + ); + } lastReceipt = await ref.bridge.sendC2cFileMessage(userId, userUid, { fileId: fileEl.fileId!, - // Fall back to a generic name — the QQ server resolves the - // file by fileUuid, not name, so a missing name only affects - // the chat bubble display. - fileName: fileEl.fileName ?? 'file', - fileSize: fileEl.fileSize ?? 0, + fileName, + fileSize, fileMd5, - fileHash: fileEl.fileHash, + fileHash, }); logSentMessage(false, userId, [fileEl]); } @@ -229,19 +245,60 @@ export async function sendGroupMessage( }); if (elements.length === 0) throw new Error('message is empty'); - const receipt = await ref.bridge.sendGroupMessage(groupId, elements); - const messageId = hashMessageIdInt32(receipt.sequence, groupId, GROUP_MESSAGE_EVENT); + // Group `{type:'file', file_id}` segments don't ride on the elems[] + // pipeline either. The QQ-NT server rejects PbSendMsg with a + // transElem(24) file payload (result=79); the correct send path is a + // dedicated OIDB call (`OidbSvcTrpcTcp.0x6d9_4`) that publishes a + // previously-uploaded file id as a chat bubble. Mirrors the c2c-file + // split below (private path) — both must be peeled off before the + // regular sendGroupMessage runs. + const fileElements = elements.filter(e => e.type === 'file' && e.fileId); + const nonFileElements = elements.filter(e => e.type !== 'file'); + if (fileElements.length !== elements.filter(e => e.type === 'file').length) { + log.warn('[OneBot] group file segment without file_id — skipped (upload first via upload_group_file)'); + } - logSentMessage(true, groupId, elements); + let lastReceipt: Awaited> | undefined; + if (nonFileElements.length > 0) { + lastReceipt = await ref.bridge.sendGroupMessage(groupId, nonFileElements); + logSentMessage(true, groupId, nonFileElements); + } + for (const fileEl of fileElements) { + // Group-file publish has no per-message sequence/random tuple to + // hash a messageId from — OIDB 0x6d9_4 is fire-and-forget on the + // wire. If this is the LAST element we still need a receipt so + // the OneBot caller can cache the id; synthesise one from the + // file_id hash + a fresh timestamp. + await ref.bridge.sendGroupFileMessage(groupId, fileEl.fileId!); + logSentMessage(true, groupId, [fileEl]); + if (!lastReceipt) { + // Use a hash of the fileId as a stable pseudo-id; this gets + // mixed with groupId in `hashMessageIdInt32` below. + let h = 0; + const s = fileEl.fileId ?? ''; + for (let i = 0; i < s.length; i++) { + h = ((h << 5) - h + s.charCodeAt(i)) | 0; + } + lastReceipt = { + messageId: 0, + sequence: h & 0x7FFFFFFF, + clientSequence: 0, + random: h & 0x7FFFFFFF, + timestamp: Math.floor(Date.now() / 1000), + }; + } + } + if (!lastReceipt) throw new Error('message is empty'); + const messageId = hashMessageIdInt32(lastReceipt.sequence, groupId, GROUP_MESSAGE_EVENT); ref.cacheMessageMeta(messageId, { isGroup: true, targetId: groupId, - sequence: receipt.sequence, + sequence: lastReceipt.sequence, eventName: GROUP_MESSAGE_EVENT, - clientSequence: receipt.clientSequence, - random: receipt.random, - timestamp: receipt.timestamp, + clientSequence: lastReceipt.clientSequence, + random: lastReceipt.random, + timestamp: lastReceipt.timestamp, }); return { messageId }; @@ -575,6 +632,13 @@ function logSentMessage(isGroup: boolean, targetId: number, elements: MessageEle case 'poke': parts.push('[戳一戳]'); break; + case 'file': + // Avoid the misleading "[空消息]" the user previously saw when + // sending a file segment — the message is NOT empty, it's a + // file post. Show the name (or id as fallback) so the log + // reflects what actually went out. + parts.push(`[文件:${elem.fileName || elem.fileId || ''}]`); + break; default: break; } diff --git a/packages/core/tests/actions/_helpers.ts b/packages/core/tests/actions/_helpers.ts index 097cdcae..85c2d402 100644 --- a/packages/core/tests/actions/_helpers.ts +++ b/packages/core/tests/actions/_helpers.ts @@ -26,11 +26,17 @@ export interface MockBridge { resolveUserUid: ReturnType; // High-level message senders. Default to no-op resolves so actions // that fire off a follow-up chat message after their main work - // (e.g. `upload_group_file` → `sendGroupMessage` to publish the + // (e.g. `upload_group_file` → `sendGroupFileMessage` to publish the // file in chat) don't crash test setups that don't care about it. sendGroupMessage: ReturnType; sendPrivateMessage: ReturnType; sendC2cFileMessage: ReturnType; + sendGroupFileMessage: ReturnType; + // Uploaded-file metadata cache helpers — actions like uploadGroupFile + // / uploadPrivateFile call these to remember the upload, so tests + // covering those code paths get a default-no-op shim. + rememberUploadedFile: ReturnType; + recallUploadedFile: ReturnType; } export function mockBridge(overrides: Partial = {}): MockBridge { @@ -59,6 +65,9 @@ export function mockBridge(overrides: Partial = {}): MockBridge { sendGroupMessage: vi.fn(async () => ({ messageId: 1, sequence: 1, clientSequence: 0, random: 1, timestamp: 0 })), sendPrivateMessage: vi.fn(async () => ({ messageId: 1, sequence: 1, clientSequence: 0, random: 1, timestamp: 0 })), sendC2cFileMessage: vi.fn(async () => ({ messageId: 1, sequence: 1, clientSequence: 0, random: 1, timestamp: 0 })), + sendGroupFileMessage: vi.fn(async () => undefined), + rememberUploadedFile: vi.fn(), + recallUploadedFile: vi.fn(() => undefined), ...overrides, }; } diff --git a/packages/core/tests/actions/group-file.test.ts b/packages/core/tests/actions/group-file.test.ts index 73bd9ae8..22394ae8 100644 --- a/packages/core/tests/actions/group-file.test.ts +++ b/packages/core/tests/actions/group-file.test.ts @@ -136,12 +136,14 @@ describe('actions/group-file', () => { .rejects.toThrow(/code=999/); }); - it('uploadGroupFile publishes the file as a chat message after upload (the "empty message" regression)', async () => { + it('uploadGroupFile 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 - // `sendGroupMessage` the file never appears in the chat. Asserts - // that `bridge.sendGroupMessage` is invoked with a single - // `{type:'file'}` element pointing at the uploaded fileId. + // stage the bytes on QQ's side; without the trailing 0x6d9_4 OIDB + // call the file never appears in the chat. Earlier attempts used + // PbSendMsg with a transElem(24) but the QQ-NT server rejects that + // with result=79 (transElem(24) is a receive-side decoding shape, + // not a send-side one). Asserts that `bridge.sendGroupFileMessage` + // is invoked with the uploaded fileId. const bridge = mockBridge(); vi.mocked(oidb.runOidb).mockResolvedValueOnce( protobuf_encode>({ @@ -149,15 +151,13 @@ describe('actions/group-file', () => { }), ); await groupFile.uploadGroupFile(bridge as any, 12345, '/path/some-file.bin', 'mynote.txt'); - expect(bridge.sendGroupMessage).toHaveBeenCalledOnce(); - const [groupId, elements] = bridge.sendGroupMessage.mock.calls[0]!; + expect(bridge.sendGroupFileMessage).toHaveBeenCalledOnce(); + const [groupId, fileId] = bridge.sendGroupFileMessage.mock.calls[0]!; expect(groupId).toBe(12345); - expect(elements).toHaveLength(1); - expect(elements[0]).toMatchObject({ - type: 'file', - fileId: 'fid-pub', - fileName: 'mynote.txt', - }); + expect(fileId).toBe('fid-pub'); + // sendGroupMessage must NOT be touched — the previous wire shape + // (PbSendMsg w/ transElem(24)) is the bug we're guarding against. + expect(bridge.sendGroupMessage).not.toHaveBeenCalled(); }); it('uploadGroupFile skips the chat post when uploadFile=false', async () => { @@ -168,12 +168,12 @@ describe('actions/group-file', () => { }), ); await groupFile.uploadGroupFile(bridge as any, 12345, '/path/file.bin', '', '/', false); - expect(bridge.sendGroupMessage).not.toHaveBeenCalled(); + expect(bridge.sendGroupFileMessage).not.toHaveBeenCalled(); }); it('uploadGroupFile returns success even when the chat post fails (file is still uploaded)', async () => { const bridge = mockBridge(); - vi.mocked(bridge.sendGroupMessage).mockRejectedValueOnce(new Error('message rejected')); + vi.mocked(bridge.sendGroupFileMessage).mockRejectedValueOnce(new Error('message rejected')); vi.mocked(oidb.runOidb).mockResolvedValueOnce( protobuf_encode>({ body: { upload: { fileId: 'fid-tolerant', boolFileExist: true } as any }, @@ -181,7 +181,55 @@ describe('actions/group-file', () => { ); const out = await groupFile.uploadGroupFile(bridge as any, 12345, '/path/file.bin'); expect(out).toEqual({ fileId: 'fid-tolerant' }); - expect(bridge.sendGroupMessage).toHaveBeenCalledOnce(); + expect(bridge.sendGroupFileMessage).toHaveBeenCalledOnce(); + }); + + it('uploadGroupFile caches the upload metadata for later resend by file_id', async () => { + // After upload, a later `send_group_msg` carrying just the file_id + // needs to recover the name/size/md5 from somewhere. Production + // populates `bridge.rememberUploadedFile` with the full tuple. + const bridge = mockBridge(); + vi.mocked(oidb.runOidb).mockResolvedValueOnce( + protobuf_encode>({ + body: { upload: { fileId: 'fid-cached', boolFileExist: true } as any }, + }), + ); + await groupFile.uploadGroupFile(bridge as any, 12345, '/path/x.bin', 'x.bin'); + expect(bridge.rememberUploadedFile).toHaveBeenCalledOnce(); + const [meta] = bridge.rememberUploadedFile.mock.calls[0]!; + expect(meta).toMatchObject({ + fileId: 'fid-cached', + scope: 'group', + groupId: 12345, + fileName: 'x.bin', + }); + }); + + it('sendGroupFileMessage hits OIDB 0x6d9_4 with the right body', async () => { + // Direct cover of the new bridge method. The previous send-shape + // (PbSendMsg + transElem(24)) failed with result=79; this is the + // Lagrange-V2-mirrored fix. + const bridge = mockBridge(); + vi.mocked(oidb.runOidb).mockResolvedValueOnce(new Uint8Array()); + await groupFile.sendGroupFileMessage(bridge as any, 12345, 'fid-publish'); + expect(oidb.runOidb).toHaveBeenCalledOnce(); + const [, cmd] = vi.mocked(oidb.runOidb).mock.calls[0]!; + expect(cmd).toBe('OidbSvcTrpcTcp.0x6d9_4'); + // The envelope wraps a `{body: {groupUin, type=2, info: {busiType=102, fileId, ...}}}`. + expect(oidb.makeOidbEnvelope).toHaveBeenCalledWith( + 0x6D9, 4, + expect.objectContaining({ + body: expect.objectContaining({ + groupUin: 12345, + type: 2, + info: expect.objectContaining({ + busiType: 102, + fileId: 'fid-publish', + field5: true, + }), + }), + }), + ); }); it('uploadPrivateFile resolves both target + self UID before OIDB call', async () => { @@ -230,6 +278,31 @@ describe('actions/group-file', () => { expect(bridge.sendPrivateMessage).not.toHaveBeenCalled(); }); + it('uploadPrivateFile caches the upload metadata for later resend by file_id', async () => { + // C2C file resend (send_private_msg with just file_id) was the + // "sends a 0 B file" bug: the wire packet needs fileSize/fileMd5/ + // fileName/fileHash, but the OneBot caller only knows the file_id. + // Caching the upload tuple lets the OneBot send-message path + // recover the rest via `bridge.recallUploadedFile(fileId)`. + const bridge = mockBridge(); + vi.mocked(bridge.resolveUserUid).mockResolvedValueOnce('target-uid'); + vi.mocked(oidb.runOidb).mockResolvedValueOnce( + protobuf_encode>({ + body: { upload: { uuid: 'pfid-cache', fileAddon: 'addon-hash', boolFileExist: true } as any }, + }), + ); + await groupFile.uploadPrivateFile(bridge as any, 67890, '/path/cache-me.txt', 'cache-me.txt'); + expect(bridge.rememberUploadedFile).toHaveBeenCalledOnce(); + const [meta] = bridge.rememberUploadedFile.mock.calls[0]!; + expect(meta).toMatchObject({ + fileId: 'pfid-cache', + scope: 'private', + userId: 67890, + fileName: 'cache-me.txt', + fileHash: 'addon-hash', + }); + }); + it('uploadPrivateFile skips the chat post when uploadFile=false', async () => { const bridge = mockBridge(); vi.mocked(bridge.resolveUserUid).mockResolvedValueOnce('target-uid'); diff --git a/packages/core/tests/element-builder.test.ts b/packages/core/tests/element-builder.test.ts index a4893110..50ca621e 100644 --- a/packages/core/tests/element-builder.test.ts +++ b/packages/core/tests/element-builder.test.ts @@ -93,16 +93,18 @@ describe('element-builder / commonElem.businessType per scene', () => { }); }); -describe('element-builder / group file element wire shape', () => { - // Regression for the same `result=79` class: the GroupFileExtra outer - // wrapper was missing the magic `field1=6` + `fileName` slots and the - // inner GroupFileInfo had fileSha/extInfoString/fileMd5 shifted one - // tag to the left (5/6/7 instead of the correct 6/7/8). Both - // mistakes made the current QQ-NT server reject the chat post. This - // test decodes the element back through the proton-generated codec - // and asserts each field lands at the right tag. - it('encodes outer field1=6 + fileName, and inner fields at tags 6/7/8', async () => { - const [elem] = await buildSendElems( +describe('element-builder / file element is no longer carried in elems[]', () => { + // 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 + // shape. The fix moves group-file publishing onto a dedicated OIDB + // call (`OidbSvcTrpcTcp.0x6d9_4`), driven from the OneBot layer in + // `modules/message-actions.ts::sendGroupMessage` after the file + // segment is split off. The element-builder therefore must NOT emit + // any element for `{type:'file'}` anymore — if it does, the message + // ships with a transElem(24) payload and result=79 returns. + it('produces an empty elems[] for a {type:"file"} segment (must be split out at OneBot layer)', async () => { + const result = await buildSendElems( [{ type: 'file', fileId: 'fid-abc', @@ -113,36 +115,6 @@ describe('element-builder / group file element wire shape', () => { } as any], { bridge: fakeBridge, groupId: 12345 }, ); - const transElem = (elem as any).transElem as { elemType: number; elemValue: Uint8Array }; - expect(transElem.elemType).toBe(24); - // 0x01 prefix + BE16 length + payload - expect(transElem.elemValue[0]).toBe(0x01); - const len = (transElem.elemValue[1] << 8) | transElem.elemValue[2]; - const payload = transElem.elemValue.subarray(3, 3 + len); - - // Hand-walk the wire bytes to verify each tag lands where the - // server expects. Each varint tag = (field << 3) | wire_type: - // outer field1=6 → tag 8 (wire 0 / varint), value 6 - // outer fileName → tag 18 (wire 2 / length-delimited), 'doc.txt' - // outer inner → tag 58 (field 7 wire 2) - // inner.info → tag 18 (field 2 wire 2) - // info.busId → tag 8 (field 1 wire 0), value 102 - // info.fileId → tag 18 (field 2 wire 2) - // info.fileSize → tag 24 (field 3 wire 0), value 123 - // info.fileName → tag 34 (field 4 wire 2) - // info.fileSha → tag 50 (field 6 wire 2) ← was 42 (field 5) - // info.extInfoString → tag 58 (field 7 wire 2) ← was 50 (field 6) - // info.fileMd5 → tag 66 (field 8 wire 2) ← was 58 (field 7) - const tagAt = (i: number) => payload[i]; - expect(tagAt(0)).toBe(8); // outer field1 tag — regression: missing entirely before - expect(payload[1]).toBe(6); // value of field1 (NapCat hardcodes 6) - expect(tagAt(2)).toBe(18); // outer fileName tag — regression: missing - // Locate the inner GroupFileExtraInfo by scanning for tag 50 (was 42 - // in the bug). A naive scan for `0x32` is enough because no string - // field happens to contain that byte in this test fixture. - expect(payload.includes(50)).toBe(true); // fileSha at tag 50 (field 6) - expect(payload.includes(58)).toBe(true); // extInfoString at tag 58 (field 7) - expect(payload.includes(66)).toBe(true); // fileMd5 at tag 66 (field 8) - expect(payload.includes(42)).toBe(false); // sanity: nothing at the old (wrong) tag for fileSha + expect(result).toEqual([]); }); }); diff --git a/packages/core/tests/onebot/send-group-file.test.ts b/packages/core/tests/onebot/send-group-file.test.ts new file mode 100644 index 00000000..c606f50a --- /dev/null +++ b/packages/core/tests/onebot/send-group-file.test.ts @@ -0,0 +1,120 @@ +// Regression coverage for the group-file-in-send_group_msg bug. +// +// Symptom in the wild: bot uploaded a group file via `upload_group_file`, +// then sent `{type:'file', file_id}` through `send_group_msg`; the +// element-builder wrapped it as `transElem(elemType=24, ...)` inside +// `richText.elems` and shipped a regular `MessageSvc.PbSendMsg`. The +// QQ-NT server rejected the message with `result=79` because that wire +// shape is RECEIVE-side only (rich-body-decoder unpacks it into a +// FileEntity for inbound messages, but the server's intake validator +// flags it on the send side). +// +// Fix: split file segments off at the OneBot layer (same pattern as +// the c2c-file split for private messages) and dispatch through +// `bridge.sendGroupFileMessage`, which calls dedicated OIDB +// `OidbSvcTrpcTcp.0x6d9_4` — Lagrange.Core V2's +// `GroupSendFileService.cs`. + +import { describe, expect, it, vi } from 'vitest'; +import type { BridgeInterface } from '../../src/bridge/bridge-interface'; +import type { OneBotInstanceContext } from '../../src/onebot/instance-context'; +import { sendGroupMessage } from '../../src/onebot/modules/message-actions'; + +function fakeBridge(overrides: Partial = {}): BridgeInterface { + return new Proxy(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`); + }, + }); +} + +function makeCtx(bridge: BridgeInterface): OneBotInstanceContext { + return { + uin: '10001', + bridge, + messageStore: { findEvent: () => null, resolveReplySequence: () => 0 } as any, + cacheMessageMeta: vi.fn(), + mediaStore: {} as any, + musicSignUrl: '', + } as unknown as OneBotInstanceContext; +} + +const goodReceipt = { + messageId: 1, sequence: 100, clientSequence: 0, random: 1, timestamp: 1700000000, +}; + +describe('send_group_msg with {type:"file"} segment', () => { + it('file-only message routes through sendGroupFileMessage (not sendGroupMessage_bridge)', async () => { + // Pure-file case — the elems[] path used to ship a transElem(24) + // and got result=79. The dedicated OIDB-0x6d9_4 route must take + // over for group file publishing. + const sendGroupMessage_bridge = vi.fn(); + const sendGroupFileMessage = vi.fn(async () => undefined); + const bridge = fakeBridge({ + sendGroupMessage: sendGroupMessage_bridge, + sendGroupFileMessage, + resolveUserUid: vi.fn(), + } as any); + const ctx = makeCtx(bridge); + + await sendGroupMessage(ctx, 12345, [{ + type: 'file', data: { file_id: 'gfid-abc', name: 'doc.txt', size: 123 }, + }] as any, false); + + expect(sendGroupFileMessage).toHaveBeenCalledOnce(); + expect(sendGroupMessage_bridge).not.toHaveBeenCalled(); + + const [groupId, fileId] = sendGroupFileMessage.mock.calls[0]!; + expect(groupId).toBe(12345); + expect(fileId).toBe('gfid-abc'); + }); + + it('mixed text + file splits across two sends (text via elems[], file via OIDB)', async () => { + const sendGroupMessage_bridge = vi.fn(async (_gid: number, _elements: any[]) => goodReceipt); + const sendGroupFileMessage = vi.fn(async () => undefined); + const bridge = fakeBridge({ + sendGroupMessage: sendGroupMessage_bridge, + sendGroupFileMessage, + resolveUserUid: vi.fn(async () => 'u_peer'), + } as any); + const ctx = makeCtx(bridge); + + await sendGroupMessage(ctx, 12345, [ + { type: 'text', data: { text: 'here is the file:' } }, + { type: 'file', data: { file_id: 'gfid-xyz', name: 'pkg.zip' } }, + ] as any, false); + + expect(sendGroupMessage_bridge).toHaveBeenCalledOnce(); + expect(sendGroupFileMessage).toHaveBeenCalledOnce(); + + const [textGid, textElements] = sendGroupMessage_bridge.mock.calls[0]!; + expect(textGid).toBe(12345); + expect(textElements).toEqual([{ type: 'text', text: 'here is the file:' }]); + + const [fileGid, fileFileId] = sendGroupFileMessage.mock.calls[0]!; + expect(fileGid).toBe(12345); + expect(fileFileId).toBe('gfid-xyz'); + }); + + it('file segment without file_id is skipped (with a warn-level log)', async () => { + // Same upload-by-reference contract as the c2c file path — + // missing file_id means there's nothing to publish. + const sendGroupMessage_bridge = vi.fn(async (_gid: number, _elements: any[]) => goodReceipt); + const sendGroupFileMessage = vi.fn(); + const bridge = fakeBridge({ + sendGroupMessage: sendGroupMessage_bridge, + sendGroupFileMessage, + resolveUserUid: vi.fn(), + } as any); + const ctx = makeCtx(bridge); + + await sendGroupMessage(ctx, 12345, [ + { type: 'text', data: { text: 'with bad file segment' } }, + { type: 'file', data: {} }, // no file_id + ] as any, false); + + expect(sendGroupMessage_bridge).toHaveBeenCalledOnce(); + expect(sendGroupFileMessage).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/core/tests/onebot/send-private-c2c-file.test.ts b/packages/core/tests/onebot/send-private-c2c-file.test.ts index 4b46d6b6..3b626cfd 100644 --- a/packages/core/tests/onebot/send-private-c2c-file.test.ts +++ b/packages/core/tests/onebot/send-private-c2c-file.test.ts @@ -50,10 +50,12 @@ describe('send_private_msg with {type:"file"} segment', () => { const sendPrivateMessage_bridge = vi.fn(); const sendC2cFileMessage = vi.fn(async (_uin: number, _uid: string, _info: any) => goodReceipt); const resolveUserUid = vi.fn(async () => 'u_peer'); + const recallUploadedFile = vi.fn(() => undefined); const bridge = fakeBridge({ sendPrivateMessage: sendPrivateMessage_bridge, sendC2cFileMessage, resolveUserUid, + recallUploadedFile, } as any); const ctx = makeCtx(bridge); @@ -77,6 +79,84 @@ describe('send_private_msg with {type:"file"} segment', () => { expect(info.fileMd5).toEqual(Buffer.from('00112233', 'hex')); }); + it('file-only with just file_id hydrates fileName/size/md5 from the upload cache', async () => { + // Reproduces the "0 B file" bug: a caller passes only `file_id` from + // a previous upload_private_file, with no size/md5/name. Without + // the cache lookup the wire packet ships fileSize=0/md5=empty and + // the recipient sees a 0-byte file. With the cache we recover the + // real tuple. + const sendC2cFileMessage = vi.fn(async (_uin: number, _uid: string, _info: any) => goodReceipt); + const recallUploadedFile = vi.fn((id: string) => id === 'uuid-cached' ? { + fileId: 'uuid-cached', + scope: 'private' as const, + userId: 67890, + fileName: 'real-doc.pdf', + fileSize: 4096, + fileMd5: Buffer.from('aabbccddeeff', 'hex'), + fileSha1: new Uint8Array(20), + fileHash: 'srv-hash', + rememberedAt: 0, + } : undefined); + const bridge = fakeBridge({ + sendPrivateMessage: vi.fn(), + sendC2cFileMessage, + resolveUserUid: vi.fn(async () => 'u_peer'), + recallUploadedFile, + } as any); + const ctx = makeCtx(bridge); + + await sendPrivateMessage(ctx, 67890, [{ + type: 'file', data: { file_id: 'uuid-cached' }, + }] as any, false); + + expect(sendC2cFileMessage).toHaveBeenCalledOnce(); + const [, , info] = sendC2cFileMessage.mock.calls[0]!; + expect(info).toMatchObject({ + fileId: 'uuid-cached', + fileName: 'real-doc.pdf', + fileSize: 4096, + fileHash: 'srv-hash', + }); + expect(info.fileMd5).toEqual(Buffer.from('aabbccddeeff', 'hex')); + }); + + it('inline segment fields take precedence over the upload cache', async () => { + // If the caller threads the metadata inline (e.g. they tracked the + // upload response themselves), honour that over the cache so a + // refresh of an evicted file still works. + const sendC2cFileMessage = vi.fn(async (_uin: number, _uid: string, _info: any) => goodReceipt); + const recallUploadedFile = vi.fn(() => ({ + fileId: 'uuid-x', + scope: 'private' as const, + userId: 67890, + fileName: 'stale-cache-name.txt', + fileSize: 99, + fileMd5: new Uint8Array(16), + fileSha1: new Uint8Array(20), + fileHash: 'stale-hash', + rememberedAt: 0, + })); + const bridge = fakeBridge({ + sendPrivateMessage: vi.fn(), + sendC2cFileMessage, + resolveUserUid: vi.fn(async () => 'u_peer'), + recallUploadedFile, + } as any); + const ctx = makeCtx(bridge); + + await sendPrivateMessage(ctx, 67890, [{ + type: 'file', data: { file_id: 'uuid-x', name: 'inline.txt', size: 200, md5: '11223344', file_hash: 'inline-hash' }, + }] as any, false); + + const [, , info] = sendC2cFileMessage.mock.calls[0]!; + expect(info).toMatchObject({ + fileName: 'inline.txt', + fileSize: 200, + fileHash: 'inline-hash', + }); + expect(info.fileMd5).toEqual(Buffer.from('11223344', 'hex')); + }); + it('mixed file + text splits across two sends (text first, file second)', async () => { const sendPrivateMessage_bridge = vi.fn(async (_uin: number, _elements: any[]) => goodReceipt); const sendC2cFileMessage = vi.fn(async (_uin: number, _uid: string, _info: any) => goodReceipt); @@ -85,6 +165,7 @@ describe('send_private_msg with {type:"file"} segment', () => { sendPrivateMessage: sendPrivateMessage_bridge, sendC2cFileMessage, resolveUserUid, + recallUploadedFile: vi.fn(() => undefined), } as any); const ctx = makeCtx(bridge); @@ -118,6 +199,7 @@ describe('send_private_msg with {type:"file"} segment', () => { sendPrivateMessage: sendPrivateMessage_bridge, sendC2cFileMessage, resolveUserUid: vi.fn(), + recallUploadedFile: vi.fn(() => undefined), } as any); const ctx = makeCtx(bridge); @@ -141,6 +223,7 @@ describe('send_private_msg with {type:"file"} segment', () => { sendPrivateMessage: vi.fn(), sendC2cFileMessage, resolveUserUid: vi.fn(async () => ''), // intentional empty + recallUploadedFile: vi.fn(() => undefined), } as any); const ctx = makeCtx(bridge); From cc574632f1258f86ccc56066bacf12113a49a691 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Wed, 20 May 2026 13:32:35 +0800 Subject: [PATCH 45/48] fix(test): declare vi.fn param types so mock.calls[0] infers tuple `vi.fn(async () => undefined)` infers `mock.calls: [][]`, so destructuring `const [groupId, fileId] = ...mock.calls[0]!` fails under TS strict tuple checks (`error TS2493: Tuple type '[]' of length '0' has no element at index '0'`). Declare the param types inline so the call-args tuple is `[number, string]`. --- packages/core/tests/onebot/send-group-file.test.ts | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/packages/core/tests/onebot/send-group-file.test.ts b/packages/core/tests/onebot/send-group-file.test.ts index c606f50a..3625c938 100644 --- a/packages/core/tests/onebot/send-group-file.test.ts +++ b/packages/core/tests/onebot/send-group-file.test.ts @@ -50,7 +50,10 @@ describe('send_group_msg with {type:"file"} segment', () => { // and got result=79. The dedicated OIDB-0x6d9_4 route must take // over for group file publishing. const sendGroupMessage_bridge = vi.fn(); - const sendGroupFileMessage = vi.fn(async () => undefined); + // Declare params on the fn so `mock.calls[0]` infers a tuple of + // [groupId, fileId] instead of `[]` (which makes the destructuring + // a tsc error under noUncheckedIndexedAccess). + const sendGroupFileMessage = vi.fn(async (_groupId: number, _fileId: string) => undefined); const bridge = fakeBridge({ sendGroupMessage: sendGroupMessage_bridge, sendGroupFileMessage, @@ -72,7 +75,7 @@ describe('send_group_msg with {type:"file"} segment', () => { it('mixed text + file splits across two sends (text via elems[], file via OIDB)', async () => { const sendGroupMessage_bridge = vi.fn(async (_gid: number, _elements: any[]) => goodReceipt); - const sendGroupFileMessage = vi.fn(async () => undefined); + const sendGroupFileMessage = vi.fn(async (_groupId: number, _fileId: string) => undefined); const bridge = fakeBridge({ sendGroupMessage: sendGroupMessage_bridge, sendGroupFileMessage, From d1aade6f87f4f269c86feaceebd325b370972bff Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Wed, 20 May 2026 13:56:31 +0800 Subject: [PATCH 46/48] fix(forward): keep file segments in long-msg payload via forwardFake flag MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Previous fix split file segments off at the OneBot live-send layer (c2c → sendC2cFileMessage, group → sendGroupFileMessage) and made element-builder drop any `{type:'file'}` segment that reached it. That broke forward messages: send_forward_msg encodes each node through buildSendElems for the long-msg upload, so file segments inside a forward node hit the drop-with-warn path and the forward bubble shipped without the file. Forward upload is NOT a live PbSendMsg — it stores the gzipped protobuf verbatim through `trpc.group.long_msg_interface.MsgService. SsoSendLongMsg`, and the recipient decodes file entities through the normal msg-push path (transElem(24) → GroupFileExtra; msgContent → FileExtra { file: NotOnlineFile }). So `result=79` doesn't apply here. Add a `forwardFake?: true` flag on SendContext; when set: * group file → element-builder emits transElem(24) again (restored makeGroupFileElem, exactly the receive-side wire shape). * c2c file → element-builder still skips; forward-builder pulls the segment off the node and writes `body.msgContent` as FileExtra { file: NotOnlineFile }, with file metadata hydrated from the upload cache when inline fields are missing (same pattern as send_private_msg). Mirrors NapCat's PacketMsgFileElement.{buildElement,buildContent} split (dev/napcatQQ/.../packet/message/element.ts:530-610) and Lagrange.Core V2's MultiMsgUploadService.cs. --- packages/core/src/bridge/actions/forward.ts | 73 +++++++- packages/core/src/bridge/element-builder.ts | 125 ++++++++++--- .../core/tests/actions/forward-file.test.ts | 165 ++++++++++++++++++ 3 files changed, 335 insertions(+), 28 deletions(-) create mode 100644 packages/core/tests/actions/forward-file.test.ts diff --git a/packages/core/src/bridge/actions/forward.ts b/packages/core/src/bridge/actions/forward.ts index 07c1db36..ddca085b 100644 --- a/packages/core/src/bridge/actions/forward.ts +++ b/packages/core/src/bridge/actions/forward.ts @@ -18,7 +18,7 @@ import type { SendLongMsgReq, SendLongMsgResp, } from '../proto/proton/longmsg'; -import type { PushMsg, PushMsgBody } from '../proto/proton/message'; +import type { FileExtra, PushMsg, PushMsgBody } from '../proto/proton/message'; import { resolveSelfUid, toInt } from './shared'; // Module-scoped cache, keyed by res_id. Survives only for the lifetime @@ -40,16 +40,67 @@ async function buildForwardPushBody( // forward's recipient: group → groupId, private → recipient uid. // Without this the OIDB upload (0x11c4/0x11c5) has no scene and the // element builder throws "private image target uid is missing". + // + // `forwardFake: true` keeps `{type:'file'}` segments in the + // long-msg payload: group → emitted as transElem(24) in elems[], + // c2c → handled below via msgContent (FileExtra { file: NotOnlineFile }). + // The QQ-NT live-send pipeline would reject these (transElem(24) → + // result=79; notOnlineFile via PbSendMsg doesn't render), but the + // long-msg upload service stores the bytes verbatim and the + // receiver decodes them through the normal msg-push path. const sendCtx = groupId !== undefined - ? { bridge, groupId } + ? { bridge, groupId, forwardFake: true } : userUid - ? { bridge, userUid } - : { bridge }; + ? { bridge, userUid, forwardFake: true } + : { bridge, forwardFake: true }; const elems = await buildSendElems(node.elements, sendCtx); const now = Math.floor(Date.now() / 1000); const random = Math.floor(Math.random() * 0x7fffffff) >>> 0; const seq = Math.floor(Math.random() * 9000000) + 1000000; + // c2c-file in a forward node — element-builder intentionally skips + // it (RichText.notOnlineFile + msgContent live outside elems[]). For + // forward fake-send we mirror what an inbound c2c file message looks + // like on the wire: serialise the FileExtra blob and ride it on + // `body.msgContent`. The receiver's rich-body-decoder reads from + // `msgContent` first (see msg-push/rich-body-decoder.ts:446+), so + // the bubble renders with the right file name + size when the + // forward is expanded. Only the FIRST c2c file in a node ships — + // QQ NT's bubble can only carry one msgContent payload, same as + // a live c2c send. Group nodes ignore this branch entirely (the + // transElem(24) elems[] entry above covers them). + let msgContent: Uint8Array | undefined; + if (groupId === undefined) { + const fileEl = node.elements.find(e => e.type === 'file' && e.fileId); + if (fileEl) { + // Honour inline segment fields first; fall back to the upload + // metadata cache (populated by upload_private_file). Without + // size/md5 the receiver would render "0 B" so prefer recovering + // them — see same logic in modules/message-actions.ts. + const cached = bridge.recallUploadedFile(fileEl.fileId ?? ''); + const fileMd5 = fileEl.md5Hex + ? hexToBytesLocal(fileEl.md5Hex) + : (cached?.fileMd5 ?? new Uint8Array(0)); + const fileSize = fileEl.fileSize ?? cached?.fileSize ?? 0; + const fileName = fileEl.fileName ?? cached?.fileName ?? 'file'; + const fileHash = fileEl.fileHash ?? cached?.fileHash ?? ''; + const sevenDays = 7 * 24 * 60 * 60; + msgContent = protobuf_encode({ + file: { + fileType: 0, + fileUuid: fileEl.fileId!, + fileMd5, + fileName, + fileSize: BigInt(fileSize), + subcmd: 1, + dangerEvel: 0, + expireTime: now + sevenDays, + fileHash, + }, + }); + } + } + return { responseHead: { fromUin, @@ -70,10 +121,24 @@ async function buildForwardPushBody( richText: { elems, }, + ...(msgContent ? { msgContent } : {}), }, }; } +// Local hex-decode helper — avoids importing the heavyweight `pipeline` +// module just for one call. Mirrors `highway/pipeline.ts::hexToBytes`. +function hexToBytesLocal(hex: string): Uint8Array { + const s = hex.trim(); + if (!s) return new Uint8Array(0); + const len = s.length >> 1; + const out = new Uint8Array(len); + for (let i = 0; i < len; i++) { + out[i] = parseInt(s.substr(i * 2, 2), 16); + } + return out; +} + // Per-layer piggyback entry. Each level of a nested forward attaches // its own msgBody under a uuid `actionCommand`, so when the receiver // fetches the outermost res_id it gets every layer in one shot diff --git a/packages/core/src/bridge/element-builder.ts b/packages/core/src/bridge/element-builder.ts index d3530c40..d2ea31c7 100644 --- a/packages/core/src/bridge/element-builder.ts +++ b/packages/core/src/bridge/element-builder.ts @@ -13,12 +13,11 @@ import type { MentionExtraSend, MarkdownData, } from './proto/proton/action'; -// `GroupFileExtra` + `hexToBytes` used to support `makeGroupFileElem` -// (removed — see comment above the former call site). The receive-side -// decoder in `msg-push/rich-body-decoder.ts` still pulls those in. +import type { GroupFileExtra } from './proto/proton/element'; import { uploadImageMsgInfo } from './highway/image-upload'; import { uploadPttMsgInfo } from './highway/ptt-upload'; import { uploadVideoMsgInfo } from './highway/video-upload'; +import { hexToBytes } from './highway/pipeline'; type ProtoElem = Partial>; @@ -26,6 +25,18 @@ export interface SendContext { bridge: Bridge; groupId?: number; userUid?: string; + /** + * Set by the forward-message upload path. When `true`, file segments + * are encoded as receive-side wire shapes (group → `transElem(24)`, + * c2c → caller writes `body.msgContent` separately) instead of being + * dropped. The QQ-NT server rejects outgoing PbSendMsg with + * `transElem(24)` (result=79), but the long-msg upload service does + * NOT — it stores the gzipped protobuf verbatim, so the receiver + * can walk it back through the regular decoder. Mirrors NapCat's + * `PacketMsgFileElement.buildElement` + `buildContent` split (see + * `dev/napcatQQ/.../packet/message/element.ts:530-610`). + */ + forwardFake?: boolean; } function makeTextElem(text: string): ProtoElem { @@ -247,12 +258,61 @@ async function makePttElem(ctx: SendContext, element: MessageElement): Promise

({ + field1: 6, + fileName, + inner: { + info: { + busId: 102, + fileId: element.fileId, + fileSize: BigInt(fileSize), + fileName, + fileSha: sha1, + extInfoString: '', + fileMd5: md5, + }, + }, + }); + if (extraBytes.length > 0xFFFF) { + // The 16-bit length prefix caps the payload at 64 KiB; even the + // densest GroupFileExtra (fileId/name/two hashes) is well under. + throw new Error(`group file extra too large (${extraBytes.length} > 65535)`); + } + const elemValue = new Uint8Array(3 + extraBytes.length); + elemValue[0] = 0x01; + elemValue[1] = (extraBytes.length >> 8) & 0xff; + elemValue[2] = extraBytes.length & 0xff; + elemValue.set(extraBytes, 3); + + return { + transElem: { + elemType: 24, + elemValue, + } as any, + }; +} async function makeVideoElem(ctx: SendContext, element: MessageElement): Promise { const isGroup = ctx.groupId !== undefined; @@ -342,22 +402,39 @@ export async function buildSendElems(elements: MessageElement[], ctx?: SendConte break; case 'file': - // Files NEVER ride on the elems[] pipeline anymore — both flavors - // route at the OneBot layer: - // * c2c (private): split off and dispatched via - // `bridge.sendC2cFileMessage` (uses routingHead.trans0x211 + - // msgContent FileExtra; see bridge.ts::sendC2cFileMessage). - // * group: split off and dispatched via - // `bridge.sendGroupFileMessage` (uses OIDB 0x6d9_4; see - // actions/group-file.ts::sendGroupFileMessage). + // Files split into two routes depending on whether this is a + // live send or a forward-message fake-send: // - // The old transElem(24) shape DOES work for receive-side decode - // (rich-body-decoder unpacks it into a FileEntity), but the - // QQ-NT server rejects it on outgoing with result=79. If a file - // segment still reaches us here the caller forgot to route at - // the OneBot layer — drop with a loud warn so it doesn't silently - // ship as "[空消息]" or a 0-byte stub. - console.warn('[ElemBuilder] BUG: {type:"file"} reached element-builder — must be split out at the OneBot layer (see modules/message-actions.ts::sendPrivateMessage / ::sendGroupMessage)'); + // 1. LIVE send (PbSendMsg / OIDB 0x6d9_4) — never carried on + // elems[]. The OneBot layer splits file segments off before + // calling buildSendElems: + // * c2c (private): split → `bridge.sendC2cFileMessage` + // (routingHead.trans0x211 + msgContent FileExtra). + // * group: split → `bridge.sendGroupFileMessage` + // (OIDB 0x6d9_4 publish). + // The QQ-NT server REJECTS outgoing PbSendMsg with a + // transElem(24) (result=79), so an element reaching here + // in live-send mode is a routing bug — drop with a warn. + // + // 2. FORWARD-FAKE upload (long-msg) — `ctx.forwardFake===true`. + // The long-msg service stores the gzipped protobuf verbatim + // and the receiver decodes file entities from transElem(24) + // + msgContent FileExtra. Mirror NapCat's split (see + // `dev/napcatQQ/.../packet/message/element.ts:530-610`): + // * group → emit transElem(24) via makeGroupFileElem + // * c2c → emit NOTHING here; the forward-builder pulls + // the file segment off and writes msgContent + // separately (because RichText.notOnlineFile + + // FileExtra both live outside elems[]). + if (ctx?.forwardFake) { + if (ctx.groupId !== undefined) { + result.push(makeGroupFileElem(elem)); + } + // c2c forwardFake intentionally falls through — handled by + // the forward-builder at the msgContent level. + } else { + console.warn('[ElemBuilder] BUG: {type:"file"} reached element-builder — must be split out at the OneBot layer (see modules/message-actions.ts::sendPrivateMessage / ::sendGroupMessage)'); + } break; default: diff --git a/packages/core/tests/actions/forward-file.test.ts b/packages/core/tests/actions/forward-file.test.ts new file mode 100644 index 00000000..3c527ce0 --- /dev/null +++ b/packages/core/tests/actions/forward-file.test.ts @@ -0,0 +1,165 @@ +// Regression coverage for the file-inside-send_forward_msg bug. +// +// Symptom: caller put `{type:'file', file_id}` inside a forward node; +// the element-builder dropped it (`[ElemBuilder] BUG: {type:"file"} +// reached element-builder — must be split out at the OneBot layer`) +// because the live-send paths route files through dedicated methods +// (sendC2cFileMessage / sendGroupFileMessage), and the forward +// builder was naïvely calling buildSendElems with the same ctx. The +// forward upload succeeded but the bubble shipped without the file +// element. +// +// Fix: forward upload passes `forwardFake: true` on the SendContext. +// The element-builder honours that flag by emitting the receive-side +// shapes: +// * group file → transElem(elemType=24, GroupFileExtra) +// * c2c file → handled at the forward-builder level, written into +// `body.msgContent` as FileExtra { file: NotOnlineFile } +// +// These shapes are RECEIVE-side: the QQ-NT live-send pipeline rejects +// transElem(24) (result=79), but the long-msg upload service stores the +// gzipped protobuf verbatim and the recipient's msg-push decoder pulls +// the file entity back out via the normal path (rich-body-decoder.ts). +// Mirrors NapCat's `PacketMsgFileElement.{buildElement,buildContent}` +// split. + +import { describe, it, expect, vi } from 'vitest'; + +vi.mock('../../src/bridge/bridge-oidb', () => ({ + runOidb: vi.fn(async () => new Uint8Array()), + makeOidbEnvelope: vi.fn((_oidbCmd, _subCmd, body) => ({ body })), + encodeOidbEnv: vi.fn(() => new Uint8Array()), + decodeOidbEnv: vi.fn(() => ({ body: {} })), +})); + +// `vi.mock` factories are hoisted above the imports — declare the spy +// inside a `vi.hoisted` block so it's available at the same moment. +const { buildSendElemsMock } = vi.hoisted(() => ({ + buildSendElemsMock: vi.fn(async () => []), +})); +vi.mock('../../src/bridge/element-builder', () => ({ + buildSendElems: buildSendElemsMock, +})); + +import { protoEncode } from '../../src/protobuf/decode'; +import { SendLongMsgRespSchema } from '../../src/bridge/proto/longmsg'; +import * as forward from '../../src/bridge/actions/forward'; +import { mockBridge } from './_helpers'; + +function uploadResponseWithResId(resId: string) { + const encoded = protoEncode({ result: { resId } }, SendLongMsgRespSchema); + return { + success: true, + gotResponse: true, + errorCode: 0, + errorMessage: '', + responseData: Buffer.from(encoded), + }; +} + +describe('actions/forward — file segment inside forward node', () => { + it('group forward sets forwardFake:true on the SendContext so transElem(24) is emitted', async () => { + // Group case: the file element rides on elems[] as transElem(24). + // The element-builder receives ctx.forwardFake=true so it knows to + // emit the receive-side shape instead of dropping the segment. + buildSendElemsMock.mockClear(); + const bridge = mockBridge({ + sendRawPacket: vi.fn(async () => uploadResponseWithResId('res-grp-file')) as any, + }); + + await forward.uploadForwardNodes(bridge as any, [ + { + userUin: 10001, + nickname: 'alice', + elements: [{ type: 'file', fileId: 'gfid-1', fileName: 'a.txt', fileSize: 99 } as any], + }, + ], 12345); + + expect(buildSendElemsMock).toHaveBeenCalled(); + const [, ctx] = buildSendElemsMock.mock.calls[0]!; + expect(ctx).toMatchObject({ groupId: 12345, forwardFake: true }); + }); + + it('c2c forward writes the file as msgContent (FileExtra { file: NotOnlineFile })', async () => { + // Private case: c2c files live on `body.msgContent`, not in elems[]. + // The forward-builder pulls the file segment off and synthesises a + // FileExtra payload so the recipient's decoder (which reads + // msgContent first) renders the file bubble. + buildSendElemsMock.mockClear(); + let captured: Uint8Array | undefined; + const bridge = mockBridge({ + sendRawPacket: vi.fn(async (_cmd: string, body: Uint8Array) => { + captured = body; + return uploadResponseWithResId('res-c2c-file'); + }) as any, + // Inline fields cover everything we need; cache lookup must not be + // required for the path to work. + recallUploadedFile: vi.fn(() => undefined), + }); + + await forward.uploadForwardNodes(bridge as any, [ + { + userUin: 10001, + nickname: 'alice', + elements: [{ + type: 'file', + fileId: 'pfid-1', + fileName: 'invoice.pdf', + fileSize: 4096, + md5Hex: 'aabbccddeeff00112233445566778899', + fileHash: 'srv-hash-abc', + } as any], + }, + ], undefined, 67890); + + expect(buildSendElemsMock).toHaveBeenCalled(); + const [, ctx] = buildSendElemsMock.mock.calls[0]!; + expect(ctx).toMatchObject({ forwardFake: true }); + expect(ctx.groupId).toBeUndefined(); + + // Spot-check that the upload body carries the file metadata. The + // payload is gzipped + protobuf-wrapped, so we just verify the + // raw filename string survived — that's enough to confirm the + // FileExtra branch ran (a "missing file" regression would drop + // these bytes entirely). + expect(captured).toBeDefined(); + const flat = Buffer.from(captured!).toString('binary'); + // The filename gets gzipped, so we can't substring-search; instead + // assert the body is large enough that the FileExtra wasn't elided. + // (A name-only forward with no msgContent runs ~80-100 bytes; with + // the FileExtra blob it's noticeably larger.) + expect(flat.length).toBeGreaterThan(80); + }); + + it('c2c forward falls back to the upload metadata cache when inline fields are missing', async () => { + // The OneBot caller often passes only `file_id` — the rest comes + // from the bridge's uploaded-file cache. This is the same + // hydration path send_private_msg uses; the forward builder must + // honour it too or every cached-only forward ships a 0 B bubble. + buildSendElemsMock.mockClear(); + const recallUploadedFile = vi.fn((id: string) => id === 'pfid-cached' ? { + fileId: 'pfid-cached', + scope: 'private' as const, + userId: 67890, + fileName: 'cached-name.zip', + fileSize: 8192, + fileMd5: Buffer.from('ffeeddccbbaa99887766554433221100', 'hex'), + fileSha1: new Uint8Array(20), + fileHash: 'cached-hash', + rememberedAt: 0, + } : undefined); + + const bridge = mockBridge({ + sendRawPacket: vi.fn(async () => uploadResponseWithResId('res-cache')) as any, + recallUploadedFile, + }); + + await forward.uploadForwardNodes(bridge as any, [{ + userUin: 10001, + nickname: 'alice', + elements: [{ type: 'file', fileId: 'pfid-cached' } as any], + }], undefined, 67890); + + expect(recallUploadedFile).toHaveBeenCalledWith('pfid-cached'); + }); +}); From 5d83aedd833674b219b28e60d074af4bbd38af54 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Wed, 20 May 2026 14:07:36 +0800 Subject: [PATCH 47/48] fix(typecheck): narrow ctx explicitly and type buildSendElems mock params MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CI tsc flagged two strict-mode issues in d1aade6: * element-builder: `ctx?.forwardFake` doesn't carry the non-null narrowing to a subsequent `ctx.groupId` access — replace with an explicit `ctx && ctx.forwardFake` guard. * forward-file.test: `vi.fn(async () => [])` infers `mock.calls` as `[][]`, so `const [, ctx] = mock.calls[0]!` is "Tuple of length '0' has no element at index '1'". Declare the mock's parameter types (`unknown[], Record?`) so the call tuple has the right arity, and use `ctx?.groupId` since the ctx slot is now typed as optional. --- packages/core/src/bridge/element-builder.ts | 2 +- packages/core/tests/actions/forward-file.test.ts | 7 +++++-- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/packages/core/src/bridge/element-builder.ts b/packages/core/src/bridge/element-builder.ts index d2ea31c7..96e7e78d 100644 --- a/packages/core/src/bridge/element-builder.ts +++ b/packages/core/src/bridge/element-builder.ts @@ -426,7 +426,7 @@ export async function buildSendElems(elements: MessageElement[], ctx?: SendConte // the file segment off and writes msgContent // separately (because RichText.notOnlineFile + // FileExtra both live outside elems[]). - if (ctx?.forwardFake) { + if (ctx && ctx.forwardFake) { if (ctx.groupId !== undefined) { result.push(makeGroupFileElem(elem)); } diff --git a/packages/core/tests/actions/forward-file.test.ts b/packages/core/tests/actions/forward-file.test.ts index 3c527ce0..d63154e1 100644 --- a/packages/core/tests/actions/forward-file.test.ts +++ b/packages/core/tests/actions/forward-file.test.ts @@ -34,8 +34,11 @@ vi.mock('../../src/bridge/bridge-oidb', () => ({ // `vi.mock` factories are hoisted above the imports — declare the spy // inside a `vi.hoisted` block so it's available at the same moment. +// Declare parameter types on the fn so `mock.calls[0]` infers a tuple +// of [elements, ctx] instead of `[]`, which makes the destructuring +// a tsc error under strict tuple checking on CI. const { buildSendElemsMock } = vi.hoisted(() => ({ - buildSendElemsMock: vi.fn(async () => []), + buildSendElemsMock: vi.fn(async (_elements: unknown[], _ctx?: Record) => []), })); vi.mock('../../src/bridge/element-builder', () => ({ buildSendElems: buildSendElemsMock, @@ -115,7 +118,7 @@ describe('actions/forward — file segment inside forward node', () => { expect(buildSendElemsMock).toHaveBeenCalled(); const [, ctx] = buildSendElemsMock.mock.calls[0]!; expect(ctx).toMatchObject({ forwardFake: true }); - expect(ctx.groupId).toBeUndefined(); + expect(ctx?.groupId).toBeUndefined(); // Spot-check that the upload body carries the file metadata. The // payload is gzipped + protobuf-wrapped, so we just verify the From 2de1ff4f0d5976971d1db1ed737d8aad33bf60c5 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Wed, 20 May 2026 14:21:03 +0800 Subject: [PATCH 48/48] chore(release): v1.9.0 --- package.json | 2 +- packages/core/package.json | 2 +- packages/proton/package.json | 2 +- packages/runtime/package.json | 2 +- packages/sdk/package.json | 2 +- packages/ui/package.json | 2 +- packages/websocket/package.json | 2 +- packages/webui/package.json | 2 +- 8 files changed, 8 insertions(+), 8 deletions(-) diff --git a/package.json b/package.json index 3029715d..e131e7c6 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "snowluma-monorepo", - "version": "1.8.5", + "version": "1.9.0", "description": "SnowLuma monorepo workspace (pnpm)", "private": true, "type": "module", diff --git a/packages/core/package.json b/packages/core/package.json index 7d7d855e..e3ff10a0 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -1,6 +1,6 @@ { "name": "@snowluma/core", - "version": "1.8.5", + "version": "1.9.0", "description": "SnowLuma core - NTQQ packet sniffer with Node.js native addon", "private": true, "type": "module", diff --git a/packages/proton/package.json b/packages/proton/package.json index 8edd7e33..9ad2d5b9 100644 --- a/packages/proton/package.json +++ b/packages/proton/package.json @@ -1,6 +1,6 @@ { "name": "@snowluma/proton", - "version": "1.8.5", + "version": "1.9.0", "private": true, "type": "module", "description": "Compile-time protobuf encoder/decoder generator for SnowLuma. TypeScript interfaces → fully-inlined, zero-runtime protobuf codec functions. Vendored from SnowLuma/protobuf-dsl (reference copy under dev/protobuf-dsl/) with edge-case fixes applied.", diff --git a/packages/runtime/package.json b/packages/runtime/package.json index ac3a169a..3e30cb7a 100644 --- a/packages/runtime/package.json +++ b/packages/runtime/package.json @@ -1,6 +1,6 @@ { "name": "@snowluma/runtime", - "version": "1.8.5", + "version": "1.9.0", "private": true, "type": "module", "main": "index.mjs", diff --git a/packages/sdk/package.json b/packages/sdk/package.json index 7462553c..50475569 100644 --- a/packages/sdk/package.json +++ b/packages/sdk/package.json @@ -4,7 +4,7 @@ "name": "MotricSeven", "email": "motricseven@gmail.com" }, - "version": "1.8.5", + "version": "1.9.0", "description": "TypeScript SDK for SnowLuma OneBot HTTP and WebSocket transports", "keywords": [ "snowluma", diff --git a/packages/ui/package.json b/packages/ui/package.json index 62f6a6f7..e1a310e4 100644 --- a/packages/ui/package.json +++ b/packages/ui/package.json @@ -4,7 +4,7 @@ "name": "MotricSeven", "email": "motricseven@gmail.com" }, - "version": "1.8.5", + "version": "1.9.0", "description": "Shared SnowLuma UI primitives — Tailwind 4 theme tokens + shadcn-style atomic components", "keywords": [ "snowluma", diff --git a/packages/websocket/package.json b/packages/websocket/package.json index ed3c0963..4fc99bce 100644 --- a/packages/websocket/package.json +++ b/packages/websocket/package.json @@ -1,6 +1,6 @@ { "name": "@snowluma/websocket", - "version": "1.8.5", + "version": "1.9.0", "private": true, "type": "module", "main": "./src/index.ts", diff --git a/packages/webui/package.json b/packages/webui/package.json index 17b798aa..d9bfbd86 100644 --- a/packages/webui/package.json +++ b/packages/webui/package.json @@ -1,7 +1,7 @@ { "name": "webui", "private": true, - "version": "1.8.5", + "version": "1.9.0", "type": "module", "scripts": { "dev": "vite",