feat(flash-transfer): QQ flash transfer (fileset) upload, share, download (#113)

* feat(proto-defs): add flash-transfer OIDB proto types

QQ 闪传(FlashTransfer / fileset)的 protobuf 类型定义:
- FlashFileEntry(0x93d2/0x93d3 文件条目)
- 0x93cf 申请 fileSet / 0x93d0 commit / 0x93db 完成 / 0x93d1 设状态
- 0x93d3 文件集详情 / 0x93d4 下载 URL(含主文件 fileId + 缩略图)
- 0x12a9 sub=100/103/200 prepare/apply/get-download
- sliceupload body + Sha1StateV
- 0x9407 删除 / 0x9427 重命名 / 0x93d7 发送
注册到 oidb-actions/index.ts,package.json 加 exports。

* feat(protocol): add flash-transfer OIDB services + sha1-stream

闪传协议层(OIDB namespace,复用 invokeOidb/OidbCallSpec):
- apply-fileset / commit-file / complete-fileset / set-status(上传流程)
- prepare-upload (0x12a9_100) / apply-upload (0x12a9_103)(sliceupload 凭证)
- get-fileset-detail (0x93d3) / list-filesets (0x93d2) / get-download-url (0x93d4)
- get-flash-download (0x12a9_200,主文件下载直链)
- delete-file (0x9407) / rename-file (0x9427,sub=0+uinForm) / send-flash (0x93d7)
- sha1-stream:SHA1 中间 state 计算器(sliceupload f107.f6 需要,Node crypto 不支持)
- byte-oracle 单测(apply/prepare/get-download-url/send-flash)+ sha1-stream 单测
package.json 加 exports。

* feat(core): add FlashTransferApi facade

FlashTransferApi 编排闪传全流程,复用 OIDB 基础设施(invokeOidb)+
computeHashes/loadBinarySource/fetch:
- createFlashTask:统一走 sub=100/103+sliceupload(含缩略图),不走小文件 PUT
  (PUT 不上报主文件 sha1,fileset 卡在未完成;QQ 客户端小文件也走 sliceupload)
- buildFileId:主文件 appid=14901(进 f14.f1),缩略图 png=14903/jpg=14902
- uploadThumbnail:随机纯色 PNG 占位(手写编码,不引入图像库),关联主文件下载入口
- getFilesetInfo/getFlashFileList/getShareLink/getFlashFileUrl/downloadFileset
- sendFlashMsg(私聊 uid / 群聊 groupId)/ getFilesetIdByCode(网页解析)
- deleteFlashFile / renameFlashFile / listFilesets
注册到 ApiHub(flashTransfer 字段)+ export。

* feat(onebot): add flash-transfer actions

OneBot action(extended.ts)10 个:
create_flash_task / get_fileset_info / get_flash_file_list /
get_flash_file_url / get_share_link / download_fileset /
send_flash_msg(私聊 user_id / 群聊 group_id)/ get_fileset_id /
rename_flash_file / delete_flash_file
MCP catalog(生成文件)同步新增 action 元数据。
extended-actions 接线单测覆盖。

* fix(onebot): align flash file list field name with NapCat

flashFileInfoToJson 的文件大小字段从 file_size 改为 size,对齐 NapCat
get_flash_file_list 响应(NapCat 用 size)。get_fileset_info 的 file_list
复用同一映射,一并生效。便于 NapCat 客户端 drop-in 迁移。

* feat(proto-defs): support multi-file commit in flash-transfer

0x93d0 commit 的 f4 改为 repeated,一个请求携带 fileset 内全部文件条目。
FlashCommitFileInfo 的 f3/f5/f6/f7/f10/f12 用 pb_optional,强制 0 值上 wire
(服务端多文件时严格校验字段存在,省略 0 会导致后续文件不计入 fileset)。

* feat(protocol): parameterize flash-transfer upload for multi-file

CommitFile.Params 改为 entries 数组,serialize 输出 repeated f4,每条 f6=文件序号。
PrepareUpload/ApplyUpload 加 fileIndex + formatCode 参数:filesetWrap.f4 用 fileIndex
(与 commit f6 对齐),f7 用 formatCode(mp4=2 非 26),f9=1。

* feat(core): multi-file flash-transfer upload

createFlashTask 支持多文件共用一个 fileset。关键改动:
- ApplyFileset 多文件时 fileName 用「<首文件名>等N个文件」、fileSize 用总和,
  服务端据此判定 fileset 为多文件,commit 的后续 entry 才被计入
- 一次性 CommitFile 提交所有文件元数据(f4 repeated)
- 两阶段上传:先全部 prepare+apply 注册 fileId,再全部 sliceupload 落盘
- 拆分原 uploadLargeFile 为 prepareAndApply + sliceuploadFile
- fileTypeCode mp4 formatCode 26→2(与 commit f7/filesetWrap.f7 一致)

* feat(onebot): multi-file create_flash_task + list_filesets action

create_flash_task 的 files 参数支持 string 或 string[],多文件共用一个 fileset。
新增 list_filesets action(facade.listFilesets 之前未暴露)。MCP catalog 同步更新
files schema(anyOf string/array)与 list_filesets 条目。

* fix(flash-transfer): multi-file download by fileIndex

0x93d4 响应 f1.f3 是 repeated fileInfo(多文件 fileset 每个文件一条,f6=序号、
f14=主文件 fileId),之前定义成单个导致多文件只能拿到第一个文件。
FlashDownloadEntry.fileInfo 改 pb_repeated,GetDownloadUrl 返回所有文件元信息,
download_fileset 按 fileIndex 选中目标文件走 0x12a9 sub=200 拿直链。

* test(protocol): inline byte-oracle hex fixtures

两个 flash-transfer byte-oracle 测试原先用 readFileSync 读仓库外的
.claude/reverse/scripts/proto/*.hex(本地逆向笔记目录),CI 上不存在导致失败。
把 hex 内容内联成常量,测试自包含。

* fix(flash-transfer): address review feedback

1. get_flash_file_url 接 file_index 参数并在 action 透传(之前漏接,多文件永远返回首文件)
2. getFileDownload 越界 fileIndex 不再静默回退首文件,找不到返回 null
3. postSliceupload status 缺失不再当成功,非 success 一律抛错
4. computeSha1StateV 改 O(n) 增量 update(之前每片 reset 重算整个前缀,O(n²))
5. get_flash_file_url 找不到文件抛错(之前返回空串当成功)
6. create_flash_task files 数组拒绝空字符串
This commit is contained in:
Qiao authored and GitHub committed 2026-06-21 14:24:51 +08:00
1 parent ebadfb968b
commit 127f2cd2d6
29 files changed
+3213 -20

No files matched your search

+252 -18
View File
@@ -54,6 +54,29 @@ async function fetchDownloadFile(
return Buffer.concat(chunks, total);
}
// 把下载好的字节落盘到 data/downloads。<preferredName> 缺省时用内容 md5 命名。
// basename + relative 检查拦截目录穿越:名称里的路径分隔符被剥成纯文件名,
// 再确认解析后仍在 downloads 目录下,避免 ../ 逃逸。
async function saveDownloadBuffer(buf: Buffer, preferredName: string): Promise<string> {
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<string, unknown>): 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));
}
},
}),
];
// 已过滤(机器人/被忽略)的入群请求。