diff --git a/packages/core/src/bridge/apis/flash-transfer.ts b/packages/core/src/bridge/apis/flash-transfer.ts new file mode 100644 index 00000000..d9dab528 --- /dev/null +++ b/packages/core/src/bridge/apis/flash-transfer.ts @@ -0,0 +1,453 @@ +// FlashTransferApi — 闪传(fileset)业务编排。 +// 复用 OIDB 基础设施(invokeOidb),协议层在 @snowluma/protocol/oidb-services/flash-transfer/。 + +import type { BridgeContext } from '../bridge-context'; +import type { FlashFileEntry } from '@snowluma/proto-defs/oidb-actions/flash-transfer'; +import { GetFilesetDetail } from '@snowluma/protocol/oidb-services/flash-transfer/get-fileset-detail'; +import { ListFilesets } from '@snowluma/protocol/oidb-services/flash-transfer/list-filesets'; +import { GetDownloadUrl } from '@snowluma/protocol/oidb-services/flash-transfer/get-download-url'; +import { GetFlashDownload } from '@snowluma/protocol/oidb-services/flash-transfer/get-flash-download'; +import { DeleteFlashFile } from '@snowluma/protocol/oidb-services/flash-transfer/delete-file'; +import { RenameFlashFile } from '@snowluma/protocol/oidb-services/flash-transfer/rename-file'; +import { ApplyFileset } from '@snowluma/protocol/oidb-services/flash-transfer/apply-fileset'; +import { CommitFile } from '@snowluma/protocol/oidb-services/flash-transfer/commit-file'; +import { CompleteFileset } from '@snowluma/protocol/oidb-services/flash-transfer/complete-fileset'; +import { SetFilesetStatus } from '@snowluma/protocol/oidb-services/flash-transfer/set-status'; +import { ApplyUpload } from '@snowluma/protocol/oidb-services/flash-transfer/apply-upload'; +import { PrepareUpload } from '@snowluma/protocol/oidb-services/flash-transfer/prepare-upload'; +import { SendFlashMsg } from '@snowluma/protocol/oidb-services/flash-transfer/send-flash'; +import { loadBinarySource, computeHashes } from '@snowluma/protocol/highway/utils'; +import { computeSha1StateV } from '@snowluma/protocol/highway/sha1-stream'; +import { protobuf_encode, protobuf_decode } from '@snowluma/proton'; +import type { FlashSliceUploadBody, FlashSliceUploadResp, FlashFileId } from '@snowluma/proto-defs/oidb-actions/flash-transfer'; +import { randomUUID, randomBytes, createHash } from 'node:crypto'; +import { deflateSync } from 'node:zlib'; + +/** 闪传文件信息(业务层,从 FlashFileEntry 转换)。 */ +export interface FlashFileInfo { + filesetUuid: string; + fileName: string; + origName: string; + fileSize: number; + /** 上传/分享链接 qfile.qq.com/q/。 */ + shareUrl: string; + fileId: string; + /** 下载链接 multimedia.qfile.qq.com/download?...&rkey=... */ + downloadUrl: string; +} + +function entryToInfo(e: FlashFileEntry): FlashFileInfo { + return { + filesetUuid: e.filesetUuid ?? '', + fileName: e.fileName ?? '', + origName: e.origName ?? '', + fileSize: Number(e.fileSize ?? 0), + shareUrl: e.uploadUrlWrap?.uploadUrl ?? '', + fileId: e.fileIdWrap?.fileId ?? '', + downloadUrl: e.fileIdWrap?.download?.downloadUrl ?? '', + }; +} + +// 手写 PNG 编码(zlib 压缩,避免引入图像库)。缩略图用随机纯色,每次 SHA1 不同, +// 避免命中服务端秒传缓存。 +const CRC_TABLE: Uint32Array = (() => { + const table = new Uint32Array(256); + for (let n = 0; n < 256; n++) { + let c = n; + for (let k = 0; k < 8; k++) c = (c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1); + table[n] = c >>> 0; + } + return table; +})(); + +function crc32(buf: Buffer): number { + let c = 0xFFFFFFFF; + for (let i = 0; i < buf.length; i++) c = CRC_TABLE[(c ^ buf[i]) & 0xFF] ^ (c >>> 8); + return (c ^ 0xFFFFFFFF) >>> 0; +} + +function pngChunk(type: string, data: Buffer): Buffer { + const len = Buffer.alloc(4); + len.writeUInt32BE(data.length, 0); + const typeBuf = Buffer.from(type, 'ascii'); + const crc = crc32(Buffer.concat([typeBuf, data])); + const crcBuf = Buffer.alloc(4); + crcBuf.writeUInt32BE(crc, 0); + return Buffer.concat([len, typeBuf, data, crcBuf]); +} + +/** 生成 width×height 随机纯色 PNG(8-bit RGB)。每次随机颜色,SHA1 不同以避免秒传。 */ +function generatePng(width: number, height: number): Buffer { + const r = Math.floor(Math.random() * 256); + const g = Math.floor(Math.random() * 256); + const b = Math.floor(Math.random() * 256); + const rowLen = 1 + width * 3; + const raw = Buffer.alloc(rowLen * height); + for (let y = 0; y < height; y++) { + const off = y * rowLen; + raw[off] = 0; // filter none + for (let x = 0; x < width; x++) { + raw[off + 1 + x * 3] = r; + raw[off + 1 + x * 3 + 1] = g; + raw[off + 1 + x * 3 + 2] = b; + } + } + const compressed = deflateSync(raw); + const sig = Buffer.from([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]); + const ihdr = Buffer.alloc(13); + ihdr.writeUInt32BE(width, 0); + ihdr.writeUInt32BE(height, 4); + ihdr[8] = 8; // bit depth + ihdr[9] = 2; // color type RGB + ihdr[10] = 0; ihdr[11] = 0; ihdr[12] = 0; + return Buffer.concat([sig, pngChunk('IHDR', ihdr), pngChunk('IDAT', compressed), pngChunk('IEND', Buffer.alloc(0))]); +} + +export class FlashTransferApi { + constructor(private readonly ctx: BridgeContext) { } + + /** 获取文件集信息(get_fileset_info)。 */ + async getFilesetInfo(filesetUuid: string): Promise { + const entries = await GetFilesetDetail.invoke(this.ctx, { filesetUuid }); + return entries.map(entryToInfo); + } + + /** 获取闪传文件列表(get_flash_file_list)。同 getFilesetInfo,返回文件数组。 */ + async getFlashFileList(filesetUuid: string): Promise { + return this.getFilesetInfo(filesetUuid); + } + + /** + * 拿指定文件的下载直链 + 元信息。0x93d4 返回 fileset 内所有文件(f3 repeated, + * 多文件时每条 f6=序号、f14=主文件 fileId),按 fileIndex 选中后走 0x12a9 sub=200 + * 拿主文件直链。0x93d3/0x93d4 的 downloadUrl 字段是缩略图(appid=14903/14902), + * 主文件必须走 0x12a9 sub=200。 + */ + private async getFileDownload( + filesetUuid: string, fileIndex: number = 1, + ): Promise<{ url: string; fileName: string; fileSize: number } | null> { + const metas = await GetDownloadUrl.invoke(this.ctx, { filesetUuid }); + const meta = metas.find((m) => m.fileIndex === fileIndex); + if (!meta || !meta.fileId) return null; + const url = await GetFlashDownload.invoke(this.ctx, { + filesetUuid: meta.filesetUuid, + fileUuid: meta.fileUuid, + fileId: meta.fileId, + fileName: meta.fileName, + }); + if (!url) return null; + return { url, fileName: meta.fileName, fileSize: meta.fileSize }; + } + + /** + * 获取闪传文件下载链接(get_flash_file_url)。主文件直链走 0x12a9 sub=200 + * (0x93d3 的 downloadUrl 是缩略图 appid=14903,非主文件)。多文件 fileset 用 + * fileIndex 指定第几个文件(默认 1)。找不到文件或拿不到直链时抛错。 + */ + async getFlashFileUrl(filesetUuid: string, fileIndex: number = 1): Promise { + const dl = await this.getFileDownload(filesetUuid, fileIndex); + if (!dl || !dl.url) throw new Error('get_flash_file_url: no download url available'); + return dl.url; + } + + /** + * 解析闪传文件下载直链(download_fileset)。返回指定文件的下载 URL + 文件名/大小, + * 不下载文件内容(由调用方拉)。多文件 fileset 用 fileIndex 指定第几个文件(默认 1)。 + */ + async downloadFileset( + filesetUuid: string, + opts?: { fileName?: string; fileIndex?: number }, + ): Promise<{ url: string; fileName: string; fileSize: number }> { + const dl = await this.getFileDownload(filesetUuid, opts?.fileIndex ?? 1); + if (!dl || !dl.url) throw new Error('download_fileset: no download url available'); + return dl; + } + + /** 获取分享链接(get_share_link)= qfile.qq.com/q/。 */ + async getShareLink(filesetUuid: string): Promise { + const entries = await GetFilesetDetail.invoke(this.ctx, { filesetUuid }); + return entries.find((e) => e.uploadUrlWrap?.uploadUrl)?.uploadUrlWrap?.uploadUrl ?? ''; + } + + /** 列出当前账号的所有 fileset(OneBot 标准未定义,QQ 面板有此入口)。 */ + async listFilesets(): Promise { + const entries = await ListFilesets.invoke(this.ctx, {}); + return entries.map(entryToInfo); + } + + /** 删除闪传文件(delete_flash_file)。 */ + async deleteFlashFile(filesetUuid: string): Promise { + await DeleteFlashFile.invoke(this.ctx, { filesetUuid }); + } + + /** 重命名闪传文件(rename_flash_file)。 */ + async renameFlashFile(filesetUuid: string, newName: string): Promise { + await RenameFlashFile.invoke(this.ctx, { filesetUuid, newName }); + } + + /** + * 发送闪传文件(send_flash_msg,0x93d7)。私聊:user_id→uid;群聊:group_id 直接用。 + * 0x93d7 响应无 message_id(分享 fileset,非传统消息),OneBot 层 message_id 由 action 返回 0。 + */ + async sendFlashMsg(filesetUuid: string, target: { userId?: number; groupId?: number }): Promise { + if (target.groupId) { + await SendFlashMsg.invoke(this.ctx, { groupId: target.groupId, filesetUuid }); + return; + } + const userId = target.userId; + if (!userId) throw new Error('send_flash_msg: user_id or group_id is required'); + const targetUid = await this.ctx.identity.resolveUid(userId); + await SendFlashMsg.invoke(this.ctx, { targetUid, filesetUuid }); + } + + /** + * 从分享码/链接获取 fileset_id(get_fileset_id)。code→UUID 不走 OIDB,QQ 客户端 + * 走 trpc HTTP API;分享页 qfile.qq.com/q/ 的 HTML 内嵌了 fileset_id(trpc + * 接口数据),直接 GET + 正则提取即可,无需复刻带签名的 trpc 调用。 + */ + async getFilesetIdByCode(shareCode: string): Promise { + const url = /^https?:\/\//i.test(shareCode) ? shareCode : `https://qfile.qq.com/q/${shareCode}`; + const resp = await fetch(url); + if (!resp.ok) throw new Error(`get_fileset_id: HTTP ${resp.status}`); + const html = await resp.text(); + // 网页里 fileset_id 以 JSON 嵌入(引号可能被转义为 \"),正则兼容两种形态。 + const m = /fileset_id\\?"\s*:\s*\\?"([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/.exec(html); + if (!m) throw new Error('get_fileset_id: fileset_id not found in share page'); + return m[1]; + } + + // ─────────────── 文件上传 ─────────────── + + /** + * 文件扩展名 → 闪传类型码映射。typeCode 用于 0x93cf f3,formatCode 用于 + * 0x93d0 commit f7 与 0x12a9 filesetWrap.f7(两者同值)。mp4 → 2,rar/zip → 4。 + * 未知扩展名按媒体类处理(formatCode=2),服务端按文件名扩展名判定。 + */ + private static fileTypeCode(fileName: string): { typeCode: number; formatCode: number } { + const ext = fileName.toLowerCase().match(/\.([^.]+)$/)?.[1] ?? ''; + switch (ext) { + case 'rar': return { typeCode: 2, formatCode: 4 }; + case 'zip': return { typeCode: 6, formatCode: 4 }; + case '7z': case 'gz': case 'tar': case 'bz2': return { typeCode: 2, formatCode: 4 }; + case 'png': case 'jpg': case 'jpeg': case 'bmp': case 'gif': case 'webp': + case 'mp4': case 'mov': case 'avi': case 'mkv': + return { typeCode: 7, formatCode: 2 }; + default: return { typeCode: 7, formatCode: 2 }; + } + } + + /** 构造 sub=103 的 fileId(客户端生成的 protobuf,base64url 编码)。 + * f2=SHA1, f3=filesize, f4=appid, f5=微秒时间戳, f6="prod", + * f10=TTL(1209600), f11=16B 会话ID, f15=3B, f16="gz"。 + * f11/f15 随机生成,服务端不校验。 + * appid 决定 fileId 落在哪个槽位:主文件用 14901(0x93d4 f14.f1), + * png 缩略图用 14903、jpg 缩略图用 14902(f13.f1)。主文件必须用 14901, + * 否则 fileId 不会被服务端采纳进 f14,对端无法拿到主文件下载入口。 */ + private static buildFileId(sha1: Uint8Array, fileSize: number, appid: number = 14901): string { + const fileId: FlashFileId = { + sha1: new Uint8Array(sha1), + fileSize, + appid, + timestamp: BigInt(Date.now()) * 1000n, // 微秒时间戳 + env: 'prod', + ttl: 1209600, + sessionId: randomBytes(16), + field15: randomBytes(3), + region: 'gz', + }; + return Buffer.from(protobuf_encode(fileId)).toString('base64url'); + } + + /** + * 创建闪传任务(create_flash_task)。所有文件统一走 sub=100/103+sliceupload, + * 不走小文件 PUT——QQ 客户端即使几百 KB 的文件也走 sliceupload。只有 sliceupload + * 路径会上报主文件 sha1/size,服务端据此把 fileset 标记为完成(对端可下载); + * PUT 路径不上报 sha1,fileset 会卡在"上传中"无法被下载。 + * + * 多文件:0x93d0 的 f4 是 repeated,一个 commit 请求同时携带 fileset 内所有文件 + * 条目,每条 f6=文件序号(1,2,3...)。commit 在上传前只发一次,之后 complete → + * 逐个 prepare/apply/sliceupload。prepare/apply 的 filesetWrap.f4 必须与 commit + * 的 f6 一致,否则文件不计入 fileset。多文件时 ApplyFileset 的 fileName 用 + * 「<首文件名>等N个文件」、fileSize 用总和——服务端据此判定 fileset 为多文件。 + */ + async createFlashTask(files: string | string[], _name?: string, _thumbPath?: string): Promise<{ filesetId: string }> { + const fileList = Array.isArray(files) ? files : [files]; + if (fileList.length === 0) throw new Error('create_flash_task: files is empty'); + const uploader = { + uin: this.ctx.identity.uin, + nickname: this.ctx.identity.nickname, + uid: this.ctx.identity.selfUid ?? '', + }; + // 读取所有文件,每个分配 fileUuid + 序号 + formatCode + const items: { bytes: Uint8Array; fileName: string; fileUuid: string; fileIndex: number; formatCode: number }[] = []; + for (let i = 0; i < fileList.length; i++) { + const { bytes, fileName } = await loadBinarySource(fileList[i], 'flash-transfer'); + const { formatCode } = FlashTransferApi.fileTypeCode(fileName); + items.push({ bytes: new Uint8Array(bytes), fileName, fileUuid: randomUUID(), fileIndex: i + 1, formatCode }); + } + // 申请 fileset。多文件时 fileName 用「<首文件名>等N个文件」、fileSize 用总和, + // 服务端据此判定 fileset 为多文件,commit 的后续 entry 才会被计入。 + const first = items[0]; + const { typeCode } = FlashTransferApi.fileTypeCode(first.fileName); + const isMulti = items.length > 1; + const filesetName = isMulti ? `${first.fileName}等${items.length}个文件` : first.fileName; + const totalSize = items.reduce((s, it) => s + it.bytes.length, 0); + const apply = await ApplyFileset.invoke(this.ctx, { + fileName: filesetName, origName: filesetName, + fileSize: totalSize, typeCode, uploader, + }); + const filesetUuid = apply.filesetUuid; + if (!filesetUuid) throw new Error('apply fileset failed: missing uuid'); + // 一次性 commit 所有文件元数据(f4 repeated,每条 f6=序号) + const commitEntries = items.map((it) => ({ + fileUuid: it.fileUuid, fileName: it.fileName, origName: it.fileName, + fileSize: it.bytes.length, formatCode: it.formatCode, fileIndex: it.fileIndex, + })); + await CommitFile.invoke(this.ctx, { filesetUuid, entries: commitEntries }); + await CompleteFileset.invoke(this.ctx, { filesetUuid }); + // 两阶段上传:先全部 prepare+apply 注册 fileId,再全部 sliceupload 落盘。 + const prepared: { it: typeof items[0]; rkey: string; sha1StateV: Uint8Array[]; sliceCount: number }[] = []; + for (const it of items) { + const p = await this.prepareAndApply(filesetUuid, it.bytes, it.fileName, it.fileUuid, it.fileIndex, it.formatCode); + if (p) prepared.push({ it, ...p }); + } + for (const p of prepared) { + await this.sliceuploadFile(p.it.bytes, p.rkey, p.sha1StateV, p.sliceCount, p.it.fileName); + } + // fileset 级缩略图(序号在主文件之后递增),主文件下载入口需要缩略图关联 + await this.uploadThumbnail(filesetUuid, items[0].fileUuid, 'png', items.length + 1); + await this.uploadThumbnail(filesetUuid, items[0].fileUuid, 'jpg', items.length + 2); + await SetFilesetStatus.invoke(this.ctx, { filesetUuid }); + return { filesetId: filesetUuid }; + } + + /** + * 阶段1:prepare(拿 rkey)+ apply(注册 fileId)。返回 sliceupload 所需的 rkey/sha1state。 + * 秒传(rkey=null)返回 null,调用方跳过 sliceupload。 + */ + private async prepareAndApply( + filesetUuid: string, bytes: Uint8Array, fileName: string, fileUuid: string, fileIndex: number, formatCode: number, + ): Promise<{ rkey: string; sha1StateV: Uint8Array[]; sliceCount: number } | null> { + const fileSize = bytes.length; + const hashes = computeHashes(bytes); + const SLICE_SIZE = 1024 * 1024; + const sliceCount = Math.ceil(fileSize / SLICE_SIZE); + const sha1StateV = computeSha1StateV(bytes, sliceCount, SLICE_SIZE); + + const rkey = await PrepareUpload.invoke(this.ctx, { + filesetUuid, fileUuid, fileName, fileSize, sha1: hashes.sha1Hex, fileIndex, formatCode, + }); + if (rkey === null) return null; // 秒传 + + const fileId = FlashTransferApi.buildFileId(hashes.sha1, fileSize); + await ApplyUpload.invoke(this.ctx, { + filesetUuid, fileUuid, fileId, fileName, fileSize, + md5: hashes.md5Hex, sha1: hashes.sha1Hex, fileIndex, formatCode, + }); + return { rkey, sha1StateV, sliceCount }; + } + + /** + * 阶段2:sliceupload 分片上传(所有文件 prepare+apply 完成后调用)。 + */ + private async sliceuploadFile( + bytes: Uint8Array, rkey: string, sha1StateV: Uint8Array[], sliceCount: number, fileName: string, + ): Promise { + const fileSize = bytes.length; + const SLICE_SIZE = 1024 * 1024; + for (let i = 0; i < sliceCount; i++) { + const start = i * SLICE_SIZE; + const chunk = bytes.subarray(start, Math.min(start + SLICE_SIZE, fileSize)); + const chunkLen = chunk.length; + const chunkSha1 = new Uint8Array(createHash('sha1').update(Buffer.from(chunk)).digest()); + const body: FlashSliceUploadBody = { + field1: 0, + appid: 14901, + field3: 2, + payload: { + field1: {}, + rkey, + start, + end: start + chunkLen - 1, + sha1: chunkSha1, + sha1StateV: { state: sha1StateV.map((s) => new Uint8Array(s)) }, + chunk: new Uint8Array(chunk), + }, + }; + const bodyBytes = protobuf_encode(body); + await this.postSliceupload(bodyBytes, `${fileName} slice ${i}`); + } + } + + /** + * POST sliceupload 并校验响应。服务端即使 HTTP 200 也可能在业务体里返回错误, + * 所以必须解析 f5(status),非 "success" 视为失败。label 用于错误信息定位切片来源。 + */ + private async postSliceupload(bodyBytes: Uint8Array, label: string): Promise { + const resp = await fetch('https://multimedia.qfile.qq.com/sliceupload', { + method: 'POST', body: bodyBytes, + headers: { + Accept: '*/*', Connection: 'Keep-Alive', + 'User-Agent': 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2)', + Pragma: 'no-cache', 'Cache-Control': 'no-cache', + 'Content-Length': String(bodyBytes.length), + 'X-Retried-Times': '1', + }, + }); + if (!resp.ok) { + const errBody = await resp.text().catch(() => ''); + throw new Error(`${label} failed: HTTP ${resp.status} ${errBody.slice(0, 300)}`); + } + const respBuf = new Uint8Array(await resp.arrayBuffer()); + const sliceResp = protobuf_decode(respBuf); + if (sliceResp.status !== 'success') { + throw new Error(`${label} failed: ${sliceResp.status || 'no status in response'}`); + } + } + + /** + * 上传占位缩略图(png+jpg)。主文件上传后调用——主文件下载入口(0x93d3 的下载 + * fileId)需要缩略图关联才会被服务端填充,不传缩略图时 bot 自身上传的 fileset + * 无法被 download_fileset 解析。缩略图用随机纯色 PNG,无需 ffmpeg/sharp。 + * fileIndex 为缩略图在 fileset 内的序号(主文件之后递增),与 commit f6 对齐。 + */ + private async uploadThumbnail( + filesetUuid: string, mainFileUuid: string, thumbType: 'png' | 'jpg', fileIndex: number, + ): Promise { + // 526x360 是 QQ 客户端缩略图尺寸;1x1 会被服务端拒(HTTP 400,宽高太小)。 + const width = 526, height = 360; + const thumbBytes = generatePng(width, height); // 随机纯色,SHA1 不同避免秒传 + const appid = thumbType === 'png' ? 14903 : 14902; // png=14903, jpg=14902 + const fileUuid = thumbType === 'png' ? randomUUID() : mainFileUuid; // png 独立,jpg 挂主文件 + const fileName = thumbType === 'png' + ? `${randomUUID().slice(0, 8)}_one.png` + : `${createHash('md5').update(thumbBytes).digest('hex').slice(0, 32)}.jpg`; + const hashes = computeHashes(new Uint8Array(thumbBytes)); + const fileSize = thumbBytes.length; + const thumbFormatCode = thumbType === 'png' ? 26 : 2; // png缩略图=26, jpg缩略图=2 + const rkey = await PrepareUpload.invoke(this.ctx, { + filesetUuid, fileUuid, fileName, fileSize, sha1: hashes.sha1Hex, + fileIndex, formatCode: thumbFormatCode, thumbType, width, height, + }); + if (rkey === null) return; // 秒传 + const fileId = FlashTransferApi.buildFileId(hashes.sha1, fileSize, appid); + await ApplyUpload.invoke(this.ctx, { + filesetUuid, fileUuid, fileId, fileName, fileSize, + md5: hashes.md5Hex, sha1: hashes.sha1Hex, fileIndex, formatCode: thumbFormatCode, thumbType, width, height, + }); + // sliceupload(缩略图小,1 片,Sha1StateV=[标准 SHA1]) + const sha1StateV = computeSha1StateV(new Uint8Array(thumbBytes), 1, fileSize); + const body: FlashSliceUploadBody = { + field1: 0, appid, field3: 2, + payload: { + field1: {}, rkey, + start: 0, end: fileSize - 1, + sha1: new Uint8Array(hashes.sha1), + sha1StateV: { state: sha1StateV.map((s) => new Uint8Array(s)) }, + chunk: new Uint8Array(thumbBytes), + }, + }; + const bodyBytes = protobuf_encode(body); + await this.postSliceupload(bodyBytes, 'thumbnail sliceupload'); + } +} diff --git a/packages/core/src/bridge/apis/index.ts b/packages/core/src/bridge/apis/index.ts index 03dc5349..d5d83b8c 100644 --- a/packages/core/src/bridge/apis/index.ts +++ b/packages/core/src/bridge/apis/index.ts @@ -1,6 +1,7 @@ import type { BridgeContext } from '../bridge-context'; import { ContactsApi } from './contacts'; import { ExtrasApi } from './extras'; +import { FlashTransferApi } from './flash-transfer'; import { ForwardApi } from './forward'; import { FriendApi } from './friend'; import { GroupAdminApi } from './group-admin'; @@ -32,6 +33,8 @@ export interface ApiHub { readonly friend: FriendApi; /** Personal profile: status / avatar / nickname / likes / custom-faces. */ readonly profile: ProfileApi; + /** QQ 闪传(fileset 文件集): 上传/查询/分享/发送/删除/重命名。 */ + readonly flashTransfer: FlashTransferApi; /** Long-message (forward / 聊天记录) upload + retrieval with NapCat piggyback. */ readonly forward: ForwardApi; /** Odds & ends: translate / mini-app ARK / inline-keyboard / group sign. */ @@ -61,6 +64,7 @@ export function buildApiHub(ctx: BridgeContext): ApiHub { interaction: new InteractionApi(ctx), friend: new FriendApi(ctx), profile: new ProfileApi(ctx), + flashTransfer: new FlashTransferApi(ctx), forward: new ForwardApi(ctx), misc: new MiscApi(ctx), extras: new ExtrasApi(ctx), @@ -83,5 +87,6 @@ export { MessageApi } from './message'; export { MiscApi } from './misc'; export { ProfileApi } from './profile'; export { QzoneApi } from './qzone'; +export { FlashTransferApi, type FlashFileInfo } from './flash-transfer'; export { WebApi } from './web'; diff --git a/packages/mcp/src/generated/catalog.ts b/packages/mcp/src/generated/catalog.ts index 73478438..0f9885a0 100644 --- a/packages/mcp/src/generated/catalog.ts +++ b/packages/mcp/src/generated/catalog.ts @@ -663,6 +663,51 @@ export const ACTIONS: CatalogAction[] = [ }, "category": "扩展" }, + { + "name": "create_flash_task", + "aliases": [], + "summary": "创建闪传任务", + "readOnly": false, + "params": [ + { + "name": "files", + "type": "raw", + "required": false, + "schema": {} + }, + { + "name": "name", + "type": "string", + "required": false, + "schema": { + "type": "string" + } + }, + { + "name": "thumb_path", + "type": "string", + "required": false, + "schema": { + "type": "string" + } + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "files": {}, + "name": { + "type": "string" + }, + "thumb_path": { + "type": "string" + } + }, + "additionalProperties": true + }, + "category": "扩展" + }, { "name": "create_group_file_folder", "aliases": [], @@ -853,6 +898,38 @@ export const ACTIONS: CatalogAction[] = [ }, "category": "扩展" }, + { + "name": "delete_flash_file", + "aliases": [], + "summary": "删除闪传文件", + "readOnly": false, + "params": [ + { + "name": "fileset_id", + "type": "string", + "required": true, + "schema": { + "type": "string", + "minLength": 1 + } + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "fileset_id": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "fileset_id" + ], + "additionalProperties": true + }, + "category": "扩展" + }, { "name": "delete_friend", "aliases": [], @@ -1245,6 +1322,61 @@ export const ACTIONS: CatalogAction[] = [ }, "category": "扩展" }, + { + "name": "download_fileset", + "aliases": [], + "summary": "解析闪传文件下载直链(不下载,由调用方实现下载)", + "returns": "{ url, file_name, file_size }", + "readOnly": false, + "params": [ + { + "name": "fileset_id", + "type": "string", + "required": true, + "schema": { + "type": "string", + "minLength": 1 + } + }, + { + "name": "file_name", + "type": "string", + "required": false, + "schema": { + "type": "string" + } + }, + { + "name": "file_index", + "type": "number", + "required": false, + "schema": { + "type": "number" + } + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "fileset_id": { + "type": "string", + "minLength": 1 + }, + "file_name": { + "type": "string" + }, + "file_index": { + "type": "number" + } + }, + "required": [ + "fileset_id" + ], + "additionalProperties": true + }, + "category": "扩展" + }, { "name": "fetch_custom_face", "aliases": [], @@ -1927,6 +2059,157 @@ export const ACTIONS: CatalogAction[] = [ }, "category": "扩展" }, + { + "name": "get_fileset_id", + "aliases": [], + "summary": "从分享码/链接获取 fileset_id", + "returns": "{ fileset_id }", + "readOnly": true, + "params": [ + { + "name": "share_code", + "type": "string", + "required": true, + "schema": { + "type": "string", + "minLength": 1 + } + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "share_code": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "share_code" + ], + "additionalProperties": true + }, + "category": "扩展" + }, + { + "name": "get_fileset_info", + "aliases": [], + "summary": "获取文件集信息", + "readOnly": false, + "params": [ + { + "name": "fileset_id", + "type": "string", + "required": true, + "schema": { + "type": "string", + "minLength": 1 + } + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "fileset_id": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "fileset_id" + ], + "additionalProperties": true + }, + "category": "扩展" + }, + { + "name": "get_flash_file_list", + "aliases": [], + "summary": "获取闪传文件列表", + "readOnly": false, + "params": [ + { + "name": "fileset_id", + "type": "string", + "required": true, + "schema": { + "type": "string", + "minLength": 1 + } + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "fileset_id": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "fileset_id" + ], + "additionalProperties": true + }, + "category": "扩展" + }, + { + "name": "get_flash_file_url", + "aliases": [], + "summary": "获取闪传文件链接", + "readOnly": false, + "params": [ + { + "name": "fileset_id", + "type": "string", + "required": true, + "schema": { + "type": "string", + "minLength": 1 + } + }, + { + "name": "file_name", + "type": "string", + "required": false, + "schema": { + "type": "string" + } + }, + { + "name": "file_index", + "type": "number", + "required": false, + "schema": { + "type": "number" + } + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "fileset_id": { + "type": "string", + "minLength": 1 + }, + "file_name": { + "type": "string" + }, + "file_index": { + "type": "number" + } + }, + "required": [ + "fileset_id" + ], + "additionalProperties": true + }, + "category": "扩展" + }, { "name": "get_forward_msg", "aliases": [], @@ -3321,6 +3604,38 @@ export const ACTIONS: CatalogAction[] = [ }, "category": "扩展" }, + { + "name": "get_share_link", + "aliases": [], + "summary": "获取文件分享链接", + "readOnly": false, + "params": [ + { + "name": "fileset_id", + "type": "string", + "required": true, + "schema": { + "type": "string", + "minLength": 1 + } + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "fileset_id": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "fileset_id" + ], + "additionalProperties": true + }, + "category": "扩展" + }, { "name": "get_status", "aliases": [], @@ -3511,6 +3826,20 @@ export const ACTIONS: CatalogAction[] = [ }, "category": "空间" }, + { + "name": "list_filesets", + "aliases": [], + "summary": "列出当前账号的所有闪传文件集", + "readOnly": false, + "params": [], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": {}, + "additionalProperties": true + }, + "category": "扩展" + }, { "name": "mark_group_msg_as_read", "aliases": [], @@ -3891,6 +4220,52 @@ export const ACTIONS: CatalogAction[] = [ }, "category": "扩展" }, + { + "name": "rename_flash_file", + "aliases": [], + "summary": "重命名闪传文件", + "readOnly": false, + "params": [ + { + "name": "fileset_id", + "type": "string", + "required": true, + "schema": { + "type": "string", + "minLength": 1 + } + }, + { + "name": "new_name", + "type": "string", + "required": true, + "schema": { + "type": "string", + "minLength": 1 + } + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "fileset_id": { + "type": "string", + "minLength": 1 + }, + "new_name": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "fileset_id", + "new_name" + ], + "additionalProperties": true + }, + "category": "扩展" + }, { "name": "rename_group_file", "aliases": [], @@ -4127,6 +4502,65 @@ export const ACTIONS: CatalogAction[] = [ }, "category": "扩展" }, + { + "name": "send_flash_msg", + "aliases": [], + "summary": "发送闪传消息(私聊或群聊,引用 fileset_id 让对端下载)", + "returns": "{ message_id }", + "readOnly": false, + "params": [ + { + "name": "fileset_id", + "type": "string", + "required": true, + "schema": { + "type": "string", + "minLength": 1 + } + }, + { + "name": "user_id", + "type": "uint", + "required": false, + "schema": { + "type": "integer", + "minimum": 1 + } + }, + { + "name": "group_id", + "type": "uint", + "required": false, + "schema": { + "type": "integer", + "minimum": 1 + } + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "fileset_id": { + "type": "string", + "minLength": 1 + }, + "user_id": { + "type": "integer", + "minimum": 1 + }, + "group_id": { + "type": "integer", + "minimum": 1 + } + }, + "required": [ + "fileset_id" + ], + "additionalProperties": true + }, + "category": "扩展" + }, { "name": "send_forward_msg", "aliases": [], @@ -6950,7 +7384,7 @@ export const CATEGORIES: CatalogCategory[] = [ }, { "category": "扩展", - "count": 98 + "count": 109 }, { "category": "群相册", diff --git a/packages/onebot/src/actions/extended.ts b/packages/onebot/src/actions/extended.ts index ba0137b8..d10265f9 100644 --- a/packages/onebot/src/actions/extended.ts +++ b/packages/onebot/src/actions/extended.ts @@ -54,6 +54,29 @@ async function fetchDownloadFile( return Buffer.concat(chunks, total); } +// 把下载好的字节落盘到 data/downloads。 缺省时用内容 md5 命名。 +// basename + relative 检查拦截目录穿越:名称里的路径分隔符被剥成纯文件名, +// 再确认解析后仍在 downloads 目录下,避免 ../ 逃逸。 +async function saveDownloadBuffer(buf: Buffer, preferredName: string): Promise { + const fs = await import('fs'); + const pathMod = await import('path'); + const cryptoMod = await import('crypto'); + const tempDir = pathMod.resolve('data', 'downloads'); + if (!fs.existsSync(tempDir)) fs.mkdirSync(tempDir, { recursive: true }); + const rawName = preferredName || cryptoMod.createHash('md5').update(buf).digest('hex'); + const safeName = pathMod.basename(rawName); + if (!safeName || safeName === '.' || safeName === '..' || /[\\/]/.test(safeName)) { + throw new Error('invalid file name'); + } + const resolved = pathMod.resolve(tempDir, safeName); + const rel = pathMod.relative(tempDir, resolved); + if (rel.startsWith('..') || pathMod.isAbsolute(rel)) { + throw new Error('invalid file name'); + } + await fs.promises.writeFile(resolved, buf); + return resolved; +} + // 从 send_*_forward_msg 的参数里提取 NapCat 兼容的转发预览元信息。四个字段都是可选的——如果没有提供,模块层会根据实际消息节点列表推断出合理的默认值。 function readForwardPreviewMeta(params: Record): ForwardPreviewMeta | undefined { const source = asString(params.source) || undefined; @@ -95,6 +118,23 @@ async function groupTodoRun( } } +/** FlashTransferApi 返回的 FlashFileInfo → OneBot JSON 响应(plain object,JsonObject 兼容)。 + * 字段名对齐 NapCat(get_flash_file_list 用 size,非 file_size),便于客户端 drop-in 迁移。 */ +function flashFileInfoToJson(f: { + filesetUuid: string; fileName: string; origName: string; fileSize: number; + shareUrl: string; fileId: string; downloadUrl: string; +}): JsonObject { + return { + fileset_id: f.filesetUuid, + file_name: f.fileName, + orig_name: f.origName, + size: f.fileSize, + share_url: f.shareUrl, + file_id: f.fileId, + download_url: f.downloadUrl, + }; +} + export const actions = [ // 赞 defineAction({ @@ -1670,20 +1710,6 @@ export const actions = [ const base64 = p.base64; const name = p.name; if (!url && !base64) return failedResponse(RETCODE.BAD_REQUEST, 'url or base64 is required'); - const fs = await import('fs'); - const pathMod = await import('path'); - const cryptoMod = await import('crypto'); - const tempDir = pathMod.resolve('data', 'downloads'); - if (!fs.existsSync(tempDir)) fs.mkdirSync(tempDir, { recursive: true }); - const resolveSafePath = (preferredName: string, fallbackBuf: Buffer): string | null => { - const rawName = preferredName || cryptoMod.createHash('md5').update(fallbackBuf).digest('hex'); - const safeName = pathMod.basename(rawName); - if (!safeName || safeName === '.' || safeName === '..' || /[\\/]/.test(safeName)) return null; - const resolved = pathMod.resolve(tempDir, safeName); - const rel = pathMod.relative(tempDir, resolved); - if (rel.startsWith('..') || pathMod.isAbsolute(rel)) return null; - return resolved; - }; let buf: Buffer; if (base64) { const upperBound = Math.floor((base64.length * 3) / 4); @@ -1697,10 +1723,12 @@ export const actions = [ return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err)); } } - const safe = resolveSafePath(name, buf); - if (!safe) return failedResponse(RETCODE.BAD_REQUEST, 'invalid file name'); - await fs.promises.writeFile(safe, buf); - return okResponse({ file: safe }); + try { + const safe = await saveDownloadBuffer(buf, name); + return okResponse({ file: safe }); + } catch (err) { + return failedResponse(RETCODE.BAD_REQUEST, err instanceof Error ? err.message : String(err)); + } }, }), @@ -1830,6 +1858,212 @@ export const actions = [ params: { message_id: f.messageId() }, run: (p, ctx) => groupTodoRun(p, ctx, (g, s) => ctx.bridge.apis.extras.cancelGroupTodo(g, s)), }), + + // ─────────────── 闪传(FlashTransfer / fileset) ─────────────── + + defineAction({ + name: 'create_flash_task', + summary: '创建闪传任务', + params: { + // files 支持单个路径(string)或多个路径(string[]),多文件共用一个 fileset + files: f.raw(), + name: f.string().optional(), + thumb_path: f.string().optional(), + }, + run: async (p, ctx) => { + // f.raw() 不做校验,这里归一化为 string[] 并校验 + const rawFiles = p.files; + let fileList: string[]; + if (typeof rawFiles === 'string') { + if (rawFiles === '') return failedResponse(RETCODE.BAD_REQUEST, 'files must not be empty'); + fileList = [rawFiles]; + } else if (Array.isArray(rawFiles) && rawFiles.every((x) => typeof x === 'string' && x !== '')) { + if (rawFiles.length === 0) return failedResponse(RETCODE.BAD_REQUEST, 'files must not be empty'); + fileList = rawFiles as string[]; + } else { + return failedResponse(RETCODE.BAD_REQUEST, 'files must be a string or string array'); + } + try { + const result = await ctx.bridge.apis.flashTransfer.createFlashTask(fileList, p.name, p.thumb_path); + return okResponse({ fileset_id: result.filesetId, task_id: result.filesetId }); + } catch (e) { + return failedResponse(RETCODE.ACTION_FAILED, String(e)); + } + }, + }), + + defineAction({ + name: 'get_fileset_info', + summary: '获取文件集信息', + params: { fileset_id: f.string({ allowEmpty: false }) }, + run: async (p, ctx) => { + try { + const list = await ctx.bridge.apis.flashTransfer.getFilesetInfo(p.fileset_id); + return okResponse({ fileset_id: p.fileset_id, file_list: list.map(flashFileInfoToJson) }); + } catch (e) { + return failedResponse(RETCODE.ACTION_FAILED, String(e)); + } + }, + }), + + defineAction({ + name: 'get_flash_file_list', + summary: '获取闪传文件列表', + params: { fileset_id: f.string({ allowEmpty: false }) }, + run: async (p, ctx) => { + try { + const list = await ctx.bridge.apis.flashTransfer.getFlashFileList(p.fileset_id); + return okResponse(list.map(flashFileInfoToJson)); + } catch (e) { + return failedResponse(RETCODE.ACTION_FAILED, String(e)); + } + }, + }), + + defineAction({ + name: 'list_filesets', + summary: '列出当前账号的所有闪传文件集', + params: {}, + run: async (_p, ctx) => { + try { + const list = await ctx.bridge.apis.flashTransfer.listFilesets(); + return okResponse(list.map(flashFileInfoToJson)); + } catch (e) { + return failedResponse(RETCODE.ACTION_FAILED, String(e)); + } + }, + }), + + defineAction({ + name: 'get_flash_file_url', + summary: '获取闪传文件链接', + params: { + fileset_id: f.string({ allowEmpty: false }), + file_name: f.string().optional(), + file_index: f.number().optional(), + }, + run: async (p, ctx) => { + try { + const url = await ctx.bridge.apis.flashTransfer.getFlashFileUrl(p.fileset_id, p.file_index); + return okResponse({ url }); + } catch (e) { + return failedResponse(RETCODE.ACTION_FAILED, String(e)); + } + }, + }), + + defineAction({ + name: 'get_share_link', + summary: '获取文件分享链接', + params: { fileset_id: f.string({ allowEmpty: false }) }, + run: async (p, ctx) => { + try { + const url = await ctx.bridge.apis.flashTransfer.getShareLink(p.fileset_id); + return okResponse(url); + } catch (e) { + return failedResponse(RETCODE.ACTION_FAILED, String(e)); + } + }, + }), + + defineAction({ + name: 'delete_flash_file', + summary: '删除闪传文件', + params: { fileset_id: f.string({ allowEmpty: false }) }, + run: async (p, ctx) => { + try { + await ctx.bridge.apis.flashTransfer.deleteFlashFile(p.fileset_id); + return okResponse(); + } catch (e) { + return failedResponse(RETCODE.ACTION_FAILED, String(e)); + } + }, + }), + + defineAction({ + name: 'rename_flash_file', + summary: '重命名闪传文件', + params: { + fileset_id: f.string({ allowEmpty: false }), + new_name: f.string({ allowEmpty: false }), + }, + run: async (p, ctx) => { + try { + await ctx.bridge.apis.flashTransfer.renameFlashFile(p.fileset_id, p.new_name); + return okResponse(); + } catch (e) { + return failedResponse(RETCODE.ACTION_FAILED, String(e)); + } + }, + }), + + defineAction({ + name: 'download_fileset', + summary: '解析闪传文件下载直链(不下载,由调用方实现下载)', + returns: '{ url, file_name, file_size }', + params: { + fileset_id: f.string({ allowEmpty: false }), + file_name: f.string().optional(), + file_index: f.number().optional(), + }, + run: async (p, ctx) => { + try { + const target = await ctx.bridge.apis.flashTransfer.downloadFileset(p.fileset_id, { + fileName: p.file_name, + fileIndex: p.file_index, + }); + return okResponse({ + url: target.url, + file_name: target.fileName, + file_size: target.fileSize, + }); + } catch (err) { + return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err)); + } + }, + }), + + defineAction({ + name: 'send_flash_msg', + summary: '发送闪传消息(私聊或群聊,引用 fileset_id 让对端下载)', + returns: '{ message_id }', + params: { + fileset_id: f.string({ allowEmpty: false }), + user_id: f.uint().optional(), + group_id: f.uint().optional(), + }, + run: async (p, ctx) => { + if (!p.user_id && !p.group_id) { + return failedResponse(RETCODE.BAD_REQUEST, 'user_id or group_id is required'); + } + try { + await ctx.bridge.apis.flashTransfer.sendFlashMsg(p.fileset_id, { + userId: p.user_id, + groupId: p.group_id, + }); + // 0x93d7 响应无 message_id(分享 fileset,非传统消息),返回 0 兼容 OneBot 形状。 + return okResponse({ message_id: 0 }); + } catch (e) { + return failedResponse(RETCODE.ACTION_FAILED, e instanceof Error ? e.message : String(e)); + } + }, + }), + + defineAction({ + name: 'get_fileset_id', + summary: '从分享码/链接获取 fileset_id', + readOnly: true, + returns: '{ fileset_id }', + params: { share_code: f.string({ allowEmpty: false }) }, + run: async (p, ctx) => { + try { + const filesetId = await ctx.bridge.apis.flashTransfer.getFilesetIdByCode(p.share_code); + return okResponse({ fileset_id: filesetId }); + } catch (e) { + return failedResponse(RETCODE.ACTION_FAILED, e instanceof Error ? e.message : String(e)); + } + }, + }), ]; // 已过滤(机器人/被忽略)的入群请求。 diff --git a/packages/onebot/tests/extended-actions.test.ts b/packages/onebot/tests/extended-actions.test.ts index af2f4b70..a1cee2e5 100644 --- a/packages/onebot/tests/extended-actions.test.ts +++ b/packages/onebot/tests/extended-actions.test.ts @@ -991,3 +991,88 @@ describe('extended-actions / get_qun_album_list', () => { expect(res.status).toBe('failed'); }); }); + +// ─── flash-transfer: download_fileset (闪传文件集下载到本地) ─── +// 接线测试:参数校验 + facade 错误传播。完整下载链路(0x93d3/0x93d4 取链接 → +// HTTP GET → 落盘 data/downloads)依赖真实 OIDB 与文件系统,与 download_file +// 一样靠端到端验证,此处不重复 mock fetch/fs。 +describe('extended-actions / download_fileset', () => { + it('rejects missing fileset_id', async () => { + const downloadFileset = vi.fn(async () => ({ url: '', fileName: '', fileSize: 0 })); + const bridge = fakeBridge({ apis: { flashTransfer: { downloadFileset: downloadFileset as any } } }); + const res = await makeHandler(fakeCtx(bridge)).handle('download_fileset', {}); + expect(res).toMatchObject({ status: 'failed', retcode: 1400 }); + expect(downloadFileset).not.toHaveBeenCalled(); + }); + + it('surfaces facade errors as action_failed', async () => { + const downloadFileset = vi.fn(async () => { throw new Error('no download url available'); }); + const bridge = fakeBridge({ apis: { flashTransfer: { downloadFileset: downloadFileset as any } } }); + const res = await makeHandler(fakeCtx(bridge)).handle('download_fileset', { fileset_id: 'abc' }); + expect(downloadFileset).toHaveBeenCalledOnce(); + expect(downloadFileset.mock.calls[0]![0]).toBe('abc'); + expect(res).toMatchObject({ status: 'failed', retcode: 100, wording: 'no download url available' }); + }); +}); + +// ─── flash-transfer: send_flash_msg (0x93d7 发送闪传文件) ─── +// 接线测试:参数校验 + 私聊/群聊转发 + 错误传播。完整链路(user_id→uid / group_id → +// 0x93d7)依赖真实 identity 与 OIDB,靠 send_packet 端到端验证。 +describe('extended-actions / send_flash_msg', () => { + it('rejects when neither user_id nor group_id given', async () => { + const sendFlashMsg = vi.fn(async () => {}); + const bridge = fakeBridge({ apis: { flashTransfer: { sendFlashMsg: sendFlashMsg as any } } }); + const res = await makeHandler(fakeCtx(bridge)).handle('send_flash_msg', { fileset_id: 'abc' }); + expect(res).toMatchObject({ status: 'failed', retcode: 1400 }); + expect(sendFlashMsg).not.toHaveBeenCalled(); + }); + + it('forwards fileset_id + user_id (private) and returns message_id 0', async () => { + const sendFlashMsg = vi.fn(async () => {}); + const bridge = fakeBridge({ apis: { flashTransfer: { sendFlashMsg: sendFlashMsg as any } } }); + const res = await makeHandler(fakeCtx(bridge)).handle('send_flash_msg', { fileset_id: 'fs-1', user_id: 12345 }); + expect(sendFlashMsg).toHaveBeenCalledWith('fs-1', { userId: 12345, groupId: undefined }); + expect(res).toMatchObject({ status: 'ok', data: { message_id: 0 } }); + }); + + it('forwards fileset_id + group_id (group) and returns message_id 0', async () => { + const sendFlashMsg = vi.fn(async () => {}); + const bridge = fakeBridge({ apis: { flashTransfer: { sendFlashMsg: sendFlashMsg as any } } }); + const res = await makeHandler(fakeCtx(bridge)).handle('send_flash_msg', { fileset_id: 'fs-1', group_id: 1017438661 }); + expect(sendFlashMsg).toHaveBeenCalledWith('fs-1', { userId: undefined, groupId: 1017438661 }); + expect(res).toMatchObject({ status: 'ok', data: { message_id: 0 } }); + }); + + it('surfaces facade errors (e.g. uid resolve failed) as action_failed', async () => { + const sendFlashMsg = vi.fn(async () => { throw new Error('failed to resolve UID for UIN 999'); }); + const bridge = fakeBridge({ apis: { flashTransfer: { sendFlashMsg: sendFlashMsg as any } } }); + const res = await makeHandler(fakeCtx(bridge)).handle('send_flash_msg', { fileset_id: 'fs-1', user_id: 999 }); + expect(res).toMatchObject({ status: 'failed', retcode: 100 }); + }); +}); + +// ─── flash-transfer: get_fileset_id (分享码→fileset_id, HTTP 网页解析) ─── +describe('extended-actions / get_fileset_id', () => { + it('forwards share_code to facade and returns fileset_id', async () => { + const getFilesetIdByCode = vi.fn(async () => '8e40afa1-829d-498b-852f-092394ddb31f'); + const bridge = fakeBridge({ apis: { flashTransfer: { getFilesetIdByCode: getFilesetIdByCode as any } } }); + const res = await makeHandler(fakeCtx(bridge)).handle('get_fileset_id', { share_code: 'K0sEqhYria' }); + expect(getFilesetIdByCode).toHaveBeenCalledWith('K0sEqhYria'); + expect(res).toMatchObject({ status: 'ok', data: { fileset_id: '8e40afa1-829d-498b-852f-092394ddb31f' } }); + }); + + it('rejects missing share_code', async () => { + const getFilesetIdByCode = vi.fn(async () => 'x'); + const bridge = fakeBridge({ apis: { flashTransfer: { getFilesetIdByCode: getFilesetIdByCode as any } } }); + const res = await makeHandler(fakeCtx(bridge)).handle('get_fileset_id', {}); + expect(res).toMatchObject({ status: 'failed', retcode: 1400 }); + expect(getFilesetIdByCode).not.toHaveBeenCalled(); + }); + + it('surfaces facade errors (e.g. not found) as action_failed', async () => { + const getFilesetIdByCode = vi.fn(async () => { throw new Error('get_fileset_id: fileset_id not found in share page'); }); + const bridge = fakeBridge({ apis: { flashTransfer: { getFilesetIdByCode: getFilesetIdByCode as any } } }); + const res = await makeHandler(fakeCtx(bridge)).handle('get_fileset_id', { share_code: 'invalid' }); + expect(res).toMatchObject({ status: 'failed', retcode: 100 }); + }); +}); diff --git a/packages/proto-defs/package.json b/packages/proto-defs/package.json index 74173ac5..3ab53bc8 100644 --- a/packages/proto-defs/package.json +++ b/packages/proto-defs/package.json @@ -80,6 +80,10 @@ "types": "./src/oidb-actions/group-file.ts", "default": "./src/oidb-actions/group-file.ts" }, + "./oidb-actions/flash-transfer": { + "types": "./src/oidb-actions/flash-transfer.ts", + "default": "./src/oidb-actions/flash-transfer.ts" + }, "./oidb-actions/media": { "types": "./src/oidb-actions/media.ts", "default": "./src/oidb-actions/media.ts" diff --git a/packages/proto-defs/src/oidb-actions/flash-transfer.ts b/packages/proto-defs/src/oidb-actions/flash-transfer.ts new file mode 100644 index 00000000..c4989f39 --- /dev/null +++ b/packages/proto-defs/src/oidb-actions/flash-transfer.ts @@ -0,0 +1,537 @@ +// OIDB 0x93cf-0x9427, 0x12a9 — QQ 闪传(FlashTransfer / fileset)协议类型。 +// 响应成功靠 OIDB envelope 的 errorCode(f3=0),业务体无 retCode。 + +import type { pb, pb_optional, pb_repeated, uint_32, uint_64, bytes } from '@snowluma/proton'; + +// ─────────────── 共用:文件条目(0x93d2/0x93d3 响应里的每个文件/fileset) ─────────────── + +/** f9.f2 — 下载信息(f1=类型,f2=下载URL,URL 里已含 rkey 或 fldc)。 */ +export interface FlashFileDownloadInfo { + field1?: pb<1, uint_32>; + downloadUrl?: pb<2, string>; +} + +/** f9 — fileId + 下载信息。 */ +export interface FlashFileIdWrap { + fileId?: pb<1, string>; + download?: pb<2, FlashFileDownloadInfo>; +} + +/** f8 — 上传/分享 URL(qfile.qq.com/q/)。 */ +export interface FlashFileUploadUrl { + uploadUrl?: pb<1, string>; +} + +/** 文件条目。0x93d3 响应 f1(单条);0x93d2 响应 f1(repeated,多个 fileset)。 */ +export interface FlashFileEntry { + filesetUuid?: pb<1, string>; + fileName?: pb<2, string>; + origName?: pb<3, string>; + fileType?: pb<4, uint_32>; + fileSize?: pb<5, uint_64>; + uploadUrlWrap?: pb<8, FlashFileUploadUrl>; + fileIdWrap?: pb<9, FlashFileIdWrap>; +} + +// ─────────────── 0x93d3 — 拉取文件集详情(点分享显示链接时触发) ─────────────── + +export interface FlashGetDetailReq { + filesetUuid?: pb<1, string>; + field2?: pb<2, uint_32>; // 7 +} +export interface FlashGetDetailResp { + entries?: pb_repeated<1, FlashFileEntry>; +} + +// ─────────────── 0x93d2 — 查询 fileset 列表 ─────────────── + +export interface FlashListFilesetsReq { + field1?: pb<1, uint_32>; // 3 + field2?: pb<2, string>; // "" + field3?: pb<3, uint_32>; // 10 +} +export interface FlashListFilesetsResp { + entries?: pb_repeated<1, FlashFileEntry>; +} + +// ─────────────── 0x93d4 — 拉取下载URL(完整参数 + fldc) ─────────────── + +export interface FlashGetDownloadUrlReqInner { + field1?: pb<1, string>; + field2?: pb<2, uint_32>; + field3?: pb<3, uint_32>; + field4?: pb<4, string>; + field5?: pb<5, FlashGetDownloadUrlReqInner5>; + field6?: pb<6, FlashGetDownloadUrlReqInner6>; +} +export interface FlashGetDownloadUrlReqInner5 { field1?: pb<1, uint_32>; } +export interface FlashGetDownloadUrlReqInner6 { field1?: pb<1, uint_32>; field2?: pb<2, uint_32>; } + +export interface FlashGetDownloadUrlReq { + filesetUuid?: pb<1, string>; + inner?: pb<2, FlashGetDownloadUrlReqInner>; + field3?: pb<3, uint_32>; // 7 + field4?: pb<4, uint_32>; // 1 +} +/** 0x93d4 响应 f1.f3.f13.f2 — downloadUrl 包装(结构不同于 0x93d3 的 FlashFileDownloadInfo)。 */ +export interface FlashDownloadUrlWrap { + field1?: pb<1, uint_32>; // 2 + downloadUrl?: pb<2, string>; +} +/** 0x93d4 响应 f1.f3.f13 — fileId + downloadUrl + sha1/md5/宽高。 */ +export interface FlashDownloadUrlInfo { + fileId?: pb<1, string>; + download?: pb<2, FlashDownloadUrlWrap>; + sha1?: pb<3, string>; + field4?: pb<4, uint_32>; + md5?: pb<5, string>; + width?: pb<6, uint_32>; + height?: pb<7, uint_32>; +} +/** 0x93d4 响应 f1.f3.f14 — 主文件 fileId(无 downloadUrl,下载 URL 需 0x12a9 sub=200)。 */ +export interface FlashDownloadMainFile { + fileId?: pb<1, string>; + field3?: pb<3, uint_32>; // 2 +} +/** 0x93d4 响应 f1.f3 — 文件信息(字段号不同于 0x93d3 的 FlashFileEntry)。 */ +export interface FlashDownloadFileInfo { + filesetUuid?: pb<1, string>; + fileUuid?: pb<2, string>; + field5?: pb<5, uint_32>; + field6?: pb<6, uint_32>; + field7?: pb<7, uint_32>; + fileName?: pb<8, string>; + origName?: pb<9, string>; + fileSize?: pb<11, uint_64>; + downloadInfo?: pb<13, FlashDownloadUrlInfo>; + mainFile?: pb<14, FlashDownloadMainFile>; +} +/** 0x93d4 响应 f1 — entry wrapper。多文件 fileset 时 f3 含每个文件的 fileInfo。 */ +export interface FlashDownloadEntry { + field2?: pb<2, uint_32>; // 1 + /** repeated:多文件 fileset 时每个文件一个 fileInfo(f6=文件序号,f14=主文件 fileId)。 */ + fileInfo?: pb_repeated<3, FlashDownloadFileInfo>; + field4?: pb<4, string>; // JSON:{"offset":N,"cursor_time":"..."} + field5?: pb<5, uint_32>; // 1 +} +/** 0x93d4 响应 — downloadUrl 在 f1.f3.f13.f2.f2(深层嵌套,非 0x93d3 的 f9.fileIdWrap)。 */ +export interface FlashGetDownloadUrlResp { + entry?: pb<1, FlashDownloadEntry>; +} + +// ─────────────── 0x9407 — 删除闪传文件(额外,OneBot 标准未定义) ─────────────── + +export interface FlashDeleteFileReq { + filesetUuid?: pb<1, string>; + field2?: pb<2, string>; // "" + field3?: pb<3, uint_32>; // 7 +} +export interface FlashDeleteFileResp {} + +// ─────────────── 0x9427 — 重命名闪传文件(额外,OneBot 标准未定义) ─────────────── + +export interface FlashRenameFileReqName { + newName?: pb<1, string>; + displayName?: pb<2, string>; +} +export interface FlashRenameFileReqFlag { + field1?: pb<1, uint_32>; +} +export interface FlashRenameFileReq { + filesetUuid?: pb<1, string>; + name?: pb<2, FlashRenameFileReqName>; + flag?: pb<3, FlashRenameFileReqFlag>; +} +export interface FlashRenameFileResp {} + +// ─────────────── 0x93cf — 申请创建 fileSet(上传起点) ─────────────── + +/** 空占位 message(Uploader.f4 / CommitInfo.f4 / f24 为空 message)。 */ +export interface FlashEmpty {} + +export interface FlashUploader { + uin?: pb<1, string>; + nickname?: pb<2, string>; + uid?: pb<3, string>; + field4?: pb<4, FlashEmpty>; +} + +/** 0x93cf 请求 f2 — 文件信息。 */ +export interface FlashUploadFileInfo { + fileName?: pb<2, string>; + origName?: pb<3, string>; + fileType?: pb<4, uint_32>; + fileSize?: pb<5, uint_64>; + uploader?: pb<10, FlashUploader>; + field16?: pb<16, uint_32>; + field20?: pb<20, uint_32>; + field21?: pb<21, uint_32>; +} + +export interface FlashApplyFilesetReq { + field1?: pb<1, uint_32>; // 1 + fileInfo?: pb<2, FlashUploadFileInfo>; + /** 文件类型码:rar=2, png/mp4=7(按扩展名映射,FlashTransferApi.fileTypeCode)。 */ + typeCode?: pb<3, uint_32>; + field12?: pb<12, uint_32>; // 1 +} +export interface FlashApplyFilesetResp { + filesetUuid?: pb<1, string>; + /** 上传会话 key(与 f1 同值)。 */ + uploadKey?: pb<2, string>; + /** 上传 URL https://qfile.qq.com/q/。 */ + uploadUrl?: pb<3, string>; + expire?: pb<4, uint_64>; + ttl?: pb<5, uint_32>; +} + +// ─────────────── 0x93d0 — 单文件上传完成上报(commit) ─────────────── + +export interface FlashCommitFileInfo { + filesetUuid?: pb<1, string>; + fileUuid?: pb<2, string>; + /** pb_optional 强制 0 值上 wire(服务端多文件严格校验字段存在,省略 0 会导致文件不计入)。 */ + field3?: pb_optional<3, uint_32>; + field4?: pb<4, FlashEmpty>; + field5?: pb_optional<5, uint_32>; + /** 文件序号:fileset 内从 1 递增(1,2,3...),多文件时每条各不相同。 + * 必须与 0x12a9 sub=100/103 filesetWrap.f4 一致,否则服务端不把文件计入 fileset。 */ + field6?: pb_optional<6, uint_32>; + /** 格式码:rar=4, mp4=2, png=26(按扩展名映射)。 */ + formatCode?: pb_optional<7, uint_32>; + fileName?: pb<8, string>; + origName?: pb<9, string>; + field10?: pb_optional<10, uint_32>; + fileSize?: pb<11, uint_64>; + field12?: pb_optional<12, uint_32>; + field24?: pb<24, FlashEmpty>; +} + +export interface FlashCommitFileReq { + field1?: pb<1, uint_32>; // 1 + filesetUuid?: pb<2, string>; + uploadKey?: pb<3, string>; // 同 filesetUuid + /** repeated:一个 0x93d0 请求同时携带 fileset 内所有文件条目(多文件机制)。 + * 每条 field6=文件序号(1,2,3...)。单文件时只有一个条目。 */ + commitInfo?: pb_repeated<4, FlashCommitFileInfo>; + field5?: pb<5, uint_32>; // 1 + field6?: pb<6, uint_32>; // 1 +} +export interface FlashCommitFileResp { + field1?: pb<1, uint_32>; + filesetUuid?: pb<2, string>; + uploadKey?: pb<3, string>; +} + +// ─────────────── 0x93db — fileSet 完成 ─────────────── + +export interface FlashCompleteFilesetReq { + filesetUuid?: pb<1, string>; + field2?: pb<2, string>; // "" +} +export interface FlashCompleteFilesetResp {} + +// ─────────────── 0x93d1 — 设置 fileSet 状态 ─────────────── + +export interface FlashSetStatusReq { + filesetUuid?: pb<1, string>; + status?: pb<2, uint_32>; // 6 +} +export interface FlashSetStatusResp {} + +// ─────────────── sliceupload(大文件分片上传) ─────────────── + +/** sliceupload f107.f6 — 累积 SHA1 state list。每片对应从文件开头到该片末尾的 + * SHA1 中间 state(不 finalize,小端 20B),最后一片是标准整文件 SHA1。 + * 服务端按此校验分片完整性,传独立分片 SHA1 会被拒(报 "file range data sha1 not match")。 */ +export interface FlashSha1StateV { + state?: pb_repeated<1, bytes>; +} + +/** sliceupload body f107 — 切片 payload。 */ +export interface FlashSlicePayload { + field1?: pb<1, FlashEmpty>; + rkey?: pb<2, string>; // 上传凭证(来自 sub=100 响应) + start?: pb_optional<3, uint_32>; // 本片字节 offset + end?: pb_optional<4, uint_32>; // start + chunkLen - 1 + sha1?: pb<5, bytes>; // 当前片 SHA1 + sha1StateV?: pb<6, FlashSha1StateV>; + chunk?: pb<7, bytes>; // 本片文件字节 +} + +/** sliceupload HTTP body — POST multimedia.qfile.qq.com/sliceupload。 */ +export interface FlashSliceUploadBody { + field1?: pb_optional<1, uint_32>; // 0 + appid?: pb<2, uint_32>; // 14901(与 fileId 的 appid 不同) + field3?: pb_optional<3, uint_32>; // 2 + payload?: pb<107, FlashSlicePayload>; +} + +/** sliceupload HTTP 响应 — f5=status,"success" 表示该片已落盘。 */ +export interface FlashSliceUploadResp { + status?: pb<5, string>; +} + +/** sub=103 wrapper.f2 fileId — 客户端构造的 protobuf,base64url 编码。 + * appid 用 14902:下载 URL(0x93d4 返回)的 appid 也是 14902,两者必须一致, + * 否则下载报 "appid is not match"。sliceupload body 的 appid 则用 14901。 */ +export interface FlashFileId { + sha1?: pb<2, bytes>; // 整文件 SHA1 + fileSize?: pb<3, uint_32>; + appid?: pb<4, uint_32>; // 14902 + timestamp?: pb<5, uint_64>; // 微秒时间戳 + env?: pb<6, string>; // "prod" + ttl?: pb<10, uint_32>; // 1209600(14 天) + sessionId?: pb<11, bytes>; // 16B,随机生成 + field15?: pb<15, bytes>; // 3B + region?: pb<16, string>; // "gz" +} + +// ─────────────── 0x12a9 sub=100/103 — prepare/apply-upload ─────────────── +// sub=100 与 sub=103 的 payload 字段号不同:sub=100 在 f2,sub=103 在 f12。 +// sub=100 返回 sliceupload rkey;sub=103 注册 fileId,响应无 rkey。 +// 下面的类型描述 sub=103 的 f12 结构(sub=100 的 f2 结构对应 FlashPrepareUploadPayload)。 + +/** FileInfo.f5 — f4 是 varint,与 FlashApplyPayloadField3.f4 的 message 类型不同。 + * pb_optional 保证 0 值显式上 wire,服务端要求字段存在。 */ +export interface FlashApplyFileInfo5 { + field1?: pb_optional<1, uint_32>; // sub=100=1 / sub=103=0 + field2?: pb_optional<2, uint_32>; + field3?: pb_optional<3, uint_32>; + field4?: pb_optional<4, uint_32>; +} + +/** f12.f3 — f4 是空 message,与 FileInfo5.f4 的 varint 类型不同。 */ +export interface FlashApplyPayloadField3 { + field1?: pb_optional<1, uint_32>; + field2?: pb_optional<2, uint_32>; + field3?: pb_optional<3, uint_32>; + field4?: pb<4, FlashEmpty>; +} + +/** f12.f10 — fileset 包装(filesetUuid + fileUuid + flags)。 */ +export interface FlashApplyFilesetWrap { + filesetUuid?: pb_optional<1, string>; + uploadKey?: pb_optional<2, string>; // 同 filesetUuid + fileUuid?: pb_optional<3, string>; + field4?: pb_optional<4, uint_32>; // 1 + field5?: pb_optional<5, uint_32>; // 0 + field6?: pb_optional<6, uint_32>; // sub=100=0 / sub=103=1 + field7?: pb_optional<7, uint_32>; // 2 + field8?: pb<8, FlashEmpty>; + field9?: pb_optional<9, uint_32>; // 1 + field10?: pb_optional<10, uint_32>; + field11?: pb_optional<11, uint_32>; + field12?: pb_optional<12, uint_32>; + field13?: pb_optional<13, uint_32>; + field14?: pb_optional<14, uint_32>; +} + +/** 0x12a9 f12.f1.f1 — FileInfo。 */ +export interface FlashApplyFileInfo { + fileSize?: pb_optional<1, uint_32>; + md5?: pb_optional<2, string>; // 32 hex(sub=100 空,sub=103 有) + sha1?: pb_optional<3, string>; // 40 hex + fileName?: pb_optional<4, string>; + field5?: pb<5, FlashApplyFileInfo5>; + field6?: pb_optional<6, uint_32>; + field7?: pb_optional<7, uint_32>; + field8?: pb_optional<8, uint_32>; + field9?: pb_optional<9, uint_32>; // sub=100=0 / sub=103=1 +} + +/** 0x12a9 f12.f1 — wrapper(FileInfo + fileId + 时间戳/TTL)。 */ +export interface FlashApplyUploadWrapper { + fileInfo?: pb<1, FlashApplyFileInfo>; + fileId?: pb_optional<2, string>; // sub=100 不带,sub=103 带 + field3?: pb_optional<3, uint_32>; // 1 + field4?: pb_optional<4, uint_32>; // 时间戳 + field5?: pb_optional<5, uint_32>; // TTL 1209600(14 天) + field6?: pb_optional<6, uint_32>; +} + +/** 0x12a9 f12 — apply-upload payload。 */ +export interface FlashApplyUploadPayload { + wrapper?: pb<1, FlashApplyUploadWrapper>; + flag2?: pb<2, FlashApplyFlag2>; // {f1:2} + field3?: pb<3, FlashApplyPayloadField3>; // {f1:0,f2:0,f3:0,f4:{}} + filesetWrap?: pb<10, FlashApplyFilesetWrap>; +} +export interface FlashApplyFlag2 { field1?: pb<1, uint_32>; } + +/** 0x12a9 请求 f1 — head(seq + sub + config)。 */ +export interface FlashApplyHeadSub { seq?: pb<1, uint_32>; sub?: pb<2, uint_32>; } +export interface FlashApplyHeadConfig { + field101?: pb<101, uint_32>; + field102?: pb<102, uint_32>; + field103?: pb<103, uint_32>; // 文件类型:jpg=24 / png=23 / mp4=22 + field200?: pb<200, uint_32>; +} +export interface FlashApplyHead { + sub?: pb<1, FlashApplyHeadSub>; + config?: pb<2, FlashApplyHeadConfig>; + field3?: pb<3, FlashApplyFlag2>; // {f1:1} +} + +/** 0x12a9 sub=103 请求(payload @ f12)。 */ +export interface FlashApplyUploadReq { + head?: pb<1, FlashApplyHead>; + payload?: pb<12, FlashApplyUploadPayload>; +} + +/** 0x12a9 apply-upload 响应 — rkey 在 f2。 */ +export interface FlashApplyUploadResp { + head?: pb<1, FlashApplyHeadResp>; + rkeyWrap?: pb<2, FlashRkeyWrap>; +} +export interface FlashApplyHeadResp { + sub?: pb<1, FlashApplyHeadSub>; + msg?: pb<3, string>; // "success" +} +export interface FlashRkeyWrap { rkey?: pb<1, string>; } + +// ─────────────── 0x12a9 sub=100 — prepare-upload ─────────────── +// sub=100 的 payload 在 f2(sub=103 在 f12),filesetWrap 在 f9(sub=103 在 f10), +// wrapper.f2 是 varint 0(sub=103 是 fileId string)。 +/** sub=100 payload.f6.f1。 */ +export interface FlashPreparePayloadF6F1 { + field1?: pb_optional<1, uint_32>; + field2?: pb<2, FlashEmpty>; +} +/** sub=100 payload.f6.f2。 */ +export interface FlashPreparePayloadF6F2 { + field3?: pb<3, FlashEmpty>; +} +/** sub=100 payload.f6.f3。 */ +export interface FlashPreparePayloadF6F3 { + field11?: pb<11, FlashEmpty>; + field12?: pb<12, FlashEmpty>; +} +/** sub=100 payload.f6 — 嵌套 message(固定值)。 */ +export interface FlashPreparePayloadF6 { + field1?: pb<1, FlashPreparePayloadF6F1>; + field2?: pb<2, FlashPreparePayloadF6F2>; + field3?: pb<3, FlashPreparePayloadF6F3>; + field10?: pb_optional<10, uint_32>; +} +/** sub=100 wrapper — f2 是 varint 0(sub=103 是 fileId)。 */ +export interface FlashPrepareWrapper { + fileInfo?: pb<1, FlashApplyFileInfo>; + field2?: pb_optional<2, uint_32>; +} +/** sub=100 payload。 */ +export interface FlashPrepareUploadPayload { + wrapper?: pb<1, FlashPrepareWrapper>; + field2?: pb_optional<2, uint_32>; // 1 + field3?: pb_optional<3, uint_32>; + field4?: pb_optional<4, uint_32>; + field5?: pb_optional<5, uint_32>; + field6?: pb<6, FlashPreparePayloadF6>; + field7?: pb_optional<7, uint_32>; + field8?: pb_optional<8, uint_32>; + filesetWrap?: pb<9, FlashApplyFilesetWrap>; // f9(sub=103 在 f10);f6=0(sub=103=1) +} +/** sub=100 请求 — payload 在 f2(sub=103 在 f12)。 */ +export interface FlashPrepareUploadReq { + head?: pb<1, FlashApplyHead>; + payload?: pb<2, FlashPrepareUploadPayload>; +} +/** sub=100 响应 — f2.f1 是 sliceupload rkey;秒传时 f1 缺失(deserialize 返回 null)。 */ +export interface FlashPrepareUploadResp { + head?: pb<1, FlashApplyHeadResp>; + rkeyWrap?: pb<2, FlashRkeyWrap>; +} + +// ─────────────── 0x93d7 — 发送闪传文件给用户(send_flash_msg) ─────────────── +// 请求 f1={f1:1, f2:{f1:targetUid}}, f2=filesetUuid(私聊); +// f1={f1:2, f3:{f1:groupId}}, f2=filesetUuid(群聊)。响应仅回显目标(无 message_id)。 +/** 0x93d7 请求 f1.f2 — 私聊目标 uid 包装。 */ +export interface FlashSendTargetUid { + targetUid?: pb<1, string>; +} +/** 0x93d7 请求 f1.f3 — 群聊目标 groupId 包装。 */ +export interface FlashSendTargetGroupId { + groupId?: pb<1, uint_32>; +} +/** 0x93d7 请求 f1 — 发送目标。私聊 f1=1+f2(uid),群聊 f1=2+f3(groupId)。 */ +export interface FlashSendTarget { + field1?: pb<1, uint_32>; + targetUid?: pb<2, FlashSendTargetUid>; + targetGroup?: pb<3, FlashSendTargetGroupId>; +} +/** 0x93d7 请求。 */ +export interface FlashSendReq { + target?: pb<1, FlashSendTarget>; + filesetUuid?: pb<2, string>; +} +/** 0x93d7 响应 f1.f3 — 回显目标。 */ +export interface FlashSendRespEcho { + target?: pb<3, FlashSendTarget>; +} +/** 0x93d7 响应 — 仅回显目标,无 message_id(分享 fileset,非传统消息)。 */ +export interface FlashSendResp { + echo?: pb<1, FlashSendRespEcho>; +} + +// ─────────────── 0x12a9 sub=200 — get-download(主文件下载直链)─────────────── +// 请求 payload @ f3(不同于 sub=100 的 f2 / sub=103 的 f12)。响应 f3 含 rkey + 主文件下载 URL。 +// 主文件下载 URL(appid=14901)的唯一来源;0x93d3/0x93d4 的 downloadUrl 是缩略图。 +/** sub=200 请求 f3.f1.f1 — FileInfo(简化,只 fileName)。 */ +export interface FlashGetDownloadFileInfo { + field1?: pb<1, uint_32>; // 0 + field4?: pb<4, string>; // fileName + field5?: pb<5, FlashApplyFileInfo5>; // {0,0,0,0} + field6?: pb<6, uint_32>; // 0 + field7?: pb<7, uint_32>; // 0 + field8?: pb<8, uint_32>; // 0 + field9?: pb<9, uint_32>; // 0 +} +/** sub=200 请求 f3.f1 — wrapper(FileInfo + 主文件 fileId)。 */ +export interface FlashGetDownloadWrapper { + fileInfo?: pb<1, FlashGetDownloadFileInfo>; + fileId?: pb<2, string>; // 主文件 fileId(来自 0x93d4 f14.f1) + field3?: pb<3, uint_32>; // 0 + field4?: pb<4, uint_32>; // 0 + field5?: pb<5, uint_32>; // 0 + field6?: pb<6, uint_32>; // 0 +} +/** sub=200 请求 f3.f2.f2 — 固定下载参数(真客户端实测值,未观察到随文件变化)。 */ +export interface FlashGetDownloadParam { + field1?: pb<1, uint_32>; // 4294967294 + field3?: pb<3, uint_32>; // 4294967295 + field5?: pb<5, uint_32>; // 111 + field6?: pb<6, FlashGetDownloadParam6>; +} +export interface FlashGetDownloadParam6 { + field1?: pb<1, uint_32>; // 3403722988 +} +export interface FlashGetDownloadFlag4 { field1?: pb<1, uint_32>; } +/** sub=200 请求 f3.f2.f10 — filesetWrap(filesetUuid + fileUuid)。 */ +export interface FlashGetDownloadFilesetWrap { + filesetUuid?: pb<1, string>; + fileUuid?: pb<2, string>; + field3?: pb<3, uint_32>; // 2 + field4?: pb<4, string>; // fileUuid +} +/** sub=200 请求 f3.f2。 */ +export interface FlashGetDownloadPayload2 { + field2?: pb<2, FlashGetDownloadParam>; + field4?: pb<4, FlashGetDownloadFlag4>; + filesetWrap?: pb<10, FlashGetDownloadFilesetWrap>; +} +/** sub=200 请求 f3 — payload。 */ +export interface FlashGetDownloadPayload { + wrapper?: pb<1, FlashGetDownloadWrapper>; + field2?: pb<2, FlashGetDownloadPayload2>; + field3?: pb<3, uint_32>; // 0 +} +/** sub=200 请求 — payload @ f3。 */ +export interface FlashGetDownloadReq { + head?: pb<1, FlashApplyHead>; // sub:200 + payload?: pb<3, FlashGetDownloadPayload>; +} +/** sub=200 响应 — f3 含 rkey + 主文件下载 URL(bytes,deserialize 正则提取 URL)。 */ +export interface FlashGetDownloadResp { + head?: pb<1, FlashApplyHeadResp>; + body?: pb<3, bytes>; +} diff --git a/packages/proto-defs/src/oidb-actions/index.ts b/packages/proto-defs/src/oidb-actions/index.ts index bafcf158..1bbee34c 100644 --- a/packages/proto-defs/src/oidb-actions/index.ts +++ b/packages/proto-defs/src/oidb-actions/index.ts @@ -1,4 +1,5 @@ export type * from './base'; export type * from './group-file'; export type * from './media'; -export type * from './group-album'; \ No newline at end of file +export type * from './group-album'; +export type * from './flash-transfer'; \ No newline at end of file diff --git a/packages/protocol/package.json b/packages/protocol/package.json index 186bf01e..0bbf1dee 100644 --- a/packages/protocol/package.json +++ b/packages/protocol/package.json @@ -72,6 +72,58 @@ "types": "./src/oidb-services/custom-face/order-custom-face.ts", "default": "./src/oidb-services/custom-face/order-custom-face.ts" }, + "./oidb-services/flash-transfer/get-fileset-detail": { + "types": "./src/oidb-services/flash-transfer/get-fileset-detail.ts", + "default": "./src/oidb-services/flash-transfer/get-fileset-detail.ts" + }, + "./oidb-services/flash-transfer/list-filesets": { + "types": "./src/oidb-services/flash-transfer/list-filesets.ts", + "default": "./src/oidb-services/flash-transfer/list-filesets.ts" + }, + "./oidb-services/flash-transfer/get-download-url": { + "types": "./src/oidb-services/flash-transfer/get-download-url.ts", + "default": "./src/oidb-services/flash-transfer/get-download-url.ts" + }, + "./oidb-services/flash-transfer/delete-file": { + "types": "./src/oidb-services/flash-transfer/delete-file.ts", + "default": "./src/oidb-services/flash-transfer/delete-file.ts" + }, + "./oidb-services/flash-transfer/rename-file": { + "types": "./src/oidb-services/flash-transfer/rename-file.ts", + "default": "./src/oidb-services/flash-transfer/rename-file.ts" + }, + "./oidb-services/flash-transfer/apply-fileset": { + "types": "./src/oidb-services/flash-transfer/apply-fileset.ts", + "default": "./src/oidb-services/flash-transfer/apply-fileset.ts" + }, + "./oidb-services/flash-transfer/commit-file": { + "types": "./src/oidb-services/flash-transfer/commit-file.ts", + "default": "./src/oidb-services/flash-transfer/commit-file.ts" + }, + "./oidb-services/flash-transfer/complete-fileset": { + "types": "./src/oidb-services/flash-transfer/complete-fileset.ts", + "default": "./src/oidb-services/flash-transfer/complete-fileset.ts" + }, + "./oidb-services/flash-transfer/set-status": { + "types": "./src/oidb-services/flash-transfer/set-status.ts", + "default": "./src/oidb-services/flash-transfer/set-status.ts" + }, + "./oidb-services/flash-transfer/apply-upload": { + "types": "./src/oidb-services/flash-transfer/apply-upload.ts", + "default": "./src/oidb-services/flash-transfer/apply-upload.ts" + }, + "./oidb-services/flash-transfer/prepare-upload": { + "types": "./src/oidb-services/flash-transfer/prepare-upload.ts", + "default": "./src/oidb-services/flash-transfer/prepare-upload.ts" + }, + "./oidb-services/flash-transfer/send-flash": { + "types": "./src/oidb-services/flash-transfer/send-flash.ts", + "default": "./src/oidb-services/flash-transfer/send-flash.ts" + }, + "./oidb-services/flash-transfer/get-flash-download": { + "types": "./src/oidb-services/flash-transfer/get-flash-download.ts", + "default": "./src/oidb-services/flash-transfer/get-flash-download.ts" + }, "./oidb-services/interaction/send-poke": { "types": "./src/oidb-services/interaction/send-poke.ts", "default": "./src/oidb-services/interaction/send-poke.ts" @@ -380,6 +432,10 @@ "types": "./src/highway/utils.ts", "default": "./src/highway/utils.ts" }, + "./highway/sha1-stream": { + "types": "./src/highway/sha1-stream.ts", + "default": "./src/highway/sha1-stream.ts" + }, "./highway/pipeline": { "types": "./src/highway/pipeline.ts", "default": "./src/highway/pipeline.ts" diff --git a/packages/protocol/src/highway/sha1-stream.ts b/packages/protocol/src/highway/sha1-stream.ts new file mode 100644 index 00000000..17659352 --- /dev/null +++ b/packages/protocol/src/highway/sha1-stream.ts @@ -0,0 +1,112 @@ +// 流式 SHA1 计算器,支持输出中间 state(不 finalize)。 +// 闪传 sliceupload 的 f107.f6 (Sha1StateV) 需要每片对应的累积 SHA1 中间 state, +// Node.js 内置 crypto 只能算完整 digest,这里自行实现 transform 以暴露中间 state。 + +import { createHash } from 'node:crypto'; + +const SHA1_BLOCK_SIZE = 64; +const SHA1_DIGEST_SIZE = 20; + +function rotl(x: number, n: number): number { + return ((x << n) | (x >>> (32 - n))) >>> 0; +} + +export class Sha1Stream { + private readonly state = new Uint32Array(5); + private readonly count = new Uint32Array(2); // [low, high] bit count + private readonly buffer = new Uint8Array(SHA1_BLOCK_SIZE); + + constructor() { this.reset(); } + + reset(): void { + this.state[0] = 0x67452301; + this.state[1] = 0xEFCDAB89; + this.state[2] = 0x98BADCFE; + this.state[3] = 0x10325476; + this.state[4] = 0xC3D2E1F0; + this.count[0] = 0; + this.count[1] = 0; + } + + private transform(data: Uint8Array, offset: number): void { + const w = new Uint32Array(80); + const dv = new DataView(data.buffer, data.byteOffset + offset, 64); + for (let i = 0; i < 16; i++) w[i] = dv.getUint32(i * 4, false); // big-endian + for (let i = 16; i < 80; i++) { + w[i] = rotl(w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16], 1); + } + let a = this.state[0], b = this.state[1], c = this.state[2], d = this.state[3], e = this.state[4]; + for (let i = 0; i < 80; i++) { + let temp: number; + if (i < 20) temp = ((b & c) | (~b & d)) + 0x5A827999; + else if (i < 40) temp = (b ^ c ^ d) + 0x6ED9EBA1; + else if (i < 60) temp = ((b & c) | (b & d) | (c & d)) + 0x8F1BBCDC; + else temp = (b ^ c ^ d) + 0xCA62C1D6; + temp = (temp + rotl(a, 5) + e + w[i]) >>> 0; + e = d; d = c; c = rotl(b, 30); b = a; a = temp; + } + this.state[0] = (this.state[0] + a) >>> 0; + this.state[1] = (this.state[1] + b) >>> 0; + this.state[2] = (this.state[2] + c) >>> 0; + this.state[3] = (this.state[3] + d) >>> 0; + this.state[4] = (this.state[4] + e) >>> 0; + } + + update(data: Uint8Array): void { + const len = data.length; + let index = (this.count[0] >>> 3) & 0x3F; + this.count[0] = (this.count[0] + (len << 3)) >>> 0; + if (this.count[0] < (len << 3)) this.count[1] = (this.count[1] + 1) >>> 0; + this.count[1] = (this.count[1] + (len >>> 29)) >>> 0; + + let partLen = SHA1_BLOCK_SIZE - index; + let i = 0; + if (len >= partLen) { + this.buffer.set(data.subarray(0, partLen), index); + this.transform(this.buffer, 0); + i = partLen; + while (i + SHA1_BLOCK_SIZE <= len) { + this.transform(data, i); + i += SHA1_BLOCK_SIZE; + } + index = 0; + } + this.buffer.set(data.subarray(i), index); + } + + /** 输出当前 state(20B)。littleEndian=true 小端,false 大端。不 finalize。 */ + hash(littleEndian: boolean): Uint8Array { + const digest = new Uint8Array(SHA1_DIGEST_SIZE); + const dv = new DataView(digest.buffer); + for (let i = 0; i < 5; i++) { + if (littleEndian) dv.setUint32(i * 4, this.state[i], true); + else dv.setUint32(i * 4, this.state[i], false); + } + return digest; + } +} + +/** + * 计算闪传 sliceupload 的 Sha1StateV(累积 SHA1 state list)。 + * states[i] = SHA1 中间 state(从初始 state 处理 file[0:(i+1)*sliceSize] 后,无 finalize,小端 20B)。 + * 最后一片 states[last] = 标准整文件 SHA1(有 finalize)。 + * + * 用单个 Sha1Stream 增量 update:每片只喂新增的 sliceSize 字节再快照,O(n)。 + * (sliceSize=1MB 是 SHA1 块大小 64B 的整数倍,增量 update 不会残留半块。) + */ +export function computeSha1StateV(bytes: Uint8Array, sliceCount: number, sliceSize: number): Uint8Array[] { + const states: Uint8Array[] = []; + const sha1 = new Sha1Stream(); + for (let i = 0; i < sliceCount; i++) { + const start = i * sliceSize; + const end = Math.min(start + sliceSize, bytes.length); + sha1.update(bytes.subarray(start, end)); + if (i !== sliceCount - 1) { + states.push(sha1.hash(true)); // 小端中间 state,不 finalize + } else { + // 最后一片:标准整文件 SHA1(有 finalize) + states.push(new Uint8Array(createHash('sha1').update(Buffer.from(bytes)).digest())); + } + } + return states; +} diff --git a/packages/protocol/src/oidb-services/flash-transfer/apply-fileset.ts b/packages/protocol/src/oidb-services/flash-transfer/apply-fileset.ts new file mode 100644 index 00000000..e1617256 --- /dev/null +++ b/packages/protocol/src/oidb-services/flash-transfer/apply-fileset.ts @@ -0,0 +1,66 @@ +// OIDB 0x93cf_1 — 申请创建 fileSet(上传起点)。 +// 请求 f1=1, f2=FileInfo{filename,origName,type=1,size,uploader}, f3=类型码, f12=1。 +// 响应 f1=filesetUuid, f2=uploadKey(同f1), f3=上传URL(qfile.qq.com/q/), f4=expire, f5=ttl。 +// subCommand=1, reserved=0(真客户端 envelope 实测确认)。 + +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { + FlashApplyFilesetReq, + FlashApplyFilesetResp, +} from '@snowluma/proto-defs/oidb-actions/flash-transfer'; +import { invokeOidb, type OidbSender } from '../../oidb-service'; + +export interface FlashUploaderInfo { + uin: string; + nickname: string; + uid: string; +} + +export namespace ApplyFileset { + export const command = 0x93cf; + export const subCommand = 1; + + export interface Params { + fileName: string; + origName: string; + fileSize: number; + /** 文件类型码:rar=2, png/mp4=7。 */ + typeCode: number; + uploader: FlashUploaderInfo; + } + + export type Deps = OidbSender; + + export const serialize = (_ctx: Deps, p: Params): FlashApplyFilesetReq => ({ + field1: 1, + fileInfo: { + fileName: p.fileName, + origName: p.origName, + fileType: 1, + fileSize: BigInt(p.fileSize), + uploader: { + uin: p.uploader.uin, + nickname: p.uploader.nickname, + uid: p.uploader.uid, + field4: {}, + }, + field16: 1, + field20: 0, + field21: 0, + }, + typeCode: p.typeCode, + field12: 1, + }); + + export const deserialize = (_ctx: Deps, body: FlashApplyFilesetResp): FlashApplyFilesetResp => body; + + export const encode = (env: OidbBase): Uint8Array => + protobuf_encode>(env); + + export const decode = (bytes: Uint8Array): OidbBase => + protobuf_decode>(bytes); + + export const invoke = (deps: Deps, params: Params): Promise => + invokeOidb(deps, ApplyFileset, params); +} diff --git a/packages/protocol/src/oidb-services/flash-transfer/apply-upload.ts b/packages/protocol/src/oidb-services/flash-transfer/apply-upload.ts new file mode 100644 index 00000000..897adf54 --- /dev/null +++ b/packages/protocol/src/oidb-services/flash-transfer/apply-upload.ts @@ -0,0 +1,98 @@ +// OIDB 0x12a9_103 — apply-upload(注册 fileId,sliceupload 前调用)。 +// uinForm=true。带 MD5 + 客户端构造的 fileId。响应无 rkey(rkey 来自 sub=100)。 + +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { + FlashApplyUploadReq, + FlashApplyUploadResp, +} from '@snowluma/proto-defs/oidb-actions/flash-transfer'; +import { invokeOidb, type OidbSender } from '../../oidb-service'; + +let seqCounter = 100; + +export namespace ApplyUpload { + export const command = 0x12a9; + export const subCommand = 103; + export const uinForm = true; + + export interface Params { + filesetUuid: string; + fileUuid: string; + fileId: string; // 来自 sub=100 响应 + fileName: string; + fileSize: number; + md5: string; // 32 hex + sha1: string; // 40 hex + /** fileset 内序号(1,2,3...),与 0x93d0 commit f6 一致。 */ + fileIndex: number; + /** 格式码:与 commit f7 一致(mp4=2, rar/zip=4)。主文件 filesetWrap.f7 用此值; + * 缩略图固定 png=26/jpg=2。 */ + formatCode: number; + /** 缩略图类型:undefined=主文件, 'png'=png 缩略图, 'jpg'=jpg 缩略图。 */ + thumbType?: 'png' | 'jpg'; + width?: number; + height?: number; + } + export type Deps = OidbSender; + + export const serialize = (_ctx: Deps, p: Params): FlashApplyUploadReq => { + // 缩略图与主文件字段差异:config.f103、FileInfo.f5.f1/f6/f7/f9、 + // filesetWrap.f4/f5/f6/f7/f9。filesetWrap.f4 统一用 fileIndex。 + const isThumb = p.thumbType !== undefined; + const isJpg = p.thumbType === 'jpg'; + return { + head: { + sub: { seq: seqCounter++, sub: 103 }, + config: { field101: 2, field102: 4, field103: isThumb ? (isJpg ? 24 : 23) : 22, field200: 5 }, + field3: { field1: 1 }, + }, + payload: { + wrapper: { + fileInfo: { + fileSize: p.fileSize, + md5: p.md5, + sha1: p.sha1, + fileName: p.fileName, + field5: { field1: isJpg ? 1 : 0, field2: 0, field3: 0, field4: 0 }, + field6: p.width ?? 0, + field7: p.height ?? 0, + field8: 0, + field9: isJpg ? 0 : 1, + }, + fileId: p.fileId, + field3: 1, + field4: Math.floor(Date.now() / 1000), + field5: 1209600, // TTL 14 天 + field6: 0, + }, + flag2: { field1: 2 }, + field3: { field1: 0, field2: 0, field3: 0, field4: {} }, + filesetWrap: { + filesetUuid: p.filesetUuid, + uploadKey: p.filesetUuid, + fileUuid: p.fileUuid, + field4: p.fileIndex, + field5: isThumb && !isJpg ? 1 : 0, // png=1, jpg/mp4=0 + field6: isThumb ? (isJpg ? 1 : 0) : 0, // png缩略图=0, jpg缩略图=1, 主文件=0 + field7: isThumb ? (isJpg ? 2 : 26) : p.formatCode, // 主文件=formatCode(mp4=2), png缩略图=26, jpg缩略图=2 + field8: {}, + field9: 1, field10: 0, field11: 0, field12: 0, field13: 0, field14: 0, + }, + }, + }; + }; + + export const deserialize = (_ctx: Deps, _body: FlashApplyUploadResp): void => { + // sub=103 resp f12={f1:filesetWrap}(注册确认,无 rkey)。rkey 来自 sub=100。 + }; + + export const encode = (env: OidbBase): Uint8Array => + protobuf_encode>(env); + + export const decode = (bytes: Uint8Array): OidbBase => + protobuf_decode>(bytes); + + export const invoke = (deps: Deps, params: Params): Promise => + invokeOidb(deps, ApplyUpload, params); +} diff --git a/packages/protocol/src/oidb-services/flash-transfer/commit-file.ts b/packages/protocol/src/oidb-services/flash-transfer/commit-file.ts new file mode 100644 index 00000000..6803b7b9 --- /dev/null +++ b/packages/protocol/src/oidb-services/flash-transfer/commit-file.ts @@ -0,0 +1,70 @@ +// OIDB 0x93d0_1 — fileset 内所有文件的元数据上报(commit)。 +// 多文件机制:f4 是 repeated,一个请求同时携带 fileset 内全部文件条目, +// 每条 f6=文件序号(1,2,3...),f7=formatCode。单文件时只有一个条目。 +// 响应 f1=1(ack), f2/f3=filesetUuid。subCommand=1, reserved=0。 + +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { + FlashCommitFileReq, + FlashCommitFileResp, +} from '@snowluma/proto-defs/oidb-actions/flash-transfer'; +import { invokeOidb, type OidbSender } from '../../oidb-service'; + +export namespace CommitFile { + export const command = 0x93d0; + export const subCommand = 1; + + /** 单个文件的 commit 元数据。fileIndex 为 fileset 内序号(从 1 递增)。 */ + export interface CommitEntry { + fileUuid: string; + fileName: string; + origName: string; + fileSize: number; + /** 格式码:rar=4, mp4=2。 */ + formatCode: number; + /** fileset 内序号(1,2,3...),与 0x12a9 filesetWrap.f4 一致。 */ + fileIndex: number; + } + + export interface Params { + filesetUuid: string; + /** fileset 内全部文件条目;一次 0x93d0 请求同时上报。 */ + entries: CommitEntry[]; + } + + export type Deps = OidbSender; + + export const serialize = (_ctx: Deps, p: Params): FlashCommitFileReq => ({ + field1: 1, + filesetUuid: p.filesetUuid, + uploadKey: p.filesetUuid, + commitInfo: p.entries.map((e) => ({ + filesetUuid: p.filesetUuid, + fileUuid: e.fileUuid, + field3: 0, + field4: {}, + field5: 1, + field6: e.fileIndex, + formatCode: e.formatCode, + fileName: e.fileName, + origName: e.origName, + field10: 0, + fileSize: BigInt(e.fileSize), + field12: 0, + field24: {}, + })), + field5: 1, + field6: 1, + }); + export const deserialize = (_ctx: Deps, body: FlashCommitFileResp): FlashCommitFileResp => body; + + export const encode = (env: OidbBase): Uint8Array => + protobuf_encode>(env); + + export const decode = (bytes: Uint8Array): OidbBase => + protobuf_decode>(bytes); + + export const invoke = (deps: Deps, params: Params): Promise => + invokeOidb(deps, CommitFile, params); +} diff --git a/packages/protocol/src/oidb-services/flash-transfer/complete-fileset.ts b/packages/protocol/src/oidb-services/flash-transfer/complete-fileset.ts new file mode 100644 index 00000000..0ea85a56 --- /dev/null +++ b/packages/protocol/src/oidb-services/flash-transfer/complete-fileset.ts @@ -0,0 +1,38 @@ +// OIDB 0x93db_1 — fileSet 完成。请求 f1=filesetUuid, f2=""。响应 ack。sub=1, reserved=0。 + +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { + FlashCompleteFilesetReq, + FlashCompleteFilesetResp, +} from '@snowluma/proto-defs/oidb-actions/flash-transfer'; +import { invokeOidb, type OidbSender } from '../../oidb-service'; + +export namespace CompleteFileset { + export const command = 0x93db; + export const subCommand = 1; + + export interface Params { + filesetUuid: string; + } + + export type Deps = OidbSender; + + export const serialize = (_ctx: Deps, p: Params): FlashCompleteFilesetReq => ({ + filesetUuid: p.filesetUuid, + field2: '', + }); + + export const deserialize = (_ctx: Deps, _body: FlashCompleteFilesetResp): void => { + // 成功靠 envelope errorCode=0。 + }; + + export const encode = (env: OidbBase): Uint8Array => + protobuf_encode>(env); + + export const decode = (bytes: Uint8Array): OidbBase => + protobuf_decode>(bytes); + + export const invoke = (deps: Deps, params: Params): Promise => + invokeOidb(deps, CompleteFileset, params); +} diff --git a/packages/protocol/src/oidb-services/flash-transfer/delete-file.ts b/packages/protocol/src/oidb-services/flash-transfer/delete-file.ts new file mode 100644 index 00000000..0c794e6d --- /dev/null +++ b/packages/protocol/src/oidb-services/flash-transfer/delete-file.ts @@ -0,0 +1,40 @@ +// OIDB 0x9407_1 — 删除闪传文件(OneBot 标准未定义,QQ 面板有此操作)。 +// 请求 f1=filesetUuid, f2="", f3=7。响应短 ack(envelope errorCode=0 即成功)。 + +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { + FlashDeleteFileReq, + FlashDeleteFileResp, +} from '@snowluma/proto-defs/oidb-actions/flash-transfer'; +import { invokeOidb, type OidbSender } from '../../oidb-service'; + +export namespace DeleteFlashFile { + export const command = 0x9407; + export const subCommand = 1; + + export interface Params { + filesetUuid: string; + } + + export type Deps = OidbSender; + + export const serialize = (_ctx: Deps, p: Params): FlashDeleteFileReq => ({ + filesetUuid: p.filesetUuid, + field2: '', + field3: 7, + }); + + export const deserialize = (_ctx: Deps, _body: FlashDeleteFileResp): void => { + // 成功靠 envelope errorCode=0(invokeOidb 已校验),业务体空。 + }; + + export const encode = (env: OidbBase): Uint8Array => + protobuf_encode>(env); + + export const decode = (bytes: Uint8Array): OidbBase => + protobuf_decode>(bytes); + + export const invoke = (deps: Deps, params: Params): Promise => + invokeOidb(deps, DeleteFlashFile, params); +} diff --git a/packages/protocol/src/oidb-services/flash-transfer/get-download-url.ts b/packages/protocol/src/oidb-services/flash-transfer/get-download-url.ts new file mode 100644 index 00000000..16e0b930 --- /dev/null +++ b/packages/protocol/src/oidb-services/flash-transfer/get-download-url.ts @@ -0,0 +1,78 @@ +// OIDB 0x93d4_1 — 拉取下载URL(完整参数 + fldc)。 +// 响应下载URL: multimedia.qfile.qq.com/download?appid=14902&client_type=win +// &client_ver=...&fileid=...&fldc=...(无 rkey,用 fldc)。 +// 响应结构与 0x93d3 不同:downloadUrl 在 f1.f3.f13.f2.f2(非 f9.fileIdWrap)。 +// 用于 get_flash_file_url / download_fileset 的完整链接变体。 + +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { + FlashGetDownloadUrlReq, + FlashGetDownloadUrlResp, +} from '@snowluma/proto-defs/oidb-actions/flash-transfer'; +import { invokeOidb, type OidbSender } from '../../oidb-service'; + +export namespace GetDownloadUrl { + export const command = 0x93d4; + export const subCommand = 1; + + export interface Params { + filesetUuid: string; + /** 指定下载 fileset 内第几个文件(1-based)。默认 1(主文件)。 */ + fileIndex?: number; + } + /** 单个文件的下载元信息;无主文件 fileId 时该条目 null。 */ + export type FileMeta = { + fileIndex: number; + fileId: string; + filesetUuid: string; + fileUuid: string; + fileName: string; + fileSize: number; + }; + /** fileset 内所有文件元信息(按 fileIndex 升序)。 */ + export type Result = FileMeta[]; + + export type Deps = OidbSender; + + export const serialize = (_ctx: Deps, p: Params): FlashGetDownloadUrlReq => ({ + filesetUuid: p.filesetUuid, + inner: { + field1: '', + field2: 1, + field3: 18, + field4: '', + field5: { field1: 0 }, + field6: { field1: 0, field2: 0 }, + }, + field3: 7, + field4: 1, + }); + + export const deserialize = (_ctx: Deps, body: FlashGetDownloadUrlResp): Result => { + // f1.f3 是 repeated fileInfo,多文件 fileset 时每个文件一条(f6=序号,f14=主文件 fileId)。 + // f13 是缩略图(appid=14902),主文件下载 URL 需 0x12a9 sub=200 拿。 + const infos = body.entry?.fileInfo ?? []; + return infos.map((info, idx) => { + const fileId = info?.mainFile?.fileId ?? ''; + const fileIndex = info?.field6 ?? idx + 1; + return { + fileIndex, + fileId, + filesetUuid: info?.filesetUuid ?? '', + fileUuid: info?.fileUuid ?? '', + fileName: info?.fileName ?? '', + fileSize: Number(info?.fileSize ?? 0), + }; + }); + }; + + export const encode = (env: OidbBase): Uint8Array => + protobuf_encode>(env); + + export const decode = (bytes: Uint8Array): OidbBase => + protobuf_decode>(bytes); + + export const invoke = (deps: Deps, params: Params): Promise => + invokeOidb(deps, GetDownloadUrl, params); +} diff --git a/packages/protocol/src/oidb-services/flash-transfer/get-fileset-detail.ts b/packages/protocol/src/oidb-services/flash-transfer/get-fileset-detail.ts new file mode 100644 index 00000000..6777bfac --- /dev/null +++ b/packages/protocol/src/oidb-services/flash-transfer/get-fileset-detail.ts @@ -0,0 +1,42 @@ +// OIDB 0x93d3_1 — 拉取文件集详情(点"分享"显示链接时触发)。 +// 请求 f1=filesetUuid, f2=7。响应 f1=repeated FlashFileEntry(含文件名/大小/ +// 上传分享URL qfile.qq.com/q/ / fileId / 下载URL,URL 里已含 rkey)。 +// 用于 get_fileset_info / get_flash_file_list / get_flash_file_url / get_share_link。 + +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { + FlashGetDetailReq, + FlashGetDetailResp, + FlashFileEntry, +} from '@snowluma/proto-defs/oidb-actions/flash-transfer'; +import { invokeOidb, type OidbSender } from '../../oidb-service'; + +export namespace GetFilesetDetail { + export const command = 0x93d3; + export const subCommand = 1; + + export interface Params { + filesetUuid: string; + } + export type Result = FlashFileEntry[]; + + export type Deps = OidbSender; + + export const serialize = (_ctx: Deps, p: Params): FlashGetDetailReq => ({ + filesetUuid: p.filesetUuid, + field2: 7, + }); + + export const deserialize = (_ctx: Deps, body: FlashGetDetailResp): Result => + body.entries ?? []; + + export const encode = (env: OidbBase): Uint8Array => + protobuf_encode>(env); + + export const decode = (bytes: Uint8Array): OidbBase => + protobuf_decode>(bytes); + + export const invoke = (deps: Deps, params: Params): Promise => + invokeOidb(deps, GetFilesetDetail, params); +} diff --git a/packages/protocol/src/oidb-services/flash-transfer/get-flash-download.ts b/packages/protocol/src/oidb-services/flash-transfer/get-flash-download.ts new file mode 100644 index 00000000..038106ff --- /dev/null +++ b/packages/protocol/src/oidb-services/flash-transfer/get-flash-download.ts @@ -0,0 +1,82 @@ +// OIDB 0x12a9_200 — get-download(拿主文件下载直链)。 +// 请求 payload @ f3(不同于 sub=100 的 f2 / sub=103 的 f12)。响应 f3 含 host + path +// (主文件下载 URL,appid=14901 + 主文件fileId + fldc + rkey)。 +// 主文件 fileId 来自 0x93d4 f14.f1。0x93d3/0x93d4 的 downloadUrl 是缩略图(appid=14903/14902), +// 主文件下载 URL 必须走 sub=200。 + +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { + FlashGetDownloadReq, + FlashGetDownloadResp, +} from '@snowluma/proto-defs/oidb-actions/flash-transfer'; +import { invokeOidb, type OidbSender } from '../../oidb-service'; + +let seqCounter = 300; + +export namespace GetFlashDownload { + export const command = 0x12a9; + export const subCommand = 200; + export const uinForm = true; + + export interface Params { + filesetUuid: string; + fileUuid: string; // 主文件 fileUuid(0x93d4 f1.f3.f2) + fileId: string; // 主文件 fileId(0x93d4 f14.f1) + fileName: string; + } + export type Result = string | null; // 主文件下载 URL + + export type Deps = OidbSender; + + export const serialize = (_ctx: Deps, p: Params): FlashGetDownloadReq => ({ + head: { + sub: { seq: seqCounter++, sub: 200 }, + config: { field101: 2, field102: 4, field103: 22, field200: 5 }, // mp4 f103=22 + field3: { field1: 1 }, + }, + payload: { + wrapper: { + fileInfo: { + field1: 0, + field4: p.fileName, + field5: { field1: 0, field2: 0, field3: 0, field4: 0 }, + field6: 0, field7: 0, field8: 0, field9: 0, + }, + fileId: p.fileId, + field3: 0, field4: 0, field5: 0, field6: 0, + }, + field2: { + // 固定下载参数(QQ 客户端实测值,未观察到随文件变化)。 + field2: { field1: 4294967294, field3: 4294967295, field5: 111, field6: { field1: 3403722988 } }, + field4: { field1: 0 }, + // field3 必须是主文件类型码 26;用 2 会被服务端拒(170019002 Service Failure)。 + filesetWrap: { filesetUuid: p.filesetUuid, fileUuid: p.fileUuid, field3: 26, field4: p.fileUuid }, + }, + field3: 0, + }, + }); + + export const deserialize = (_ctx: Deps, body: FlashGetDownloadResp): Result => { + // 响应 f3 含 rkey + host(multimedia.qfile.qq.com)+ path(/download?appid=14901...&fldc=...)。 + // rkey 在 f3 单独字段(path 不含 rkey),拼完整 URL 需拼接 &rkey=。 + const raw = body.body; + if (!raw || raw.length === 0) return null; + const text = Buffer.from(raw).toString('latin1'); + const host = /multimedia\.qfile\.qq\.com/.exec(text); + const path = /\/download\?appid=14901[\x20-\x7e]*/.exec(text); + const rkey = /rkey=([A-Za-z0-9_-]+)/.exec(text); + if (!host || !path) return null; + const base = `https://${host[0]}${path[0]}`; + return rkey ? `${base}&${rkey[0]}` : base; + }; + + export const encode = (env: OidbBase): Uint8Array => + protobuf_encode>(env); + + export const decode = (bytes: Uint8Array): OidbBase => + protobuf_decode>(bytes); + + export const invoke = (deps: Deps, params: Params): Promise => + invokeOidb(deps, GetFlashDownload, params); +} diff --git a/packages/protocol/src/oidb-services/flash-transfer/list-filesets.ts b/packages/protocol/src/oidb-services/flash-transfer/list-filesets.ts new file mode 100644 index 00000000..14f084bc --- /dev/null +++ b/packages/protocol/src/oidb-services/flash-transfer/list-filesets.ts @@ -0,0 +1,42 @@ +// OIDB 0x93d2_1 — 查询 fileset 列表(全部 fileset,无 UUID 入参)。 +// 请求 f1=3, f2="", f3=10。响应 f1=repeated FlashFileEntry。 + +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { + FlashListFilesetsReq, + FlashListFilesetsResp, + FlashFileEntry, +} from '@snowluma/proto-defs/oidb-actions/flash-transfer'; +import { invokeOidb, type OidbSender } from '../../oidb-service'; + +export namespace ListFilesets { + export const command = 0x93d2; + export const subCommand = 1; + + export interface Params { + field1?: number; // 默认 3 + field3?: number; // 默认 10 + } + export type Result = FlashFileEntry[]; + + export type Deps = OidbSender; + + export const serialize = (_ctx: Deps, p: Params): FlashListFilesetsReq => ({ + field1: p.field1 ?? 3, + field2: '', + field3: p.field3 ?? 10, + }); + + export const deserialize = (_ctx: Deps, body: FlashListFilesetsResp): Result => + body.entries ?? []; + + export const encode = (env: OidbBase): Uint8Array => + protobuf_encode>(env); + + export const decode = (bytes: Uint8Array): OidbBase => + protobuf_decode>(bytes); + + export const invoke = (deps: Deps, params: Params = {}): Promise => + invokeOidb(deps, ListFilesets, params); +} diff --git a/packages/protocol/src/oidb-services/flash-transfer/prepare-upload.ts b/packages/protocol/src/oidb-services/flash-transfer/prepare-upload.ts new file mode 100644 index 00000000..b19dda41 --- /dev/null +++ b/packages/protocol/src/oidb-services/flash-transfer/prepare-upload.ts @@ -0,0 +1,103 @@ +// OIDB 0x12a9_100 — prepare-upload(大文件分片上传前申请 sliceupload rkey)。 +// sub=100,uinForm=true。sub=100 的 payload 在 f2(sub=103 在 f12),结构完全不同。 +// 响应 f2.f1 是 sliceupload rkey;秒传(文件已在服务端)时 f1 缺失,deserialize 返回 null。 +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { + FlashPrepareUploadReq, + FlashPrepareUploadResp, +} from '@snowluma/proto-defs/oidb-actions/flash-transfer'; +import { invokeOidb, type OidbSender } from '../../oidb-service'; + +let seqCounter = 200; + +export namespace PrepareUpload { + export const command = 0x12a9; + export const subCommand = 100; + export const uinForm = true; + + export interface Params { + filesetUuid: string; + fileUuid: string; + fileName: string; + fileSize: number; + sha1: string; // 40 hex + /** fileset 内序号(1,2,3...),与 0x93d0 commit f6 一致。缩略图序号在主文件之后递增。 */ + fileIndex: number; + /** 格式码:与 commit f7 一致(mp4=2, rar/zip=4)。主文件 filesetWrap.f7 用此值; + * 缩略图固定 png=26/jpg=2。 */ + formatCode: number; + /** 缩略图类型:undefined=主文件, 'png'=png 缩略图, 'jpg'=jpg 缩略图。 + * 主文件下载入口需要缩略图关联才会被服务端填充,缩略图字段差异据此切换。 */ + thumbType?: 'png' | 'jpg'; + width?: number; // 缩略图宽(主文件=0) + height?: number; // 缩略图高(主文件=0) + } + export type Deps = OidbSender; + + export const serialize = (_ctx: Deps, p: Params): FlashPrepareUploadReq => { + // 缩略图与主文件字段差异:config.f103、FileInfo.f5.f1/f6/f7/f9、filesetWrap.f6/f7。 + // filesetWrap.f4 统一用 fileIndex(主文件和缩略图都从 facade 传入,保证与 commit f6 一致)。 + const isThumb = p.thumbType !== undefined; + const isJpg = p.thumbType === 'jpg'; + return { + head: { + sub: { seq: seqCounter++, sub: 100 }, + config: { field101: 2, field102: 4, field103: isThumb ? (isJpg ? 24 : 23) : 22, field200: 5 }, + field3: { field1: 1 }, + }, + payload: { + wrapper: { + fileInfo: { + fileSize: p.fileSize, + md5: '', // sub=100 不带 MD5 + sha1: p.sha1, + fileName: p.fileName, + field5: { field1: isJpg ? 1 : 0, field2: 0, field3: 0, field4: 0 }, + field6: p.width ?? 0, + field7: p.height ?? 0, + field8: 0, + field9: isJpg ? 0 : 1, + }, + field2: 0, // wrapper.f2=0(varint,不是 fileId) + }, + field2: 1, + field3: 0, + field4: 0, + field5: 0, + field6: { + field1: { field1: 0, field2: {} }, + field2: { field3: {} }, + field3: { field11: {}, field12: {} }, + field10: 0, + }, + field7: 0, + field8: 0, + filesetWrap: { + filesetUuid: p.filesetUuid, + uploadKey: p.filesetUuid, + fileUuid: p.fileUuid, + field4: p.fileIndex, + field5: 0, + field6: isThumb ? 1 : 0, // 缩略图=1, 主文件=0 + field7: isThumb ? (isJpg ? 2 : 26) : p.formatCode, // 主文件=formatCode(mp4=2), png缩略图=26, jpg缩略图=2 + field8: {}, + field9: 1, field10: 0, field11: 0, field12: 0, field13: 0, field14: 0, + }, + }, + }; + }; + + export const deserialize = (_ctx: Deps, body: FlashPrepareUploadResp): string | null => { + // sub-100 resp f2={f1:rkey}(正常上传,CAES/CAIS/CAQS/CAMS)。 + // 秒传(文件已在服务端)时 f2 无 f1(rkey),返回 null,调用方跳过 sliceupload。 + return body.rkeyWrap?.rkey ?? null; + }; + + export const encode = (env: OidbBase): Uint8Array => + protobuf_encode>(env); + export const decode = (bytes: Uint8Array): OidbBase => + protobuf_decode>(bytes); + export const invoke = (deps: Deps, params: Params): Promise => + invokeOidb(deps, PrepareUpload, params); +} diff --git a/packages/protocol/src/oidb-services/flash-transfer/rename-file.ts b/packages/protocol/src/oidb-services/flash-transfer/rename-file.ts new file mode 100644 index 00000000..37cf40e3 --- /dev/null +++ b/packages/protocol/src/oidb-services/flash-transfer/rename-file.ts @@ -0,0 +1,45 @@ +// OIDB 0x9427_0 — 重命名闪传文件(OneBot 标准未定义,QQ 面板有此操作)。 +// 请求 f1=filesetUuid, f2={f1=新文件名, f2=显示名}, f3={f1=0}。 +// 注意 envelope 与其他闪传 cmd 不同:subCommand=0(不是 1)+ uinForm=true(reserved=1)。 +// 不能按 0x93cf_1 类推,用 sub=1 会被服务端拒(no privilege)。 + +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { + FlashRenameFileReq, + FlashRenameFileResp, +} from '@snowluma/proto-defs/oidb-actions/flash-transfer'; +import { invokeOidb, type OidbSender } from '../../oidb-service'; + +export namespace RenameFlashFile { + export const command = 0x9427; + export const subCommand = 0; + export const uinForm = true; + + export interface Params { + filesetUuid: string; + /** 新文件名(同时用作显示名,与 QQ 面板行为一致)。 */ + newName: string; + } + + export type Deps = OidbSender; + + export const serialize = (_ctx: Deps, p: Params): FlashRenameFileReq => ({ + filesetUuid: p.filesetUuid, + name: { newName: p.newName, displayName: p.newName }, + flag: { field1: 0 }, + }); + + export const deserialize = (_ctx: Deps, _body: FlashRenameFileResp): void => { + // 成功靠 envelope errorCode=0。 + }; + + export const encode = (env: OidbBase): Uint8Array => + protobuf_encode>(env); + + export const decode = (bytes: Uint8Array): OidbBase => + protobuf_decode>(bytes); + + export const invoke = (deps: Deps, params: Params): Promise => + invokeOidb(deps, RenameFlashFile, params); +} diff --git a/packages/protocol/src/oidb-services/flash-transfer/send-flash.ts b/packages/protocol/src/oidb-services/flash-transfer/send-flash.ts new file mode 100644 index 00000000..790a22fb --- /dev/null +++ b/packages/protocol/src/oidb-services/flash-transfer/send-flash.ts @@ -0,0 +1,52 @@ +// OIDB 0x93d7_1 — 发送闪传文件给用户(send_flash_msg)。 +// 请求 f1={f1:1, f2:{f1:targetUid}}, f2=filesetUuid。响应仅回显目标 uid(无 message_id)。 +// 0x93d7 是「分享 fileset 给用户」(对端通过 fileset 链接下载),非传统消息。 +// envelope 用 0x93xx 默认的 sub=1/reserved=0,实测通过。 + +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { + FlashSendReq, + FlashSendResp, +} from '@snowluma/proto-defs/oidb-actions/flash-transfer'; +import { invokeOidb, type OidbSender } from '../../oidb-service'; + +export namespace SendFlashMsg { + export const command = 0x93d7; + export const subCommand = 1; + + export interface Params { + targetUid?: string; // 私聊(与 groupId 二选一) + groupId?: number; // 群聊 + filesetUuid: string; + } + export type Deps = OidbSender; + + export const serialize = (_ctx: Deps, p: Params): FlashSendReq => { + // 群聊:f1={f1:2, f3:{f1:groupId}}(groupId 直接用群号,无需转 uid)。 + if (p.groupId !== undefined) { + return { + target: { field1: 2, targetGroup: { groupId: p.groupId } }, + filesetUuid: p.filesetUuid, + }; + } + // 私聊:f1={f1:1, f2:{f1:targetUid}}。 + return { + target: { field1: 1, targetUid: { targetUid: p.targetUid! } }, + filesetUuid: p.filesetUuid, + }; + }; + + export const deserialize = (_ctx: Deps, _body: FlashSendResp): void => { + // 响应仅回显目标 uid,无 message_id。 + }; + + export const encode = (env: OidbBase): Uint8Array => + protobuf_encode>(env); + + export const decode = (bytes: Uint8Array): OidbBase => + protobuf_decode>(bytes); + + export const invoke = (deps: Deps, params: Params): Promise => + invokeOidb(deps, SendFlashMsg, params); +} diff --git a/packages/protocol/src/oidb-services/flash-transfer/set-status.ts b/packages/protocol/src/oidb-services/flash-transfer/set-status.ts new file mode 100644 index 00000000..70ef98f8 --- /dev/null +++ b/packages/protocol/src/oidb-services/flash-transfer/set-status.ts @@ -0,0 +1,39 @@ +// OIDB 0x93d1_1 — 设置 fileSet 状态。请求 f1=filesetUuid, f2=6(状态码)。响应 ack。sub=1, reserved=0。 + +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { + FlashSetStatusReq, + FlashSetStatusResp, +} from '@snowluma/proto-defs/oidb-actions/flash-transfer'; +import { invokeOidb, type OidbSender } from '../../oidb-service'; + +export namespace SetFilesetStatus { + export const command = 0x93d1; + export const subCommand = 1; + + export interface Params { + filesetUuid: string; + status?: number; // 默认 6 + } + + export type Deps = OidbSender; + + export const serialize = (_ctx: Deps, p: Params): FlashSetStatusReq => ({ + filesetUuid: p.filesetUuid, + status: p.status ?? 6, + }); + + export const deserialize = (_ctx: Deps, _body: FlashSetStatusResp): void => { + // 成功靠 envelope errorCode=0。 + }; + + export const encode = (env: OidbBase): Uint8Array => + protobuf_encode>(env); + + export const decode = (bytes: Uint8Array): OidbBase => + protobuf_decode>(bytes); + + export const invoke = (deps: Deps, params: Params): Promise => + invokeOidb(deps, SetFilesetStatus, params); +} diff --git a/packages/protocol/tests/highway/sha1-stream.test.ts b/packages/protocol/tests/highway/sha1-stream.test.ts new file mode 100644 index 00000000..382f01e1 --- /dev/null +++ b/packages/protocol/tests/highway/sha1-stream.test.ts @@ -0,0 +1,190 @@ +import { describe, expect, it } from 'vitest'; +import { createHash } from 'node:crypto'; +import { Sha1Stream, computeSha1StateV } from '@snowluma/protocol/highway/sha1-stream'; + +// SHA1 标准填充:msg + 0x80 + 0x00...(k 个) + 8 字节大端 bit 长度,总长为 64 倍数。 +// 用于把任意输入变成「已 finalize」的完整 block 序列——这样 Sha1Stream 对它逐 block +// transform 后取大端 state,应当等于 Node crypto 对原始 msg 的 digest。 +function sha1Pad(msg: Uint8Array): Uint8Array { + const msgLen = msg.length; + const k = (56 - ((msgLen + 1) % 64) + 64) % 64; + const padded = new Uint8Array(msgLen + 1 + k + 8); + padded.set(msg, 0); + padded[msgLen] = 0x80; + const view = new DataView(padded.buffer, padded.byteOffset + padded.byteLength - 8, 8); + view.setBigUint64(0, BigInt(msgLen) * 8n, false); // 大端 bit 长度 + return padded; +} + +// padding oracle 的核心:Node crypto 的 SHA1 digest 内部就是对 padding 后的输入逐 block +// transform、取最终 state 的大端表示。Sha1Stream 自行实现 transform 且不 finalize, +// 因此对「已 padding 的输入」transform 后大端输出必须等于 digest。Node crypto 走 +// OpenSSL,与本实现完全独立,是验证 transform 正确性的可靠参照。 +function expectSha1StreamMatchesCrypto(msg: Uint8Array): void { + const expected = createHash('sha1').update(Buffer.from(msg)).digest(); + const stream = new Sha1Stream(); + stream.update(sha1Pad(msg)); + const bigEndian = stream.hash(false); + expect(Buffer.from(bigEndian).equals(expected)).toBe(true); +} + +describe('Sha1Stream transform (padding oracle vs Node crypto)', () => { + it('matches for empty input (single padded block)', () => { + expectSha1StreamMatchesCrypto(Buffer.alloc(0)); + }); + + it('matches for "abc" (single padded block)', () => { + expectSha1StreamMatchesCrypto(Buffer.from('abc', 'utf8')); + }); + + it('matches across the 56-byte boundary (forces a second padded block)', () => { + // 56 字节:0x80 后只剩 0 字节给 zeros 不够放 8 字节长度,padding 溢出到第二块。 + expectSha1StreamMatchesCrypto(Buffer.alloc(56, 0x41)); + }); + + it('matches for exactly one block (64 bytes → two padded blocks)', () => { + expectSha1StreamMatchesCrypto(Buffer.alloc(64, 0x42)); + }); + + it('matches for multi-block input (200 bytes → four padded blocks)', () => { + expectSha1StreamMatchesCrypto(Buffer.alloc(200, 0x43)); + }); + + it('matches for pseudo-random multi-block input', () => { + const data = Buffer.alloc(313, 0); + for (let i = 0; i < data.length; i++) data[i] = (i * 1103515245 + 12345) & 0xff; + expectSha1StreamMatchesCrypto(data); + }); +}); + +describe('Sha1Stream update chunk-equivalence', () => { + // update 内部维护 64 字节 buffer + 128 位 bit 计数;分块喂入必须与一次性喂入 + // 产生相同的内部 state。切分点覆盖 block 边界附近以暴露 buffer/count 管理 bug。 + it('two-chunk split at various boundaries yields the same state as one update', () => { + const data = Buffer.alloc(200, 0x44); + const full = new Sha1Stream(); + full.update(data); + const fullHash = Buffer.from(full.hash(true)); + for (const split of [0, 1, 32, 63, 64, 65, 127, 128, 129, 199]) { + const s = new Sha1Stream(); + s.update(data.subarray(0, split)); + s.update(data.subarray(split)); + expect(Buffer.from(s.hash(true)).equals(fullHash)).toBe(true); + } + }); + + it('three-chunk split yields the same state as one update', () => { + const data = Buffer.alloc(300, 0x45); + const full = new Sha1Stream(); + full.update(data); + const fullHash = Buffer.from(full.hash(true)); + const s = new Sha1Stream(); + s.update(data.subarray(0, 100)); + s.update(data.subarray(100, 200)); + s.update(data.subarray(200)); + expect(Buffer.from(s.hash(true)).equals(fullHash)).toBe(true); + }); + + it('empty updates do not change the state', () => { + const data = Buffer.alloc(130, 0x46); + const full = new Sha1Stream(); + full.update(data); + const fullHash = Buffer.from(full.hash(true)); + const s = new Sha1Stream(); + s.update(Buffer.alloc(0)); + s.update(data); + s.update(Buffer.alloc(0)); + expect(Buffer.from(s.hash(true)).equals(fullHash)).toBe(true); + }); +}); + +describe('Sha1Stream hash endianness', () => { + // hash(true) 小端与 hash(false) 大端是同一组 5 个 state word 的不同字节序表示。 + // 结合上面的 padding oracle(大端 == digest),即可间接确认小端中间 state 的值。 + it('little-endian is the per-word byte-swap of big-endian', () => { + const s = new Sha1Stream(); + s.update(Buffer.alloc(64, 0x47)); + const le = Buffer.from(s.hash(true)); + const be = Buffer.from(s.hash(false)); + expect(le.length).toBe(20); + for (let i = 0; i < 5; i++) { + expect(le.readUInt32LE(i * 4)).toBe(be.readUInt32BE(i * 4)); + } + }); + + it('reset restores the initial SHA1 state', () => { + const s = new Sha1Stream(); + s.update(Buffer.alloc(200, 0x48)); + s.reset(); + const initial = Buffer.from(s.hash(false)); + const expected = Buffer.from([ + 0x67, 0x45, 0x23, 0x01, 0xef, 0xcd, 0xab, 0x89, + 0x98, 0xba, 0xdc, 0xfe, 0x10, 0x32, 0x54, 0x76, + 0xc3, 0xd2, 0xe1, 0xf0, + ]); + expect(initial.equals(expected)).toBe(true); + }); +}); + +describe('computeSha1StateV', () => { + const SLICE = 1024 * 1024; // 1 MB,与上传链路一致,且是 64 的倍数 + + it('returns one 20-byte state per slice', () => { + const data = Buffer.alloc(SLICE + 100, 0x49); // 2 片 + const states = computeSha1StateV(data, 2, SLICE); + expect(states.length).toBe(2); + for (const st of states) expect(st.length).toBe(20); + }); + + // 末片定义为「标准整文件 SHA1(有 finalize/padding)」,直接对齐 Node crypto。 + it('last slice equals the standard full-file SHA1 digest', () => { + const data = Buffer.alloc(SLICE + 100, 0x4a); + const states = computeSha1StateV(data, 2, SLICE); + const expected = createHash('sha1').update(data).digest(); + expect(Buffer.from(states[1]).equals(expected)).toBe(true); + }); + + it('last slice equals full-file SHA1 for a three-slice file', () => { + const data = Buffer.alloc(SLICE * 2 + 1, 0x4b); + const states = computeSha1StateV(data, 3, SLICE); + expect(Buffer.from(states[2]).equals(createHash('sha1').update(data).digest())).toBe(true); + }); + + // 非末片是「累积 SHA1 中间 state(不 finalize,小端)」。若误用标准 finalize + // 计算,会得到 file[0:slice] 的完整 digest,与本实现必然不等——以此锁定 + // 「中间 state 而非独立片 digest」的语义。 + it('non-last slice is NOT the finalized digest of the prefix', () => { + const data = Buffer.alloc(SLICE + 100, 0x4c); + const states = computeSha1StateV(data, 2, SLICE); + const prefixDigest = createHash('sha1').update(data.subarray(0, SLICE)).digest(); + expect(Buffer.from(states[0]).equals(prefixDigest)).toBe(false); + }); + + // 非末片中间 state 的正确性来自 transform(padding oracle 已验)与 update + // 分块等价(已验)。这里再做一次直接对照:computeSha1StateV 对首片的处理 + // 等价于手动 reset + update(prefix) + 小端输出。 + it('non-last slice equals manual Sha1Stream reset+update of the prefix', () => { + const data = Buffer.alloc(SLICE + 100, 0x4d); + const states = computeSha1StateV(data, 2, SLICE); + const manual = new Sha1Stream(); + manual.update(data.subarray(0, SLICE)); + expect(Buffer.from(states[0]).equals(Buffer.from(manual.hash(true)))).toBe(true); + }); + + // 单片文件只有末片,直接是整文件 digest。 + it('single-slice file has only the finalized digest', () => { + const data = Buffer.alloc(100, 0x4e); + const states = computeSha1StateV(data, 1, SLICE); + expect(states.length).toBe(1); + expect(Buffer.from(states[0]).equals(createHash('sha1').update(data).digest())).toBe(true); + }); + + // 中间 state 与「把它当末片算出的 digest」必须不同——这是 sliceupload 服务端 + // 校验「累积 state 而非独立片 digest」的核心区分点。 + it('non-last slice differs from a single-slice digest of the same prefix', () => { + const data = Buffer.alloc(SLICE + 100, 0x4f); + const multiFirst = computeSha1StateV(data, 2, SLICE)[0]; + const singleAsLast = computeSha1StateV(data.subarray(0, SLICE), 1, SLICE)[0]; + expect(Buffer.from(multiFirst).equals(Buffer.from(singleAsLast))).toBe(false); + }); +}); diff --git a/packages/protocol/tests/oidb-services/flash-transfer/apply-upload-byteoracle.test.ts b/packages/protocol/tests/oidb-services/flash-transfer/apply-upload-byteoracle.test.ts new file mode 100644 index 00000000..798a0e1e --- /dev/null +++ b/packages/protocol/tests/oidb-services/flash-transfer/apply-upload-byteoracle.test.ts @@ -0,0 +1,70 @@ +import { describe, expect, it } from 'vitest'; +import { protobuf_encode, protobuf_decode } from '@snowluma/proton'; +import type { FlashApplyUploadReq } from '@snowluma/proto-defs/oidb-actions/flash-transfer'; + +// ENC#8: 0x12a9 sub=103 apply-upload 真实客户端请求 body(frida 抓包,QQ 9.9.26-44343, +// 2026-06-19)。用 ENC#8 的精确值手工构造 req,encode 后必须 byte-for-byte 匹配 ENC#8 hex。 +// 这是真正的 byte-oracle:字段号/wire type/0值显式编码任一错误都会 hex 不等。 +const ENC8_HEX = + '0a190a0508ac011067120ca80602b00604b80616c00c051a020801629d030a81020a870108b4cdcc01122063396631303334663062303431653933353339653937663839356363333139621a28306636326234663763646463373965326662666431343065646531326431633434646462373937612222e5b18fe5b995e5bd95e588b620323032352d30312d3135203030323133302e6d70342a0808001000180020003000380040004801126745685150597254337a64783534767639464137654574484554647435656869307a637742494c56304b4b4b516938796a6b3555444d675277636d396b5549447153566f51496f38546b56454c72776f454c5746544c6a433268586f445947505f676745435a336f180120fae4d4d1062880ea493000120208021a0808001000180022005288010a2438363866633433312d336361372d346130632d383538322d666135656365613062666134122438363866633433312d336361372d346130632d383538322d6661356563656130626661341a2436656639316166322d363830302d373633632d313936642d38353231303537353536343020012800300138024200480150005800600068007000'; + +// ENC#8 抓包值(sub=103 mp4)。 +const ENC8_REQ: FlashApplyUploadReq = { + head: { + sub: { seq: 172, sub: 103 }, + config: { field101: 2, field102: 4, field103: 22, field200: 5 }, + field3: { field1: 1 }, + }, + payload: { + wrapper: { + fileInfo: { + fileSize: 3352244, + md5: 'c9f1034f0b041e93539e97f895cc319b', + sha1: '0f62b4f7cddc79e2fbfd140ede12d1c44ddb797a', + fileName: '屏幕录制 2025-01-15 002130.mp4', + field5: { field1: 0, field2: 0, field3: 0, field4: 0 }, + field6: 0, field7: 0, field8: 0, field9: 1, + }, + fileId: 'EhQPYrT3zdx54vv9FA7eEtHETdt5ehi0zcwBILV0KKKQi8yjk5UDMgRwcm9kUIDqSVoQIo8TkVELrwoELWFTLjC2hXoDYGP_ggECZ3o', + field3: 1, field4: 1781871226, field5: 1209600, field6: 0, + }, + flag2: { field1: 2 }, + field3: { field1: 0, field2: 0, field3: 0, field4: {} }, + filesetWrap: { + filesetUuid: '868fc431-3ca7-4a0c-8582-fa5ecea0bfa4', + uploadKey: '868fc431-3ca7-4a0c-8582-fa5ecea0bfa4', + fileUuid: '6ef91af2-6800-763c-196d-852105755640', + field4: 1, field5: 0, field6: 1, field7: 2, field8: {}, + field9: 1, field10: 0, field11: 0, field12: 0, field13: 0, field14: 0, + }, + }, +}; + +describe('ApplyUpload byte-oracle (0x12a9_103 encode == ENC#8)', () => { + it('encodes the ENC#8 field values to the exact frida-captured wire bytes', () => { + const out = Buffer.from(protobuf_encode(ENC8_REQ)).toString('hex'); + if (out !== ENC8_HEX) { + // 定位首个差异字节 + const n = Math.min(out.length, ENC8_HEX.length); + let i = 0; + while (i < n && out[i] === ENC8_HEX[i]) i++; + throw new Error( + `hex mismatch at char ${i} (byte ${i >> 1}):\n` + + ` bot: ...${out.slice(Math.max(0, i - 20), i + 20)}\n` + + ` ENC#8: ...${ENC8_HEX.slice(Math.max(0, i - 20), i + 20)}\n` + + ` bot len=${out.length / 2}B, ENC#8 len=${ENC8_HEX.length / 2}B`, + ); + } + expect(out).toBe(ENC8_HEX); + }); + + it('round-trips: encode → decode preserves the field tree', () => { + const bytes = protobuf_encode(ENC8_REQ); + const back = protobuf_decode(bytes); + expect(back.head?.sub?.sub).toBe(103); + expect(back.head?.config?.field103).toBe(22); + expect(back.payload?.wrapper?.fileInfo?.field9).toBe(1); + expect(back.payload?.wrapper?.fileInfo?.field5?.field4).toBe(0); + expect(back.payload?.filesetWrap?.fileUuid).toBe('6ef91af2-6800-763c-196d-852105755640'); + }); +}); diff --git a/packages/protocol/tests/oidb-services/flash-transfer/apply-upload.test.ts b/packages/protocol/tests/oidb-services/flash-transfer/apply-upload.test.ts new file mode 100644 index 00000000..06a46164 --- /dev/null +++ b/packages/protocol/tests/oidb-services/flash-transfer/apply-upload.test.ts @@ -0,0 +1,60 @@ +import { describe, expect, it } from 'vitest'; +import { protobuf_decode } from '@snowluma/proton'; +import type { FlashApplyUploadReq } from '@snowluma/proto-defs/oidb-actions/flash-transfer'; +import { ApplyUpload } from '../../../src/oidb-services/flash-transfer/apply-upload'; + +// ENC#8: 0x12a9 sub=103 apply-upload 真实客户端请求 body(frida 抓包,QQ 9.9.26-44343, +// 2026-06-19)。字段树逐字节解码见 flash_transfer_protocol_full.md §9.5。 +// 独立 byte-oracle:从 frida 抓的 hex decode 回来,字段号/wire type 错则值读不出。 +const ENC8_HEX = + '0a190a0508ac011067120ca80602b00604b80616c00c051a020801629d030a81020a870108b4cdcc01122063396631303334663062303431653933353339653937663839356363333139621a28306636326234663763646463373965326662666431343065646531326431633434646462373937612222e5b18fe5b995e5bd95e588b620323032352d30312d3135203030323133302e6d70342a0808001000180020003000380040004801126745685150597254337a64783534767639464137654574484554647435656869307a637742494c56304b4b4b516938796a6b3555444d675277636d396b5549447153566f51496f38546b56454c72776f454c5746544c6a433268586f445947505f676745435a336f180120fae4d4d1062880ea493000120208021a0808001000180022005288010a2438363866633433312d336361372d346130632d383538322d666135656365613062666134122438363866633433312d336361372d346130632d383538322d6661356563656130626661341a2436656639316166322d363830302d373633632d313936642d38353231303537353536343020012800300138024200480150005800600068007000'; + +describe('ApplyUpload namespace (0x12a9_103)', () => { + it('declares command 0x12a9 sub 103 uinForm=true', () => { + expect(ApplyUpload.command).toBe(0x12a9); + expect(ApplyUpload.subCommand).toBe(103); + expect(ApplyUpload.uinForm).toBe(true); + }); + + it('decodes ENC#8 frida capture with the exact field tree', () => { + const req = protobuf_decode(Buffer.from(ENC8_HEX, 'hex')); + + // head: { f1:{seq,sub}, f2:config{f101,f102,f103,f200}, f3:{f1:1} } + expect(req.head?.sub?.seq).toBe(172); + expect(req.head?.sub?.sub).toBe(103); + expect(req.head?.config).toMatchObject({ field101: 2, field102: 4, field103: 22, field200: 5 }); + expect(req.head?.field3?.field1).toBe(1); + + // payload.wrapper.fileInfo(f12.f1.f1) + const fi = req.payload?.wrapper?.fileInfo; + expect(fi?.fileSize).toBe(3352244); + expect(fi?.md5).toBe('c9f1034f0b041e93539e97f895cc319b'); + expect(fi?.sha1).toBe('0f62b4f7cddc79e2fbfd140ede12d1c44ddb797a'); + expect(fi?.fileName).toBe('屏幕录制 2025-01-15 002130.mp4'); + // field5 = {f1:0,f2:0,f3:0,f4:0},f4 是 varint(不是 message) + expect(fi?.field5).toMatchObject({ field1: 0, field2: 0, field3: 0, field4: 0 }); + expect(fi?.field9).toBe(1); + + // payload.wrapper(f12.f1):fileId + 时间戳 + TTL + expect(req.payload?.wrapper?.fileId).toBe('EhQPYrT3zdx54vv9FA7eEtHETdt5ehi0zcwBILV0KKKQi8yjk5UDMgRwcm9kUIDqSVoQIo8TkVELrwoELWFTLjC2hXoDYGP_ggECZ3o'); + expect(req.payload?.wrapper?.field3).toBe(1); + expect(req.payload?.wrapper?.field4).toBe(1781871226); + expect(req.payload?.wrapper?.field5).toBe(1209600); + + // payload.flag2(f12.f2 = {f1:2}) + expect(req.payload?.flag2?.field1).toBe(2); + + // payload.field3(f12.f3 = {f1:0,f2:0,f3:0,f4:空message}) + expect(req.payload?.field3).toMatchObject({ field1: 0, field2: 0, field3: 0 }); + + // payload.filesetWrap(f12.f10 = filesetUuid + fileUuid + flags) + const fw = req.payload?.filesetWrap; + expect(fw?.filesetUuid).toBe('868fc431-3ca7-4a0c-8582-fa5ecea0bfa4'); + expect(fw?.uploadKey).toBe('868fc431-3ca7-4a0c-8582-fa5ecea0bfa4'); + expect(fw?.fileUuid).toBe('6ef91af2-6800-763c-196d-852105755640'); + expect(fw?.field4).toBe(1); + expect(fw?.field6).toBe(1); + expect(fw?.field7).toBe(2); + expect(fw?.field9).toBe(1); + }); +}); diff --git a/packages/protocol/tests/oidb-services/flash-transfer/get-download-url-byteoracle.test.ts b/packages/protocol/tests/oidb-services/flash-transfer/get-download-url-byteoracle.test.ts new file mode 100644 index 00000000..8619a719 --- /dev/null +++ b/packages/protocol/tests/oidb-services/flash-transfer/get-download-url-byteoracle.test.ts @@ -0,0 +1,28 @@ +import { describe, expect, it } from 'vitest'; +import { protobuf_decode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { FlashGetDownloadUrlResp } from '@snowluma/proto-defs/oidb-actions/flash-transfer'; +import { GetDownloadUrl } from '@snowluma/protocol/oidb-services/flash-transfer/get-download-url'; + +// 0x93d4 真实响应(send_packet 抓于 QQ 9.9.26-44343, 2026-06-20, fileset e7453377 已发送)。 +// byte-oracle:decode + deserialize 必须从 f1.f3.f14.f1 提取到主文件 fileId。 +// 0x93d4 响应结构与 0x93d3 不同(downloadUrl 在深层嵌套,非 f9.fileIdWrap),这个测试 +// 锁定该结构,防止 deserialize 退回错误的 FlashFileEntry 解读。 +const RESP_HEX = '08d4a7021001180022b8090ab50910011afa080a2465373435333337372d633865612d343034652d393238352d353361613566616431393832122466613038663938332d323337662d303833632d656536332d6139646164336161616565352801300138024222e5b18fe5b995e5bd95e588b620323032352d30352d3033203135313234312e6d70344a2162696e676d756c757a686920323032352d30352d3033203135313234312e6d703458bcf7e3036ae9050a6645685330442d4c3261494b306b74314d51424f764f5377746465753574426a7939774567746e516f724c6d736d5961566c514d794248427962325251674f704a5768424d3744724a3276364843594c766576376b6f30587565674d4d61502d4341514a6e656712a804080212a30468747470733a2f2f6d756c74696d656469612e7166696c652e71712e636f6d2f646f776e6c6f61643f61707069643d313439303226636c69656e745f747970653d77696e26636c69656e745f7665723d392e322e33342666696c6569643d45685330442d4c3261494b306b74314d51424f764f5377746465753574426a7939774567746e516f724c6d736d5961566c514d794248427962325251674f704a5768424d3744724a3276364843594c766576376b6f30587565674d4d61502d4341514a6e656726666c64633d696358456459355a6b5346395f59347239514f526e58562d6a6b31536d397753546b4a316a6876334f357a5f747331484966612d4c6a7662416b52494531526c4373704a4776336c453469635434467437414a794c33577242304b78696a555f423270386a75367a3371314d26726b65793d43414d5371414878697a55514532647437517975726675552d78446d3568666a4d727073325a69723764535f42354d55694349644e594c495167792d5264776d495a797a584a6f31714a687834464d756b346a337042306a5f37787850315a7a6748706469315f3158376178422d736541556c5f3646546f4679597638564d5337645a577036414275597a3875517a79306c487574676a6762714271477138336d70417a6465426475555833513043732d426b54676952767768664b3835696661774a3874477371576e70784871394f444c762d5f37566a78526e424456587046314f306343551a286234306665326636363838326234393264643463343031336166333932633264373565626239623420f2f7012a20393365643461306234383164623936343335323034363339626366393133313830800438c002726b0a674568512d63526273544d5338304c79484637745658626c38536c5a4e63426938392d4d44494c56304b497154305a6d476c5a55444d675277636d396b5549447153566f5156637648434d53585865556b54726c384e555f4a41586f444c6b625f676745435a336f18027a2466613038663938332d323337662d303833632d656536332d613964616433616161656535900103a2012833653731313665633463633462636430626338373137626235353564623937633461353634643730a801bcf7e303b2010308d547ca0120346365613333363331386338303864646431646630613333633938316339316122327b226f6666736574223a31382c22637572736f725f74696d65223a22303030312d30312d30315430303a30303a30305a227d28012a005a1d0a0f636c69656e745f636f6e6e5f736571120a313738313932393033395a200a1a747270632d6f632d7072696f726974792d706173732d6261636b12022d315a1c0a0e73736f5f647965696e675f6b6579120a323535303431393036385a160a0c73736f5f636c69656e74696412063133333034375a9c040a08747270632d73736f128f04000000147061d586907300000ba05fe3000207b7000001fb0073c9510000000e3235353034313930363820071b1b000008040000000000000000000003000000004c668066ca67e24ac9a81bd08aa343840338fa2f632ec020158218d5d2a35f1a2ab856dcbdcc486af66c8ba961db5532e2a065d882604a01539050c7ad17748f95521b4dac5e1834160000001b4f696462537663547270635463702e3078393364345f31000000188e0800005f3a366a000000008d0b00000000000000000000000000002462376234353837623661333666373535346564353235613563396230303166660000000000000000000000040000011d1a007a91020a047061d58610081a06392e322e333420c19e0c4220633165633037346532323533303539633230303530333039653965643932666552005a10b7b4587b6a36f7554ed525a5c9b001ff62206237623435383762366133366637353534656435323561356339623030316666688008720757696e646f7773820118755f6c5253732d3243757359575a6a455851707045694d518a01009001019a015208081248668066ca67e24ac9a81bd08aa343840338fa2f632ec020158218d5d2a35f1a2ab856dcbdcc486af66c8ba961db5532e2a065d882604a01539050c7ad17748f95521b4dac5e18341618c4acf8fa05a00100b80165c00100d201174f696462537663547270635463702e3078393364345f3190010d'; + +describe('GetDownloadUrl byte-oracle (0x93d4 deserialize)', () => { + it('extracts main file fileId from f1.f3.f14.f1', () => { + const bytes = Uint8Array.from(Buffer.from(RESP_HEX, 'hex')); + const env = protobuf_decode>(bytes); + const result = GetDownloadUrl.deserialize(null as never, env.body!); + // 0x93d4 f1.f3 是 repeated fileInfo,单文件场景返回一个元素的数组。 + expect(result).toHaveLength(1); + const meta = result[0]; + // 主文件 fileId(0x93d4 f14.f1),用于 0x12a9 sub=200 拿主文件下载直链。 + expect(meta.fileId).toBe('EhQ-cRbsTMS80LyHF7tVXbl8SlZNcBi89-MDILV0KIqT0ZmGlZUDMgRwcm9kUIDqSVoQVcvHCMSXXeUkTrl8NU_JAXoDLkb_ggECZ3o'); + expect(meta.filesetUuid).toBe('e7453377-c8ea-404e-9285-53aa5fad1982'); + expect(meta.fileName).toContain('mp4'); + expect(meta.fileSize).toBe(7928764); + expect(meta.fileIndex).toBe(1); + }); +}); diff --git a/packages/protocol/tests/oidb-services/flash-transfer/prepare-upload-byteoracle.test.ts b/packages/protocol/tests/oidb-services/flash-transfer/prepare-upload-byteoracle.test.ts new file mode 100644 index 00000000..e54fcfa9 --- /dev/null +++ b/packages/protocol/tests/oidb-services/flash-transfer/prepare-upload-byteoracle.test.ts @@ -0,0 +1,69 @@ +import { describe, expect, it } from 'vitest'; +import { protobuf_encode, protobuf_decode } from '@snowluma/proton'; +import type { FlashPrepareUploadReq } from '@snowluma/proto-defs/oidb-actions/flash-transfer'; + +// 真实 sub=100 (mp4) frida 抓包(QQ 9.9.26-44343, 2026-06-19)。payload @ f2(不是 f12!)。 +// byte-oracle:用抓包值构造 req,encode 必须 byte-for-byte 匹配。 +const SUB100_MP4_HEX = '0a180a0408081064120ca80602b00604b80616c00c051a0208011298020a6b0a6708a0d2e40212001a28643138333762626336666131653031396136326330343734616332386563363131343565656138612222e5b18fe5b995e5bd95e588b620323032352d31322d3232203135313432392e6d70342a08080010001800200030003800400048011000100118002000280032120a040800120012021a001a045a0062005000380040004a88010a2432383564346530622d363465342d343961642d396430632d666234383938393930626162122432383564346530622d363465342d343961642d396430632d6662343839383939306261621a2432343166356438382d333637352d623030612d303261302d30633035306138343032656520012800300038024200480150005800600068007000'; + +const SUB100_MP4_REQ: FlashPrepareUploadReq = { + head: { + sub: { seq: 8, sub: 100 }, + config: { field101: 2, field102: 4, field103: 22, field200: 5 }, + field3: { field1: 1 }, + }, + payload: { + wrapper: { + fileInfo: { + fileSize: 5843232, + md5: '', + sha1: 'd1837bbc6fa1e019a62c0474ac28ec61145eea8a', + fileName: '屏幕录制 2025-12-22 151429.mp4', + field5: { field1: 0, field2: 0, field3: 0, field4: 0 }, + field6: 0, field7: 0, field8: 0, field9: 1, + }, + field2: 0, + }, + field2: 1, field3: 0, field4: 0, field5: 0, + field6: { + field1: { field1: 0, field2: {} }, + field2: { field3: {} }, + field3: { field11: {}, field12: {} }, + field10: 0, + }, + field7: 0, field8: 0, + filesetWrap: { + filesetUuid: '285d4e0b-64e4-49ad-9d0c-fb4898990bab', + uploadKey: '285d4e0b-64e4-49ad-9d0c-fb4898990bab', + fileUuid: '241f5d88-3675-b00a-02a0-0c050a8402ee', + field4: 1, field5: 0, field6: 0, field7: 2, field8: {}, + field9: 1, field10: 0, field11: 0, field12: 0, field13: 0, field14: 0, + }, + }, +}; + +describe('PrepareUpload byte-oracle (0x12a9_100 encode == frida 抓包)', () => { + it('encodes the sub=100 mp4 capture to the exact wire bytes', () => { + const out = Buffer.from(protobuf_encode(SUB100_MP4_REQ)).toString('hex'); + if (out !== SUB100_MP4_HEX) { + const n = Math.min(out.length, SUB100_MP4_HEX.length); + let i = 0; + while (i < n && out[i] === SUB100_MP4_HEX[i]) i++; + throw new Error( + `hex mismatch at char ${i} (byte ${i >> 1}):\n` + + ` bot: ...${out.slice(Math.max(0, i - 24), i + 24)}\n` + + ` frida: ...${SUB100_MP4_HEX.slice(Math.max(0, i - 24), i + 24)}\n` + + ` bot len=${out.length / 2}B, frida len=${SUB100_MP4_HEX.length / 2}B`, + ); + } + expect(out).toBe(SUB100_MP4_HEX); + }); + + it('round-trips: encode → decode preserves key fields', () => { + const bytes = protobuf_encode(SUB100_MP4_REQ); + const back = protobuf_decode(bytes); + expect(back.head?.sub?.sub).toBe(100); + expect(back.payload?.wrapper?.fileInfo?.fileSize).toBe(5843232); + expect(back.payload?.filesetWrap?.fileUuid).toBe('241f5d88-3675-b00a-02a0-0c050a8402ee'); + }); +}); diff --git a/packages/protocol/tests/oidb-services/flash-transfer/send-flash-byteoracle.test.ts b/packages/protocol/tests/oidb-services/flash-transfer/send-flash-byteoracle.test.ts new file mode 100644 index 00000000..c918bd42 --- /dev/null +++ b/packages/protocol/tests/oidb-services/flash-transfer/send-flash-byteoracle.test.ts @@ -0,0 +1,60 @@ +import { describe, expect, it } from 'vitest'; +import { protobuf_encode, protobuf_decode } from '@snowluma/proton'; +import type { FlashSendReq } from '@snowluma/proto-defs/oidb-actions/flash-transfer'; + +// 0x93d7 send_flash_msg 真实客户端请求 body(frida 抓包,QQ 9.9.26-44343, 2026-06-20)。 +// fileset e7453377-c8ea-404e-9285-53aa5fad1982 发送给 uid u_0aHrwL1tyskEWkhChJoeJg。 +// byte-oracle:用抓包值构造 req,encode 必须 byte-for-byte 匹配。 +const SEND_HEX = '0a1e0801121a0a18755f30614872774c317479736b45576b6843684a6f654a67122465373435333337372d633865612d343034652d393238352d353361613566616431393832'; + +const SEND_REQ: FlashSendReq = { + target: { field1: 1, targetUid: { targetUid: 'u_0aHrwL1tyskEWkhChJoeJg' } }, + filesetUuid: 'e7453377-c8ea-404e-9285-53aa5fad1982', +}; + +describe('SendFlashMsg byte-oracle (0x93d7 encode == frida 抓包)', () => { + it('encodes the send capture to the exact wire bytes', () => { + const out = Buffer.from(protobuf_encode(SEND_REQ)).toString('hex'); + if (out !== SEND_HEX) { + const n = Math.min(out.length, SEND_HEX.length); + let i = 0; + while (i < n && out[i] === SEND_HEX[i]) i++; + throw new Error( + `hex mismatch at char ${i} (byte ${i >> 1}):\n` + + ` bot: ...${out.slice(Math.max(0, i - 20), i + 20)}\n` + + ` frida: ...${SEND_HEX.slice(Math.max(0, i - 20), i + 20)}\n` + + ` bot len=${out.length / 2}B, frida len=${SEND_HEX.length / 2}B`, + ); + } + expect(out).toBe(SEND_HEX); + }); + + it('round-trips: encode → decode preserves target + filesetUuid', () => { + const bytes = protobuf_encode(SEND_REQ); + const back = protobuf_decode(bytes); + expect(back.target?.field1).toBe(1); + expect(back.target?.targetUid?.targetUid).toBe('u_0aHrwL1tyskEWkhChJoeJg'); + expect(back.filesetUuid).toBe('e7453377-c8ea-404e-9285-53aa5fad1982'); + }); +}); + +// 群聊 0x93d7:f1={f1:2, f3:{f1:groupId}}, f2=filesetUuid(groupId 直接用群号,无需转 uid)。 +// 真实客户端 frida 抓包(2026-06-20),fileset e7453377 发送给群 1017438661。 +const SEND_GROUP_HEX = '0a0a08021a0608c5c393e503122465373435333337372d633865612d343034652d393238352d353361613566616431393832'; +const SEND_GROUP_REQ: FlashSendReq = { + target: { field1: 2, targetGroup: { groupId: 1017438661 } }, + filesetUuid: 'e7453377-c8ea-404e-9285-53aa5fad1982', +}; + +describe('SendFlashMsg byte-oracle (0x93d7 群聊 encode == frida 抓包)', () => { + it('encodes the group send capture to the exact wire bytes', () => { + const out = Buffer.from(protobuf_encode(SEND_GROUP_REQ)).toString('hex'); + expect(out).toBe(SEND_GROUP_HEX); + }); + + it('round-trips: encode → decode preserves groupId', () => { + const back = protobuf_decode(protobuf_encode(SEND_GROUP_REQ)); + expect(back.target?.field1).toBe(2); + expect(back.target?.targetGroup?.groupId).toBe(1017438661); + }); +});