Merge pull request #57 from SnowLuma/dev

chore: promote dev → main (2de1ff4)
This commit is contained in:
snowluma-bot[bot] authored and GitHub committed 2026-05-20 06:21:32 +00:00
commit 1bd0cbc359
168 files changed
+15250 -1160

No files matched your search

+119
View File
@@ -0,0 +1,119 @@
name: Bug 反馈
description: 报告一个可复现的问题
title: "[Bug] "
labels: ["bug"]
body:
- type: markdown
attributes:
value: |
感谢花时间反馈 Bug。请尽量填全以下信息,方便我们定位问题。
在提交前,请先在 [Issues](https://github.com/SnowLuma/SnowLuma/issues?q=is%3Aissue) 中搜索是否已有相同问题。
- type: checkboxes
id: preflight
attributes:
label: 提交前检查
options:
- label: 我已搜索过 Issues,确认没有重复的反馈
required: true
- label: 我使用的是 [最新 Release](https://github.com/SnowLuma/SnowLuma/releases) 或当前 `dev` 分支构建
required: true
- type: input
id: snowluma-version
attributes:
label: SnowLuma 版本
description: 启动日志首行或 `package.json` 里的版本号
placeholder: "例如 1.8.5"
validations:
required: true
- type: dropdown
id: adapter
attributes:
label: 出问题的适配器
description: 可多选
multiple: true
options:
- WebSocket Server
- WebSocket Client
- HTTP Server
- HTTP Post
- WebUI
- Bridge / Core(协议层)
- 其他 / 不确定
validations:
required: true
- type: input
id: os
attributes:
label: 操作系统
placeholder: "例如 Windows 11 23H2 / macOS 14.5 / Ubuntu 22.04"
validations:
required: true
- type: input
id: node-version
attributes:
label: Node.js 版本
description: '`node -v` 的输出。如果使用预构建包可填"预构建包"'
placeholder: "例如 v20.11.0 或 预构建包"
validations:
required: true
- type: input
id: qq-version
attributes:
label: QQ 客户端版本
description: QQ NT 客户端的版本号
placeholder: "例如 9.9.15-29722"
- type: textarea
id: description
attributes:
label: 问题描述
description: 简要说明发生了什么
validations:
required: true
- type: textarea
id: reproduce
attributes:
label: 复现步骤
description: 详细列出如何触发这个问题
placeholder: |
1. 启动 SnowLuma 并登录账号 ...
2. 通过 HTTP Server 调用 `send_group_msg` ...
3. 观察到 ...
validations:
required: true
- type: textarea
id: expected
attributes:
label: 期望行为
validations:
required: true
- type: textarea
id: actual
attributes:
label: 实际行为
validations:
required: true
- type: textarea
id: logs
attributes:
label: 相关日志 / 错误堆栈
description: |
粘贴控制台日志、SSE 实时日志或错误堆栈。
请注意脱敏:移除 access token、账号密码、私聊内容等敏感信息。
render: shell
- type: textarea
id: extra
attributes:
label: 补充信息
description: 配置片段(脱敏后)、截图、相关 Issue / PR 链接等
+11
View File
@@ -0,0 +1,11 @@
blank_issues_enabled: false
contact_links:
- name: QQ 群
url: https://qm.qq.com/q/g3UMLpWALe
about: 日常使用问题、快速交流可以先来 QQ 群
- name: Telegram
url: https://t.me/napcatqq
about: 海外用户交流频道
- name: Releases
url: https://github.com/SnowLuma/SnowLuma/releases
about: 在反馈 Bug 前,请先确认已使用最新发布版本
@@ -0,0 +1,76 @@
name: 功能请求
description: 提议一个新功能或对现有功能的增强
title: "[Feature] "
labels: ["enhancement"]
body:
- type: markdown
attributes:
value: |
感谢您的建议。在提交前,请先在 [Issues](https://github.com/SnowLuma/SnowLuma/issues?q=is%3Aissue) 中搜索是否已有类似提案。
- type: checkboxes
id: preflight
attributes:
label: 提交前检查
options:
- label: 我已搜索过 Issues,确认没有重复的提案
required: true
- type: dropdown
id: scope
attributes:
label: 涉及范围
multiple: true
options:
- OneBot 协议 / 消息段
- WebSocket Server / Client 适配器
- HTTP Server / Post 适配器
- WebUI 管理面板
- SDK (`@snowluma/sdk`)
- UI 组件 (`@snowluma/ui`)
- Bridge / Core(协议层)
- 构建 / 发布流程
- 文档
- 其他
validations:
required: true
- type: textarea
id: problem
attributes:
label: 需求场景 / 当前痛点
description: 这个功能要解决什么问题?目前是如何变通处理的?
validations:
required: true
- type: textarea
id: proposal
attributes:
label: 期望方案
description: 您希望它如何工作?如果是 API 改动,建议给出示例输入 / 输出
validations:
required: true
- type: textarea
id: alternatives
attributes:
label: 已考虑的替代方案
description: 还想过哪些其他实现路径,为什么放弃
- type: textarea
id: references
attributes:
label: 参考链接
description: 例如 OneBot 规范条目、其他实现的对应特性、相关 Issue / PR
placeholder: |
- OneBot v11 规范: https://github.com/botuniverse/onebot-11/...
- 相关讨论: #xxx
- type: checkboxes
id: willingness
attributes:
label: 您是否愿意提交 PR 来实现这个功能?
options:
- label: 愿意,且需要维护者讨论方案后再动手
- label: 愿意,已有大致实现思路
- label: 暂时只提建议
-4
View File
@@ -110,10 +110,6 @@ jobs:
SNOWLUMA_TARGET: ${{ matrix.target }}
run: pnpm run build:all
- name: Bundle runtime dependencies
working-directory: dist
run: npm install --omit=dev
# Naming convention:
# SnowLuma-dev-<arch>.zip|tar.gz – zero-install (node bundled)
# SnowLuma-dev-<arch>-lite.zip|tar.gz – user provides Node >= 22
+1
View File
@@ -11,6 +11,7 @@ dist/
/config/
/data/
logs/
# macOS metadata
.DS_Store
+1
View File
@@ -68,6 +68,7 @@ WebUI 默认监听 `5099` 端口。首次启动会在控制台打印 `initial cr
| [`@snowluma/sdk`](packages/sdk) | OneBot HTTP & WebSocket TypeScript SDK,发布到 npm。 |
| [`@snowluma/ui`](packages/ui) | Tailwind 4 共享组件库(shadcn 风格),发布到 npm。 |
| [`@snowluma/websocket`](packages/websocket) | OneBot WebSocket 适配器底层。 |
| [`@snowluma/proton`](packages/proton) | 编译期 protobuf 编/解码器生成器:TS interface 标注 `pb<N, T>`,Vite 插件在构建时把 `protobuf_encode<T>` / `protobuf_decode<T>` 替换为内联 codec,零运行时反射。 |
| [`@snowluma/runtime`](packages/runtime) | 运行时清单与发布包资源。 |
| [`webui`](packages/webui) | Web 管理面板前端。 |
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "snowluma-monorepo",
"version": "1.8.5",
"version": "1.9.0",
"description": "SnowLuma monorepo workspace (pnpm)",
"private": true,
"type": "module",
+172
View File
@@ -0,0 +1,172 @@
// Proton vs legacy runtime ProtoSchema encoder/decoder benchmark.
//
// Compares the codec functions generated at build time by @snowluma/proton
// against the runtime schema-walking implementation in src/protobuf/decode.ts,
// using the actual long-message schemas already in the codebase.
//
// Methodology:
// - Proton codecs are produced by calling its `analyzeSource` + `generateCode`
// API on the existing proto/proton/longmsg.ts source file, then `new
// Function`-eval'd into a callable. This is identical to what the Vite
// plugin does at build time, minus the file-replacement step.
// - Legacy codecs are the existing `protoEncode` / `protoDecode` functions
// called against the existing `*Schema` constants.
// - Each measurement does 2 000 warmup iterations, then N timed iterations.
// - Operation cost is reported as ops/sec and ns/op. The first row's
// ops/sec is the relative baseline.
//
// Run:
// pnpm --filter @snowluma/core exec tsx bench/proton-vs-legacy.ts
import { readFileSync } from 'fs';
import { resolve, dirname } from 'path';
import { fileURLToPath } from 'url';
import { analyzeSource, generateCode } from '@snowluma/proton/vite';
import { protoEncode, protoDecode } from '../src/protobuf/decode';
import {
LongMsgSettingsSchema,
SendLongMsgRespSchema,
SendLongMsgReqSchema,
RecvLongMsgRespSchema,
} from '../src/bridge/proto/longmsg';
// ── proton codec materialisation ─────────────────────────────────────
const __dirname = dirname(fileURLToPath(import.meta.url));
const protonSchemaPath = resolve(__dirname, '..', 'src', 'bridge', 'proto', 'proton', 'longmsg.ts');
const protonSchemaSource = readFileSync(protonSchemaPath, 'utf-8');
function materialiseProton(messageNames: readonly string[]): Record<string, { encode: (o: unknown) => Uint8Array; decode: (b: Uint8Array) => unknown }> {
// Append synthetic call sites so the registry actually contains the messages
// we want — `selectUsedRegistry` only retains call-site roots, and the
// proton/longmsg.ts source itself has no `protobuf_encode` calls.
const callSites = messageNames
.map((n) => `protobuf_encode<${n}>({} as any); protobuf_decode<${n}>(new Uint8Array());`)
.join('\n');
const sourceWithCallSites = protonSchemaSource + `\n\n// synthetic call sites for bench codegen\n` + callSites;
const registry = analyzeSource(sourceWithCallSites, protonSchemaPath);
const code = generateCode(registry);
const factoryBody = `
${code}
const out = {};
${messageNames.map(n => `out.${n} = { encode: protobuf_encode_${n}, decode: protobuf_decode_${n} };`).join('\n')}
return out;
`;
return new Function(factoryBody)() as Record<string, { encode: (o: unknown) => Uint8Array; decode: (b: Uint8Array) => unknown }>;
}
const proton = materialiseProton([
'LongMsgSettings',
'SendLongMsgResp',
'SendLongMsgReq',
'RecvLongMsgResp',
]);
// ── bench harness ────────────────────────────────────────────────────
interface BenchResult { name: string; opsPerSec: number; nsPerOp: number; }
function bench(name: string, fn: () => void, iterations: number): BenchResult {
for (let i = 0; i < 2000; i++) fn();
const start = performance.now();
for (let i = 0; i < iterations; i++) fn();
const ms = performance.now() - start;
return {
name,
opsPerSec: Math.round((iterations / ms) * 1000),
nsPerOp: Math.round((ms / iterations) * 1_000_000),
};
}
function printSection(title: string, results: BenchResult[]) {
console.log(`\n## ${title}`);
console.log('| Encoder | ops/sec | ns/op | relative |');
console.log('|------------|-------------|--------|----------|');
const baseline = results[0].opsPerSec;
for (const r of results) {
const rel = r.opsPerSec / baseline;
const relStr = r === results[0] ? '1.00×' : `${rel.toFixed(2)}×`;
console.log(
`| ${r.name.padEnd(10)} | ${r.opsPerSec.toLocaleString().padStart(11)} | ${String(r.nsPerOp).padStart(6)} | ${relStr.padStart(8)} |`,
);
}
}
// ── workloads ────────────────────────────────────────────────────────
const settingsObj = { field1: 4, field2: 1, field3: 7, field4: 2 };
const sendRespObj = { result: { resId: 'res-001' } };
const sendReqObj = {
info: {
type: 1,
uid: { uid: 'u_test' },
groupUin: 123456,
payload: new Uint8Array([0xde, 0xad, 0xbe, 0xef]),
},
settings: { field1: 4, field2: 1, field3: 7, field4: 2 },
};
const recvRespObj = {
result: { resId: 'r-1', payload: new Uint8Array(64).fill(0x42) },
settings: { field1: 4, field2: 1, field3: 7, field4: 2 },
};
// Pre-encoded bytes for decode benches (use proton output so both sides see
// identical, proto3-conforming input).
const settingsBytes = proton.LongMsgSettings.encode(settingsObj);
const sendRespBytes = proton.SendLongMsgResp.encode(sendRespObj);
const sendReqBytes = proton.SendLongMsgReq.encode(sendReqObj);
const recvRespBytes = proton.RecvLongMsgResp.encode(recvRespObj);
// ── run ──────────────────────────────────────────────────────────────
console.log('# @snowluma/proton vs legacy runtime benchmark\n');
console.log(`Node ${process.version} | ${process.platform} ${process.arch}`);
console.log(`Date: ${new Date().toISOString().slice(0, 19).replace('T', ' ')}`);
const N = 300_000;
printSection('Encode — LongMsgSettings (4× uint32)', [
{ ...bench('proton', () => proton.LongMsgSettings.encode(settingsObj), N) },
{ ...bench('legacy', () => protoEncode(settingsObj, LongMsgSettingsSchema), N) },
]);
printSection('Decode — LongMsgSettings (4× uint32)', [
{ ...bench('proton', () => proton.LongMsgSettings.decode(settingsBytes), N) },
{ ...bench('legacy', () => protoDecode(settingsBytes, LongMsgSettingsSchema), N) },
]);
printSection('Encode — SendLongMsgResp (1 nested message, 1 string)', [
{ ...bench('proton', () => proton.SendLongMsgResp.encode(sendRespObj), N) },
{ ...bench('legacy', () => protoEncode(sendRespObj, SendLongMsgRespSchema), N) },
]);
printSection('Decode — SendLongMsgResp', [
{ ...bench('proton', () => proton.SendLongMsgResp.decode(sendRespBytes), N) },
{ ...bench('legacy', () => protoDecode(sendRespBytes, SendLongMsgRespSchema), N) },
]);
printSection('Encode — SendLongMsgReq (deeply nested, bytes + uint32 + string)', [
{ ...bench('proton', () => proton.SendLongMsgReq.encode(sendReqObj), N) },
{ ...bench('legacy', () => protoEncode(sendReqObj, SendLongMsgReqSchema), N) },
]);
printSection('Decode — SendLongMsgReq', [
{ ...bench('proton', () => proton.SendLongMsgReq.decode(sendReqBytes), N) },
{ ...bench('legacy', () => protoDecode(sendReqBytes, SendLongMsgReqSchema), N) },
]);
printSection('Encode — RecvLongMsgResp (64-byte payload + settings)', [
{ ...bench('proton', () => proton.RecvLongMsgResp.encode(recvRespObj), N) },
{ ...bench('legacy', () => protoEncode(recvRespObj, RecvLongMsgRespSchema), N) },
]);
printSection('Decode — RecvLongMsgResp', [
{ ...bench('proton', () => proton.RecvLongMsgResp.decode(recvRespBytes), N) },
{ ...bench('legacy', () => protoDecode(recvRespBytes, RecvLongMsgRespSchema), N) },
]);
console.log('');
+2 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@snowluma/core",
"version": "1.8.5",
"version": "1.9.0",
"description": "SnowLuma core - NTQQ packet sniffer with Node.js native addon",
"private": true,
"type": "module",
@@ -14,6 +14,7 @@
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@snowluma/proton": "workspace:*",
"@snowluma/websocket": "workspace:*"
},
"devDependencies": {
+36 -57
View File
@@ -4,42 +4,33 @@
// the NTQQ NodeIKernel — every wire trip is one runOidb round-trip.
import type { Bridge } from '../bridge';
import { runOidb } from '../bridge-oidb';
import {
OidbGroupTodoSchema,
OidbStrangerStatusReqSchema,
OidbStrangerStatusRespSchema,
OidbAiVoiceListReqSchema,
OidbAiVoiceListRespSchema,
OidbAiVoiceReqSchema,
OidbAiVoiceRespSchema,
} from '../proto/oidb-action';
import { runOidb, makeOidbEnvelope, encodeOidbEnv, decodeOidbEnv } from '../bridge-oidb';
import type {
OidbAiVoiceListReq,
OidbAiVoiceListResp,
OidbAiVoiceReq,
OidbAiVoiceResp,
OidbGroupTodo,
OidbStrangerStatusReq,
OidbStrangerStatusResp,
} from '../proto/proton/oidb-action';
import type { MediaIndexNode } from './shared';
// ─────────────── Group todo (0xF90) ───────────────
export async function setGroupTodo(bridge: Bridge, groupId: number, msgSeq: bigint): Promise<void> {
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0xf90_1',
oidbCmd: 0xF90, subCmd: 1,
request: { schema: OidbGroupTodoSchema, value: { groupUin: groupId, msgSeq } },
});
const env = makeOidbEnvelope<OidbGroupTodo>(0xF90, 1, { groupUin: groupId, msgSeq });
await runOidb(bridge, 'OidbSvcTrpcTcp.0xf90_1', encodeOidbEnv<OidbGroupTodo>(env));
}
export async function completeGroupTodo(bridge: Bridge, groupId: number, msgSeq: bigint): Promise<void> {
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0xf90_2',
oidbCmd: 0xF90, subCmd: 2,
request: { schema: OidbGroupTodoSchema, value: { groupUin: groupId, msgSeq } },
});
const env = makeOidbEnvelope<OidbGroupTodo>(0xF90, 2, { groupUin: groupId, msgSeq });
await runOidb(bridge, 'OidbSvcTrpcTcp.0xf90_2', encodeOidbEnv<OidbGroupTodo>(env));
}
export async function cancelGroupTodo(bridge: Bridge, groupId: number, msgSeq: bigint): Promise<void> {
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0xf90_3',
oidbCmd: 0xF90, subCmd: 3,
request: { schema: OidbGroupTodoSchema, value: { groupUin: groupId, msgSeq } },
});
const env = makeOidbEnvelope<OidbGroupTodo>(0xF90, 3, { groupUin: groupId, msgSeq });
await runOidb(bridge, 'OidbSvcTrpcTcp.0xf90_3', encodeOidbEnv<OidbGroupTodo>(env));
}
// ─────────────── Stranger online/ext status (0xFE1_2) ───────────────
@@ -60,18 +51,15 @@ export interface StrangerStatus {
*/
export async function getStrangerStatus(bridge: Bridge, uin: number): Promise<StrangerStatus | null> {
try {
const resp = await runOidb<{ data?: { status?: { value?: bigint | number } } }>(bridge, {
cmd: 'OidbSvcTrpcTcp.0xfe1_2',
oidbCmd: 0xFE1, subCmd: 2,
request: {
schema: OidbStrangerStatusReqSchema,
value: { uin, key: [{ key: 27372 }] },
// Same UIN-form flag fetchUserProfile sets — without it newer
// QQ NT rejects with `[oidb] one of uid/openid is invaild`.
isUid: true,
},
response: { schema: OidbStrangerStatusRespSchema },
});
const env = makeOidbEnvelope<OidbStrangerStatusReq>(
0xFE1, 2,
{ uin, key: [{ key: 27372 }] } as any,
// Same UIN-form flag fetchUserProfile sets — without it newer
// QQ NT rejects with `[oidb] one of uid/openid is invaild`.
true,
);
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xfe1_2', encodeOidbEnv<OidbStrangerStatusReq>(env));
const resp = decodeOidbEnv<OidbStrangerStatusResp>(respBytes).body;
const raw = resp?.data?.status?.value;
if (raw === undefined || raw === null) return null;
const extBig = typeof raw === 'bigint' ? raw : BigInt(raw);
@@ -110,13 +98,10 @@ export async function fetchAiVoiceList(
groupId: number,
chatType: AiVoiceChatType,
): Promise<AiVoiceCategory[]> {
const resp = await runOidb<{ content?: AiVoiceCategory[] }>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x929d_0',
oidbCmd: 0x929D, subCmd: 0,
request: { schema: OidbAiVoiceListReqSchema, value: { groupUin: groupId, chatType } },
response: { schema: OidbAiVoiceListRespSchema },
});
return resp?.content ?? [];
const env = makeOidbEnvelope<OidbAiVoiceListReq>(0x929D, 0, { groupUin: groupId, chatType });
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x929d_0', encodeOidbEnv<OidbAiVoiceListReq>(env));
const resp = decodeOidbEnv<OidbAiVoiceListResp>(respBytes).body;
return (resp?.content as AiVoiceCategory[] | undefined) ?? [];
}
/**
@@ -139,19 +124,13 @@ export async function fetchAiVoice(
// Random 32-bit session id — server uses this to deduplicate polls.
const sessionId = Math.floor(Math.random() * 0xFFFFFFFF) >>> 0;
for (let i = 0; i < maxRetries; i++) {
const resp = await runOidb<{
statusCode?: number;
msgInfo?: { msgInfoBody?: Array<{ index?: MediaIndexNode }> };
}>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x929b_0',
oidbCmd: 0x929B, subCmd: 0,
request: {
schema: OidbAiVoiceReqSchema,
value: { groupUin: groupId, voiceId, text, chatType, session: { sessionId } },
},
response: { schema: OidbAiVoiceRespSchema },
});
const node = resp?.msgInfo?.msgInfoBody?.[0]?.index;
const env = makeOidbEnvelope<OidbAiVoiceReq>(
0x929B, 0,
{ groupUin: groupId, voiceId, text, chatType, session: { sessionId } },
);
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x929b_0', encodeOidbEnv<OidbAiVoiceReq>(env));
const resp = decodeOidbEnv<OidbAiVoiceResp>(respBytes).body;
const node = resp?.msgInfo?.msgInfoBody?.[0]?.index as MediaIndexNode | undefined;
if (node) return node;
}
throw new Error(`AI voice synthesis did not complete after ${maxRetries} polls`);
+250 -38
View File
@@ -5,19 +5,20 @@
import type { Bridge } from '../bridge';
import { gunzipSync, gzipSync } from 'zlib';
import { protoDecode, protoEncode } from '../../protobuf/decode';
import { randomUUID } from 'crypto';
import { protobuf_encode, protobuf_decode } from '@snowluma/proton';
import { buildSendElems } from '../element-builder';
import { parseMsgPush } from '../msg-push';
import type { ForwardNodePayload } from '../events';
import type { ForwardNodePayload, MessageElement } from '../events';
import type { PacketInfo } from '../../protocol/types';
import {
LongMsgResultSchema,
RecvLongMsgReqSchema,
RecvLongMsgRespSchema,
SendLongMsgReqSchema,
SendLongMsgRespSchema,
} from '../proto/longmsg';
import { PushMsgSchema } from '../proto/message';
import type {
LongMsgResult,
RecvLongMsgReq,
RecvLongMsgResp,
SendLongMsgReq,
SendLongMsgResp,
} from '../proto/proton/longmsg';
import type { FileExtra, PushMsg, PushMsgBody } from '../proto/proton/message';
import { resolveSelfUid, toInt } from './shared';
// Module-scoped cache, keyed by res_id. Survives only for the lifetime
@@ -30,7 +31,7 @@ async function buildForwardPushBody(
node: ForwardNodePayload,
groupId?: number,
userUid?: string,
): Promise<Record<string, unknown>> {
): Promise<PushMsgBody> {
const fromUin = node.userUin > 0 ? node.userUin : toInt(bridge.identity.uin);
if (fromUin <= 0) throw new Error('forward node user uin is invalid');
@@ -39,16 +40,67 @@ async function buildForwardPushBody(
// forward's recipient: group → groupId, private → recipient uid.
// Without this the OIDB upload (0x11c4/0x11c5) has no scene and the
// element builder throws "private image target uid is missing".
//
// `forwardFake: true` keeps `{type:'file'}` segments in the
// long-msg payload: group → emitted as transElem(24) in elems[],
// c2c → handled below via msgContent (FileExtra { file: NotOnlineFile }).
// The QQ-NT live-send pipeline would reject these (transElem(24) →
// result=79; notOnlineFile via PbSendMsg doesn't render), but the
// long-msg upload service stores the bytes verbatim and the
// receiver decodes them through the normal msg-push path.
const sendCtx = groupId !== undefined
? { bridge, groupId }
? { bridge, groupId, forwardFake: true }
: userUid
? { bridge, userUid }
: { bridge };
? { bridge, userUid, forwardFake: true }
: { bridge, forwardFake: true };
const elems = await buildSendElems(node.elements, sendCtx);
const now = Math.floor(Date.now() / 1000);
const random = Math.floor(Math.random() * 0x7fffffff) >>> 0;
const seq = Math.floor(Math.random() * 9000000) + 1000000;
// c2c-file in a forward node — element-builder intentionally skips
// it (RichText.notOnlineFile + msgContent live outside elems[]). For
// forward fake-send we mirror what an inbound c2c file message looks
// like on the wire: serialise the FileExtra blob and ride it on
// `body.msgContent`. The receiver's rich-body-decoder reads from
// `msgContent` first (see msg-push/rich-body-decoder.ts:446+), so
// the bubble renders with the right file name + size when the
// forward is expanded. Only the FIRST c2c file in a node ships —
// QQ NT's bubble can only carry one msgContent payload, same as
// a live c2c send. Group nodes ignore this branch entirely (the
// transElem(24) elems[] entry above covers them).
let msgContent: Uint8Array | undefined;
if (groupId === undefined) {
const fileEl = node.elements.find(e => e.type === 'file' && e.fileId);
if (fileEl) {
// Honour inline segment fields first; fall back to the upload
// metadata cache (populated by upload_private_file). Without
// size/md5 the receiver would render "0 B" so prefer recovering
// them — see same logic in modules/message-actions.ts.
const cached = bridge.recallUploadedFile(fileEl.fileId ?? '');
const fileMd5 = fileEl.md5Hex
? hexToBytesLocal(fileEl.md5Hex)
: (cached?.fileMd5 ?? new Uint8Array(0));
const fileSize = fileEl.fileSize ?? cached?.fileSize ?? 0;
const fileName = fileEl.fileName ?? cached?.fileName ?? 'file';
const fileHash = fileEl.fileHash ?? cached?.fileHash ?? '';
const sevenDays = 7 * 24 * 60 * 60;
msgContent = protobuf_encode<FileExtra>({
file: {
fileType: 0,
fileUuid: fileEl.fileId!,
fileMd5,
fileName,
fileSize: BigInt(fileSize),
subcmd: 1,
dangerEvel: 0,
expireTime: now + sevenDays,
fileHash,
},
});
}
}
return {
responseHead: {
fromUin,
@@ -69,16 +121,78 @@ async function buildForwardPushBody(
richText: {
elems,
},
...(msgContent ? { msgContent } : {}),
},
};
}
// Local hex-decode helper — avoids importing the heavyweight `pipeline`
// module just for one call. Mirrors `highway/pipeline.ts::hexToBytes`.
function hexToBytesLocal(hex: string): Uint8Array {
const s = hex.trim();
if (!s) return new Uint8Array(0);
const len = s.length >> 1;
const out = new Uint8Array(len);
for (let i = 0; i < len; i++) {
out[i] = parseInt(s.substr(i * 2, 2), 16);
}
return out;
}
// Per-layer piggyback entry. Each level of a nested forward attaches
// its own msgBody under a uuid `actionCommand`, so when the receiver
// fetches the outermost res_id it gets every layer in one shot
// (modelled on NapCat's `uploadForwardedNodesPacket` — see
// `dev/NapCatQQ/.../SendMsg.ts:208-347`). Lagrange.Core master + V2
// both ship a single-action model and silently break when the
// recipient is a NapCat instance trying to walk the tree.
interface ForwardInnerAction {
uuid: string;
msgBody: PushMsgBody[];
}
interface ForwardUploadResult {
resId: string;
// The current level's msgBody + uuid — what an outer caller would
// piggyback to expose this layer through the tree.
msgBody: PushMsgBody[];
uuid: string;
// All accumulated piggyback entries from deeper levels. Outer
// callers concatenate these to their own actions list so the
// outermost upload carries the full tree.
innerActions: ForwardInnerAction[];
}
export async function uploadForwardNodes(
bridge: Bridge,
nodes: ForwardNodePayload[],
groupId?: number,
userId?: number,
): Promise<string> {
const { resId } = await uploadForwardNodesRecursive(bridge, nodes, groupId, userId);
return resId;
}
/**
* Recursive upload with NapCat-style piggyback. Each invocation:
* 1. Walks `nodes`. For any node whose `innerForward` is set,
* recursively uploads that inner chain first (which itself runs
* this same recursion).
* 2. Replaces the node's `elements` with an ARK preview pointing at
* the inner res_id (and inner uuid for receiver-side walking).
* 3. Accumulates the inner level's `{uuid, msgBody}` plus all of
* ITS accumulated `innerActions` into this level's piggyback list.
* 4. Encodes this level's long-msg payload as
* `[MultiMsg + thisMsgBody, ...innerActions]`, uploads it,
* returns `{resId, msgBody, uuid, innerActions}` so an outer
* caller can keep piggybacking up the tree.
*/
async function uploadForwardNodesRecursive(
bridge: Bridge,
nodes: ForwardNodePayload[],
groupId?: number,
userId?: number,
): Promise<ForwardUploadResult> {
if (!Array.isArray(nodes) || nodes.length === 0) {
throw new Error('forward nodes are required');
}
@@ -86,37 +200,89 @@ export async function uploadForwardNodes(
// For a private forward to `userId`, any image/record/video inside a node
// needs the recipient's uid as upload scene. Resolve it once up-front,
// and only when at least one node actually contains media (saves an RPC
// for text-only forwards).
// for text-only forwards). Also need it when a node is itself a nested
// forward — the inner upload uses the same scene.
let userUid: string | undefined;
if (groupId === undefined && userId !== undefined && userId > 0) {
const hasMedia = nodes.some(node => node.elements.some(
e => e.type === 'image' || e.type === 'record' || e.type === 'video',
));
if (hasMedia) {
const needsUid = nodes.some(node => !!node.innerForward
|| node.elements.some(e => e.type === 'image' || e.type === 'record' || e.type === 'video'));
if (needsUid) {
const resolved = await bridge.resolveUserUid(userId);
if (resolved) userUid = resolved;
}
}
const msgBody = await Promise.all(nodes.map(node => buildForwardPushBody(bridge, node, groupId, userUid)));
const longMsgResult = protoEncode({
// Walk nodes and resolve nested forwards first (so we know their
// res_id / uuid before encoding the outer ARK previews). Build
// `processedNodes` with elements rewritten for nested layers,
// and collect every inner level's piggyback in `myInnerActions`.
const myInnerActions: ForwardInnerAction[] = [];
const processedNodes: ForwardNodePayload[] = [];
const isGroup = groupId !== undefined;
for (const node of nodes) {
if (node.innerForward && node.innerForward.length > 0) {
const inner = await uploadForwardNodesRecursive(bridge, node.innerForward, groupId, userId);
// NapCat piggybacks `{uuid: inner.uuid, packetMsg: inner.packetMsg}`
// + the entire `inner.innerPacketMsg` array up to its caller. We
// mirror that — `inner.uuid` indexes the inner level itself,
// and `inner.innerActions` already contains deeper layers.
myInnerActions.push({ uuid: inner.uuid, msgBody: inner.msgBody });
myInnerActions.push(...inner.innerActions);
// Replace the inner placeholder element with a forward preview
// pointing at the inner res_id. The wire-side element builder
// turns this into the same XML m_resid blob it already produced
// for top-level forwards — see `makeForwardElem` in
// element-builder.ts:153.
const previewElement: MessageElement = {
type: 'forward',
resId: inner.resId,
forwardSource: deriveInnerSource(node.innerForward, isGroup),
forwardSummary: `查看${node.innerForward.length}条转发消息`,
forwardPrompt: '[聊天记录]',
forwardNews: previewLinesFromNodes(node.innerForward),
forwardTSum: node.innerForward.length,
};
processedNodes.push({
userUin: node.userUin,
nickname: node.nickname,
elements: [previewElement],
time: node.time,
msgId: node.msgId,
msgSeq: node.msgSeq,
groupId: node.groupId,
senderCard: node.senderCard,
messageType: node.messageType,
});
} else {
processedNodes.push(node);
}
}
// Encode this level's msgBody.
const msgBody = await Promise.all(processedNodes.map(
node => buildForwardPushBody(bridge, node, groupId, userUid),
));
// Compose the action list: own MultiMsg + piggybacked inner actions.
const longMsgResult = protobuf_encode<LongMsgResult>({
action: [
{
actionCommand: 'MultiMsg',
actionData: { msgBody: msgBody as any },
},
{ actionCommand: 'MultiMsg', actionData: { msgBody } },
...myInnerActions.map(a => ({
actionCommand: a.uuid,
actionData: { msgBody: a.msgBody },
})),
],
}, LongMsgResultSchema);
});
const selfUid = await resolveSelfUid(bridge);
const info: any = {
const info: SendLongMsgReq['info'] = {
type: groupId ? 3 : 1,
uid: { uid: groupId ? String(groupId) : selfUid },
payload: gzipSync(Buffer.from(longMsgResult)),
};
if (groupId) info.groupUin = groupId;
const request = protoEncode({
const request = protobuf_encode<SendLongMsgReq>({
info,
settings: {
field1: 4,
@@ -124,20 +290,20 @@ export async function uploadForwardNodes(
field3: 7,
field4: 0,
},
}, SendLongMsgReqSchema);
});
const result = await bridge.sendRawPacket('trpc.group.long_msg_interface.MsgService.SsoSendLongMsg', request);
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(result.errorMessage || 'upload forward message failed');
}
const resp = protoDecode(result.responseData, SendLongMsgRespSchema);
const resp = protobuf_decode<SendLongMsgResp>(result.responseData);
const resId = typeof resp?.result?.resId === 'string' ? resp.result.resId : '';
if (!resId) {
throw new Error('upload forward message response missing res_id');
}
forwardResCache.set(resId, nodes.map(node => ({
forwardResCache.set(resId, processedNodes.map(node => ({
userUin: node.userUin,
nickname: node.nickname,
elements: [...node.elements],
@@ -149,7 +315,53 @@ export async function uploadForwardNodes(
messageType: node.messageType ?? (groupId ? 'group' : 'private'),
})));
return resId;
return {
resId,
msgBody,
uuid: randomUUID(),
innerActions: myInnerActions,
};
}
// Inner forward preview metadata — kept minimal here (the OneBot
// `parseForwardNodes` caller can override these on the top-level
// node by passing custom forwardSource/forwardSummary on the
// non-nested send path; nested levels just get sensible defaults
// since they're synthesised by us and never reach OneBot input).
function deriveInnerSource(innerNodes: ForwardNodePayload[], isGroup: boolean): string {
const nicks: string[] = [];
const seen = new Set<string>();
for (const node of innerNodes) {
const name = (node.nickname ?? '').trim();
if (name && !seen.has(name)) {
seen.add(name);
nicks.push(name);
}
if (nicks.length >= 4) break;
}
if (nicks.length === 0) return isGroup ? '群聊的聊天记录' : '聊天记录';
return `${nicks.join('和')}的聊天记录`;
}
function previewLinesFromNodes(innerNodes: ForwardNodePayload[]): Array<{ text: string }> {
return innerNodes.slice(0, 4).map(node => {
const name = (node.nickname ?? '').trim() || String(node.userUin || 'QQ用户');
const previewText = previewFromElements(node.elements);
return { text: previewText ? `${name}: ${previewText}` : name };
});
}
function previewFromElements(elements: MessageElement[]): string {
for (const elem of elements) {
if (elem.type === 'text' && elem.text) return elem.text.slice(0, 30);
if (elem.type === 'image') return '[图片]';
if (elem.type === 'record') return '[语音]';
if (elem.type === 'video') return '[视频]';
if (elem.type === 'file') return '[文件]';
if (elem.type === 'forward') return '[聊天记录]';
if (elem.type === 'face') return '[表情]';
}
return '';
}
export async function fetchForwardNodes(bridge: Bridge, resId: string): Promise<ForwardNodePayload[]> {
@@ -169,7 +381,7 @@ export async function fetchForwardNodes(bridge: Bridge, resId: string): Promise<
}
const selfUid = await resolveSelfUid(bridge);
const request = protoEncode({
const request = protobuf_encode<RecvLongMsgReq>({
info: {
uid: { uid: selfUid },
resId,
@@ -181,27 +393,27 @@ export async function fetchForwardNodes(bridge: Bridge, resId: string): Promise<
field3: 0,
field4: 0,
},
}, RecvLongMsgReqSchema);
});
const result = await bridge.sendRawPacket('trpc.group.long_msg_interface.MsgService.SsoRecvLongMsg', request);
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(result.errorMessage || 'download forward message failed');
}
const resp = protoDecode(result.responseData, RecvLongMsgRespSchema);
const resp = protobuf_decode<RecvLongMsgResp>(result.responseData);
const payload = resp?.result?.payload;
if (!(payload instanceof Uint8Array) || payload.length === 0) {
throw new Error('download forward message payload is empty');
}
const inflate = gunzipSync(Buffer.from(payload));
const longMsg = protoDecode(inflate, LongMsgResultSchema);
const action = longMsg?.action?.find((item: any) => item?.actionCommand === 'MultiMsg');
const longMsg = protobuf_decode<LongMsgResult>(inflate);
const action = longMsg?.action?.find((item) => item?.actionCommand === 'MultiMsg');
const msgBodyList = Array.isArray(action?.actionData?.msgBody) ? action.actionData.msgBody : [];
const nodes: ForwardNodePayload[] = [];
for (const msgBody of msgBodyList) {
const wrapped = protoEncode({ message: msgBody }, PushMsgSchema);
const wrapped = protobuf_encode<PushMsg>({ message: msgBody });
const pkt: PacketInfo = {
pid: 0,
uin: bridge.identity.uin,
+23 -35
View File
@@ -3,50 +3,41 @@
// protocol uses opaque UIDs rather than QQ uin numbers.
import type { Bridge } from '../bridge';
import { runOidb } from '../bridge-oidb';
import {
OidbDeleteFriendSchema,
OidbFriendRequestActionSchema,
OidbSetFriendRemarkSchema,
} from '../proto/oidb-action';
import { runOidb, makeOidbEnvelope, encodeOidbEnv } from '../bridge-oidb';
import type {
OidbDeleteFriend,
OidbFriendRequestAction,
OidbSetFriendRemark,
} from '../proto/proton/oidb-action';
export async function setFriendAddRequest(bridge: Bridge, uidOrFlag: string, approve: boolean): Promise<void> {
let targetUid = uidOrFlag;
if (/^\d+$/.test(uidOrFlag)) {
targetUid = await bridge.resolveUserUid(parseInt(uidOrFlag, 10));
}
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0xb5d_44',
oidbCmd: 0xB5D, subCmd: 44,
request: { schema: OidbFriendRequestActionSchema, value: { accept: approve ? 3 : 5, targetUid } },
});
const env = makeOidbEnvelope<OidbFriendRequestAction>(0xB5D, 44, { accept: approve ? 3 : 5, targetUid });
await runOidb(bridge, 'OidbSvcTrpcTcp.0xb5d_44', encodeOidbEnv<OidbFriendRequestAction>(env));
}
export async function deleteFriend(bridge: Bridge, userId: number, block = false): Promise<void> {
const targetUid = await bridge.resolveUserUid(userId);
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0x126b_0',
oidbCmd: 0x126B, subCmd: 0,
request: {
schema: OidbDeleteFriendSchema,
value: {
field1: {
targetUid,
field2: {
field1: 130,
field2: 109,
field3: {
field1: 8,
field2: 8,
field3: 50,
},
},
block,
field4: false,
const env = makeOidbEnvelope<OidbDeleteFriend>(0x126B, 0, {
field1: {
targetUid,
field2: {
field1: 130,
field2: 109,
field3: {
field1: 8,
field2: 8,
field3: 50,
},
},
block,
field4: false,
},
});
await runOidb(bridge, 'OidbSvcTrpcTcp.0x126b_0', encodeOidbEnv<OidbDeleteFriend>(env));
// Refresh friend cache after deletion so subsequent reads don't
// surface a ghost entry. Best-effort: a transient OIDB hiccup here
@@ -56,9 +47,6 @@ export async function deleteFriend(bridge: Bridge, userId: number, block = false
export async function setFriendRemark(bridge: Bridge, userId: number, remark: string): Promise<void> {
const uid = await bridge.resolveUserUid(userId);
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0xb6e_2',
oidbCmd: 0xB6E, subCmd: 2,
request: { schema: OidbSetFriendRemarkSchema, value: { targetUid: uid, remark } },
});
const env = makeOidbEnvelope<OidbSetFriendRemark>(0xB6E, 2, { targetUid: uid, remark });
await runOidb(bridge, 'OidbSvcTrpcTcp.0xb6e_2', encodeOidbEnv<OidbSetFriendRemark>(env));
}
+59 -110
View File
@@ -4,72 +4,56 @@
// so callers can grep across the two layers.
import type { Bridge } from '../bridge';
import { runOidb } from '../bridge-oidb';
import {
Oidb0x89a_0AddOptionSchema,
Oidb0x89a_0SearchSchema,
Oidb0x8a0ReqSchema,
Oidb0x8a7ReqSchema,
Oidb0x8a7RespSchema,
OidbGroupRequestActionSchema,
OidbKickMemberSchema,
OidbLeaveGroupSchema,
OidbMuteAllSchema,
OidbMuteMemberSchema,
OidbRenameGroupSchema,
OidbRenameMemberSchema,
OidbSetAdminSchema,
OidbSpecialTitleSchema,
Oidb0xf16ReqSchema,
} from '../proto/oidb-action';
import { runOidb, makeOidbEnvelope, encodeOidbEnv, decodeOidbEnv } from '../bridge-oidb';
import type {
Oidb0x89a_0AddOption,
Oidb0x89a_0Search,
Oidb0x8a0Req,
Oidb0x8a7Req,
Oidb0x8a7Resp,
Oidb0xf16Req,
OidbGroupRequestAction,
OidbKickMember,
OidbLeaveGroup,
OidbMuteAll,
OidbMuteMember,
OidbRenameGroup,
OidbRenameMember,
OidbSetAdmin,
OidbSpecialTitle,
} from '../proto/proton/oidb-action';
// ─────────────── mute / un-mute ───────────────
export async function muteGroupMember(bridge: Bridge, groupId: number, userId: number, duration: number): Promise<void> {
const uid = await bridge.resolveUserUid(userId, groupId);
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0x1253_1',
oidbCmd: 0x1253, subCmd: 1,
request: {
schema: OidbMuteMemberSchema,
value: { groupUin: groupId, type: 1, body: { targetUid: uid, duration } },
},
const env = makeOidbEnvelope<OidbMuteMember>(0x1253, 1, {
groupUin: groupId, type: 1, body: { targetUid: uid, duration },
});
await runOidb(bridge, 'OidbSvcTrpcTcp.0x1253_1', encodeOidbEnv<OidbMuteMember>(env));
}
export async function muteGroupAll(bridge: Bridge, groupId: number, enable: boolean): Promise<void> {
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0x89a_0',
oidbCmd: 0x89A, subCmd: 0,
request: {
schema: OidbMuteAllSchema,
value: { groupUin: groupId, muteState: { state: enable ? 0xFFFFFFFF : 0 } },
},
const env = makeOidbEnvelope<OidbMuteAll>(0x89A, 0, {
groupUin: groupId, muteState: { state: enable ? 0xFFFFFFFF : 0 },
});
await runOidb(bridge, 'OidbSvcTrpcTcp.0x89a_0', encodeOidbEnv<OidbMuteAll>(env));
}
// ─────────────── join-policy ───────────────
export async function setGroupAddOption(bridge: Bridge, groupId: number, addType: number): Promise<void> {
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0x89a_0',
oidbCmd: 0x89A, subCmd: 0,
request: {
schema: Oidb0x89a_0AddOptionSchema,
value: { groupUin: BigInt(groupId), settings: { addType }, field12: 0 },
},
const env = makeOidbEnvelope<Oidb0x89a_0AddOption>(0x89A, 0, {
groupUin: BigInt(groupId), settings: { addType }, field12: 0,
});
await runOidb(bridge, 'OidbSvcTrpcTcp.0x89a_0', encodeOidbEnv<Oidb0x89a_0AddOption>(env));
}
export async function setGroupSearch(bridge: Bridge, groupId: number): Promise<void> {
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0x89a_0',
oidbCmd: 0x89A, subCmd: 0,
request: {
schema: Oidb0x89a_0SearchSchema,
value: { groupUin: BigInt(groupId), settings: new Uint8Array(0), field12: 0 },
},
const env = makeOidbEnvelope<Oidb0x89a_0Search>(0x89A, 0, {
groupUin: BigInt(groupId), settings: new Uint8Array(0), field12: 0,
});
await runOidb(bridge, 'OidbSvcTrpcTcp.0x89a_0', encodeOidbEnv<Oidb0x89a_0Search>(env));
}
export async function setGroupAddRequest(
@@ -78,92 +62,64 @@ export async function setGroupAddRequest(
): Promise<void> {
const subCmd = filtered ? 2 : 1;
const cmd = filtered ? 'OidbSvcTrpcTcp.0x10c8_2' : 'OidbSvcTrpcTcp.0x10c8_1';
await runOidb(bridge, {
cmd,
oidbCmd: 0x10C8, subCmd,
request: {
schema: OidbGroupRequestActionSchema,
value: { accept: approve ? 1 : 2, body: { sequence: BigInt(sequence), eventType, groupUin: groupId, message: reason } },
isUid: true,
},
});
const env = makeOidbEnvelope<OidbGroupRequestAction>(
0x10C8, subCmd,
{ accept: approve ? 1 : 2, body: { sequence: BigInt(sequence), eventType, groupUin: groupId, message: reason } },
true,
);
await runOidb(bridge, cmd, encodeOidbEnv<OidbGroupRequestAction>(env));
}
// ─────────────── kick / leave ───────────────
export async function kickGroupMember(bridge: Bridge, groupId: number, userId: number, reject: boolean, reason = ''): Promise<void> {
const uid = await bridge.resolveUserUid(userId, groupId);
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0x8a0_1',
oidbCmd: 0x8A0, subCmd: 1,
request: {
schema: OidbKickMemberSchema,
value: { groupUin: groupId, targetUid: uid, rejectAddRequest: reject, reason },
},
const env = makeOidbEnvelope<OidbKickMember>(0x8A0, 1, {
groupUin: groupId, targetUid: uid, rejectAddRequest: reject, reason,
});
await runOidb(bridge, 'OidbSvcTrpcTcp.0x8a0_1', encodeOidbEnv<OidbKickMember>(env));
}
export async function kickGroupMembers(bridge: Bridge, groupId: number, userIds: number[], reject: boolean): Promise<void> {
const targetUids = await Promise.all(userIds.map(userId => bridge.resolveUserUid(userId, groupId)));
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0x8a0_1',
oidbCmd: 0x8A0, subCmd: 1,
request: {
schema: Oidb0x8a0ReqSchema,
value: { groupId: BigInt(groupId), targetUids, rejectAddRequest: reject ? 1 : 0, kickReason: new Uint8Array(0), field12: 0 },
},
const env = makeOidbEnvelope<Oidb0x8a0Req>(0x8A0, 1, {
groupId: BigInt(groupId), targetUids, rejectAddRequest: reject ? 1 : 0, kickReason: new Uint8Array(0), field12: 0,
});
await runOidb(bridge, 'OidbSvcTrpcTcp.0x8a0_1', encodeOidbEnv<Oidb0x8a0Req>(env));
}
export async function leaveGroup(bridge: Bridge, groupId: number): Promise<void> {
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0x1097_1',
oidbCmd: 0x1097, subCmd: 1,
request: { schema: OidbLeaveGroupSchema, value: { groupUin: groupId } },
});
const env = makeOidbEnvelope<OidbLeaveGroup>(0x1097, 1, { groupUin: groupId });
await runOidb(bridge, 'OidbSvcTrpcTcp.0x1097_1', encodeOidbEnv<OidbLeaveGroup>(env));
}
// ─────────────── role / display name ───────────────
export async function setGroupAdmin(bridge: Bridge, groupId: number, userId: number, enable: boolean): Promise<void> {
const uid = await bridge.resolveUserUid(userId, groupId);
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0x1096_1',
oidbCmd: 0x1096, subCmd: 1,
request: { schema: OidbSetAdminSchema, value: { groupUin: groupId, uid, isAdmin: enable } },
});
const env = makeOidbEnvelope<OidbSetAdmin>(0x1096, 1, { groupUin: groupId, uid, isAdmin: enable });
await runOidb(bridge, 'OidbSvcTrpcTcp.0x1096_1', encodeOidbEnv<OidbSetAdmin>(env));
}
export async function setGroupCard(bridge: Bridge, groupId: number, userId: number, card: string): Promise<void> {
const uid = await bridge.resolveUserUid(userId, groupId);
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0x8fc_3',
oidbCmd: 0x8FC, subCmd: 3,
request: {
schema: OidbRenameMemberSchema,
value: { groupUin: groupId, body: { targetUid: uid, targetName: card } },
},
const env = makeOidbEnvelope<OidbRenameMember>(0x8FC, 3, {
groupUin: groupId, body: { targetUid: uid, targetName: card },
});
await runOidb(bridge, 'OidbSvcTrpcTcp.0x8fc_3', encodeOidbEnv<OidbRenameMember>(env));
}
export async function setGroupName(bridge: Bridge, groupId: number, name: string): Promise<void> {
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0x89a_15',
oidbCmd: 0x89A, subCmd: 15,
request: { schema: OidbRenameGroupSchema, value: { groupUin: groupId, body: { targetName: name } } },
});
const env = makeOidbEnvelope<OidbRenameGroup>(0x89A, 15, { groupUin: groupId, body: { targetName: name } });
await runOidb(bridge, 'OidbSvcTrpcTcp.0x89a_15', encodeOidbEnv<OidbRenameGroup>(env));
}
export async function setGroupSpecialTitle(bridge: Bridge, groupId: number, userId: number, title: string): Promise<void> {
const uid = await bridge.resolveUserUid(userId, groupId);
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0x8fc_2',
oidbCmd: 0x8FC, subCmd: 2,
request: {
schema: OidbSpecialTitleSchema,
value: { groupUin: groupId, body: { targetUid: uid, specialTitle: title, expireTime: -1 } },
},
const env = makeOidbEnvelope<OidbSpecialTitle>(0x8FC, 2, {
groupUin: groupId, body: { targetUid: uid, specialTitle: title, expireTime: -1 },
});
await runOidb(bridge, 'OidbSvcTrpcTcp.0x8fc_2', encodeOidbEnv<OidbSpecialTitle>(env));
}
// ─────────────── personal-side metadata ───────────────
@@ -172,11 +128,8 @@ export async function setGroupSpecialTitle(bridge: Bridge, groupId: number, user
// here rather than in friend.ts because the semantic is "operate on a
// group" rather than "operate on a contact list".
export async function setGroupRemark(bridge: Bridge, groupId: number, remark: string): Promise<void> {
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0xf16_1',
oidbCmd: 0xF16, subCmd: 1,
request: { schema: Oidb0xf16ReqSchema, value: { inner: { groupId: BigInt(groupId), remark }, field12: 0 } },
});
const env = makeOidbEnvelope<Oidb0xf16Req>(0xF16, 1, { inner: { groupId: BigInt(groupId), remark }, field12: 0 });
await runOidb(bridge, 'OidbSvcTrpcTcp.0xf16_1', encodeOidbEnv<Oidb0xf16Req>(env));
}
// ─────────────── group-level quota query ───────────────
@@ -194,12 +147,9 @@ export async function getGroupAtAllRemain(
type: 0,
};
const result = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x8a7_0',
oidbCmd: 0x8A7, subCmd: 0,
request: { schema: Oidb0x8a7ReqSchema, value: req },
response: { schema: Oidb0x8a7RespSchema },
});
const env = makeOidbEnvelope<Oidb0x8a7Req>(0x8A7, 0, req);
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x8a7_0', encodeOidbEnv<Oidb0x8a7Req>(env));
const result = decodeOidbEnv<Oidb0x8a7Resp>(respBytes).body;
if (!result) {
throw new Error('get group at all remain result empty');
@@ -213,4 +163,3 @@ export async function getGroupAtAllRemain(
remain_at_all_count_for_uin: Number(result.uinRemain || 0),
};
}
@@ -0,0 +1,289 @@
// Group album actions via TRPC protocol.
//
// Unlike the OIDB action family, these endpoints speak raw TRPC
// (service command `QunAlbum.trpc.qzone.webapp_qun_*`) without an
// `OidbBase<T>` envelope. We hit `bridge.sendRawPacket` directly with
// proton-encoded bodies and decode the responses through proton's
// monomorphized codecs.
import type { Bridge } from '../bridge';
import { protobuf_encode, protobuf_decode } from '@snowluma/proton';
import type {
GetMediaListRequest,
GetMediaListResponse,
DoQunCommentRequest,
DoQunCommentResponse,
DoQunLikeRequest,
DoQunLikeResponse,
DeleteMediasRequest,
DeleteMediasResponse,
} from '../proto/proton/oidb-action';
export interface GroupAlbumMediaResult {
mediaList: any[];
nextAttachInfo: string;
}
export interface GroupAlbumCommentResult {
id: string;
user: { uin: string };
content: Array<{ type: number; content: string }>;
time: string;
clientKey: string;
}
function convertBigIntToString(obj: any): any {
if (obj === null || obj === undefined) return obj;
if (typeof obj === 'bigint') return obj.toString();
if (Array.isArray(obj)) return obj.map(convertBigIntToString);
if (typeof obj === 'object') {
const result: any = {};
for (const key in obj) {
result[key] = convertBigIntToString(obj[key]);
}
return result;
}
return obj;
}
export async function getGroupAlbumMediaList(
bridge: Bridge,
groupId: number,
albumId: string,
attachInfo: string = ''
): Promise<GroupAlbumMediaResult> {
const traceId = `_${Date.now()}_${Math.floor(Math.random() * 100000)}`;
const body = protobuf_encode<GetMediaListRequest>({
field1: 0,
field2: new Uint8Array(0),
field3: new Uint8Array(0),
reqInfo: {
groupId: groupId.toString(),
albumId: albumId,
field3: 0,
attachInfo: attachInfo,
field5: '',
},
traceId: traceId,
extMap: [{ key: 'fc-appid', value: '100' }],
});
const result = await bridge.sendRawPacket(
'QunAlbum.trpc.qzone.webapp_qun_media.QunMedia.GetMediaList',
body,
15000
);
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(result.errorMessage || 'failed to get album media list');
}
const resp = protobuf_decode<GetMediaListResponse>(result.responseData);
if (resp.field1 !== 0) {
throw new Error(`fetch album media list error: retCode ${resp.field1 ?? 'unknown'}`);
}
const data = resp.data ?? {};
const mediaList = data.mediaList ?? [];
const nextAttachInfo = data.nextAttachInfo ?? '';
return convertBigIntToString({
mediaList,
nextAttachInfo,
});
}
export async function commentGroupAlbumMedia(
bridge: Bridge,
groupId: number,
albumId: string,
lloc: string,
content: string
): Promise<GroupAlbumCommentResult> {
const traceId = `_${Date.now()}_${Math.floor(Math.random() * 100000)}`;
const clientKey = Date.now().toString();
const uin = bridge.identity.uin;
const body = protobuf_encode<DoQunCommentRequest>({
field1: 8527,
field2: new Uint8Array(0),
field3: new Uint8Array(0),
body: {
groupId: groupId.toString(),
field3: 2,
reqBody: {
field1: { field3: 0, field4: "" },
field2: {
field1: { uin }
},
field5: {
field1: {
field2: {
field1: 0, field2: "",
lloc,
field4: "", field6: "", field7: 0, field8: 0, field9: 0, field14: 0, field15: 0, field17: 0
}
},
albumId,
field5: 0
},
},
field5: {
field2: { uin },
field3: {
field1: 0,
field2: content,
field3: "", field4: "", field5: 0, field6: ""
},
clientKey,
}
},
traceId,
extMap: [{ key: 'fc-appid', value: '100' }],
});
const result = await bridge.sendRawPacket(
'QunAlbum.trpc.qzone.webapp_qun_operation.FeedsWriter.DoQunComment',
body,
15000
);
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(result.errorMessage || 'failed to comment on album media');
}
const resp = protobuf_decode<DoQunCommentResponse>(result.responseData);
const resCode = resp.field1;
if (resCode !== 0 && resCode !== 8527 && !resp.comment) {
throw new Error(`comment album media error: retCode ${resCode ?? 'unknown'}`);
}
const commentData = resp.comment?.data ?? {};
return convertBigIntToString({
id: commentData.id ?? '',
user: { uin: commentData.user?.uin ?? '' },
content: commentData.content ?? [],
time: commentData.time ?? '0',
clientKey: commentData.clientKey ?? '',
});
}
export async function likeGroupAlbumMedia(
bridge: Bridge,
groupId: number,
albumId: string,
batchId: string,
lloc: string | undefined,
isLike: boolean
): Promise<any> {
const uin = bridge.identity.uin;
const clientKey = `${uin}_${Date.now()}_${Math.floor(Math.random() * 100000)}`;
const type = isLike ? 2 : 1;
const status = isLike ? 0 : 1;
let id = '';
if (lloc) {
id = `421_1_0_${groupId}|${albumId}|${batchId}^||^421_1_0_${groupId}|${albumId}|${lloc}^||^0`;
} else {
id = `421_1_0_${groupId}|${albumId}|${batchId}`;
}
const body = protobuf_encode<DoQunLikeRequest>({
field1: 5495,
field2: "h5_test",
field3: "h5_test",
body: {
type,
like: { id, status },
publish: {
cellCommon: {
time: BigInt(Date.now()),
feedId: `422_0_${batchId}`
},
cellUserInfo: {
user: { uin }
},
cellMedia: {
albumId: albumId,
batchId: BigInt(batchId)
},
cellQunInfo: {
qunId: groupId.toString()
}
},
clientKey
},
extMap: [{ key: 'fc-appid', value: '100' }],
});
const result = await bridge.sendRawPacket(
'QunAlbum.trpc.qzone.webapp_qun_operation.FeedsWriter.DoQunLike',
body,
15000
);
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(result.errorMessage || 'failed to like album media');
}
const resp = protobuf_decode<DoQunLikeResponse>(result.responseData);
const resCode = resp.field1;
if (resCode !== 5495) {
throw new Error(`like album media error: retCode ${resCode ?? 'unknown'}`);
}
return convertBigIntToString(resp.body?.like ?? {});
}
export async function deleteGroupAlbumMedia(
bridge: Bridge,
groupId: number,
albumId: string,
lloc: string
): Promise<any> {
const uin = bridge.identity.uin;
const clientKey = `${uin}_${Date.now()}_${Math.floor(Math.random() * 100000)}`;
const body = protobuf_encode<DeleteMediasRequest>({
field1: 8694,
field2: "h5_test",
field3: "h5_test",
body: {
groupId: groupId.toString(),
albumId: albumId,
lloc: lloc,
},
traceId: clientKey,
extMap: [{ key: 'fc-appid', value: '100' }],
});
const result = await bridge.sendRawPacket(
'QunAlbum.trpc.qzone.webapp_qun_media.QunMedia.DeleteMedias',
body,
15000
);
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(result.errorMessage || 'failed to delete album media');
}
const resp = protobuf_decode<DeleteMediasResponse>(result.responseData);
const resCode = resp.field1;
const errCode = resp.field2;
const errMsg = resp.field3;
if (resCode !== 8694 || errCode) {
throw new Error(`delete album media error [${errCode ?? 'unknown'}]: ${errMsg ?? 'unknown'}`);
}
return { success: true };
}
+371 -214
View File
@@ -6,30 +6,34 @@
// stay as separate functions.
import type { Bridge } from '../bridge';
import { protoEncode } from '../../protobuf/decode';
import { runOidb } from '../bridge-oidb';
import { protobuf_encode } from '@snowluma/proton';
import { runOidb, makeOidbEnvelope, encodeOidbEnv, decodeOidbEnv } from '../bridge-oidb';
import { fetchHighwaySession, uploadHighwayHttp } from '../highway/highway-client';
import { computeHashes, computeMd5, FILE_UPLOAD_MAX_BYTES, loadBinarySource } from '../highway/utils';
import {
OidbGroupFileCountViewReqSchema,
OidbGroupFileCountViewRespSchema,
OidbGroupFileFolderReqSchema,
OidbGroupFileFolderRespSchema,
OidbGroupFileReqSchema,
OidbGroupFileRespSchema,
OidbGroupFileViewReqSchema,
OidbGroupFileViewRespSchema,
OidbPrivateFileDownloadReqSchema,
OidbPrivateFileDownloadRespSchema,
OidbPrivateFileUploadReqSchema,
OidbPrivateFileUploadRespSchema,
NTV2RichMediaReqSchema,
NTV2RichMediaRespSchema,
} from '../proto/oidb-action';
import { FileUploadExtSchema } from '../proto/highway';
import type {
OidbGroupFileCountViewReq,
OidbGroupFileCountViewResp,
OidbGroupFileFolderReq,
OidbGroupFileFolderResp,
OidbGroupFileReq,
OidbGroupFileResp,
OidbGroupFileViewReq,
OidbGroupFileViewResp,
OidbGroupSendFileReq,
OidbPrivateFileDownloadReq,
OidbPrivateFileDownloadResp,
OidbPrivateFileUploadReq,
OidbPrivateFileUploadResp,
NTV2RichMediaReq,
NTV2RichMediaResp,
} from '../proto/proton/oidb-action';
import type { FileUploadExt } from '../proto/proton/highway';
import { toHexUpper } from '../../utils/hex';
import { createLogger } from '../../utils/logger';
import { ensureRetCodeZero, resolveSelfUid, toInt, type MediaIndexNode } from './shared';
const log = createLogger('GroupFile');
// ─────────────── public result types ───────────────
export interface GroupFileInfo {
@@ -80,6 +84,19 @@ function bytesToHexUpper(data: unknown): string {
return toHexUpper(data);
}
// Reverses acidify's `Int.toIpString()`: the 32-bit IP arrives
// little-endian-packed (byte0 = first dotted octet) and we unpack it the
// same way. Force-unsigned the shift to keep negative ints (high bit set)
// rendering correctly — JS `>>` is arithmetic and would turn 0xFF000000
// into a negative number.
function int32ToIpv4Dotted(value: number): string {
const b1 = value & 0xFF;
const b2 = (value >>> 8) & 0xFF;
const b3 = (value >>> 16) & 0xFF;
const b4 = (value >>> 24) & 0xFF;
return `${b1}.${b2}.${b3}.${b4}`;
}
function normalizeUploadFileName(name: string, fallback: string): string {
const trimmed = name.trim();
if (trimmed) return trimmed;
@@ -104,7 +121,7 @@ function buildGroupFileUploadExt(
uploadHost: string,
uploadPort: number,
): Uint8Array {
return protoEncode({
return protobuf_encode<FileUploadExt>({
unknown1: 100,
unknown2: 1,
entry: {
@@ -145,7 +162,7 @@ function buildGroupFileUploadExt(
},
},
unknown200: 0,
}, FileUploadExtSchema);
});
}
function buildPrivateFileUploadExt(
@@ -159,7 +176,7 @@ function buildPrivateFileUploadExt(
uploadHost: string,
uploadPort: number,
): Uint8Array {
return protoEncode({
return protobuf_encode<FileUploadExt>({
unknown1: 100,
unknown2: 1,
entry: {
@@ -201,7 +218,7 @@ function buildPrivateFileUploadExt(
},
unknown3: 0,
unknown200: 1,
}, FileUploadExtSchema);
});
}
function normalizeMediaNode(node: MediaIndexNode): Record<string, unknown> {
@@ -242,12 +259,9 @@ async function fetchNtv2DownloadUrl(
oidbCmd: number,
payload: Record<string, unknown>,
): Promise<string> {
const resp = await runOidb<any>(bridge, {
cmd: serviceCmd,
oidbCmd, subCmd: 200,
request: { schema: NTV2RichMediaReqSchema, value: payload, isUid: true },
response: { schema: NTV2RichMediaRespSchema },
});
const env = makeOidbEnvelope<NTV2RichMediaReq>(oidbCmd, 200, payload as any, true);
const respBytes = await runOidb(bridge, serviceCmd, encodeOidbEnv<NTV2RichMediaReq>(env));
const resp = decodeOidbEnv<NTV2RichMediaResp>(respBytes).body;
ensureRetCodeZero('ntv2 download', resp?.respHead?.retCode, resp?.respHead?.message, undefined);
const domain = typeof resp?.download?.info?.domain === 'string' ? resp.download.info.domain : '';
@@ -260,18 +274,57 @@ async function fetchNtv2DownloadUrl(
return `https://${domain}${path}${rKeyParam}`;
}
// ─────────────── publish (group file → chat) ───────────────
/**
* Publish a previously-uploaded group file as a chat message.
*
* Wire is OIDB `OidbSvcTrpcTcp.0x6d9_4` — NOT `MessageSvc.PbSendMsg`.
* Lagrange.Core V2 splits these two roles: the file UPLOAD path goes
* via 0x6D6_0 + highway PUT, then a SECOND OIDB hop (this one) tells
* the QQ server "now publish that staged blob as a chat message" so
* everyone in the group can see the file bubble.
*
* The old approach — wrap the file as `TransElem(elemType=24)` inside
* `richText.elems[]` and ship it via PbSendMsg — works for INCOMING
* messages (the receive decoder unpacks transElem(24) into a
* FileEntity) but the QQ-NT server REJECTS it on outgoing with
* `result=79` ("invalid element on send-side"). Mirror Lagrange's
* dedicated GroupSendFileService instead.
*
* The unused `field4` slot and the `field3=random` value match
* Lagrange's send-side defaults (`OidbSvcTrpcTcp0x6D9_4.cs` + the
* `Random.Shared.Next()` call in `GroupSendFileService.cs`). Field 5
* is the `Field5=true` flag the receiver's deserializer expects.
*/
export async function sendGroupFileMessage(bridge: Bridge, groupId: number, fileId: string): Promise<void> {
if (!fileId) throw new Error('sendGroupFileMessage requires fileId');
const env = makeOidbEnvelope<OidbGroupSendFileReq>(0x6D9, 4, {
body: {
groupUin: groupId,
type: 2,
info: {
busiType: 102,
fileId,
field3: Math.floor(Math.random() * 0x7fffffff) >>> 0,
field5: true,
},
},
});
// The envelope-level errorCode peek inside `runOidb` covers the
// happy-path validation; failures surface as a thrown OIDB error.
await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d9_4', encodeOidbEnv<OidbGroupSendFileReq>(env));
}
// ─────────────── file count ───────────────
export async function fetchGroupFileCount(bridge: Bridge, groupId: number): Promise<{ fileCount: number; maxCount: number }> {
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x6d8_3',
oidbCmd: 0x6D8, subCmd: 3,
request: {
schema: OidbGroupFileCountViewReqSchema,
value: { count: { groupUin: groupId, appId: 7, busId: 0 } },
},
response: { schema: OidbGroupFileCountViewRespSchema },
});
const env = makeOidbEnvelope<OidbGroupFileCountViewReq>(
0x6D8, 3,
{ count: { groupUin: groupId, appId: 7, busId: 0 } },
);
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d8_3', encodeOidbEnv<OidbGroupFileCountViewReq>(env));
const resp = decodeOidbEnv<OidbGroupFileCountViewResp>(respBytes).body;
return {
fileCount: toInt(resp?.count?.fileCount ?? 0),
maxCount: toInt(resp?.count?.maxCount ?? 10000),
@@ -296,31 +349,28 @@ export async function uploadGroupFile(
const fileName = normalizeUploadFileName(name, loaded.fileName);
const hashes = computeHashes(loaded.bytes);
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x6d6_0',
oidbCmd: 0x6D6, subCmd: 0,
request: {
schema: OidbGroupFileReqSchema,
value: {
file: {
groupUin: groupId,
appId: 4,
busId: 102,
entrance: 6,
targetDirectory: normalizeDirectory(folderId),
fileName,
localDirectory: `/${fileName}`,
fileSize: BigInt(loaded.bytes.length),
fileSha1: hashes.sha1,
fileSha3: new Uint8Array(0),
fileMd5: hashes.md5,
field15: true,
},
const env = makeOidbEnvelope<OidbGroupFileReq>(
0x6D6, 0,
{
file: {
groupUin: groupId,
appId: 4,
busId: 102,
entrance: 6,
targetDirectory: normalizeDirectory(folderId),
fileName,
localDirectory: `/${fileName}`,
fileSize: BigInt(loaded.bytes.length),
fileSha1: hashes.sha1,
fileSha3: new Uint8Array(0),
fileMd5: hashes.md5,
field15: true,
},
isUid: true,
},
response: { schema: OidbGroupFileRespSchema },
});
true,
);
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d6_0', encodeOidbEnv<OidbGroupFileReq>(env));
const resp = decodeOidbEnv<OidbGroupFileResp>(respBytes).body;
const upload = resp?.upload;
if (!upload) throw new Error('group file upload response missing');
@@ -329,6 +379,23 @@ export async function uploadGroupFile(
const fileId = typeof upload.fileId === 'string' && upload.fileId ? upload.fileId : null;
if (!fileId) throw new Error('group file upload response missing file_id');
// Remember the upload so a later `send_group_msg` carrying just the
// file_id can route via `sendGroupFileMessage` without forcing the
// OneBot caller to thread fileName/size/md5 separately. For groups
// the wire publish (OIDB 0x6d9_4) only needs the file_id itself, so
// this is mainly for log-line correctness; the c2c counterpart in
// `uploadPrivateFile` is where the cache is actually load-bearing.
bridge.rememberUploadedFile({
fileId,
scope: 'group',
groupId,
fileName,
fileSize: loaded.bytes.length,
fileMd5: hashes.md5,
fileSha1: hashes.sha1,
rememberedAt: Date.now(),
});
if (!upload.boolFileExist && uploadFile) {
const senderUin = toInt(bridge.identity.uin);
if (senderUin <= 0) throw new Error('invalid self uin for group file upload');
@@ -358,6 +425,31 @@ export async function uploadGroupFile(
await uploadHighwayHttp(bridge, session, 71, loaded.bytes, hashes.md5, ext);
}
// Stage 3: file is on the server, now publish it as a chat message.
//
// Without this, OIDB 0x6D6_0 + highway PUT only stages the bytes —
// the chat shows nothing. The publish step goes via a dedicated OIDB
// call (0x6D9_4), NOT via `MessageSvc.PbSendMsg` with a transElem(24)
// payload — the QQ-NT server rejects that with `result=79`. Mirrors
// Lagrange.Core V2's `GroupSendFileService.cs`. Suppressed when the
// caller opts out via `uploadFile=false` (treat that as "I only
// wanted the slot allocated, hold the chat post"). Routes through
// the public bridge method (rather than the local `sendGroupFileMessage`)
// so tests can mock at the bridge boundary, matching the pattern
// `uploadPrivateFile` uses with `bridge.sendC2cFileMessage`.
if (uploadFile) {
try {
await bridge.sendGroupFileMessage(groupId, fileId);
} catch (err) {
// The bytes are already on the server and the fileId is valid —
// fail loud but don't lose the upload result the action handler
// committed to returning. Callers can still resolve the file by
// id; they'll just have to re-publish it themselves.
log.warn('group file uploaded (fileId=%s) but chat post failed: %s',
fileId, err instanceof Error ? err.message : String(err));
}
}
return { fileId };
}
@@ -389,32 +481,26 @@ export async function uploadPrivateFile(
const fileName = normalizeUploadFileName(name, loaded.fileName);
const hashes = computeHashes(loaded.bytes);
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0xe37_1700',
oidbCmd: 0xE37, subCmd: 1700,
request: {
schema: OidbPrivateFileUploadReqSchema,
value: {
command: 1700,
seq: 0,
upload: {
senderUid: selfUid,
receiverUid: targetUid,
fileSize: loaded.bytes.length,
fileName,
md510MCheckSum: md5First10MB(loaded.bytes),
sha1CheckSum: hashes.sha1,
localPath: '/',
md5CheckSum: hashes.md5,
sha3CheckSum: new Uint8Array(0),
},
businessId: 3,
clientType: 1,
flagSupportMediaPlatform: 1,
},
const env = makeOidbEnvelope<OidbPrivateFileUploadReq>(0xE37, 1700, {
command: 1700,
seq: 0,
upload: {
senderUid: selfUid,
receiverUid: targetUid,
fileSize: loaded.bytes.length,
fileName,
md510MCheckSum: md5First10MB(loaded.bytes),
sha1CheckSum: hashes.sha1,
localPath: '/',
md5CheckSum: hashes.md5,
sha3CheckSum: new Uint8Array(0),
},
response: { schema: OidbPrivateFileUploadRespSchema },
businessId: 3,
clientType: 1,
flagSupportMediaPlatform: 1,
});
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xe37_1700', encodeOidbEnv<OidbPrivateFileUploadReq>(env));
const resp = decodeOidbEnv<OidbPrivateFileUploadResp>(respBytes).body;
const upload = resp?.upload;
if (!upload) throw new Error('private file upload response missing');
@@ -424,11 +510,88 @@ export async function uploadPrivateFile(
const fileHash = typeof upload.fileAddon === 'string' && upload.fileAddon ? upload.fileAddon : null;
if (!fileId) throw new Error('private file upload response missing file_id');
// Cache the metadata so a later `send_private_msg` carrying just
// `{type:'file', file_id}` can resurrect the full c2c-file packet
// (NotOnlineFile { fileSize, fileMd5, fileName, fileHash }). Without
// this the recipient sees a 0-byte file because the OneBot send path
// has no way to recover those fields from the file_id alone.
bridge.rememberUploadedFile({
fileId,
scope: 'private',
userId,
fileName,
fileSize: loaded.bytes.length,
fileMd5: hashes.md5,
fileSha1: hashes.sha1,
fileHash: fileHash ?? '',
rememberedAt: Date.now(),
});
if (!upload.boolFileExist && uploadFile) {
const uploadHost = (typeof upload.uploadIp === 'string' && upload.uploadIp)
// Host selection.
//
// Current QQ-NT server rollout has stopped populating the legacy
// `uploadIp` (field 60) entirely. The host now arrives as the first
// entry of `rtpMediaPlatformUploadAddress` (field 210, repeated
// IPv4 message) — same place acidify reads it from since their
// 2026-04 protobuf refactor. Each IPv4 has paired `inIP`/`inPort`
// (LAN, same DC as the OIDB endpoint) and `outIP`/`outPort` (WAN);
// acidify uses `inIP`/`inPort` exclusively and so do we, because
// that's the address the highway PUT actually needs to reach.
//
// The 32-bit IPs are little-endian-packed (byte0 = first octet)
// per acidify's `Int.toIpString()`. Cross-checked the byte order
// by inspecting their highway flow — there's no separate htonl
// step, so the integer is already in network-octet-first order.
//
// Older server versions still populate the legacy string fields
// (uploadIp / uploadDomain / uploadIpList[0] / uploadHttpsDomain /
// uploadDns), so we fall through to those after rtpMediaPlatform.
// Pair an HTTPS-flavored host with `uploadHttpsPort` if that's
// what we picked.
const rtpFirst = (Array.isArray(upload.rtpMediaPlatformUploadAddress)
&& upload.rtpMediaPlatformUploadAddress[0])
? upload.rtpMediaPlatformUploadAddress[0] : null;
const rtpInIP = rtpFirst && typeof rtpFirst.inIP === 'number' && rtpFirst.inIP !== 0
? int32ToIpv4Dotted(rtpFirst.inIP) : '';
const rtpInPort = rtpFirst && typeof rtpFirst.inPort === 'number'
? rtpFirst.inPort : 0;
const ipListFirst = (Array.isArray(upload.uploadIpList) && upload.uploadIpList[0])
? upload.uploadIpList[0] : '';
const uploadHost = (rtpInIP)
|| (typeof upload.uploadIp === 'string' && upload.uploadIp)
|| (typeof upload.uploadDomain === 'string' && upload.uploadDomain)
|| (ipListFirst)
|| (typeof upload.uploadHttpsDomain === 'string' && upload.uploadHttpsDomain)
|| (typeof upload.uploadDns === 'string' && upload.uploadDns)
|| '';
const uploadPort = toInt(upload.uploadPort);
const httpsHostUsed = !rtpInIP && !upload.uploadIp && !upload.uploadDomain && !ipListFirst
&& typeof upload.uploadHttpsDomain === 'string' && !!upload.uploadHttpsDomain;
const uploadPort = rtpInIP && rtpInPort > 0
? rtpInPort
: httpsHostUsed && toInt(upload.uploadHttpsPort) > 0
? toInt(upload.uploadHttpsPort)
: toInt(upload.uploadPort);
if (!uploadHost || uploadPort <= 0) {
// Surface every host-bearing field we know about so a user
// hitting this can show us exactly which slot the server filled
// (or whether it returned nothing at all — which would point at
// a request mismatch rather than a missing decoder).
const rtpDump = Array.isArray(upload.rtpMediaPlatformUploadAddress)
? JSON.stringify(upload.rtpMediaPlatformUploadAddress.map((e) => ({
outIP: e.outIP, outPort: e.outPort, inIP: e.inIP, inPort: e.inPort,
iPType: e.iPType,
})))
: '[]';
log.warn(
'private file upload host missing — rtp=%s ip=%s domain=%s ipList=%s httpsDomain=%s dns=%s lanip=%s port=%s httpsPort=%s',
rtpDump,
upload.uploadIp ?? '', upload.uploadDomain ?? '',
JSON.stringify(upload.uploadIpList ?? []),
upload.uploadHttpsDomain ?? '', upload.uploadDns ?? '',
upload.uploadLanip ?? '', upload.uploadPort ?? 0,
upload.uploadHttpsPort ?? 0,
);
throw new Error('private file upload host is invalid');
}
@@ -450,6 +613,27 @@ export async function uploadPrivateFile(
await uploadHighwayHttp(bridge, session, 95, loaded.bytes, hashes.md5, ext);
}
// Stage 3: publish the file as a c2c chat message. C2C files use
// `RichText.notOnlineFile` (parallel to `elems`), so we go through
// the dedicated `sendC2cFileMessage` instead of `sendPrivateMessage`
// which only knows about elems[]. NapCat does the same atomic
// upload+send dance — without it the file sits on the server and
// the recipient sees nothing.
if (uploadFile) {
try {
await bridge.sendC2cFileMessage(userId, targetUid, {
fileId,
fileName,
fileSize: loaded.bytes.length,
fileMd5: hashes.md5,
fileHash: fileHash ?? '',
});
} catch (err) {
log.warn('private file uploaded (fileId=%s) but chat post failed: %s',
fileId, err instanceof Error ? err.message : String(err));
}
}
return { fileId, fileHash };
}
@@ -463,27 +647,24 @@ export async function fetchGroupFiles(bridge: Bridge, groupId: number, folderId
const pageSize = 20;
let startIndex = 0;
for (let page = 0; page < 200; page++) {
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x6d8_1',
oidbCmd: 0x6D8, subCmd: 1,
request: {
schema: OidbGroupFileViewReqSchema,
value: {
list: {
groupUin: groupId,
appId: 7,
targetDirectory,
fileCount: pageSize,
sortBy: 1,
startIndex,
field17: 2,
field18: 0,
},
const env = makeOidbEnvelope<OidbGroupFileViewReq>(
0x6D8, 1,
{
list: {
groupUin: groupId,
appId: 7,
targetDirectory,
fileCount: pageSize,
sortBy: 1,
startIndex,
field17: 2,
field18: 0,
},
isUid: true,
},
response: { schema: OidbGroupFileViewRespSchema },
});
true,
);
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d8_1', encodeOidbEnv<OidbGroupFileViewReq>(env));
const resp = decodeOidbEnv<OidbGroupFileViewResp>(respBytes).body;
const list = resp?.list;
if (!list) break;
@@ -538,23 +719,20 @@ export async function fetchGroupFiles(bridge: Bridge, groupId: number, folderId
// ─────────────── url fetch (group / private files) ───────────────
export async function fetchGroupFileUrl(bridge: Bridge, groupId: number, fileId: string, busId = 102): Promise<string> {
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x6d6_2',
oidbCmd: 0x6D6, subCmd: 2,
request: {
schema: OidbGroupFileReqSchema,
value: {
download: {
groupUin: groupId,
appId: 7,
busId,
fileId,
},
const env = makeOidbEnvelope<OidbGroupFileReq>(
0x6D6, 2,
{
download: {
groupUin: groupId,
appId: 7,
busId,
fileId,
},
isUid: true,
},
response: { schema: OidbGroupFileRespSchema },
});
true,
);
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d6_2', encodeOidbEnv<OidbGroupFileReq>(env));
const resp = decodeOidbEnv<OidbGroupFileResp>(respBytes).body;
const download = resp?.download;
if (!download) throw new Error('group file url response missing');
@@ -574,29 +752,23 @@ export async function fetchGroupFileUrl(bridge: Bridge, groupId: number, fileId:
export async function fetchPrivateFileUrl(bridge: Bridge, userId: number, fileId: string, fileHash: string): Promise<string> {
const uid = await bridge.resolveUserUid(userId);
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0xe37_1200',
oidbCmd: 0xE37, subCmd: 1200,
request: {
schema: OidbPrivateFileDownloadReqSchema,
value: {
subCommand: 1200,
field2: 1,
body: {
receiverUid: uid,
fileUuid: fileId,
type: 2,
fileHash,
t2: 0,
},
field101: 3,
field102: 103,
field200: 1,
field99999: new Uint8Array([0xC0, 0x85, 0x2C, 0x01]),
},
const env = makeOidbEnvelope<OidbPrivateFileDownloadReq>(0xE37, 1200, {
subCommand: 1200,
field2: 1,
body: {
receiverUid: uid,
fileUuid: fileId,
type: 2,
fileHash,
t2: 0,
},
response: { schema: OidbPrivateFileDownloadRespSchema },
field101: 3,
field102: 103,
field200: 1,
field99999: new Uint8Array([0xC0, 0x85, 0x2C, 0x01]),
});
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xe37_1200', encodeOidbEnv<OidbPrivateFileDownloadReq>(env));
const resp = decodeOidbEnv<OidbPrivateFileDownloadResp>(respBytes).body;
const result = resp?.body?.result;
const server = typeof result?.server === 'string' ? result.server : '';
@@ -611,22 +783,19 @@ export async function fetchPrivateFileUrl(bridge: Bridge, userId: number, fileId
// ─────────────── delete / move ───────────────
export async function deleteGroupFile(bridge: Bridge, groupId: number, fileId: string): Promise<void> {
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x6d6_3',
oidbCmd: 0x6D6, subCmd: 3,
request: {
schema: OidbGroupFileReqSchema,
value: {
delete: {
groupUin: groupId,
busId: 102,
fileId,
},
const env = makeOidbEnvelope<OidbGroupFileReq>(
0x6D6, 3,
{
delete: {
groupUin: groupId,
busId: 102,
fileId,
},
isUid: true,
},
response: { schema: OidbGroupFileRespSchema },
});
true,
);
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d6_3', encodeOidbEnv<OidbGroupFileReq>(env));
const resp = decodeOidbEnv<OidbGroupFileResp>(respBytes).body;
const result = resp?.delete;
if (!result) throw new Error('group file delete response missing');
@@ -640,25 +809,22 @@ export async function moveGroupFile(
parentDirectory: string,
targetDirectory: string,
): Promise<void> {
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x6d6_5',
oidbCmd: 0x6D6, subCmd: 5,
request: {
schema: OidbGroupFileReqSchema,
value: {
move: {
groupUin: groupId,
appId: 7,
busId: 102,
fileId,
parentDirectory,
targetDirectory,
},
const env = makeOidbEnvelope<OidbGroupFileReq>(
0x6D6, 5,
{
move: {
groupUin: groupId,
appId: 7,
busId: 102,
fileId,
parentDirectory,
targetDirectory,
},
isUid: true,
},
response: { schema: OidbGroupFileRespSchema },
});
true,
);
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d6_5', encodeOidbEnv<OidbGroupFileReq>(env));
const resp = decodeOidbEnv<OidbGroupFileResp>(respBytes).body;
const result = resp?.move;
if (!result) throw new Error('group file move response missing');
@@ -668,22 +834,19 @@ export async function moveGroupFile(
// ─────────────── folders ───────────────
export async function createGroupFileFolder(bridge: Bridge, groupId: number, name: string, parentId = '/'): Promise<void> {
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x6d7_0',
oidbCmd: 0x6D7, subCmd: 0,
request: {
schema: OidbGroupFileFolderReqSchema,
value: {
create: {
groupUin: groupId,
rootDirectory: normalizeDirectory(parentId),
folderName: name,
},
const env = makeOidbEnvelope<OidbGroupFileFolderReq>(
0x6D7, 0,
{
create: {
groupUin: groupId,
rootDirectory: normalizeDirectory(parentId),
folderName: name,
},
isUid: true,
},
response: { schema: OidbGroupFileFolderRespSchema },
});
true,
);
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d7_0', encodeOidbEnv<OidbGroupFileFolderReq>(env));
const resp = decodeOidbEnv<OidbGroupFileFolderResp>(respBytes).body;
const result = resp?.create;
if (!result) throw new Error('group folder create response missing');
@@ -691,21 +854,18 @@ export async function createGroupFileFolder(bridge: Bridge, groupId: number, nam
}
export async function deleteGroupFileFolder(bridge: Bridge, groupId: number, folderId: string): Promise<void> {
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x6d7_1',
oidbCmd: 0x6D7, subCmd: 1,
request: {
schema: OidbGroupFileFolderReqSchema,
value: {
delete: {
groupUin: groupId,
folderId,
},
const env = makeOidbEnvelope<OidbGroupFileFolderReq>(
0x6D7, 1,
{
delete: {
groupUin: groupId,
folderId,
},
isUid: true,
},
response: { schema: OidbGroupFileFolderRespSchema },
});
true,
);
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d7_1', encodeOidbEnv<OidbGroupFileFolderReq>(env));
const resp = decodeOidbEnv<OidbGroupFileFolderResp>(respBytes).body;
const result = resp?.delete;
if (!result) throw new Error('group folder delete response missing');
@@ -713,22 +873,19 @@ export async function deleteGroupFileFolder(bridge: Bridge, groupId: number, fol
}
export async function renameGroupFileFolder(bridge: Bridge, groupId: number, folderId: string, newFolderName: string): Promise<void> {
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x6d7_2',
oidbCmd: 0x6D7, subCmd: 2,
request: {
schema: OidbGroupFileFolderReqSchema,
value: {
rename: {
groupUin: groupId,
folderId,
newFolderName,
},
const env = makeOidbEnvelope<OidbGroupFileFolderReq>(
0x6D7, 2,
{
rename: {
groupUin: groupId,
folderId,
newFolderName,
},
isUid: true,
},
response: { schema: OidbGroupFileFolderRespSchema },
});
true,
);
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d7_2', encodeOidbEnv<OidbGroupFileFolderReq>(env));
const resp = decodeOidbEnv<OidbGroupFileFolderResp>(respBytes).body;
const result = resp?.rename;
if (!result) throw new Error('group folder rename response missing');
@@ -5,13 +5,13 @@
import type { Bridge } from '../bridge';
import { protoEncode } from '../../protobuf/decode';
import { runOidb } from '../bridge-oidb';
import { runOidb, makeOidbEnvelope, encodeOidbEnv } from '../bridge-oidb';
import {
C2CRecallRequestSchema,
GroupRecallRequestSchema,
OidbEssenceSchema,
SsoReadedReportReqSchema,
} from '../proto/oidb-action';
import type { OidbEssence } from '../proto/proton/oidb-action';
export async function recallGroupMessage(bridge: Bridge, groupId: number, sequence: number): Promise<void> {
const request = protoEncode({
@@ -96,9 +96,6 @@ export async function markGroupMessageRead(
export async function setGroupEssence(bridge: Bridge, groupId: number, sequence: number, random: number, enable: boolean): Promise<void> {
const subCmd = enable ? 1 : 2;
const cmd = enable ? 'OidbSvcTrpcTcp.0xeac_1' : 'OidbSvcTrpcTcp.0xeac_2';
await runOidb(bridge, {
cmd,
oidbCmd: 0xEAC, subCmd,
request: { schema: OidbEssenceSchema, value: { groupUin: groupId, sequence, random } },
});
const env = makeOidbEnvelope<OidbEssence>(0xEAC, subCmd, { groupUin: groupId, sequence, random });
await runOidb(bridge, cmd, encodeOidbEnv<OidbEssence>(env));
}
+22 -40
View File
@@ -3,37 +3,28 @@
// edit message content — they're purely social signals.
import type { Bridge } from '../bridge';
import { runOidb } from '../bridge-oidb';
import {
Oidb0x9083ReqSchema,
Oidb0x9083RespSchema,
OidbGroupReactionSchema,
OidbLikeSchema,
OidbPokeSchema,
} from '../proto/oidb-action';
import { runOidb, makeOidbEnvelope, encodeOidbEnv, decodeOidbEnv } from '../bridge-oidb';
import type {
Oidb0x9083Req,
Oidb0x9083Resp,
OidbGroupReaction,
OidbLike,
OidbPoke,
} from '../proto/proton/oidb-action';
export async function sendPoke(bridge: Bridge, isGroup: boolean, peerUin: number, targetUin?: number): Promise<void> {
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0xed3_1',
oidbCmd: 0xED3, subCmd: 1,
request: {
schema: OidbPokeSchema,
value: {
uin: targetUin ?? peerUin,
groupUin: isGroup ? peerUin : 0,
friendUin: isGroup ? 0 : peerUin,
ext: 0,
},
},
const env = makeOidbEnvelope<OidbPoke>(0xED3, 1, {
uin: targetUin ?? peerUin,
groupUin: isGroup ? peerUin : 0,
friendUin: isGroup ? 0 : peerUin,
ext: 0,
});
await runOidb(bridge, 'OidbSvcTrpcTcp.0xed3_1', encodeOidbEnv<OidbPoke>(env));
}
export async function sendLike(bridge: Bridge, userId: number, count: number): Promise<void> {
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0x7e5_104',
oidbCmd: 0x7E5, subCmd: 104,
request: { schema: OidbLikeSchema, value: { targetUin: userId, count } },
});
const env = makeOidbEnvelope<OidbLike>(0x7E5, 104, { targetUin: userId, count });
await runOidb(bridge, 'OidbSvcTrpcTcp.0x7e5_104', encodeOidbEnv<OidbLike>(env));
}
export async function setGroupReaction(bridge: Bridge, groupId: number, sequence: number, code: string, isSet: boolean): Promise<void> {
@@ -44,14 +35,8 @@ export async function setGroupReaction(bridge: Bridge, groupId: number, sequence
// type field to pick the right resolution table; omitting it makes
// unicode reactions silently fail.
const type = code.length > 3 ? 2 : 1;
await runOidb(bridge, {
cmd,
oidbCmd: 0x9082, subCmd,
request: {
schema: OidbGroupReactionSchema,
value: { groupUin: groupId, sequence, code, type },
},
});
const env = makeOidbEnvelope<OidbGroupReaction>(0x9082, subCmd, { groupUin: groupId, sequence, code, type });
await runOidb(bridge, cmd, encodeOidbEnv<OidbGroupReaction>(env));
}
export async function getEmojiLikes(
@@ -63,7 +48,7 @@ export async function getEmojiLikes(
count: number = 10,
cookie: string = '',
): Promise<{ users: Array<{ uin: number }>, cookie: string, isLast: boolean }> {
const req = {
const req: any = {
groupId: BigInt(groupId),
sequence,
emojiType,
@@ -73,12 +58,9 @@ export async function getEmojiLikes(
count,
field12: 1,
};
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x9083_1',
oidbCmd: 0x9083, subCmd: 1,
request: { schema: Oidb0x9083ReqSchema, value: req },
response: { schema: Oidb0x9083RespSchema },
});
const env = makeOidbEnvelope<Oidb0x9083Req>(0x9083, 1, req);
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x9083_1', encodeOidbEnv<Oidb0x9083Req>(env));
const resp = decodeOidbEnv<Oidb0x9083Resp>(respBytes).body;
const uin = resp?.inner?.userInfo?.uin;
const users = uin ? [{ uin: Number(uin) }] : [];
const respCookie = resp?.cookie ? Buffer.from(resp.cookie).toString('base64') : '';
+19 -25
View File
@@ -4,17 +4,19 @@
import type { Bridge } from '../bridge';
import { protoDecode, protoEncode } from '../../protobuf/decode';
import { runOidb } from '../bridge-oidb';
import { runOidb, makeOidbEnvelope, encodeOidbEnv, decodeOidbEnv } from '../bridge-oidb';
import {
MiniAppShareReqSchema,
MiniAppShareRespSchema,
Oidb0x112eReqSchema,
Oidb0x112eRespSchema,
Oidb0x990ReqSchema,
Oidb0x990RespSchema,
Oidb0xeb7ReqSchema,
Oidb0xeb7RespSchema,
} from '../proto/oidb-action';
import type {
Oidb0x112eReq,
Oidb0x112eResp,
Oidb0x990Req,
Oidb0x990Resp,
Oidb0xeb7Req,
Oidb0xeb7Resp,
} from '../proto/proton/oidb-action';
export async function translateEn2Zh(
bridge: Bridge,
@@ -30,12 +32,9 @@ export async function translateEn2Zh(
tag12: 1,
};
const result = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x990_2',
oidbCmd: 0x990, subCmd: 2,
request: { schema: Oidb0x990ReqSchema, value: req },
response: { schema: Oidb0x990RespSchema },
});
const env = makeOidbEnvelope<Oidb0x990Req>(0x990, 2, req);
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x990_2', encodeOidbEnv<Oidb0x990Req>(env));
const result = decodeOidbEnv<Oidb0x990Resp>(respBytes).body;
const resp = result?.translateResp;
if (!resp) {
@@ -122,12 +121,9 @@ export async function clickInlineKeyboardButton(
unknown9: 1,
};
const result = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x112e_1',
oidbCmd: 0x112E, subCmd: 1,
request: { schema: Oidb0x112eReqSchema, value: req },
response: { schema: Oidb0x112eRespSchema },
});
const env = makeOidbEnvelope<Oidb0x112eReq>(0x112E, 1, req);
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x112e_1', encodeOidbEnv<Oidb0x112eReq>(env));
const result = decodeOidbEnv<Oidb0x112eResp>(respBytes).body;
if (!result) {
throw new Error('click inline keyboard button result empty');
@@ -155,10 +151,8 @@ export async function sendGroupSign(
},
};
await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0xEB7_1',
oidbCmd: 0xEB7, subCmd: 1,
request: { schema: Oidb0xeb7ReqSchema, value: req },
response: { schema: Oidb0xeb7RespSchema },
});
const env = makeOidbEnvelope<Oidb0xeb7Req>(0xEB7, 1, req);
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xEB7_1', encodeOidbEnv<Oidb0xeb7Req>(env));
// Decode just to maintain the original behaviour of "consume the response".
decodeOidbEnv<Oidb0xeb7Resp>(respBytes);
}
+28 -39
View File
@@ -4,25 +4,27 @@
import type { Bridge } from '../bridge';
import { protoDecode, protoEncode } from '../../protobuf/decode';
import { runOidb } from '../bridge-oidb';
import { runOidb, makeOidbEnvelope, encodeOidbEnv, decodeOidbEnv } from '../bridge-oidb';
import { fetchHighwaySession, uploadHighwayHttp } from '../highway/highway-client';
import { computeHashes, loadBinarySource } from '../highway/utils';
import {
FaceroamOpReqSchema,
FaceroamOpRespSchema,
GroupAvatarExtraSchema,
Oidb0x112aReqSchema,
Oidb0x112aRespSchema,
Oidb0x7edReqSchema,
Oidb0x7edRespSchema,
Oidb0xcd4ReqSchema,
Oidb0xcd4RespSchema,
Oidb0xe17ReqSchema,
Oidb0xe17RespSchema,
OidbSetProfileSchema,
SetStatusReqSchema,
SetStatusRespSchema,
} from '../proto/oidb-action';
import type {
Oidb0x112aReq,
Oidb0x112aResp,
Oidb0x7edReq,
Oidb0x7edResp,
Oidb0xcd4Req,
Oidb0xcd4Resp,
Oidb0xe17Req,
Oidb0xe17Resp,
OidbSetProfile,
} from '../proto/proton/oidb-action';
import { resolveSelfUid } from './shared';
// ─────────────── status / profile setters ───────────────
@@ -110,11 +112,8 @@ export async function setProfile(
stringProfiles,
};
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0x112a_2',
oidbCmd: 0x112A, subCmd: 2,
request: { schema: OidbSetProfileSchema, value: req },
});
const env = makeOidbEnvelope<OidbSetProfile>(0x112A, 2, req);
await runOidb(bridge, 'OidbSvcTrpcTcp.0x112a_2', encodeOidbEnv<OidbSetProfile>(env));
}
export async function setSelfLongNick(
@@ -129,12 +128,10 @@ export async function setSelfLongNick(
},
};
await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x112a_2',
oidbCmd: 0x112A, subCmd: 2,
request: { schema: Oidb0x112aReqSchema, value: req },
response: { schema: Oidb0x112aRespSchema },
});
const env = makeOidbEnvelope<Oidb0x112aReq>(0x112A, 2, req);
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x112a_2', encodeOidbEnv<Oidb0x112aReq>(env));
// Decode just to maintain the original behaviour of "consume the response".
decodeOidbEnv<Oidb0x112aResp>(respBytes);
}
export async function setInputStatus(
@@ -156,12 +153,10 @@ export async function setInputStatus(
},
};
await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0xcd4_1',
oidbCmd: 0xCD4, subCmd: 1,
request: { schema: Oidb0xcd4ReqSchema, value: req },
response: { schema: Oidb0xcd4RespSchema },
});
const env = makeOidbEnvelope<Oidb0xcd4Req>(0xCD4, 1, req);
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xcd4_1', encodeOidbEnv<Oidb0xcd4Req>(env));
// Decode just to maintain the original behaviour of "consume the response".
decodeOidbEnv<Oidb0xcd4Resp>(respBytes);
}
export async function setAvatar(
@@ -232,12 +227,9 @@ export async function getProfileLike(
limit: limit,
};
const result = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x7ed_12',
oidbCmd: 0x7ED, subCmd: 12,
request: { schema: Oidb0x7edReqSchema, value: req },
response: { schema: Oidb0x7edRespSchema },
});
const env = makeOidbEnvelope<Oidb0x7edReq>(0x7ED, 12, req);
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x7ed_12', encodeOidbEnv<Oidb0x7edReq>(env));
const result = decodeOidbEnv<Oidb0x7edResp>(respBytes).body;
const data = result?.userLikeInfos?.[0];
if (!data) {
@@ -277,12 +269,9 @@ export async function getUnidirectionalFriendList(
jsonBody: JSON.stringify(reqObj),
};
const result = await runOidb<any>(bridge, {
cmd: 'MQUpdateSvc_com_qq_ti.web.OidbSvc.0xe17_0',
oidbCmd: 0xE17, subCmd: 0,
request: { schema: Oidb0xe17ReqSchema, value: req },
response: { schema: Oidb0xe17RespSchema },
});
const env = makeOidbEnvelope<Oidb0xe17Req>(0xE17, 0, req);
const respBytes = await runOidb(bridge, 'MQUpdateSvc_com_qq_ti.web.OidbSvc.0xe17_0', encodeOidbEnv<Oidb0xe17Req>(env));
const result = decodeOidbEnv<Oidb0xe17Resp>(respBytes).body;
if (!result || !result.jsonBody) {
throw new Error('get unidirectional friend list empty');
+36 -54
View File
@@ -4,24 +4,24 @@ import type { Bridge } from './bridge';
import type { DownloadRKeyInfo } from './bridge';
import type { FriendInfo, QQGroupInfo, GroupMemberInfo, UserProfileInfo, GroupRequestInfo } from './qq-info';
import { protoDecode } from '../protobuf/decode';
import { runOidb } from './bridge-oidb';
import {
OidbSvcTrpcTcp0xFD4_1ResponseSchema,
OidbSvcTrpcTcp0xFE5_2ResponseSchema,
OidbSvcTrpcTcp0xFE7_3ResponseSchema,
OidbSvcTrpcTcp0x10C0ResponseSchema,
} from './proto/oidb';
import {
OidbFriendListRequestSchema,
OidbGroupListRequestSchema,
OidbGroupMemberListRequestSchema,
OidbUserInfoRequestSchema,
OidbUserInfoResponseSchema,
AvatarInfoSchema,
OidbGroupRequestListSchema,
NTV2RichMediaReqSchema,
NTV2RichMediaRespSchema,
} from './proto/oidb-action';
import { runOidb, makeOidbEnvelope, encodeOidbEnv, decodeOidbEnv } from './bridge-oidb';
import { AvatarInfoSchema } from './proto/oidb-action';
import type {
OidbSvcTrpcTcp0xFD4_1Response,
OidbSvcTrpcTcp0xFE5_2Response,
OidbSvcTrpcTcp0xFE7_3Response,
OidbSvcTrpcTcp0x10C0Response,
} from './proto/proton/oidb';
import type {
OidbFriendListRequest,
OidbGroupListRequest,
OidbGroupMemberListRequest,
OidbUserInfoRequest,
OidbUserInfoResponse,
OidbGroupRequestList,
NTV2RichMediaReq,
NTV2RichMediaResp,
} from './proto/proton/oidb-action';
// ---------------------------------------------------------------------------
// Helpers
@@ -71,12 +71,9 @@ export async function fetchFriendList(bridge: Bridge): Promise<FriendInfo[]> {
body.nextUin = { uin: nextUin };
}
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0xfd4_1',
oidbCmd: 0xFD4, subCmd: 1,
request: { schema: OidbFriendListRequestSchema, value: body },
response: { schema: OidbSvcTrpcTcp0xFD4_1ResponseSchema },
});
const env = makeOidbEnvelope<OidbFriendListRequest>(0xFD4, 1, body);
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xfd4_1', encodeOidbEnv<OidbFriendListRequest>(env));
const resp = decodeOidbEnv<OidbSvcTrpcTcp0xFD4_1Response>(respBytes).body;
if (resp?.friends) {
for (const raw of resp.friends) {
@@ -137,12 +134,9 @@ export async function fetchGroupList(bridge: Bridge): Promise<QQGroupInfo[]> {
},
};
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0xfe5_2',
oidbCmd: 0xFE5, subCmd: 2,
request: { schema: OidbGroupListRequestSchema, value: body, isUid: true },
response: { schema: OidbSvcTrpcTcp0xFE5_2ResponseSchema },
});
const env = makeOidbEnvelope<OidbGroupListRequest>(0xFE5, 2, body, true);
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xfe5_2', encodeOidbEnv<OidbGroupListRequest>(env));
const resp = decodeOidbEnv<OidbSvcTrpcTcp0xFE5_2Response>(respBytes).body;
const groups: QQGroupInfo[] = [];
if (resp?.groups) {
@@ -184,12 +178,9 @@ export async function fetchGroupMemberList(bridge: Bridge, groupId: number): Pro
};
if (token) body.token = token;
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0xfe7_3',
oidbCmd: 0xFE7, subCmd: 3,
request: { schema: OidbGroupMemberListRequestSchema, value: body },
response: { schema: OidbSvcTrpcTcp0xFE7_3ResponseSchema },
});
const env = makeOidbEnvelope<OidbGroupMemberListRequest>(0xFE7, 3, body);
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xfe7_3', encodeOidbEnv<OidbGroupMemberListRequest>(env));
const resp = decodeOidbEnv<OidbSvcTrpcTcp0xFE7_3Response>(respBytes).body;
if (resp?.members) {
for (const raw of resp.members) {
@@ -234,12 +225,9 @@ export async function fetchUserProfile(bridge: Bridge, uin: number): Promise<Use
// UID-form validation path, find neither uid nor openid in the body
// and bounce the request with `[oidb] one of uid/openid is invaild`.
// Matches Lagrange.Core's FetchStrangerByUin (Reserved = 1).
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0xfe1_2',
oidbCmd: 0xFE1, subCmd: 2,
request: { schema: OidbUserInfoRequestSchema, value: body, isUid: true },
response: { schema: OidbUserInfoResponseSchema },
});
const env = makeOidbEnvelope<OidbUserInfoRequest>(0xFE1, 2, body, true);
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xfe1_2', encodeOidbEnv<OidbUserInfoRequest>(env));
const resp = decodeOidbEnv<OidbUserInfoResponse>(respBytes).body;
if (!resp?.body) throw new Error('user info response body missing');
@@ -291,12 +279,9 @@ export async function fetchUserProfile(bridge: Bridge, uin: number): Promise<Use
export async function fetchGroupRequests(bridge: Bridge, filtered = false): Promise<GroupRequestInfo[]> {
const subCmd = filtered ? 2 : 1;
const cmd = filtered ? 'OidbSvcTrpcTcp.0x10c0_2' : 'OidbSvcTrpcTcp.0x10c0_1';
const resp = await runOidb<any>(bridge, {
cmd,
oidbCmd: 0x10C0, subCmd,
request: { schema: OidbGroupRequestListSchema, value: { count: 20, field2: 0 } },
response: { schema: OidbSvcTrpcTcp0x10C0ResponseSchema },
});
const env = makeOidbEnvelope<OidbGroupRequestList>(0x10C0, subCmd, { count: 20, field2: 0 });
const respBytes = await runOidb(bridge, cmd, encodeOidbEnv<OidbGroupRequestList>(env));
const resp = decodeOidbEnv<OidbSvcTrpcTcp0x10C0Response>(respBytes).body;
const requests: GroupRequestInfo[] = [];
for (const raw of resp?.requests ?? []) {
@@ -343,12 +328,9 @@ export async function fetchDownloadRKeys(bridge: Bridge): Promise<DownloadRKeyIn
},
};
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x9067_202',
oidbCmd: 0x9067, subCmd: 202,
request: { schema: NTV2RichMediaReqSchema, value: body, isUid: true },
response: { schema: NTV2RichMediaRespSchema },
});
const env = makeOidbEnvelope<NTV2RichMediaReq>(0x9067, 202, body, true);
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x9067_202', encodeOidbEnv<NTV2RichMediaReq>(env));
const resp = decodeOidbEnv<NTV2RichMediaResp>(respBytes).body;
if (resp?.respHead?.retCode && resp.respHead.retCode !== 0) {
throw new Error(resp.respHead.message ?? 'fetch download rkey failed');
@@ -22,6 +22,7 @@ import type {
SendMessageReceipt,
DownloadRKeyInfo,
ClientKeyInfo,
UploadedFileMeta,
} from './bridge';
import type { SendPacketResult } from '../protocol/packet-sender';
@@ -43,6 +44,18 @@ export interface BridgeInterface {
// ─── Send (messages) ───
sendGroupMessage(groupId: number, elements: MessageElement[]): Promise<SendMessageReceipt>;
sendPrivateMessage(userUin: number, elements: MessageElement[]): Promise<SendMessageReceipt>;
/**
* Send a c2c file as a chat message. Bypasses the regular elems[]
* pipeline because c2c files live on `RichText.notOnlineFile`, not
* inside the elems array. Group files go through `sendGroupMessage`
* with a `{type:'file', fileId, fileName, fileSize, md5Hex, sha1Hex}`
* element instead.
*/
sendC2cFileMessage(
userUin: number,
userUid: string,
info: { fileId: string; fileName: string; fileSize: number; fileMd5: Uint8Array; fileHash?: string },
): Promise<SendMessageReceipt>;
// ─── Fetch (contacts / profile / system) ───
fetchFriendList(): Promise<FriendInfo[]>;
@@ -77,6 +90,16 @@ export interface BridgeInterface {
// ─── Files ───
uploadGroupFile(groupId: number, file: string, name?: string, folderId?: string, uploadFile?: boolean): Promise<{ fileId: string | null }>;
uploadPrivateFile(userId: number, file: string, name?: string, uploadFile?: boolean): Promise<{ fileId: string | null }>;
/**
* Publish a previously-uploaded group file as a chat message via
* `OidbSvcTrpcTcp.0x6d9_4`. The atomic upload+publish flow inside
* `uploadGroupFile` already does this, but the OneBot send-message
* path needs it too for {type:'file', file_id} segments.
*/
sendGroupFileMessage(groupId: number, fileId: string): Promise<void>;
/** Cache file metadata so a later send_msg with just `file_id` can rehydrate it. */
rememberUploadedFile(meta: UploadedFileMeta): void;
recallUploadedFile(fileId: string): UploadedFileMeta | undefined;
fetchGroupFiles(groupId: number, folderId?: string): Promise<GroupFilesResult>;
fetchGroupFileUrl(groupId: number, fileId: string, busId?: number): Promise<string>;
fetchPrivateFileUrl(userId: number, fileId: string, fileHash: string): Promise<string>;
@@ -91,6 +114,14 @@ export interface BridgeInterface {
renameGroupFileFolder(groupId: number, folderId: string, newFolderName: string): Promise<void>;
fetchGroupFileCount(groupId: number): Promise<{ fileCount: number; maxCount: number }>;
// ─── Group Album ───
getGroupAlbumList(groupId: number): Promise<any>;
uploadImageToGroupAlbum(groupId: number, albumId: string, albumName: string, filePath: string): Promise<void>;
getGroupAlbumMediaList(groupId: number, albumId: string, attachInfo?: string): Promise<any>;
commentGroupAlbumMedia(groupId: number, albumId: string, lloc: string, content: string): Promise<any>;
deleteGroupAlbumMedia(groupId: number, albumId: string, lloc: string): Promise<any>;
likeGroupAlbumMedia(groupId: number, albumId: string, batchId: string, lloc: string | undefined, isLike: boolean): Promise<any>;
// ─── Forward ───
uploadForwardNodes(nodes: ForwardNodePayload[], groupId?: number, userId?: number): Promise<string>;
fetchForwardNodes(resId: string): Promise<ForwardNodePayload[]>;
+88 -83
View File
@@ -1,96 +1,101 @@
// One deep entry point for a single OIDB round-trip: build the envelope,
// dispatch via Bridge.sendRawPacket, validate the response status, and
// optionally decode the body. Replaces the three positional helpers
// (makeOidbRequest / sendOidbAndCheck / sendOidbAndDecode) that used to
// scatter the same five-step pattern across every action file.
// One deep entry point for a single OIDB round-trip: dispatch a
// pre-encoded envelope via Bridge.sendRawPacket, validate the envelope
// retCode, and return the raw response bytes.
//
// History note. The legacy implementation used a runtime
// `makeOidbBaseSchema(InnerSchema)` factory and ran a runtime
// schema-walking encoder. Proton is compile-time, so the envelope is
// the generic interface `OidbBase<T>` (proto/proton/oidb.ts). Proton's
// wrapper-binding requires *pass-through* wrappers (the wrapper's first
// arg must be forwarded unchanged to the inner codec — see
// proton/src/transform/replacer.ts), so this file exposes thin
// pass-through helpers (`encodeOidbEnv<T>` / `decodeOidbEnv<T>`) that
// proton monomorphizes at every call site. `runOidb` itself is
// non-generic — it just sends pre-encoded bytes and peeks at the
// envelope retCode via the non-generic `OidbBaseMeta` view.
import type { Bridge } from './bridge';
import type { ProtoSchema } from '../protobuf/decode';
import { protoEncode, protoDecode } from '../protobuf/decode';
import { makeOidbBaseSchema } from './proto/oidb';
import { protobuf_encode, protobuf_decode } from '@snowluma/proton';
import type { OidbBase, OidbBaseMeta } from './proto/proton/oidb';
export interface OidbCall<TResp = void> {
/** Service-cmd string sent on the wire, e.g. 'OidbSvcTrpcTcp.0x1253_1'. */
cmd: string;
/** OIDB command number, e.g. 0x1253. */
oidbCmd: number;
/** OIDB sub-command, e.g. 1. */
subCmd: number;
request: {
schema: ProtoSchema;
value: any;
/**
* Sets the OIDB envelope `reserved` field to 1 when true.
*
* The name is historical and misleading: empirically (see Lagrange
* FetchStrangerByUin vs FetchStrangerByUid, fetchGroupList, our own
* highway uploads) the `reserved = 1` flag indicates the UIN-form
* variant of an OIDB call — it tells newer QQ NT to translate the
* UIN in the body to an internal UID rather than running the
* UID-form validator that expects a uid/openid string in the body.
*
* Omit (default false) for genuinely UID-keyed calls.
*/
isUid?: boolean;
};
/** Omit to skip decoding the response body (fire-and-check). */
response?: {
schema: ProtoSchema;
/**
* Build the OidbBase<T>-shaped TS value. Pure helper, no protobuf
* encoding happens here — pair with `encodeOidbEnv<T>` to produce the
* wire bytes.
*
* The `isUid` flag sets the envelope `reserved` field to 1; despite the
* name (kept for back-compat with the legacy API), `reserved = 1`
* empirically signals the UIN-form variant of an OIDB call. Omit
* (default false) for genuinely UID-keyed calls.
*/
export function makeOidbEnvelope<T>(
oidbCmd: number,
subCmd: number,
body: T,
isUid: boolean = false,
): OidbBase<T> {
return {
command: oidbCmd,
subCommand: subCmd,
errorCode: 0,
body,
errorMsg: '',
reserved: isUid ? 1 : 0,
};
}
/**
* Issue one OIDB request. Without `response`, returns void after
* verifying the envelope's retCode. With `response`, decodes the
* envelope, validates retCode, and returns the inner body.
*
* Throws on transport failure, missing response, decode failure, or any
* non-zero envelope retCode. Action modules layer their own retCode
* checks (on inner sub-replies like `upload.retCode`) on top of this.
* Pass-through encoder for the OIDB envelope. Single type param, body
* literally forwards its arg to `protobuf_encode<OidbBase<T>>` — proton
* wrapper-binds this and replaces every `encodeOidbEnv<MyReq>(env)` call
* site with `protobuf_encode_OidbBase__MyReq(env)` at build time.
*/
export function runOidb(bridge: Bridge, call: OidbCall<void> & { response?: undefined }): Promise<void>;
export function runOidb<TResp>(bridge: Bridge, call: OidbCall<TResp> & { response: { schema: ProtoSchema } }): Promise<TResp>;
export async function runOidb<TResp>(bridge: Bridge, call: OidbCall<TResp>): Promise<TResp | void> {
const envelope = encodeOidbEnvelope(call);
const result = await bridge.sendRawPacket(call.cmd, envelope);
export function encodeOidbEnv<T>(env: OidbBase<T>): Uint8Array {
return protobuf_encode<OidbBase<T>>(env);
}
/**
* Pass-through decoder for the OIDB envelope. Mirror of `encodeOidbEnv`
* — proton monomorphizes `OidbBase<TResp>` per call site.
*
* Returns the full envelope; the caller usually wants `.body`.
*/
export function decodeOidbEnv<T>(bytes: Uint8Array): OidbBase<T> {
return protobuf_decode<OidbBase<T>>(bytes);
}
/**
* Issue one OIDB request and return the raw response bytes.
*
* Typical usage:
* const env = makeOidbEnvelope<MyReq>(0x1253, 1, value);
* const buf = await runOidb(bridge, cmd, encodeOidbEnv<MyReq>(env));
* const resp = decodeOidbEnv<MyResp>(buf).body;
*
* Fire-and-check (no body decode):
* await runOidb(bridge, cmd, encodeOidbEnv<MyReq>(env));
*
* Always peeks at the envelope errorCode via the non-generic
* `OidbBaseMeta` view so a server-side rejection cannot slip past
* silently. Returns the raw response bytes (empty `Uint8Array` if the
* packet carried no payload).
*/
export async function runOidb(
bridge: Bridge,
cmd: string,
envelopeBytes: Uint8Array,
): Promise<Uint8Array> {
const result = await bridge.sendRawPacket(cmd, envelopeBytes);
if (!result.success) throw new Error(result.errorMessage || 'packet send failed');
if (call.response) {
if (!result.gotResponse || !result.responseData) {
throw new Error(result.errorMessage || 'no response');
}
const baseSchema = makeOidbBaseSchema(call.response.schema);
const resp = protoDecode(result.responseData, baseSchema);
if (!resp) throw new Error('failed to decode OIDB response');
throwIfOidbError(resp);
return (resp as any).body as TResp;
}
// Fire-and-check: response data is optional, but if present we still
// peek at the envelope so a server-side retCode doesn't silently slip past.
if (!result.gotResponse) throw new Error(result.errorMessage || 'no response');
if (result.responseData && result.responseData.length > 0) {
const emptyBase = makeOidbBaseSchema({ _dummy: { field: 99, type: 'uint32' as const } });
const resp = protoDecode(result.responseData, emptyBase);
if (resp) throwIfOidbError(resp);
}
}
function encodeOidbEnvelope(call: OidbCall<unknown>): Uint8Array {
const baseSchema = makeOidbBaseSchema(call.request.schema);
return protoEncode({
command: call.oidbCmd,
subCommand: call.subCmd,
errorCode: 0,
body: call.request.value,
errorMsg: '',
reserved: call.request.isUid ? 1 : 0,
}, baseSchema);
}
function throwIfOidbError(resp: unknown): void {
const code = (resp as any).errorCode;
if (code && code !== 0) {
throw new Error(`OIDB error ${code}: ${(resp as any).errorMsg ?? ''}`);
const bytes = result.responseData ?? new Uint8Array(0);
if (bytes.length > 0) {
const meta = protobuf_decode<OidbBaseMeta>(bytes);
const code = meta?.errorCode;
if (code && code !== 0) {
throw new Error(`OIDB error ${code}: ${meta?.errorMsg ?? ''}`);
}
}
return bytes;
}
+231 -16
View File
@@ -7,16 +7,17 @@ import type { ForwardNodePayload, QQEventVariant, MessageElement } from './event
import type { FriendInfo, QQGroupInfo, GroupMemberInfo, UserProfileInfo, GroupRequestInfo } from './qq-info';
import { MSG_PUSH_CMD, parseMsgPush } from './msg-push';
import type { PacketSender, SendPacketResult } from '../protocol/packet-sender';
import { protoEncode, protoDecode } from '../protobuf/decode';
import { protobuf_encode, protobuf_decode } from '@snowluma/proton';
import { buildSendElems } from './element-builder';
import { IdentityService } from './identity-service';
import type { BridgeInterface } from './bridge-interface';
import { IncomingPacketPipeline, type CmdParser } from './packet-pipeline';
import { createLogger } from '../utils/logger';
import {
SendMessageRequestSchema,
SendMessageResponseSchema,
} from './proto/action';
import type {
SendMessageRequest,
SendMessageResponse,
} from './proto/proton/action';
import type { FileExtra } from './proto/proton/message';
// Delegated modules
import {
@@ -47,6 +48,7 @@ import {
import {
uploadGroupFile as uploadGroupFile_,
uploadPrivateFile as uploadPrivateFile_,
sendGroupFileMessage as sendGroupFileMessage_,
fetchGroupFiles as fetchGroupFiles_,
fetchGroupFileUrl as fetchGroupFileUrl_,
fetchPrivateFileUrl as fetchPrivateFileUrl_,
@@ -126,7 +128,14 @@ import {
getCookiesStr as getCookiesStr_,
getCsrfToken as getCsrfToken_,
getCredentials as getCredentials_,
getGroupAlbumListWeb as getGroupAlbumListWeb_,
uploadImageToGroupAlbumWeb as uploadImageToGroupAlbumWeb_,
} from './web-actions';
import { getGroupAlbumMediaList as getGroupAlbumMediaList_,
commentGroupAlbumMedia as commentGroupAlbumMedia_,
likeGroupAlbumMedia as likeGroupAlbumMedia_,
deleteGroupAlbumMedia as deleteGroupAlbumMedia_,
} from './actions/group-album';
import type { GroupFilesResult } from './actions/group-file';
import type { MediaIndexNode } from './actions/shared';
import { BridgeEventBus } from './event-bus';
@@ -139,6 +148,29 @@ export interface SendMessageReceipt {
timestamp: number;
}
/**
* Metadata remembered after `upload_group_file` / `upload_private_file`
* succeeds. Lets the OneBot send-message path reconstruct the full
* payload when the caller only echoes the `file_id` back later. See
* `Bridge.rememberUploadedFile` / `recallUploadedFile`.
*/
export interface UploadedFileMeta {
fileId: string;
scope: 'group' | 'private';
/** Group id if scope='group', else `undefined`. */
groupId?: number;
/** Friend uin if scope='private', else `undefined`. */
userId?: number;
fileName: string;
fileSize: number;
fileMd5: Uint8Array;
fileSha1: Uint8Array;
/** Server-issued hash returned alongside the upload (private only). */
fileHash?: string;
/** Insert time — used to evict the oldest entry when the cache fills. */
rememberedAt: number;
}
export interface DownloadRKeyInfo {
rkey: string;
ttlSeconds: number;
@@ -178,6 +210,24 @@ export class Bridge implements BridgeInterface {
private memberListInflight_ = new Map<number, Promise<GroupMemberInfo[]>>();
private memberListLastFetch_ = new Map<number, { at: number; data: GroupMemberInfo[] }>();
// ── Uploaded-file metadata cache ────────────────────────────────────
//
// After a file goes through `upload_group_file` / `upload_private_file`
// we remember the (fileName, fileSize, fileMd5, fileHash) tuple keyed
// by the returned file_id. The OneBot send-message paths consult this
// when the caller later passes `{type:'file', file_id:'xxx'}` without
// the rest of the metadata — c2c file send needs the size/md5/name
// for the wire packet (server-side rejection / "0 byte file" otherwise),
// and the group send path falls back to the name for the log line.
//
// Bounded at ~1024 entries with simple FIFO eviction. Files older
// than 7 days expire on QQ's side anyway, so this isn't load-bearing
// for correctness — just a UX convenience cache so the OneBot caller
// doesn't have to thread the metadata themselves between upload and
// send_msg.
private static readonly UPLOADED_FILE_CACHE_MAX = 1024;
private uploadedFileMeta_ = new Map<string, UploadedFileMeta>();
// Sequence and random generators for outgoing messages
private clientSeq_ = 100000000 + (Date.now() % 1000000000);
private msgRandom_ = (Date.now() & 0xFFFFFFFF) >>> 0;
@@ -244,6 +294,37 @@ export class Bridge implements BridgeInterface {
return true;
}
// --- Uploaded-file metadata cache ---
/**
* Remember a freshly-uploaded file so a later `send_*_msg` carrying
* just the file_id can reconstruct the full c2c-file packet (fileName
* / fileSize / fileMd5 are required by the QQ NT server's c2c file
* intake, even if only the uuid is needed for the OIDB lookup
* internally — without them the file shows as 0 B in the recipient's
* chat or is silently rejected). Insertion is FIFO; oldest entry is
* evicted when the cache hits `UPLOADED_FILE_CACHE_MAX`.
*/
rememberUploadedFile(meta: UploadedFileMeta): void {
if (!meta.fileId) return;
if (this.uploadedFileMeta_.size >= Bridge.UPLOADED_FILE_CACHE_MAX) {
// Map iteration order is insertion order — drop the oldest.
const oldest = this.uploadedFileMeta_.keys().next().value;
if (oldest !== undefined) this.uploadedFileMeta_.delete(oldest);
}
this.uploadedFileMeta_.set(meta.fileId, meta);
}
/**
* Recall metadata for a previously-uploaded file. Returns `undefined`
* if the file_id was never uploaded through this bridge instance, or
* if it's been evicted from the cache.
*/
recallUploadedFile(fileId: string): UploadedFileMeta | undefined {
if (!fileId) return undefined;
return this.uploadedFileMeta_.get(fileId);
}
// --- Sequence / random generators ---
private nextClientSequence(): number {
@@ -275,13 +356,13 @@ export class Bridge implements BridgeInterface {
const protoElems = await buildSendElems(elements, { bridge: this, groupId });
const random = this.nextMessageRandom();
const request = protoEncode({
const request = protobuf_encode<SendMessageRequest>({
routingHead: {
grp: { groupCode: BigInt(groupId) },
} as any,
},
contentHead: {
type: 1,
} as any,
},
messageBody: {
richText: {
elems: protoElems,
@@ -293,7 +374,7 @@ export class Bridge implements BridgeInterface {
via: 0,
dataStatist: 0,
multiSendSeq: 0,
}, SendMessageRequestSchema);
});
const result = await this.sendRawPacket(Bridge.SEND_MSG_CMD, request);
@@ -301,7 +382,7 @@ export class Bridge implements BridgeInterface {
throw new Error(`send group message failed: ${result.errorMessage || 'no response'}`);
}
const response = protoDecode(result.responseData, SendMessageResponseSchema);
const response = protobuf_decode<SendMessageResponse>(result.responseData);
if (!response) {
throw new Error('failed to decode SendMessageResponse');
}
@@ -336,18 +417,18 @@ export class Bridge implements BridgeInterface {
const random = this.nextMessageRandom();
const clientSeq = this.nextClientSequence();
const request = protoEncode({
const request = protobuf_encode<SendMessageRequest>({
routingHead: {
c2c: {
uin: userUin,
...(userUid ? { uid: userUid } : {}),
},
} as any,
},
contentHead: {
type: 1,
subType: 0,
c2cCmd: 11,
} as any,
},
messageBody: {
richText: {
elems: protoElems,
@@ -360,9 +441,9 @@ export class Bridge implements BridgeInterface {
dataStatist: 0,
ctrl: {
msgFlag: Math.floor(Date.now() / 1000),
} as any,
},
multiSendSeq: 0,
}, SendMessageRequestSchema);
});
const result = await this.sendRawPacket(Bridge.SEND_MSG_CMD, request);
@@ -370,7 +451,7 @@ export class Bridge implements BridgeInterface {
throw new Error(`send private message failed: ${result.errorMessage || 'no response'}`);
}
const response = protoDecode(result.responseData, SendMessageResponseSchema);
const response = protobuf_decode<SendMessageResponse>(result.responseData);
if (!response) {
throw new Error('failed to decode SendMessageResponse');
}
@@ -391,6 +472,113 @@ export class Bridge implements BridgeInterface {
};
}
/**
* Send a c2c file as a chat message.
*
* The wire shape isn't the same as a regular c2c message — the c2c
* file path uses three slots that differ from a normal text/image
* send (verified against `dev/Lagrange.Core/.../MessagePacker.cs:
* BuildPacketBase` + `FileEntity.PackMessageContent`):
*
* 1. `routingHead.trans0x211 { ccCmd: 4, uid: peer }` instead of
* `routingHead.c2c { uin, uid }`. The server rejects c2c file
* messages routed through the regular c2c slot.
* 2. `messageBody.msgContent` carries the serialised
* `FileExtra { file: NotOnlineFile }` bytes. NOT
* `richText.notOnlineFile` — the receiver doesn't read that
* slot for file metadata.
* 3. `contentHead.c2cCmd` left at 0 (Lagrange's default). The
* previous `c2cCmd: 11` was a stale go-cqhttp value the QQ-NT
* server doesn't recognise.
*
* NotOnlineFile carries three required-on-send fields the receiver
* itself ignores but the server's intake validator checks:
* - `subcmd: 1` — c2c file send command code
* - `dangerEvel: 0` — virus-scan severity, always 0 client-side
* - `expireTime` — 7 days from now (Lagrange convention)
*/
async sendC2cFileMessage(
userUin: number,
userUid: string,
info: { fileId: string; fileName: string; fileSize: number; fileMd5: Uint8Array; fileHash?: string },
): Promise<SendMessageReceipt> {
const random = this.nextMessageRandom();
const clientSeq = this.nextClientSequence();
const nowSec = Math.floor(Date.now() / 1000);
const sevenDaysSec = 7 * 24 * 60 * 60;
// Serialise `FileExtra { file: NotOnlineFile }` for `msgContent`.
// The NotOnlineFile field tags (1/3/4/5/6/9/50/55/57) are shared
// between send and receive — the schema is symmetric.
const fileExtraBytes = protobuf_encode<FileExtra>({
file: {
fileType: 0,
fileUuid: info.fileId,
fileMd5: info.fileMd5,
fileName: info.fileName,
fileSize: BigInt(info.fileSize),
subcmd: 1,
dangerEvel: 0,
expireTime: nowSec + sevenDaysSec,
fileHash: info.fileHash ?? '',
},
});
const request = protobuf_encode<SendMessageRequest>({
routingHead: {
// c2c-file scene: route through `trans0x211` (field 15) with
// ccCmd=4. The regular `c2c { uin, uid }` routing slot causes
// the server to reject this with a routing-mismatch error.
trans0x211: { ccCmd: 4, uid: userUid },
},
contentHead: {
type: 1,
subType: 0,
// c2cCmd intentionally omitted (defaults to 0). Was `11`,
// which produced an unknown-command error in the QQ-NT
// server's c2c file handler. `userUin` is unused on this path
// (routing carries the uid only) but kept in the function
// signature for symmetry with the OneBot caller.
},
messageBody: {
// No elems — the file metadata lives in msgContent below.
msgContent: fileExtraBytes,
},
clientSequence: clientSeq,
random,
syncCookie: new Uint8Array(0),
via: 0,
dataStatist: 0,
ctrl: {
msgFlag: nowSec,
},
multiSendSeq: 0,
});
// Silence the unused-parameter lint — `userUin` is part of our
// BridgeInterface contract (the OneBot layer threads it through)
// but the wire shape only needs the uid.
void userUin;
const result = await this.sendRawPacket(Bridge.SEND_MSG_CMD, request);
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(`send c2c file message failed: ${result.errorMessage || 'no response'}`);
}
const response = protobuf_decode<SendMessageResponse>(result.responseData);
if (!response) {
throw new Error('failed to decode SendMessageResponse');
}
if (response.result !== undefined && response.result !== 0) {
throw new Error(`send c2c file message rejected: result=${response.result} err=${response.errMsg ?? ''}`);
}
const seq = response.privateSequence ?? 0;
const messageId = (random & 0x7FFFFFFF) || seq;
const timestamp = response.timestamp1 ?? Math.floor(Date.now() / 1000);
return { messageId, sequence: seq, clientSequence: clientSeq, random, timestamp };
}
// --- Delegated: OIDB helpers ---
async resolveUserUid(uin: number, groupId?: number): Promise<string> {
@@ -447,6 +635,9 @@ export class Bridge implements BridgeInterface {
async uploadPrivateFile(userId: number, file: string, name = '', uploadFile = true): Promise<{ fileId: string | null }> {
return uploadPrivateFile_(this, userId, file, name, uploadFile);
}
async sendGroupFileMessage(groupId: number, fileId: string): Promise<void> {
return sendGroupFileMessage_(this, groupId, fileId);
}
async fetchGroupFiles(groupId: number, folderId = '/'): Promise<GroupFilesResult> { return fetchGroupFiles_(this, groupId, folderId); }
async fetchGroupFileUrl(groupId: number, fileId: string, busId = 102): Promise<string> { return fetchGroupFileUrl_(this, groupId, fileId, busId); }
async fetchPrivateFileUrl(userId: number, fileId: string, fileHash: string): Promise<string> { return fetchPrivateFileUrl_(this, userId, fileId, fileHash); }
@@ -484,6 +675,30 @@ export class Bridge implements BridgeInterface {
return getGroupEssenceAll_(this, groupId);
}
async getGroupAlbumList(groupId: number): Promise<any> {
return getGroupAlbumListWeb_(this, groupId);
}
async uploadImageToGroupAlbum(groupId: number, albumId: string, albumName: string, filePath: string): Promise<void> {
return uploadImageToGroupAlbumWeb_(this, groupId, albumId, albumName, filePath);
}
async getGroupAlbumMediaList(groupId: number, albumId: string, attachInfo?: string): Promise<any> {
return getGroupAlbumMediaList_(this, groupId, albumId, attachInfo);
}
async commentGroupAlbumMedia(groupId: number, albumId: string, lloc: string, content: string): Promise<any> {
return commentGroupAlbumMedia_(this, groupId, albumId, lloc, content);
}
async likeGroupAlbumMedia(groupId: number, albumId: string, batchId: string, lloc: string | undefined, isLike: boolean): Promise<any> {
return likeGroupAlbumMedia_(this, groupId, albumId, batchId, lloc, isLike);
}
async deleteGroupAlbumMedia(groupId: number, albumId: string, lloc: string): Promise<any> {
return deleteGroupAlbumMedia_(this, groupId, albumId, lloc);
}
async sendGroupNotice(groupId: number, content: string, options?: any) {
return sendGroupNotice_(this, groupId, content, options);
}
+114 -8
View File
@@ -5,17 +5,19 @@
import type { Bridge } from './bridge';
import type { MessageElement } from './events';
import type { ProtoDecoded } from '../protobuf/decode';
import { protoEncode } from '../protobuf/decode';
import { protobuf_encode } from '@snowluma/proton';
import {
ElemSchema,
} from './proto/element';
import {
MentionExtraSendSchema,
MarkdownDataSchema,
} from './proto/action';
import type {
MentionExtraSend,
MarkdownData,
} from './proto/proton/action';
import type { GroupFileExtra } from './proto/proton/element';
import { uploadImageMsgInfo } from './highway/image-upload';
import { uploadPttMsgInfo } from './highway/ptt-upload';
import { uploadVideoMsgInfo } from './highway/video-upload';
import { hexToBytes } from './highway/pipeline';
type ProtoElem = Partial<ProtoDecoded<typeof ElemSchema>>;
@@ -23,6 +25,18 @@ export interface SendContext {
bridge: Bridge;
groupId?: number;
userUid?: string;
/**
* Set by the forward-message upload path. When `true`, file segments
* are encoded as receive-side wire shapes (group → `transElem(24)`,
* c2c → caller writes `body.msgContent` separately) instead of being
* dropped. The QQ-NT server rejects outgoing PbSendMsg with
* `transElem(24)` (result=79), but the long-msg upload service does
* NOT — it stores the gzipped protobuf verbatim, so the receiver
* can walk it back through the regular decoder. Mirrors NapCat's
* `PacketMsgFileElement.buildElement` + `buildContent` split (see
* `dev/napcatQQ/.../packet/message/element.ts:530-610`).
*/
forwardFake?: boolean;
}
function makeTextElem(text: string): ProtoElem {
@@ -51,12 +65,12 @@ function makeMentionElem(element: MessageElement, ctx?: SendContext): ProtoElem
const mentionAll = element.uid === 'all' || element.targetUin === 0;
const targetUin = element.targetUin ?? 0;
const extra = protoEncode({
const extra = protobuf_encode<MentionExtraSend>({
type: mentionAll ? 1 : 2,
uin: mentionAll ? 0 : targetUin,
field5: 0,
uid: mentionAll ? 'all' : (element.uid ?? ''),
}, MentionExtraSendSchema);
});
// Prefer an explicit display string from the caller; otherwise look the
// target up in the roster so QQ renders `@昵称` instead of `@QQ号`.
@@ -128,7 +142,7 @@ function makeXmlElem(element: MessageElement): ProtoElem {
}
function makeMarkdownElem(element: MessageElement): ProtoElem {
const data = protoEncode({ content: element.text ?? '' }, MarkdownDataSchema);
const data = protobuf_encode<MarkdownData>({ content: element.text ?? '' });
return {
commonElem: {
@@ -244,6 +258,62 @@ async function makePttElem(ctx: SendContext, element: MessageElement): Promise<P
};
}
/**
* Receive-side group file element shape — `transElem(elemType=24,
* elemValue: 0x01 | BE16(len) | GroupFileExtra)`.
*
* NOT used for outgoing PbSendMsg (the QQ-NT server rejects that with
* result=79); the group-file send-side flow goes through dedicated
* OIDB 0x6d9_4 via `bridge.sendGroupFileMessage`. This shape IS used
* inside the long-msg upload (forward / multi-msg) — the long-msg
* service stores the gzipped protobuf verbatim, and the receiver
* decodes file entities from `transElem(24)` (see
* `msg-push/rich-body-decoder.ts:169-187`).
*/
function makeGroupFileElem(element: MessageElement): ProtoElem {
if (!element.fileId) throw new Error('file element missing fileId');
const fileSize = element.fileSize ?? 0;
const fileName = element.fileName ?? '';
const md5 = element.md5Hex ? hexToBytes(element.md5Hex) : new Uint8Array(0);
const sha1 = element.sha1Hex ? hexToBytes(element.sha1Hex) : new Uint8Array(0);
// Outer field1 is hardcoded to 6 in NapCat's encoder
// (`packet/message/element.ts:589`). Inner GroupFileExtraInfo carries
// busId=102 + the file_id + name + size + sha1/md5 hashes.
const extraBytes = protobuf_encode<GroupFileExtra>({
field1: 6,
fileName,
inner: {
info: {
busId: 102,
fileId: element.fileId,
fileSize: BigInt(fileSize),
fileName,
fileSha: sha1,
extInfoString: '',
fileMd5: md5,
},
},
});
if (extraBytes.length > 0xFFFF) {
// The 16-bit length prefix caps the payload at 64 KiB; even the
// densest GroupFileExtra (fileId/name/two hashes) is well under.
throw new Error(`group file extra too large (${extraBytes.length} > 65535)`);
}
const elemValue = new Uint8Array(3 + extraBytes.length);
elemValue[0] = 0x01;
elemValue[1] = (extraBytes.length >> 8) & 0xff;
elemValue[2] = extraBytes.length & 0xff;
elemValue.set(extraBytes, 3);
return {
transElem: {
elemType: 24,
elemValue,
} as any,
};
}
async function makeVideoElem(ctx: SendContext, element: MessageElement): Promise<ProtoElem> {
const isGroup = ctx.groupId !== undefined;
const targetIdOrUid = isGroup ? ctx.groupId! : (ctx.userUid ?? '');
@@ -331,6 +401,42 @@ export async function buildSendElems(elements: MessageElement[], ctx?: SendConte
}
break;
case 'file':
// Files split into two routes depending on whether this is a
// live send or a forward-message fake-send:
//
// 1. LIVE send (PbSendMsg / OIDB 0x6d9_4) — never carried on
// elems[]. The OneBot layer splits file segments off before
// calling buildSendElems:
// * c2c (private): split → `bridge.sendC2cFileMessage`
// (routingHead.trans0x211 + msgContent FileExtra).
// * group: split → `bridge.sendGroupFileMessage`
// (OIDB 0x6d9_4 publish).
// The QQ-NT server REJECTS outgoing PbSendMsg with a
// transElem(24) (result=79), so an element reaching here
// in live-send mode is a routing bug — drop with a warn.
//
// 2. FORWARD-FAKE upload (long-msg) — `ctx.forwardFake===true`.
// The long-msg service stores the gzipped protobuf verbatim
// and the receiver decodes file entities from transElem(24)
// + msgContent FileExtra. Mirror NapCat's split (see
// `dev/napcatQQ/.../packet/message/element.ts:530-610`):
// * group → emit transElem(24) via makeGroupFileElem
// * c2c → emit NOTHING here; the forward-builder pulls
// the file segment off and writes msgContent
// separately (because RichText.notOnlineFile +
// FileExtra both live outside elems[]).
if (ctx && ctx.forwardFake) {
if (ctx.groupId !== undefined) {
result.push(makeGroupFileElem(elem));
}
// c2c forwardFake intentionally falls through — handled by
// the forward-builder at the msgContent level.
} else {
console.warn('[ElemBuilder] BUG: {type:"file"} reached element-builder — must be split out at the OneBot layer (see modules/message-actions.ts::sendPrivateMessage / ::sendGroupMessage)');
}
break;
default:
console.warn(`[ElemBuilder] unsupported element type for send: ${elem.type}`);
break;
+12
View File
@@ -83,6 +83,18 @@ export interface ForwardNodePayload {
groupId?: number;
senderCard?: string;
messageType?: 'group' | 'private';
// When set, this node's `content` is a nested forward chain. The
// upload pipeline (see `actions/forward.ts::uploadForwardNodes`)
// recursively uploads the inner chain and replaces this node's
// `elements` with an ARK preview element pointing at the inner
// res_id. We also piggyback the inner chain's msgBody onto the
// outer long-msg upload as an extra `actionCommand` slot so the
// NapCat-compatible receiver can walk the whole tree from one
// server fetch without resolving each layer's res_id separately
// (modelled after `dev/NapCatQQ/.../SendMsg.uploadForwardedNodesPacket`).
// Caller never sets this on top-level OneBot input — `parseForward
// Nodes` synthesises it when it detects a nested-node array.
innerForward?: ForwardNodePayload[];
}
export interface QQEvent {
@@ -3,15 +3,14 @@
import net from 'net';
import type { Bridge } from '../bridge';
import { protoEncode, protoDecode } from '../../protobuf/decode';
import {
HttpConn0x6FF501RequestSchema,
HttpConn0x6FF501ResponseSchema,
ReqDataHighwayHeadSchema,
RespDataHighwayHeadSchema,
NTV2RichMediaHighwayExtSchema,
HighwayMsgInfoBodySchema,
} from '../proto/highway';
import { protobuf_encode, protobuf_decode } from '@snowluma/proton';
import type {
HttpConn0x6FF501Request,
HttpConn0x6FF501Response,
ReqDataHighwayHead,
RespDataHighwayHead,
NTV2RichMediaHighwayExt,
} from '../proto/proton/highway';
import { packHighwayFrame, unpackHighwayFrame, computeMd5 } from './utils';
const HIGHWAY_APP_ID = 1600001604;
@@ -32,20 +31,20 @@ function ipv4ToString(value: number): string {
}
export async function fetchHighwaySession(bridge: Bridge): Promise<HighwaySession> {
const request = protoEncode({
const request = protobuf_encode<HttpConn0x6FF501Request>({
httpConn: {
field1: 0, field2: 0, field3: 16, field4: 1, field6: 3,
serviceTypes: [1, 5, 10, 21],
field9: 2, field10: 9, field11: 8, ver: '1.0.1',
},
}, HttpConn0x6FF501RequestSchema);
});
const result = await bridge.sendRawPacket('HttpConn.0x6ff_501', request);
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(result.errorMessage || 'HttpConn request failed');
}
const resp = protoDecode(result.responseData, HttpConn0x6FF501ResponseSchema);
const resp = protobuf_decode<HttpConn0x6FF501Response>(result.responseData);
if (!resp?.httpConn) throw new Error('HttpConn response body missing');
if (!resp.httpConn.sigSession || (resp.httpConn.sigSession as Uint8Array).length === 0) {
throw new Error('HttpConn response missing sig_session');
@@ -78,7 +77,7 @@ function makeHighwayHead(
uin: string, commandId: number, fileSize: number, offset: number, length: number,
chunkMd5: Uint8Array, fileMd5: Uint8Array, sigSession: Uint8Array, extend: Uint8Array,
): Uint8Array {
return protoEncode({
return protobuf_encode<ReqDataHighwayHead>({
msgBaseHead: {
version: 1, uin, command: 'PicUp.DataUp', seq: 0, retryTimes: 0,
appId: HIGHWAY_APP_ID, dataFlag: 16, commandId,
@@ -90,7 +89,7 @@ function makeHighwayHead(
bytesReqExtendInfo: extend,
timestamp: 0n,
msgLoginSigHead: { loginSigType: 8, appId: HIGHWAY_APP_ID },
}, ReqDataHighwayHeadSchema);
});
}
export function buildHighwayExtend(
@@ -113,7 +112,7 @@ export function buildHighwayExtend(
}
}
return protoEncode({
return protobuf_encode<NTV2RichMediaHighwayExt>({
fileUuid: selected?.index?.fileUuid ?? '',
uKey,
network: { ipv4s: networkIpv4s },
@@ -122,7 +121,7 @@ export function buildHighwayExtend(
})),
blockSize: HIGHWAY_BLOCK_SIZE,
hash: { fileSha1: Array.isArray(sha1) ? sha1 : [sha1] },
}, NTV2RichMediaHighwayExtSchema);
});
}
// --- TCP-based HTTP highway upload ---
@@ -241,7 +240,7 @@ export async function uploadHighwayHttp(
const frame = packHighwayFrame(head, chunk);
const responseBody = await httpPostFrame(socket, session.host, pathStr, frame);
const { head: respHead } = unpackHighwayFrame(responseBody);
const resp = protoDecode(respHead, RespDataHighwayHeadSchema);
const resp = protobuf_decode<RespDataHighwayHead>(respHead);
if (resp?.errorCode && resp.errorCode !== 0) {
throw new Error(`highway upload error_code=${resp.errorCode}`);
}
+13 -16
View File
@@ -17,13 +17,13 @@
import crypto from 'crypto';
import type { Bridge } from '../bridge';
import { protoDecode, protoEncode } from '../../protobuf/decode';
import { makeOidbBaseSchema } from '../proto/oidb';
import {
EncodableMediaMsgInfoSchema,
NTV2UploadRichMediaReqSchema,
NTV2UploadRichMediaRespSchema,
} from '../proto/highway';
import { protobuf_encode } from '@snowluma/proton';
import { makeOidbEnvelope, encodeOidbEnv, decodeOidbEnv } from '../bridge-oidb';
import type {
EncodableMediaMsgInfo,
NTV2UploadRichMediaReq,
NTV2UploadRichMediaResp,
} from '../proto/proton/highway';
import { buildHighwayExtend, fetchHighwaySession, uploadHighwayHttp } from './highway-client';
import { createLogger } from '../../utils/logger';
@@ -159,24 +159,21 @@ export async function runNtv2Upload(params: NtV2UploadParams): Promise<any> {
},
};
const baseSchema = makeOidbBaseSchema(NTV2UploadRichMediaReqSchema);
const request = protoEncode({
command: oidbCmd, subCommand: 100, errorCode: 0, body, errorMsg: '', reserved: 1,
}, baseSchema);
const env = makeOidbEnvelope<NTV2UploadRichMediaReq>(oidbCmd, 100, body, true);
const requestBytes = encodeOidbEnv<NTV2UploadRichMediaReq>(env);
const result = await bridge.sendRawPacket(serviceCmd, request);
const result = await bridge.sendRawPacket(serviceCmd, requestBytes);
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(result.errorMessage || `${label} upload request failed`);
}
const respBaseSchema = makeOidbBaseSchema(NTV2UploadRichMediaRespSchema);
const resp: any = protoDecode(result.responseData, respBaseSchema);
const resp = decodeOidbEnv<NTV2UploadRichMediaResp>(result.responseData);
if (!resp) throw new Error(`failed to decode ${label} upload response`);
if (resp.errorCode && resp.errorCode !== 0) {
throw new Error(`OIDB error ${resp.errorCode}: ${resp.errorMsg ?? ''}`);
}
const uploadBody = resp.body;
const uploadBody: any = resp.body;
if (!uploadBody) throw new Error(`${label} upload response body missing`);
if (uploadBody.respHead?.retCode && uploadBody.respHead.retCode !== 0) {
throw new Error(uploadBody.respHead.message ?? `${label} upload failed`);
@@ -262,5 +259,5 @@ export function finalizeMediaMsgInfo(
extBizInfo.busiType = upload.msgInfo.extBizInfo.busiType;
}
return protoEncode({ msgInfoBody, extBizInfo }, EncodableMediaMsgInfoSchema);
return protobuf_encode<EncodableMediaMsgInfo>({ msgInfoBody, extBizInfo });
}
@@ -480,14 +480,24 @@ export async function uploadVideoMsgInfo(
fileHash: video.md5Hex,
fileSha1: video.sha1Hex,
fileName: 'nya.mp4',
// NapCat sends type.videoFormat=0 and width/height/time=0
// for the main video sub-file (only the thumb carries
// dimensions). The QQ NT server treats non-zero values
// here as a schema mismatch on c2c sends.
type: { type: 2, picFormat: 0, videoFormat: 0, voiceFormat: 0 },
// Width/height kept at 0 — NapCat does the same and the QQ-NT
// server has been observed to reject non-zero dimensions
// here on c2c sends with a schema-mismatch error. acidify
// *does* fill them (`payload.videoWidth/Height`) but we
// leave that alone until c2c regression coverage exists.
height: 0,
width: 0,
time: 0,
// `time` MUST be the real duration in seconds, otherwise
// every receiving client renders "00:00" on the video.
// NapCat ships `time: 0` because it sits on top of QQ-NT's
// IPC layer, which the desktop client patches up before
// the wire message goes out. We're a protocol-direct
// client (same position as acidify), so we own this field.
// acidify writes `payload.videoDuration` here for the same
// reason — verified against `RichMediaUpload.kt::
// buildVideoUploadInfoList` (2026-04 refactor).
time: video.duration,
original: 0,
},
subFileType: 0,
@@ -1,13 +1,29 @@
// Handles Event0x210 wrapper (528). Internal switch on subType dispatches
// to FriendRequest (35) / FriendRecall (138) / FriendPoke (290).
// to FriendRequest (35) / FriendRecall (138, 139) / NewFriend
// (179, 226) / FriendPoke (290).
import { protoDecode } from '../../../protobuf/decode';
import {
FriendRequestSchema, FriendRecallSchema, GeneralGrayTipInfoSchema,
} from '../../proto/notify';
import { protobuf_decode } from '@snowluma/proton';
// Proto types imported unaliased — proton's import-resolver registers
// `importedTypeSources` keyed on the *imported* name. If we also did
// `import type { FriendRecall } from '../../events'` it would shadow
// the proto-side mapping (last-write-wins), point the resolver at the
// event-side file which has no `pb<>` schema, and the codec would
// never get generated — `protobuf_decode<FriendRecall>(...)` then
// falls through to the runtime fallback and throws (silently caught
// by `MsgPushRegistry.decode`). The event-side colliding names are
// re-derived from `QQEventVariant` below via `Extract` instead.
import type {
FriendRequestEvent, FriendRecall, FriendPokeEvent, QQEventVariant,
FriendRequest,
FriendRecall,
GeneralGrayTipInfo,
NewFriend,
} from '../../proto/proton/notify';
import type {
FriendRequestEvent, FriendPokeEvent,
FriendAddEvent, QQEventVariant,
} from '../../events';
type FriendRecallEvent = Extract<QQEventVariant, { kind: 'friend_recall' }>;
import type { MsgPushDecoder } from '../registry';
import type { MsgPushContext } from '../context';
import { Event0x210SubType } from '../enums';
@@ -21,15 +37,38 @@ const unknownLog = createLogger('MsgPush.Unknown');
export const decodeEvent0x210: MsgPushDecoder = (ctx) => {
switch (ctx.head.subType as Event0x210SubType) {
case Event0x210SubType.FriendRequestNotice: return decodeFriendRequest(ctx);
case Event0x210SubType.FriendRecallNotice: return decodeFriendRecall(ctx);
// 138 (other-recalled) and 139 (self-recalled) share the same
// FriendRecall wire shape; the helper picks the right uid side
// based on the subType.
case Event0x210SubType.FriendRecallNotice:
case Event0x210SubType.FriendRecallSelfNotice:
return decodeFriendRecall(ctx);
case Event0x210SubType.FriendPokeNotice: return decodeFriendPoke(ctx);
// 179 + 226 both carry the NewFriend payload — see enum comment.
case Event0x210SubType.NewFriendNotice:
case Event0x210SubType.NewFriendNoticeAlt:
return decodeNewFriend(ctx);
case Event0x210SubType.GroupAppStatePush:
// QQ-client-internal troop shortcut bar / discussion app state
// push — no OneBot-level event. See enum comment for the
// decompiled-source breakdown of the sub_cmd dispatch.
return [];
case Event0x210SubType.UnmappedClientState380:
// QQ-NT-era subType with no reference handler: the legacy QQ
// Android decompile (tsuzcx/qq_apk) only enumerates SubType0x26
// through SubType0x146 under msgType0x210/, so 380 / 0x17C is
// an NT-era addition. None of the NT clients (Lagrange.Core,
// LagrangeGo, lagrange-python, mania) handle it either. See the
// enum comment for the full investigation; acknowledge silently
// until someone maps the schema.
return [];
}
unknownLog.debug('Event0x210 unknown subType=%d', ctx.head.subType);
return [];
};
function decodeFriendRequest(ctx: MsgPushContext): QQEventVariant[] {
const request = protoDecode(ctx.content, FriendRequestSchema);
const request = protobuf_decode<FriendRequest>(ctx.content);
if (!request?.info) return [];
const sourceUid = request.info.newSource || request.info.sourceUid || '';
const ev: FriendRequestEvent = {
@@ -45,20 +84,45 @@ function decodeFriendRequest(ctx: MsgPushContext): QQEventVariant[] {
}
function decodeFriendRecall(ctx: MsgPushContext): QQEventVariant[] {
const recall = protoDecode(ctx.content, FriendRecallSchema);
const recall = protobuf_decode<FriendRecall>(ctx.content);
if (!recall?.info) return [];
const ev: FriendRecall = {
// 138 = friend recalled their own message sent to bot (peer = fromUid).
// 139 = bot recalled own message sent to friend (peer = toUid). Same
// ambiguity acidify handles in `parseFriendRecall:380`. Without this
// split, self-recall events surface `userUin` as the bot itself which
// confuses downstream OneBot consumers that key off `user_id`.
const isSelfRecall = ctx.head.subType === Event0x210SubType.FriendRecallSelfNotice;
const peerUid = (isSelfRecall ? recall.info.toUid : recall.info.fromUid) ?? '';
const ev: FriendRecallEvent = {
kind: 'friend_recall',
time: recall.info.time ?? ctx.head.timestamp,
selfUin: ctx.selfUin,
userUin: resolveUidToUin(ctx.identity, 0, recall.info.fromUid ?? '', ctx.fromUin),
userUin: resolveUidToUin(ctx.identity, 0, peerUid, ctx.fromUin),
msgSeq: recall.info.clientSequence ?? 0,
};
return [ev];
}
function decodeNewFriend(ctx: MsgPushContext): QQEventVariant[] {
const nf = protobuf_decode<NewFriend>(ctx.content);
if (!nf?.info) return [];
const newFriendUid = nf.info.uid ?? '';
const newFriendUin = resolveUidToUin(ctx.identity, 0, newFriendUid, ctx.fromUin);
if (newFriendUin <= 0) return []; // can't surface a `user_id`-less friend_add to OneBot
const ev: FriendAddEvent = {
kind: 'friend_add',
// proto field is `fixed32 Time` — already uint32 seconds epoch.
// Fall back to head.timestamp if the field is missing (some
// captures have it as 0).
time: nf.info.time && nf.info.time > 0 ? nf.info.time : ctx.head.timestamp,
selfUin: ctx.selfUin,
userUin: newFriendUin,
};
return [ev];
}
function decodeFriendPoke(ctx: MsgPushContext): QQEventVariant[] {
const grayTip = protoDecode(ctx.content, GeneralGrayTipInfoSchema);
const grayTip = protobuf_decode<GeneralGrayTipInfo>(ctx.content);
if (!grayTip || (grayTip.busiType ?? 0n) !== 12n) return [];
const templates = buildTemplateMap(grayTip.msgTemplParam ?? []);
const actor = findTemplateValue(templates, 'uin_str1');
@@ -2,10 +2,10 @@
// to GroupMute (12) / GroupMsgEmojiLike (16) / GroupRecall (17) /
// GroupGreyTip (20) / GroupEssence (21).
import { protoDecode } from '../../../protobuf/decode';
import {
GroupMuteSchema, NotifyMessageBodySchema, GroupReactNotifySchema,
} from '../../proto/notify';
import { protobuf_decode } from '@snowluma/proton';
import type {
GroupMute, NotifyMessageBody, GroupReactNotify,
} from '../../proto/proton/notify';
import type {
GroupMuteEvent, GroupRecallEvent, GroupPokeEvent, GroupEssenceEvent,
GroupMsgEmojiLikeEvent,
@@ -35,7 +35,7 @@ export const decodeEvent0x2DC: MsgPushDecoder = (ctx) => {
};
function decodeGroupMute(ctx: MsgPushContext): QQEventVariant[] {
const mute = protoDecode(ctx.content, GroupMuteSchema);
const mute = protobuf_decode<GroupMute>(ctx.content);
if (!mute?.data?.state) return [];
const duration = mute.data.state.duration ?? 0;
const ev: GroupMuteEvent = {
@@ -53,7 +53,7 @@ function decodeGroupMute(ctx: MsgPushContext): QQEventVariant[] {
function decodeGroupRecall(ctx: MsgPushContext): QQEventVariant[] {
const payload = unwrapGroupNotifyPayload(ctx.content);
if (!payload) return [];
const notify = protoDecode(payload, NotifyMessageBodySchema);
const notify = protobuf_decode<NotifyMessageBody>(payload);
if (!notify?.recall?.recallMessages || notify.recall.recallMessages.length === 0) return [];
const recalled = notify.recall.recallMessages[0];
const ev: GroupRecallEvent = {
@@ -72,7 +72,7 @@ function decodeGroupRecall(ctx: MsgPushContext): QQEventVariant[] {
function decodeGroupGreyTip(ctx: MsgPushContext): QQEventVariant[] {
const payload = unwrapGroupNotifyPayload(ctx.content);
if (!payload) return [];
const notify = protoDecode(payload, NotifyMessageBodySchema);
const notify = protobuf_decode<NotifyMessageBody>(payload);
if (!notify?.generalGrayTip || (notify.generalGrayTip.busiType ?? 0n) !== 12n) return [];
const templates = buildTemplateMap(notify.generalGrayTip.msgTemplParam ?? []);
const actor = findTemplateValue(templates, 'uin_str1');
@@ -94,7 +94,7 @@ function decodeGroupGreyTip(ctx: MsgPushContext): QQEventVariant[] {
function decodeGroupEssence(ctx: MsgPushContext): QQEventVariant[] {
const payload = unwrapGroupNotifyPayload(ctx.content);
if (!payload) return [];
const notify = protoDecode(payload, NotifyMessageBodySchema);
const notify = protobuf_decode<NotifyMessageBody>(payload);
if (!notify?.essenceMessage) return [];
const essence = notify.essenceMessage;
const setFlag = essence.setFlag ?? essence.setFlag2 ?? 0;
@@ -124,7 +124,7 @@ const GROUP_REACT_DISCRIMINATOR = 35;
function decodeGroupMsgEmojiLike(ctx: MsgPushContext): QQEventVariant[] {
if (ctx.content.length <= GROUP_REACT_PREFIX_BYTES) return [];
const payload = ctx.content.subarray(GROUP_REACT_PREFIX_BYTES);
const notify = protoDecode(payload, GroupReactNotifySchema);
const notify = protobuf_decode<GroupReactNotify>(payload);
if (!notify) return [];
if ((notify.field13 ?? 0) !== GROUP_REACT_DISCRIMINATOR) {
unknownLog.debug('Event0x2DC subType=16 unhandled field13=%d (expected %d for emoji react)',
@@ -1,14 +1,14 @@
// Handles GroupAdminChangedNotice (44). extraEnable / extraDisable
// distinguishes set vs. unset.
import { protoDecode } from '../../../protobuf/decode';
import { GroupAdminSchema } from '../../proto/notify';
import { protobuf_decode } from '@snowluma/proton';
import type { GroupAdmin } from '../../proto/proton/notify';
import type { GroupAdminEvent } from '../../events';
import type { MsgPushDecoder } from '../registry';
import { resolveUidToUin } from '../helpers';
export const decodeGroupAdmin: MsgPushDecoder = (ctx) => {
const admin = protoDecode(ctx.content, GroupAdminSchema);
const admin = protobuf_decode<GroupAdmin>(ctx.content);
if (!admin?.body) return [];
const extra = admin.body.extraEnable ?? admin.body.extraDisable;
if (!extra) return [];
@@ -2,16 +2,16 @@
// + GroupInviteNotice (87). All three produce GroupInviteEvent with
// different subType ('add' / 'invite') and flag prefixes.
import { protoDecode } from '../../../protobuf/decode';
import {
GroupJoinSchema, GroupInvitationSchema, GroupInviteSchema,
} from '../../proto/notify';
import { protobuf_decode } from '@snowluma/proton';
import type {
GroupJoin, GroupInvitation, GroupInvite,
} from '../../proto/proton/notify';
import type { GroupInviteEvent } from '../../events';
import type { MsgPushDecoder } from '../registry';
import { resolveUidToUin } from '../helpers';
export const decodeGroupJoinRequest: MsgPushDecoder = (ctx) => {
const join = protoDecode(ctx.content, GroupJoinSchema);
const join = protobuf_decode<GroupJoin>(ctx.content);
if (!join) return [];
const ev: GroupInviteEvent = {
kind: 'group_invite',
@@ -28,7 +28,7 @@ export const decodeGroupJoinRequest: MsgPushDecoder = (ctx) => {
};
export const decodeGroupInvitation: MsgPushDecoder = (ctx) => {
const invitation = protoDecode(ctx.content, GroupInvitationSchema);
const invitation = protobuf_decode<GroupInvitation>(ctx.content);
if (!invitation?.info?.inner) return [];
const inner = invitation.info.inner;
const ev: GroupInviteEvent = {
@@ -46,7 +46,7 @@ export const decodeGroupInvitation: MsgPushDecoder = (ctx) => {
};
export const decodeGroupInvite: MsgPushDecoder = (ctx) => {
const invite = protoDecode(ctx.content, GroupInviteSchema);
const invite = protobuf_decode<GroupInvite>(ctx.content);
if (!invite) return [];
const ev: GroupInviteEvent = {
kind: 'group_invite',
@@ -1,15 +1,27 @@
// Handles GroupMemberIncreaseNotice (33) + GroupMemberDecreaseNotice (34).
// Both share GroupChangeSchema; the decreaseType field distinguishes kick vs
// voluntary leave (dt != 0 && dt != 130 means kicked).
// Handles GroupMemberIncreaseNotice (33) + GroupMemberDecreaseNotice (34) +
// GroupSelfJoinedNotice (85, bot-self admittance).
//
// 33/34 share GroupChangeSchema; the decreaseType field distinguishes
// kick vs voluntary leave (dt != 0 && dt != 130 means kicked).
//
// 85 carries a different wire shape (`SelfJoinInGroup`) — without it
// the bot has no signal that its own `set_group_add_request` was
// approved (33 fires only for *other* members joining). We surface
// 85 as a regular GroupMemberJoin with `userUin = selfUin` so the
// existing OneBot converter naturally produces
// `notice.group_increase` with `sub_type: 'approve' | 'invite'`
// (the converter compares operator == user to pick the sub_type;
// for self-join the operator is the admin/inviter, so 'invite' is
// emitted — matching go-cqhttp / NapCat semantics).
import { protoDecode } from '../../../protobuf/decode';
import { GroupChangeSchema } from '../../proto/notify';
import { protobuf_decode } from '@snowluma/proton';
import type { GroupChange, SelfJoinInGroup } from '../../proto/proton/notify';
import type { GroupMemberJoin, GroupMemberLeave } from '../../events';
import type { MsgPushDecoder } from '../registry';
import { decodeOperatorUid, resolveUidToUin } from '../helpers';
export const decodeGroupMemberJoin: MsgPushDecoder = (ctx) => {
const change = protoDecode(ctx.content, GroupChangeSchema);
const change = protobuf_decode<GroupChange>(ctx.content);
if (!change) return [];
const groupId = change.groupUin ?? 0;
const userUid = change.memberUid ?? '';
@@ -28,7 +40,7 @@ export const decodeGroupMemberJoin: MsgPushDecoder = (ctx) => {
};
export const decodeGroupMemberLeave: MsgPushDecoder = (ctx) => {
const change = protoDecode(ctx.content, GroupChangeSchema);
const change = protobuf_decode<GroupChange>(ctx.content);
if (!change) return [];
const dt = change.decreaseType ?? 0;
const groupId = change.groupUin ?? 0;
@@ -47,3 +59,29 @@ export const decodeGroupMemberLeave: MsgPushDecoder = (ctx) => {
};
return [ev];
};
export const decodeGroupSelfJoined: MsgPushDecoder = (ctx) => {
const joined = protobuf_decode<SelfJoinInGroup>(ctx.content);
if (!joined) return [];
// groupUin is uint_64 on the wire (bigint). Real group IDs fit in
// uint32 (≤ 10 digits in practice), so Number() conversion is safe
// — saturate to 0 on the unlikely overflow rather than letting
// BigInt propagate downstream where consumers expect a number.
const groupUinBig = joined.groupUin ?? 0n;
const groupId = groupUinBig > 0n && groupUinBig <= 0x7FFFFFFFn ? Number(groupUinBig) : 0;
const operatorUid = joined.operatorUid ?? '';
// We're the one joining — surface the bot's own identity as userUin
// so the existing converter's `notice.group_increase` shape works
// unchanged.
const ev: GroupMemberJoin = {
kind: 'group_member_join',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
groupId,
userUin: ctx.selfUin,
userUid: ctx.identity.selfUid ?? '',
operatorUin: resolveUidToUin(ctx.identity, groupId, operatorUid, 0),
operatorUid,
};
return [ev];
};
@@ -13,6 +13,17 @@ export enum PkgType {
PrivateFileMessage = 529,
GroupRequestInvitationNotice = 525,
GroupRequestJoinNotice = 84,
/**
* Self-join admittance — fires on the bot's session right after an
* admin approves its `set_group_add_request` or an invite-accept
* goes through. Ported from `lagrange-python`'s
* `server_push/msg.py:108 case 85`. Maps to OneBot11
* `notice.group_increase` with the bot itself as `user_id` —
* existing 33 (GroupMemberIncreaseNotice) doesn't fire for the
* bot's own join, so without this case the bot never knows it
* just entered a group until the first message arrives.
*/
GroupSelfJoinedNotice = 85,
GroupInviteNotice = 87,
GroupAdminChangedNotice = 44,
GroupMemberIncreaseNotice = 33,
@@ -29,6 +40,73 @@ export enum Event0x2DCSubType {
export enum Event0x210SubType {
FriendRequestNotice = 35,
/**
* Outgoing friend-message recall — bot recalled its own message that
* was sent to a friend. Same `FriendRecall` wire shape as 138; the
* difference is direction (138 = friend recalled their own message
* sent to bot, 139 = bot recalled own message sent to friend).
* Cross-referenced against Lagrange V2 (`FriendRecallMessageProcessor`
* registered for both 138 and 139) + acidify (`138, 139 ->
* parseFriendRecall`). The decoder uses the subType to figure out
* which UID side ends up as `userUin` on the emitted event.
*/
FriendRecallSelfNotice = 139,
FriendRecallNotice = 138,
FriendPokeNotice = 290,
/**
* Mutual-accept friend notice — 179 fires when bot sent a friend
* request and the other side accepted; 226 fires for the opposite
* direction. Both decode through the same `NewFriend` wire shape
* (LagrangeGo registers them via a `case 226: case 179:` fallthrough
* in `client/listener.go:248-258`). Maps to OneBot11
* `notice.friend_add`.
*/
NewFriendNotice = 179,
NewFriendNoticeAlt = 226,
/**
* Group-app state push (troop shortcut bar / discussion app).
*
* Sourced from the decompiled stock QQ Android client decoder at
* `com.tencent.imcore.message.ext.codec.decoder.msgType0x210.SubType0x26`
* (tsuzcx/qq_apk @ afe46ef). The payload is `submsgtype0x26.MsgBody`
* dispatching on `uint32_sub_cmd`:
*
* - 0x1 → `UpdateAppUnreadNum`: a list of
* `{group_code, app_id, unread_num}` entries the QQ client uses
* to keep group-internal "mini-app" badges (e.g. `appId=101846662`
* / `101896870` for the shortcut bar) in sync.
* - 0x3 → `UpdateDiscussAppInfo`: `{conf_uin, app_tip_notify.text}`
* for discussion-group app tips, routed to `getGAudioHandler()`.
* - 0x4 → delegated to the troop online-push handler.
*
* None of these have a OneBot event mapping — they're QQ-client-UI
* state pushes (unread badges, in-app tips), not user-visible
* conversation events. Acknowledge the subType so it doesn't keep
* showing up as "unknown" in debug logs and drop it silently.
* Lagrange V2 / lagrange-python / LagrangeGo / acidify all also
* fall through on this one because they don't surface the shortcut
* bar either.
*/
GroupAppStatePush = 38,
/**
* Unmapped QQ-NT-internal subType — first seen as a recurring
* "Event0x210 unknown subType=380" debug log in production captures.
*
* The tsuzcx/qq_apk decompile of the legacy QQ Android client only
* enumerates SubType0x26 (38) through SubType0x146 (326) under
* `com.tencent.imcore.message.ext.codec.decoder.msgType0x210/` —
* `SubType0x17c.java` (380) literally doesn't exist in that tree, so
* 380 is a QQ-NT-era addition rather than a missed legacy subType.
*
* The NT-era reference clients also don't handle it: Lagrange.Core
* (`PushMessageService.cs`), LagrangeGo (`client/listener.go`),
* lagrange-python (`server_push/msg.py`), and mania (`push_msg.rs`)
* each enumerate explicit 0x210 subtypes and none include 380 / 0x17C.
*
* Most likely a QQ-NT-client-UI state push (similar to 38) that
* doesn't map to any OneBot event. Acknowledge silently to keep the
* unknown log clean; if a real OneBot event ends up depending on it,
* revisit with whichever NT-era project finally maps the schema.
*/
UnmappedClientState380 = 380,
}
+3 -3
View File
@@ -2,8 +2,8 @@
// and the rich-body decoder. No state, no I/O.
import { inflateSync } from 'zlib';
import { protoDecode } from '../../protobuf/decode';
import { OperatorInfoSchema } from '../proto/notify';
import { protobuf_decode } from '@snowluma/proton';
import type { OperatorInfo } from '../proto/proton/notify';
import type { IdentityService } from '../identity-service';
export function makeImageUrl(origUrl: string): string {
@@ -52,7 +52,7 @@ export function resolveUidToUin(identity: IdentityService, groupId: number, uid:
export function decodeOperatorUid(bytes: Uint8Array): string {
if (!bytes || bytes.length === 0) return '';
const info = protoDecode(bytes, OperatorInfoSchema);
const info = protobuf_decode<OperatorInfo>(bytes);
if (info?.operatorField?.uid) return info.operatorField.uid;
return Buffer.from(bytes).toString('utf8');
}
+2 -1
View File
@@ -9,7 +9,7 @@ import { buildContext } from './context';
import { MsgPushRegistry } from './registry';
import { PkgType } from './enums';
import {
decodeGroupMemberJoin, decodeGroupMemberLeave,
decodeGroupMemberJoin, decodeGroupMemberLeave, decodeGroupSelfJoined,
} from './decoders/group-member-change';
import { decodeGroupAdmin } from './decoders/group-admin';
import {
@@ -26,6 +26,7 @@ export const MSG_PUSH_CMD = 'trpc.msg.olpush.OlPushService.MsgPush';
const registry = new MsgPushRegistry();
registry.register(PkgType.GroupMemberIncreaseNotice, decodeGroupMemberJoin);
registry.register(PkgType.GroupMemberDecreaseNotice, decodeGroupMemberLeave);
registry.register(PkgType.GroupSelfJoinedNotice, decodeGroupSelfJoined);
registry.register(PkgType.GroupAdminChangedNotice, decodeGroupAdmin);
registry.register(PkgType.GroupRequestJoinNotice, decodeGroupJoinRequest);
registry.register(PkgType.GroupRequestInvitationNotice, decodeGroupInvitation);
@@ -434,14 +434,24 @@ function extractRichtextExtras(
}
function extractMsgContent(msgContent: Uint8Array, elements: MessageElement[]): void {
// `MessageBody.msgContent` is where the QQ-NT server actually puts
// c2c file metadata — serialised `FileExtra { file: NotOnlineFile }`
// bytes. The previous schema (`FileExtraInfoSchema` with fileSize=1/
// fileName=2/fileMd5=3/fileUuid=4/fileHash=5) didn't match the wire
// shape — every field landed at the wrong tag, so the four-field
// truthiness check below filtered out every real c2c file push as
// "incomplete metadata". After consolidating FileExtra to wrap
// `NotOnlineFile` (Lagrange.Core's `FileExtra { File: NotOnlineFile }`),
// this reads the right tags.
const extra = protoDecode(msgContent, FileExtraSchema);
if (!extra?.file) return;
const f = extra.file;
if (f.fileSize !== undefined && f.fileName && f.fileMd5 && f.fileUuid && f.fileHash) {
elements.push({
type: 'file', fileName: f.fileName, fileId: f.fileUuid,
fileSize: f.fileSize !== undefined ? Number(f.fileSize) : 0,
fileHash: f.fileHash,
});
}
if (!f.fileUuid) return;
elements.push({
type: 'file',
fileId: f.fileUuid,
fileName: f.fileName ?? '',
fileSize: f.fileSize !== undefined ? Number(f.fileSize) : 0,
fileHash: f.fileHash ?? '',
});
}
+17 -3
View File
@@ -15,9 +15,20 @@ export const RoutingGroupSchema = {
groupCode: { field: 1, type: 'uint64' as const },
} satisfies ProtoSchema;
// `Trans0x211` is the c2c-file scene's routing header (Lagrange.Core
// `Routing/Trans0X211.cs`). See proton/action.ts:RoutingTrans0x211
// for the rationale — c2c file sends *must* route through this slot,
// not `c2c`, or the server rejects them.
export const RoutingTrans0x211Schema = {
toUin: { field: 1, type: 'uint64' as const },
ccCmd: { field: 2, type: 'uint32' as const },
uid: { field: 8, type: 'string' as const },
} satisfies ProtoSchema;
export const RoutingHeadSchema = {
c2c: { field: 1, type: 'message' as const, schema: RoutingC2CSchema },
grp: { field: 2, type: 'message' as const, schema: RoutingGroupSchema },
c2c: { field: 1, type: 'message' as const, schema: RoutingC2CSchema },
grp: { field: 2, type: 'message' as const, schema: RoutingGroupSchema },
trans0x211: { field: 15, type: 'message' as const, schema: RoutingTrans0x211Schema },
} satisfies ProtoSchema;
// --- Content Head (for send) ---
@@ -43,7 +54,10 @@ export const SendRichTextSchema = {
// --- MessageBody (for send) ---
export const SendMessageBodySchema = {
richText: { field: 1, type: 'message' as const, schema: SendRichTextSchema },
richText: { field: 1, type: 'message' as const, schema: SendRichTextSchema },
// C2C file payload — serialised `FileExtra { file: NotOnlineFile }`
// bytes. See proton/action.ts:SendMessageBody for the WHY.
msgContent: { field: 2, type: 'bytes' as const },
} satisfies ProtoSchema;
// --- SendMessageRequest ---
+13 -3
View File
@@ -390,14 +390,21 @@ export const MsgInfoSchema = {
// --- GroupFileExtra (TransElem type=24) ---
// Field numbers cross-checked against NapCat (component.ts:146) +
// acidify (GroupFileExtra.kt:Inner.Info). Old schema had fileSha at 5
// / extInfoString at 6 / fileMd5 at 7 which mismatched the real wire
// shape — the server rejected the chat post with `result=79` because
// fileSha bytes were landing where it expected a uint32 (field 5).
// See proton/element.ts for the WHY comment.
export const GroupFileInfoSchema = {
busId: { field: 1, type: 'uint32' as const },
fileId: { field: 2, type: 'string' as const },
fileSize: { field: 3, type: 'uint64' as const },
fileName: { field: 4, type: 'string' as const },
fileSha: { field: 5, type: 'bytes' as const },
extInfoString: { field: 6, type: 'string' as const },
fileMd5: { field: 7, type: 'bytes' as const },
field5: { field: 5, type: 'uint32' as const },
fileSha: { field: 6, type: 'bytes' as const },
extInfoString: { field: 7, type: 'string' as const },
fileMd5: { field: 8, type: 'bytes' as const },
} satisfies ProtoSchema;
export const GroupFileExtraInnerSchema = {
@@ -405,6 +412,9 @@ export const GroupFileExtraInnerSchema = {
} satisfies ProtoSchema;
export const GroupFileExtraSchema = {
field1: { field: 1, type: 'uint32' as const },
fileName: { field: 2, type: 'string' as const },
display: { field: 3, type: 'string' as const },
inner: { field: 7, type: 'message' as const, schema: GroupFileExtraInnerSchema },
} satisfies ProtoSchema;
@@ -334,3 +334,10 @@ export const NTV2UploadRichMediaRespSchema = {
respHead: { field: 1, type: 'message' as const, schema: NTV2UploadRespHeadSchema },
upload: { field: 2, type: 'message' as const, schema: NTV2UploadRespBodySchema },
} satisfies ProtoSchema;
// (The legacy `GroupAvatarUploadExtSchema` definition that briefly
// lived here in PR #31 was removed: it was a residual artifact of an
// alternative `setGroupAvatar` implementation that got dropped during
// review — the canonical Lagrange-derived `GroupAvatarExtraSchema`
// further up this file is the one `actions/profile.setGroupAvatar`
// actually uses.)
+22 -15
View File
@@ -59,13 +59,20 @@ export const PttSchema = {
// --- NotOnlineFile (C2C file) ---
// Field numbers per `dev/Lagrange.Core/.../Component/NotOnlineFile.cs`.
// fields 9 (subcmd), 50 (dangerEvel), 55 (expireTime) are required
// on c2c file SEND (the receiver ignores them); the identification
// fields (1/3/4/5/6/57) are read both directions.
export const NotOnlineFileSchema = {
fileType: { field: 1, type: 'uint32' as const },
fileUuid: { field: 3, type: 'string' as const },
fileMd5: { field: 4, type: 'bytes' as const },
fileName: { field: 5, type: 'string' as const },
fileSize: { field: 6, type: 'uint64' as const },
fileHash: { field: 57, type: 'string' as const },
fileType: { field: 1, type: 'uint32' as const },
fileUuid: { field: 3, type: 'string' as const },
fileMd5: { field: 4, type: 'bytes' as const },
fileName: { field: 5, type: 'string' as const },
fileSize: { field: 6, type: 'uint64' as const },
subcmd: { field: 9, type: 'uint32' as const },
dangerEvel: { field: 50, type: 'uint32' as const },
expireTime: { field: 55, type: 'uint32' as const },
fileHash: { field: 57, type: 'string' as const },
} satisfies ProtoSchema;
// --- RichText ---
@@ -84,17 +91,17 @@ export const MessageBodySchema = {
} satisfies ProtoSchema;
// --- FileExtra (for C2C file in msg_content) ---
export const FileExtraInfoSchema = {
fileSize: { field: 1, type: 'uint64' as const },
fileName: { field: 2, type: 'string' as const },
fileMd5: { field: 3, type: 'bytes' as const },
fileUuid: { field: 4, type: 'string' as const },
fileHash: { field: 5, type: 'string' as const },
} satisfies ProtoSchema;
//
// `FileExtra { file: NotOnlineFile }` is the wrapper QQ-NT actually
// uses at `MessageBody.msgContent` for c2c file sends. The previous
// `FileExtraInfoSchema` had fileSize=1, fileName=2, fileMd5=3,
// fileUuid=4, fileHash=5 — every field at the wrong tag, so received
// c2c-file payloads silently failed to parse. Consolidated to the
// shared `NotOnlineFileSchema` (Lagrange.Core's `FileExtra.cs` does
// the same — `[ProtoMember(1)] public NotOnlineFile? File`).
export const FileExtraSchema = {
file: { field: 1, type: 'message' as const, schema: FileExtraInfoSchema },
file: { field: 1, type: 'message' as const, schema: NotOnlineFileSchema },
} satisfies ProtoSchema;
// --- PushMsgBody ---
+260 -1
View File
@@ -1277,4 +1277,263 @@ export const GroupAvatarExtraSchema = {
field3: { field: 3, type: 'message' as const, schema: GroupAvatarExtraField3Schema },
field5: { field: 5, type: 'uint32' as const }, // observed value: 3
field6: { field: 6, type: 'uint32' as const }, // observed value: 1
} satisfies ProtoSchema;
} satisfies ProtoSchema;
///////// --- group album
// --- Request Schemas ---
export const ExtMapEntrySchema = {
key: { field: 1, type: 'string' as const },
value: { field: 2, type: 'string' as const },
} satisfies ProtoSchema;
export const ReqInfoSchema = {
groupId: { field: 1, type: 'string' as const },
albumId: { field: 2, type: 'string' as const },
field3: { field: 3, type: 'int32' as const },
attachInfo: { field: 4, type: 'string' as const },
field5: { field: 5, type: 'string' as const },
} satisfies ProtoSchema;
export const GetMediaListRequestSchema = {
field1: { field: 1, type: 'int32' as const },
field2: { field: 2, type: 'bytes' as const },
field3: { field: 3, type: 'bytes' as const },
reqInfo: { field: 4, type: 'message' as const, schema: ReqInfoSchema },
traceId: { field: 5, type: 'string' as const },
extMap: { field: 10, type: 'repeated_message' as const, schema: ExtMapEntrySchema },
} satisfies ProtoSchema;
// --- Response Schemas ---
export const UrlInfoSchema = {
url: { field: 1, type: 'string' as const },
width: { field: 2, type: 'uint32' as const },
height: { field: 3, type: 'uint32' as const },
} satisfies ProtoSchema;
export const PhotoUrlSchema = {
spec: { field: 1, type: 'uint32' as const },
url: { field: 2, type: 'message' as const, schema: UrlInfoSchema }
} satisfies ProtoSchema;
export const ImageInfoSchema = {
name: { field: 1, type: 'string' as const },
sloc: { field: 2, type: 'string' as const },
lloc: { field: 3, type: 'string' as const },
photoUrls: { field: 4, type: 'repeated_message' as const, schema: PhotoUrlSchema },
defaultUrl: { field: 5, type: 'message' as const, schema: UrlInfoSchema },
isGif: { field: 6, type: 'bool' as const },
hasRaw: { field: 7, type: 'bool' as const },
} satisfies ProtoSchema;
export const MediaInfoSchema = {
type: { field: 1, type: 'uint32' as const },
image: { field: 2, type: 'message' as const, schema: ImageInfoSchema },
uploader: { field: 6, type: 'string' as const },
batchId: { field: 7, type: 'uint64' as const },
uploadTime: { field: 8, type: 'uint64' as const },
} satisfies ProtoSchema;
export const GetMediaListRspDataSchema = {
albumInfo: {
field: 1,
type: 'message' as const,
schema: {
albumId: { field: 1, type: 'string' as const },
owner: { field: 2, type: 'string' as const },
name: { field: 3, type: 'string' as const },
} satisfies ProtoSchema
},
mediaList: { field: 3, type: 'repeated_message' as const, schema: MediaInfoSchema },
prevAttachInfo: { field: 4, type: 'string' as const },
nextAttachInfo: { field: 5, type: 'string' as const }, // 用于翻页拉取的 token
} satisfies ProtoSchema;
export const GetMediaListResponseSchema = {
field1: { field: 1, type: 'int32' as const },
field2: { field: 2, type: 'bytes' as const },
field3: { field: 3, type: 'bytes' as const },
data: { field: 4, type: 'message' as const, schema: GetMediaListRspDataSchema }, // 将原本的 bytes 修正为 message 解析
} satisfies ProtoSchema;
// --- DoQunComment: Comment on group album media ---
// --- DoQunComment: 严格对齐底层字节的字段定义 ---
export const CommentContentItemSchema = {
type: { field: 1, type: 'uint32' as const },
content: { field: 2, type: 'string' as const },
} satisfies ProtoSchema;
export const CommentUserSchema = {
uin: { field: 13, type: 'string' as const },
} satisfies ProtoSchema;
// 评论具体内容结构 (原 CommentReqContentSchema)
export const CommentReqContentSchema = {
field2: { field: 2, type: 'message' as const, schema: CommentUserSchema },
field3: { field: 3, type: 'message' as const, schema: {
field1: { field: 1, type: 'uint32' as const },
field2: { field: 2, type: 'string' as const },
field3: { field: 3, type: 'string' as const },
field4: { field: 4, type: 'string' as const },
field5: { field: 5, type: 'uint32' as const },
field6: { field: 6, type: 'string' as const },
} satisfies ProtoSchema },
clientKey: { field: 7, type: 'string' as const }, // 对应你的 clientKey
} satisfies ProtoSchema;
export const CommentReqPhotoInfoSchema = {
field1: { field: 1, type: 'message' as const, schema: {
field2: { field: 2, type: 'message' as const, schema: {
field1: { field: 1, type: 'uint32' as const },
field2: { field: 2, type: 'string' as const },
lloc: { field: 3, type: 'string' as const },
field4: { field: 4, type: 'string' as const },
field6: { field: 6, type: 'string' as const },
field7: { field: 7, type: 'uint32' as const },
field8: { field: 8, type: 'uint32' as const },
field9: { field: 9, type: 'uint32' as const },
field14: { field: 14, type: 'uint32' as const },
field15: { field: 15, type: 'uint32' as const },
field17: { field: 17, type: 'uint32' as const },
} satisfies ProtoSchema },
} satisfies ProtoSchema },
albumId: { field: 3, type: 'string' as const },
field5: { field: 5, type: 'uint32' as const },
} satisfies ProtoSchema;
export const CommentReqBodySchema = {
field1: { field: 1, type: 'message' as const, schema: {
field3: { field: 3, type: 'uint32' as const },
field4: { field: 4, type: 'string' as const },
} satisfies ProtoSchema },
field2: { field: 2, type: 'message' as const, schema: {
field1: { field: 1, type: 'message' as const, schema: CommentUserSchema }
} satisfies ProtoSchema },
field5: { field: 5, type: 'message' as const, schema: CommentReqPhotoInfoSchema }, // 注意:抓包证实照片在 field 5
} satisfies ProtoSchema;
export const DoQunCommentRequestSchema = {
field1: { field: 1, type: 'int32' as const },
field2: { field: 2, type: 'bytes' as const },
field3: { field: 3, type: 'bytes' as const },
body: { field: 4, type: 'message' as const, schema: {
groupId: { field: 2, type: 'string' as const },
field3: { field: 3, type: 'uint32' as const },
reqBody: { field: 4, type: 'message' as const, schema: CommentReqBodySchema },
field5: { field: 5, type: 'message' as const, schema: CommentReqContentSchema }, // 注意:评论文本实际在外层的 field 5
} satisfies ProtoSchema },
traceId: { field: 5, type: 'string' as const },
extMap: { field: 10, type: 'repeated_message' as const, schema: ExtMapEntrySchema },
} satisfies ProtoSchema;
export const CommentRespUserSchema = {
uin: { field: 13, type: 'string' as const },
} satisfies ProtoSchema;
export const CommentRespContentSchema = {
type: { field: 1, type: 'uint32' as const },
content: { field: 2, type: 'string' as const },
} satisfies ProtoSchema;
export const CommentRespDataSchema = {
id: { field: 1, type: 'string' as const },
user: { field: 2, type: 'message' as const, schema: CommentRespUserSchema },
content: { field: 3, type: 'repeated_message' as const, schema: CommentRespContentSchema },
time: { field: 4, type: 'uint64' as const },
clientKey: { field: 7, type: 'string' as const },
} satisfies ProtoSchema;
export const DoQunCommentResponseSchema = {
field1: { field: 1, type: 'int32' as const },
comment: { field: 4, type: 'message' as const, schema: {
data: { field: 2, type: 'message' as const, schema: CommentRespDataSchema },
} satisfies ProtoSchema },
} satisfies ProtoSchema;
// --- DoQunLike: Like group album media ---
export const DoQunLikeReqLikeInfoSchema = {
id: { field: 1, type: 'string' as const },
status: { field: 3, type: 'uint32' as const },
} satisfies ProtoSchema;
export const DoQunLikeReqCellCommonSchema = {
time: { field: 3, type: 'uint64' as const },
feedId: { field: 4, type: 'string' as const },
} satisfies ProtoSchema;
export const DoQunLikeReqCellUserSchema = {
uin: { field: 13, type: 'string' as const }, // 修复:抓包证实 uin 是 field 13
} satisfies ProtoSchema;
export const DoQunLikeReqCellUserInfoSchema = {
user: { field: 1, type: 'message' as const, schema: DoQunLikeReqCellUserSchema },
} satisfies ProtoSchema;
export const DoQunLikeReqCellQunInfoSchema = {
qunId: { field: 1, type: 'string' as const },
} satisfies ProtoSchema;
export const DoQunLikeReqCellMediaSchema = {
albumId: { field: 3, type: 'string' as const },
batchId: { field: 5, type: 'uint64' as const },
} satisfies ProtoSchema;
export const DoQunLikeReqFeedPublishSchema = {
cellCommon: { field: 1, type: 'message' as const, schema: DoQunLikeReqCellCommonSchema },
cellUserInfo: { field: 2, type: 'message' as const, schema: DoQunLikeReqCellUserInfoSchema },
cellMedia: { field: 5, type: 'message' as const, schema: DoQunLikeReqCellMediaSchema },
cellQunInfo: { field: 12, type: 'message' as const, schema: DoQunLikeReqCellQunInfoSchema },
} satisfies ProtoSchema;
export const DoQunLikeReqBodySchema = {
type: { field: 2, type: 'uint32' as const },
like: { field: 3, type: 'message' as const, schema: DoQunLikeReqLikeInfoSchema },
publish: { field: 4, type: 'message' as const, schema: DoQunLikeReqFeedPublishSchema },
clientKey: { field: 5, type: 'string' as const },
} satisfies ProtoSchema;
export const DoQunLikeRequestSchema = {
field1: { field: 1, type: 'int32' as const },
field2: { field: 2, type: 'string' as const },
field3: { field: 3, type: 'string' as const },
body: { field: 4, type: 'message' as const, schema: DoQunLikeReqBodySchema },
extMap: { field: 10, type: 'repeated_message' as const, schema: ExtMapEntrySchema },
} satisfies ProtoSchema;
export const DoQunLikeRespBodySchema = {
like: { field: 2, type: 'message' as const, schema: DoQunLikeReqLikeInfoSchema },
} satisfies ProtoSchema;
export const DoQunLikeResponseSchema = {
field1: { field: 1, type: 'int32' as const },
body: { field: 4, type: 'message' as const, schema: DoQunLikeRespBodySchema },
} satisfies ProtoSchema;
// --- DeleteMedias: Delete group album media ---
export const DeleteMediasReqBodySchema = {
groupId: { field: 1, type: 'string' as const },
albumId: { field: 2, type: 'string' as const },
lloc: { field: 3, type: 'string' as const },
} satisfies ProtoSchema;
export const DeleteMediasRequestSchema = {
field1: { field: 1, type: 'int32' as const },
field2: { field: 2, type: 'string' as const },
field3: { field: 3, type: 'string' as const },
body: { field: 4, type: 'message' as const, schema: DeleteMediasReqBodySchema },
traceId: { field: 5, type: 'string' as const }, // <-- 把它挪到外层了!
extMap: { field: 10, type: 'repeated_message' as const, schema: ExtMapEntrySchema },
} satisfies ProtoSchema;
export const DeleteMediasResponseSchema = {
field1: { field: 1, type: 'int32' as const }, // 8694
field2: { field: 2, type: 'int32' as const }, // 错误码 (例如: 10023)
field3: { field: 3, type: 'string' as const }, // 错误信息 (例如: "no right delete...")
} satisfies ProtoSchema;
@@ -0,0 +1,113 @@
// Proton (compile-time) form of bridge/proto/action.ts.
// One-to-one mirror; legacy `*Schema` constants stay alongside for back-compat.
import type { pb, pb_repeated, int_32, uint_32, uint_64, bytes } from '@snowluma/proton';
import type { Elem } from './element';
// ── Routing ─────────────────────────────────────────────────────────
export interface RoutingC2C {
uin?: pb<1, uint_32>;
uid?: pb<2, string>;
}
export interface RoutingGroup {
groupCode?: pb<1, uint_64>;
}
// `Trans0x211` is the c2c-file scene's routing header. The server
// rejects c2c file messages routed through `RoutingC2C` — instead it
// expects `trans0x211 { ccCmd: 4, uid: <peer uid> }`. Confirmed against
// `dev/Lagrange.Core/Lagrange.Core/Internal/Packets/Message/
// Routing/Trans0X211.cs` + `RoutingHead.cs` (Trans0X211 sits at
// field 15) + `MessagePacker.BuildPacketBase` (`Trans0X211 =
// !chain.HasTypeOf<FileEntity>() ? null : new Trans0X211 { CcCmd = 4,
// Uid = chain.Uid }`).
export interface RoutingTrans0x211 {
toUin?: pb<1, uint_64>;
ccCmd?: pb<2, uint_32>;
uid?: pb<8, string>;
}
export interface RoutingHead {
c2c?: pb<1, RoutingC2C>;
grp?: pb<2, RoutingGroup>;
trans0x211?: pb<15, RoutingTrans0x211>;
}
// ── Content Head (for send) ─────────────────────────────────────────
export interface SendContentHead {
type?: pb<1, uint_32>;
subType?: pb<2, uint_32>;
c2cCmd?: pb<3, uint_32>;
}
// ── Message Control ─────────────────────────────────────────────────
export interface MessageControl {
msgFlag?: pb<1, int_32>;
}
// ── RichText (for send — only elems) ────────────────────────────────
export interface SendRichText {
elems?: pb_repeated<2, Elem>;
}
// ── MessageBody (for send) ──────────────────────────────────────────
export interface SendMessageBody {
richText?: pb<1, SendRichText>;
// C2C file payload — serialised `FileExtra { file: NotOnlineFile }`
// bytes. The server reads c2c file metadata from this slot, NOT
// from `richText.notOnlineFile`. Confirmed against `dev/Lagrange.Core/
// .../MessageBody.cs:12` (commented "Offline file is now put here").
msgContent?: pb<2, bytes>;
}
// ── SendMessageRequest ──────────────────────────────────────────────
export interface SendMessageRequest {
routingHead?: pb<1, RoutingHead>;
contentHead?: pb<2, SendContentHead>;
messageBody?: pb<3, SendMessageBody>;
clientSequence?: pb<4, uint_32>;
random?: pb<5, uint_32>;
syncCookie?: pb<6, bytes>;
via?: pb<8, uint_32>;
dataStatist?: pb<9, uint_32>;
ctrl?: pb<12, MessageControl>;
multiSendSeq?: pb<14, uint_32>;
}
// ── SendMessageResponse ─────────────────────────────────────────────
export interface SendMessageResponse {
result?: pb<1, int_32>;
errMsg?: pb<2, string>;
timestamp1?: pb<3, uint_32>;
field10?: pb<10, uint_32>;
groupSequence?: pb<11, uint_32>;
timestamp2?: pb<12, uint_32>;
privateSequence?: pb<14, uint_32>;
}
// ── MentionExtra (for building @mention text element) ───────────────
//
// Same wire shape as element.ts's MentionExtra (which is used for decoding
// inbound mentions) — kept under a distinct name to mark the send-side
// usage, matching the legacy convention.
export interface MentionExtraSend {
type?: pb<3, int_32>;
uin?: pb<4, uint_32>;
field5?: pb<5, int_32>;
uid?: pb<9, string>;
}
// ── MarkdownData ────────────────────────────────────────────────────
export interface MarkdownData {
content?: pb<1, string>;
}
@@ -0,0 +1,441 @@
// Proton (compile-time) form of bridge/proto/element.ts.
//
// One-to-one mirror of every schema in element.ts. The legacy `*Schema`
// constants stay in place for back-compat; both forms produce wire-equivalent
// output (modulo the proto3 default-value omission — see README).
import type { pb, pb_repeated, int_32, uint_32, uint_64, bool, bytes } from '@snowluma/proton';
// ── Nested / helper schemas ─────────────────────────────────────────
export interface CustomFacePbReserve {
subType?: pb<1, int_32>;
summary?: pb<9, string>;
}
export interface NotOnlineImagePbReserve2 {
field1?: pb<1, int_32>;
field2?: pb<2, string>;
field3?: pb<3, int_32>;
field4?: pb<4, int_32>;
field5?: pb<5, int_32>;
field7?: pb<7, string>;
}
export interface NotOnlineImagePbReserve {
subType?: pb<1, int_32>;
field3?: pb<3, int_32>;
field4?: pb<4, int_32>;
summary?: pb<8, string>;
field10?: pb<10, int_32>;
field20?: pb<20, NotOnlineImagePbReserve2>;
url?: pb<30, string>;
md5Str?: pb<31, string>;
}
// ── Core element schemas ────────────────────────────────────────────
export interface TextElem {
str?: pb<1, string>;
link?: pb<2, string>;
attr6Buf?: pb<3, bytes>;
attr7Buf?: pb<4, bytes>;
buf?: pb<11, bytes>;
pbReserve?: pb<12, bytes>;
}
export interface FaceElem {
index?: pb<1, int_32>;
oldData?: pb<2, bytes>;
buf?: pb<11, bytes>;
}
export interface OnlineImage {
guid?: pb<1, bytes>;
filePath?: pb<2, bytes>;
oldVerSendFile?: pb<3, bytes>;
}
export interface NotOnlineImage {
filePath?: pb<1, string>;
fileLen?: pb<2, uint_32>;
downloadPath?: pb<3, string>;
oldVerSendFile?:pb<4, bytes>;
imgType?: pb<5, int_32>;
previewsImage?: pb<6, bytes>;
picMd5?: pb<7, bytes>;
picHeight?: pb<8, uint_32>;
picWidth?: pb<9, uint_32>;
resId?: pb<10, string>;
flag?: pb<11, bytes>;
thumbUrl?: pb<12, string>;
original?: pb<13, int_32>;
bigUrl?: pb<14, string>;
origUrl?: pb<15, string>;
bizType?: pb<16, int_32>;
result?: pb<17, int_32>;
index?: pb<18, int_32>;
opFaceBuf?: pb<19, bytes>;
oldPicMd5?: pb<20, bool>;
thumbWidth?: pb<21, int_32>;
thumbHeight?: pb<22, int_32>;
fileId?: pb<23, int_32>;
showLen?: pb<24, uint_32>;
downloadLen?: pb<25, uint_32>;
x400Url?: pb<26, string>;
x400Width?: pb<27, int_32>;
x400Height?: pb<28, int_32>;
pbRes?: pb<29, NotOnlineImagePbReserve>;
}
export interface TransElem {
elemType?: pb<1, int_32>;
elemValue?: pb<2, bytes>;
}
export interface MarketFace {
faceName?: pb<1, string>;
itemType?: pb<2, uint_32>;
faceInfo?: pb<3, uint_32>;
faceId?: pb<4, bytes>;
tabId?: pb<5, uint_32>;
subType?: pb<6, uint_32>;
key?: pb<7, bytes>;
param?: pb<8, bytes>;
mediaType?: pb<9, uint_32>;
imageWidth?: pb<10, uint_32>;
imageHeight?: pb<11, uint_32>;
mobileParam?: pb<12, bytes>;
pbReserve?: pb<13, bytes>;
}
export interface CustomFace {
guid?: pb<1, bytes>;
filePath?: pb<2, string>;
shortcut?: pb<3, string>;
buffer?: pb<4, bytes>;
flag?: pb<5, bytes>;
oldData?: pb<6, bytes>;
fileId?: pb<7, uint_32>;
serverIp?: pb<8, int_32>;
serverPort?: pb<9, int_32>;
fileType?: pb<10, int_32>;
signature?: pb<11, bytes>;
useful?: pb<12, int_32>;
md5?: pb<13, bytes>;
thumbUrl?: pb<14, string>;
bigUrl?: pb<15, string>;
origUrl?: pb<16, string>;
bizType?: pb<17, int_32>;
repeatIndex?: pb<18, int_32>;
repeatImage?: pb<19, int_32>;
imageType?: pb<20, int_32>;
index?: pb<21, int_32>;
width?: pb<22, int_32>;
height?: pb<23, int_32>;
source?: pb<24, int_32>;
size?: pb<25, uint_32>;
origin?: pb<26, int_32>;
thumbWidth?: pb<27, int_32>;
thumbHeight?: pb<28, int_32>;
showLen?: pb<29, int_32>;
downloadLen?: pb<30, int_32>;
x400Url?: pb<31, string>;
x400Width?: pb<32, int_32>;
x400Height?: pb<33, int_32>;
pbRes?: pb<34, CustomFacePbReserve>;
}
export interface RichMsg {
template1?: pb<1, bytes>;
serviceId?: pb<2, int_32>;
msgResId?: pb<3, bytes>;
rand?: pb<4, int_32>;
seq?: pb<5, uint_32>;
}
export interface GroupFileElem {
filename?: pb<1, string>;
fileSize?: pb<2, uint_64>;
fileId?: pb<3, string>;
batchId?: pb<4, string>;
fileKey?: pb<5, string>;
mark?: pb<6, bytes>;
sequence?: pb<7, uint_64>;
batchItemId?: pb<8, bytes>;
feedMsgTime?: pb<9, int_32>;
pbReserve?: pb<10, bytes>;
}
export interface ExtraInfo {
nick?: pb<1, bytes>;
groupCard?: pb<2, bytes>;
level?: pb<3, int_32>;
flags?: pb<4, int_32>;
groupMask?: pb<5, int_32>;
msgTailId?: pb<6, int_32>;
senderTitle?: pb<7, bytes>;
apnsTips?: pb<8, bytes>;
uin?: pb<9, uint_64>;
msgStateFlag?: pb<10, int_32>;
apnsSoundType?: pb<11, int_32>;
newGroupFlag?: pb<12, int_32>;
}
export interface VideoFile {
fileUuid?: pb<1, string>;
fileMd5?: pb<2, bytes>;
fileName?: pb<3, string>;
fileFormat?: pb<4, int_32>;
fileTime?: pb<5, int_32>;
fileSize?: pb<6, int_32>;
thumbWidth?: pb<7, int_32>;
thumbHeight?: pb<8, int_32>;
thumbFileMd5?: pb<9, bytes>;
source?: pb<10, bytes>;
thumbFileSize?: pb<11, int_32>;
busiType?: pb<12, int_32>;
fromChatType?: pb<13, int_32>;
toChatType?: pb<14, int_32>;
supportProgressive?: pb<15, bool>;
fileWidth?: pb<16, int_32>;
fileHeight?: pb<17, int_32>;
subBusiType?: pb<18, int_32>;
videoAttr?: pb<19, int_32>;
pbReserve?: pb<24, bytes>;
}
export interface SrcMsg {
origSeqs?: pb_repeated<1, uint_32>;
senderUin?: pb<2, uint_64>;
time?: pb<3, int_32>;
flag?: pb<4, int_32>;
elemsRaw?: pb_repeated<5, bytes>;
type?: pb<6, int_32>;
richMsg?: pb<7, bytes>;
pbReserve?: pb<8, bytes>;
sourceMsg?: pb<9, bytes>;
toUin?: pb<10, uint_64>;
troopName?: pb<11, bytes>;
}
export interface LightAppElem {
data?: pb<1, bytes>;
msgResid?: pb<2, bytes>;
}
export interface CommonElem {
serviceType?: pb<1, int_32>;
pbElem?: pb<2, bytes>;
businessType?: pb<3, uint_32>;
}
export interface GeneralFlags {
bubbleDiyTextId?: pb<1, int_32>;
groupFlagNew?: pb<2, int_32>;
uin?: pb<3, uint_64>;
longTextFlag?: pb<6, int_32>;
longTextResId?: pb<7, string>;
}
// ── Elem (union of all element types) ───────────────────────────────
export interface Elem {
text?: pb<1, TextElem>;
face?: pb<2, FaceElem>;
onlineImage?: pb<3, OnlineImage>;
notOnlineImage?: pb<4, NotOnlineImage>;
transElem?: pb<5, TransElem>;
marketFace?: pb<6, MarketFace>;
customFace?: pb<8, CustomFace>;
richMsg?: pb<12, RichMsg>;
groupFile?: pb<13, GroupFileElem>;
extraInfo?: pb<16, ExtraInfo>;
videoFile?: pb<19, VideoFile>;
generalFlags?: pb<37, GeneralFlags>;
srcMsg?: pb<45, SrcMsg>;
lightApp?: pb<51, LightAppElem>;
commonElem?: pb<53, CommonElem>;
}
// ── Extra decode types (for CommonElem.pbElem sub-messages) ─────────
export interface MentionExtra {
type?: pb<3, int_32>;
uin?: pb<4, uint_32>;
field5?: pb<5, int_32>;
uid?: pb<9, string>;
}
export interface QFaceExtra {
packId?: pb<1, string>;
stickerId?: pb<2, string>;
qsid?: pb<3, int_32>;
sourceType?: pb<4, int_32>;
stickerType?: pb<5, int_32>;
resultId?: pb<6, string>;
text?: pb<7, string>;
randomType?: pb<9, int_32>;
}
export interface QSmallFaceExtra {
faceId?: pb<1, uint_32>;
preview?: pb<2, string>;
preview2?: pb<3, string>;
}
// ── NTQQ MsgInfo types (CommonElem service_type 48) ─────────────────
export interface FileType {
type?: pb<1, uint_32>;
picFormat?: pb<2, uint_32>;
videoFormat?: pb<3, uint_32>;
voiceFormat?: pb<4, uint_32>;
}
export interface FileInfo {
fileSize?: pb<1, uint_32>;
fileHash?: pb<2, string>;
fileSha1?: pb<3, string>;
fileName?: pb<4, string>;
type?: pb<5, FileType>;
width?: pb<6, uint_32>;
height?: pb<7, uint_32>;
time?: pb<8, uint_32>;
original?: pb<9, uint_32>;
}
export interface IndexNode {
info?: pb<1, FileInfo>;
fileUuid?: pb<2, string>;
storeId?: pb<3, uint_32>;
uploadTime?: pb<4, uint_32>;
ttl?: pb<5, uint_32>;
subType?: pb<6, uint_32>;
}
export interface PicUrlExtInfo {
originalParameter?: pb<1, string>;
bigParameter?: pb<2, string>;
thumbParameter?: pb<3, string>;
}
export interface PictureInfo {
urlPath?: pb<1, string>;
ext?: pb<2, PicUrlExtInfo>;
domain?: pb<3, string>;
}
export interface PicExtData {
subType?: pb<1, uint_32>;
textSummary?: pb<9, string>;
}
export interface PicExtBizInfo {
bizType?: pb<1, uint_32>;
textSummary?: pb<2, string>;
bytesPbReserveC2c?: pb<11, bytes>;
extData?: pb<12, PicExtData>;
fromScene?: pb<1001, uint_32>;
toScene?: pb<1002, uint_32>;
oldFileId?: pb<1003, uint_32>;
}
export interface VideoExtBizInfo {
fromScene?: pb<1, uint_32>;
toScene?: pb<2, uint_32>;
bytesPbReserve?: pb<3, bytes>;
}
export interface PttExtBizInfo {
srcUin?: pb<1, uint_64>;
pttScene?: pb<2, uint_32>;
pttType?: pb<3, uint_32>;
changeVoice?: pb<4, uint_32>;
waveform?: pb<5, bytes>;
autoConvertText?: pb<6, uint_32>;
bytesReserve?: pb<11, bytes>;
bytesPbReserve?: pb<12, bytes>;
bytesGeneralFlags?: pb<13, bytes>;
}
export interface ExtBizInfo {
pic?: pb<1, PicExtBizInfo>;
video?: pb<2, VideoExtBizInfo>;
ptt?: pb<3, PttExtBizInfo>;
busiType?: pb<10, uint_32>;
}
export interface C2cSource {
friendUid?: pb<2, string>;
}
export interface TroopSource {
groupUin?: pb<1, uint_32>;
}
export interface HashSum {
bytesPbReserveC2c?: pb<201, C2cSource>;
troopSource?: pb<202, TroopSource>;
}
export interface MsgInfoBody {
index?: pb<1, IndexNode>;
picture?: pb<2, PictureInfo>;
fileExist?: pb<5, bool>;
hashSum?: pb<6, HashSum>;
}
export interface MsgInfo {
msgInfoBody?: pb_repeated<1, MsgInfoBody>;
extBizInfo?: pb<2, ExtBizInfo>;
}
// ── GroupFileExtra (TransElem type=24) ──────────────────────────────
//
// Sourced from NapCat's `GroupFileExtraInfo` (component.ts:146-155)
// cross-checked against acidify's `GroupFileExtra.Inner.Info`
// (proto/message/extra/GroupFileExtra.kt). Field numbers had been
// shifted by one in the previous schema (fileSha at 5, ext at 6,
// fileMd5 at 7) which caused the server to reject group-file chat
// posts with `result=79` — the server saw fileSha bytes where it
// expected a uint32 placeholder (field 5) and silently dropped the
// rest. Field 5 is a uint32 placeholder both refs label `field5`;
// fileSha is at 6, extInfoString at 7, fileMd5 at 8.
export interface GroupFileInfo {
busId?: pb<1, uint_32>;
fileId?: pb<2, string>;
fileSize?: pb<3, uint_64>;
fileName?: pb<4, string>;
field5?: pb<5, uint_32>;
fileSha?: pb<6, bytes>;
extInfoString?: pb<7, string>;
fileMd5?: pb<8, bytes>;
}
export interface GroupFileExtraInner {
info?: pb<2, GroupFileInfo>;
}
// Outer wrapper carries three additional fields the server expects:
// field1 (uint32, NapCat hardcodes to 6 — "magic op tag"), fileName
// (string mirror of the inner info.fileName), display (optional UI
// preview string, NapCat leaves empty but writes the slot). Without
// these the server still recognized the message in older builds but
// rejects it in the current rollout.
export interface GroupFileExtra {
field1?: pb<1, uint_32>;
fileName?: pb<2, string>;
display?: pb<3, string>;
inner?: pb<7, GroupFileExtraInner>;
}
// ── Preserve (for message receipt info) ─────────────────────────────
export interface Preserve {
messageId?: pb<3, uint_64>;
senderUid?: pb<6, string>;
receiverUid?: pb<7, string>;
clientSequence?: pb<8, uint_32>;
}
@@ -0,0 +1,333 @@
// Proton (compile-time) form of bridge/proto/highway.ts.
// One-to-one mirror; legacy `*Schema` constants stay alongside for back-compat.
import type { pb, pb_repeated, int_32, uint_32, uint_64, bool, bytes } from '@snowluma/proton';
import type {
IndexNode,
PictureInfo,
HashSum,
PicExtBizInfo,
VideoExtBizInfo,
PttExtBizInfo,
} from './element';
// ── DataHighwayHead ─────────────────────────────────────────────────
export interface DataHighwayHead {
version?: pb<1, uint_32>;
uin?: pb<2, string>;
command?: pb<3, string>;
seq?: pb<4, uint_32>;
retryTimes?: pb<5, uint_32>;
appId?: pb<6, uint_32>;
dataFlag?: pb<7, uint_32>;
commandId?: pb<8, uint_32>;
}
export interface SegHead {
serviceId?: pb<1, uint_32>;
filesize?: pb<2, uint_64>;
dataOffset?: pb<3, uint_64>;
dataLength?: pb<4, uint_32>;
retCode?: pb<5, uint_32>;
serviceTicket?: pb<6, bytes>;
flag?: pb<7, uint_32>;
md5?: pb<8, bytes>;
fileMd5?: pb<9, bytes>;
cacheAddr?: pb<10, uint_32>;
cachePort?: pb<13, uint_32>;
}
export interface LoginSigHead {
loginSigType?: pb<1, uint_32>;
appId?: pb<3, uint_32>;
}
export interface ReqDataHighwayHead {
msgBaseHead?: pb<1, DataHighwayHead>;
msgSegHead?: pb<2, SegHead>;
bytesReqExtendInfo?: pb<3, bytes>;
timestamp?: pb<4, uint_64>;
msgLoginSigHead?: pb<5, LoginSigHead>;
}
export interface RespDataHighwayHead {
msgBaseHead?: pb<1, DataHighwayHead>;
msgSegHead?: pb<2, SegHead>;
errorCode?: pb<3, uint_32>;
}
// ── Highway extend (NTV2RichMediaHighwayExt) ────────────────────────
export interface HighwayDomain {
isEnable?: pb<1, bool>;
ip?: pb<2, string>;
}
export interface HighwayIPv4 {
domain?: pb<1, HighwayDomain>;
port?: pb<2, uint_32>;
}
export interface HighwayNetwork {
ipv4s?: pb_repeated<1, HighwayIPv4>;
}
export interface HighwayHash {
fileSha1?: pb_repeated<1, bytes>;
}
export interface HighwayMsgInfoBody {
index?: pb<1, IndexNode>;
picture?: pb<2, PictureInfo>;
fileExist?: pb<5, bool>;
hashSum?: pb<6, HashSum>;
}
export interface NTV2RichMediaHighwayExt {
fileUuid?: pb<1, string>;
uKey?: pb<2, string>;
network?: pb<5, HighwayNetwork>;
msgInfoBody?: pb_repeated<6, HighwayMsgInfoBody>;
blockSize?: pb<10, uint_32>;
hash?: pb<11, HighwayHash>;
}
// ── File upload extend (group/private file highway) ─────────────────
export interface FileUploadUrl {
unknown?: pb<1, int_32>;
host?: pb<2, string>;
}
export interface FileUploadHost {
url?: pb<1, FileUploadUrl>;
port?: pb<2, uint_32>;
}
export interface FileUploadHostConfig {
hosts?: pb_repeated<200, FileUploadHost>;
}
export interface FileUploadNameInfo {
fileName?: pb<100, string>;
}
export interface FileUploadClientInfo {
clientType?: pb<100, int_32>;
appId?: pb<200, string>;
terminalType?: pb<300, int_32>;
clientVer?: pb<400, string>;
unknown?: pb<600, int_32>;
}
export interface FileUploadFileEntry {
fileSize?: pb<100, uint_64>;
md5?: pb<200, bytes>;
checkKey?: pb<300, bytes>;
md5S2?: pb<400, bytes>;
fileId?: pb<600, string>;
uploadKey?: pb<700, bytes>;
}
export interface FileUploadBusiInfo {
busId?: pb<1, int_32>;
senderUin?: pb<100, uint_64>;
receiverUin?: pb<200, uint_64>;
groupCode?: pb<400, uint_64>;
}
export interface FileUploadEntry {
busiBuff?: pb<100, FileUploadBusiInfo>;
fileEntry?: pb<200, FileUploadFileEntry>;
clientInfo?: pb<300, FileUploadClientInfo>;
fileNameInfo?: pb<400, FileUploadNameInfo>;
host?: pb<500, FileUploadHostConfig>;
}
export interface FileUploadExt {
unknown1?: pb<1, int_32>;
unknown2?: pb<2, int_32>;
unknown3?: pb<3, int_32>;
entry?: pb<100, FileUploadEntry>;
unknown200?: pb<200, int_32>;
}
// ── Encodable MsgInfo (for embedding in message element) ────────────
export interface EncodableMediaExtBizInfo {
pic?: pb<1, PicExtBizInfo>;
video?: pb<2, VideoExtBizInfo>;
ptt?: pb<3, PttExtBizInfo>;
busiType?: pb<10, uint_32>;
}
export interface EncodableMediaMsgInfo {
msgInfoBody?: pb_repeated<1, HighwayMsgInfoBody>;
extBizInfo?: pb<2, EncodableMediaExtBizInfo>;
}
// ── HttpConn.0x6ff_501 (highway session) ────────────────────────────
export interface HttpConn {
field1?: pb<1, int_32>;
field2?: pb<2, int_32>;
field3?: pb<3, int_32>;
field4?: pb<4, int_32>;
field6?: pb<6, int_32>;
serviceTypes?: pb_repeated<7, uint_32>;
field9?: pb<9, int_32>;
field10?: pb<10, int_32>;
field11?: pb<11, int_32>;
ver?: pb<15, string>;
}
export interface HttpConn0x6FF501Request {
httpConn?: pb<0x501, HttpConn>;
}
export interface ServerAddr {
type?: pb<1, uint_32>;
ip?: pb<2, uint_32>;
port?: pb<3, uint_32>;
area?: pb<4, uint_32>;
}
export interface ServerInfo {
serviceType?: pb<1, uint_32>;
serverAddrs?: pb_repeated<2, ServerAddr>;
}
export interface HttpConnResponse {
sigSession?: pb<1, bytes>;
sessionKey?: pb<2, bytes>;
serverInfos?: pb_repeated<3, ServerInfo>;
}
export interface HttpConn0x6FF501Response {
httpConn?: pb<0x501, HttpConnResponse>;
}
// ── NTV2 Upload Request (for OIDB 0x11C4/0x11C5) ────────────────────
export interface NTV2FileType {
type?: pb<1, uint_32>;
picFormat?: pb<2, uint_32>;
videoFormat?: pb<3, uint_32>;
voiceFormat?: pb<4, uint_32>;
}
export interface NTV2FileInfo {
fileSize?: pb<1, uint_32>;
fileHash?: pb<2, string>;
fileSha1?: pb<3, string>;
fileName?: pb<4, string>;
type?: pb<5, NTV2FileType>;
width?: pb<6, uint_32>;
height?: pb<7, uint_32>;
time?: pb<8, uint_32>;
original?: pb<9, uint_32>;
}
export interface NTV2UploadInfo {
fileInfo?: pb<1, NTV2FileInfo>;
subFileType?: pb<2, uint_32>;
}
// The NTV2 upload request + response carry the same ExtBizInfo shape that
// element-side incoming-message decoding uses. See bridge/proto/highway.ts
// for the rationale (the video fromScene/toScene drop was responsible for
// c2c result=79 rejections on send_private_msg [{type:'video'}]).
export interface NTV2ExtBizInfo {
pic?: pb<1, PicExtBizInfo>;
video?: pb<2, VideoExtBizInfo>;
ptt?: pb<3, PttExtBizInfo>;
busiType?: pb<10, uint_32>;
}
export interface NTV2UploadReq {
uploadInfo?: pb_repeated<1, NTV2UploadInfo>;
tryFastUploadCompleted?: pb<2, bool>;
srvSendMsg?: pb<3, bool>;
clientRandomId?: pb<4, uint_64>;
compatQmsgSceneType?: pb<5, uint_32>;
extBizInfo?: pb<6, NTV2ExtBizInfo>;
clientSeq?: pb<7, uint_32>;
noNeedCompatMsg?: pb<8, bool>;
}
export interface NTV2C2CUserInfo {
accountType?: pb<1, uint_32>;
targetUid?: pb<2, string>;
}
export interface NTV2GroupInfo {
groupUin?: pb<1, uint_32>;
}
export interface NTV2UploadSceneInfo {
requestType?: pb<101, uint_32>;
businessType?: pb<102, uint_32>;
sceneType?: pb<200, uint_32>;
c2c?: pb<201, NTV2C2CUserInfo>;
group?: pb<202, NTV2GroupInfo>;
}
export interface NTV2CommonHead {
requestId?: pb<1, uint_32>;
command?: pb<2, uint_32>;
}
export interface NTV2ClientMeta {
agentType?: pb<1, uint_32>;
}
export interface NTV2UploadReqHead {
common?: pb<1, NTV2CommonHead>;
scene?: pb<2, NTV2UploadSceneInfo>;
client?: pb<3, NTV2ClientMeta>;
}
export interface NTV2UploadRichMediaReq {
reqHead?: pb<1, NTV2UploadReqHead>;
upload?: pb<2, NTV2UploadReq>;
}
// ── NTV2 Upload Response ────────────────────────────────────────────
export interface NTV2IPv4 {
outIp?: pb<1, uint_32>;
outPort?: pb<2, uint_32>;
}
export interface NTV2SubFileInfoResp {
subType?: pb<1, uint_32>;
uKey?: pb<2, string>;
uKeyTtl?: pb<3, uint_32>;
ipv4s?: pb_repeated<4, NTV2IPv4>;
}
export interface NTV2UploadRespMsgInfo {
msgInfoBody?: pb_repeated<1, HighwayMsgInfoBody>;
extBizInfo?: pb<2, NTV2ExtBizInfo>;
}
export interface NTV2UploadRespBody {
uKey?: pb<1, string>;
uKeyTtl?: pb<2, uint_32>;
ipv4s?: pb_repeated<3, NTV2IPv4>;
msgSeq?: pb<5, uint_64>;
msgInfo?: pb<6, NTV2UploadRespMsgInfo>;
subFileInfos?: pb_repeated<10, NTV2SubFileInfoResp>;
}
export interface NTV2UploadRespHead {
common?: pb<1, NTV2CommonHead>;
retCode?: pb<2, uint_32>;
message?: pb<3, string>;
}
export interface NTV2UploadRichMediaResp {
respHead?: pb<1, NTV2UploadRespHead>;
upload?: pb<2, NTV2UploadRespBody>;
}
@@ -0,0 +1,77 @@
// Proton (compile-time) form of the long-message schemas.
//
// One-to-one mirror of `bridge/proto/longmsg.ts`. All 12 schemas are now
// migrated — the three (`LongMsgContent` / `LongMsgAction` / `LongMsgResult`)
// that reach into `PushMsgBody` resolve via the proton-form `message.ts`
// migration alongside this file.
import type { pb, pb_repeated, uint_32, bool, bytes } from '@snowluma/proton';
import type { PushMsgBody } from './message';
export interface LongMsgUid {
uid?: pb<2, string>;
}
export interface LongMsgSettings {
field1?: pb<1, uint_32>;
field2?: pb<2, uint_32>;
field3?: pb<3, uint_32>;
field4?: pb<4, uint_32>;
}
export interface SendLongMsgInfo {
type?: pb<1, uint_32>;
uid?: pb<2, LongMsgUid>;
groupUin?: pb<3, uint_32>;
payload?: pb<4, bytes>;
}
export interface SendLongMsgReq {
info?: pb<2, SendLongMsgInfo>;
settings?: pb<15, LongMsgSettings>;
}
export interface SendLongMsgRespResult {
resId?: pb<3, string>;
}
export interface SendLongMsgResp {
result?: pb<2, SendLongMsgRespResult>;
settings?: pb<15, LongMsgSettings>;
}
export interface RecvLongMsgInfo {
uid?: pb<1, LongMsgUid>;
resId?: pb<2, string>;
acquire?: pb<3, bool>;
}
export interface RecvLongMsgReq {
info?: pb<1, RecvLongMsgInfo>;
settings?: pb<15, LongMsgSettings>;
}
export interface RecvLongMsgRespResult {
resId?: pb<3, string>;
payload?: pb<4, bytes>;
}
export interface RecvLongMsgResp {
result?: pb<1, RecvLongMsgRespResult>;
settings?: pb<15, LongMsgSettings>;
}
// ── Schemas that reach into PushMsgBody (via message.ts) ────────────
export interface LongMsgContent {
msgBody?: pb_repeated<1, PushMsgBody>;
}
export interface LongMsgAction {
actionCommand?: pb<1, string>;
actionData?: pb<2, LongMsgContent>;
}
export interface LongMsgResult {
action?: pb_repeated<2, LongMsgAction>;
}
@@ -0,0 +1,126 @@
// Proton (compile-time) form of bridge/proto/message.ts.
// One-to-one mirror; legacy `*Schema` constants stay alongside for back-compat.
import type { pb, pb_repeated, int_32, uint_32, uint_64, bytes } from '@snowluma/proton';
import type { Elem } from './element';
// ── ResponseHead.Grp ────────────────────────────────────────────────
export interface ResponseGrp {
groupUin?: pb<1, uint_32>;
memberName?: pb<2, string>;
groupName?: pb<4, string>;
}
export interface ResponseForward {
friendName?: pb<6, string>;
}
// ── ResponseHead ────────────────────────────────────────────────────
export interface ResponseHead {
fromUin?: pb<1, uint_32>;
fromUid?: pb<2, string>;
type?: pb<3, uint_32>;
sigMap?: pb<4, uint_32>;
toUin?: pb<5, uint_32>;
toUid?: pb<6, string>;
forward?: pb<7, ResponseForward>;
grp?: pb<8, ResponseGrp>;
}
// ── ContentHead ─────────────────────────────────────────────────────
export interface ContentHead {
msgType?: pb<1, uint_32>;
subType?: pb<2, uint_32>;
divSeq?: pb<3, uint_32>;
msgId?: pb<4, uint_32>;
sequence?: pb<5, uint_32>;
timestamp?: pb<6, uint_32>;
field7?: pb<7, uint_64>;
newId?: pb<12, uint_64>;
}
// ── Ptt (voice) ─────────────────────────────────────────────────────
export interface Ptt {
fileType?: pb<1, uint_32>;
fileId?: pb<2, uint_64>;
fileUuid?: pb<3, bytes>;
fileMd5?: pb<4, bytes>;
fileName?: pb<5, string>;
fileSize?: pb<6, uint_32>;
groupFileKey?: pb<10, string>;
fileKey?: pb<14, bytes>;
time?: pb<19, uint_32>;
format?: pb<29, uint_32>;
}
// ── NotOnlineFile (C2C file) ────────────────────────────────────────
//
// Field numbers cross-checked against `dev/Lagrange.Core/.../Component/
// NotOnlineFile.cs`. This same shape is what gets serialised inside
// `FileExtra` (below) and ridden as `MessageBody.msgContent` for c2c
// file sends — fields 9/50/55 are required on send (subcmd=1,
// dangerEvel=0, expireTime=now+7d), the receiver only reads the
// identification slots.
export interface NotOnlineFile {
fileType?: pb<1, uint_32>;
fileUuid?: pb<3, string>;
fileMd5?: pb<4, bytes>;
fileName?: pb<5, string>;
fileSize?: pb<6, uint_64>;
subcmd?: pb<9, uint_32>;
dangerEvel?: pb<50, uint_32>;
expireTime?: pb<55, uint_32>;
fileHash?: pb<57, string>;
}
// ── RichText ────────────────────────────────────────────────────────
export interface RichText {
elems?: pb_repeated<2, Elem>;
notOnlineFile?: pb<3, NotOnlineFile>;
ptt?: pb<4, Ptt>;
}
// ── MessageBody ─────────────────────────────────────────────────────
export interface MessageBody {
richText?: pb<1, RichText>;
msgContent?: pb<2, bytes>;
}
// ── FileExtra (for C2C file in msg_content) ─────────────────────────
//
// `FileExtra { file: NotOnlineFile }` is the wrapper the server expects
// at `MessageBody.msgContent` (per `dev/Lagrange.Core/.../FileExtra.cs`).
// Old code had a parallel `FileExtraInfo` with fileSize=1, fileName=2,
// fileMd5=3, fileUuid=4, fileHash=5 — that schema didn't match the
// wire shape at all (every field was at the wrong tag), which is why
// c2c file messages we received via msgContent silently failed to
// parse, and c2c file messages we sent through `richText.notOnlineFile`
// (also wrong — see SendMessageBody) shipped a payload the recipient
// couldn't render. Consolidating to a single shared `NotOnlineFile`
// (identification fields 1/3/4/5/6/57) fixes both directions.
export interface FileExtra {
file?: pb<1, NotOnlineFile>;
}
// ── PushMsgBody ─────────────────────────────────────────────────────
export interface PushMsgBody {
responseHead?: pb<1, ResponseHead>;
contentHead?: pb<2, ContentHead>;
body?: pb<3, MessageBody>;
}
// ── PushMsg (top-level) ─────────────────────────────────────────────
export interface PushMsg {
message?: pb<1, PushMsgBody>;
status?: pb<3, int_32>;
}
@@ -0,0 +1,278 @@
// Proton (compile-time) form of bridge/proto/notify.ts.
// One-to-one mirror; legacy `*Schema` constants stay alongside for back-compat.
import type { pb, pb_repeated, int_32, uint_32, uint_64, bool, bytes } from '@snowluma/proton';
export interface OperatorField1 {
uid?: pb<1, string>;
field2?: pb<2, uint_32>;
field3?: pb<3, bytes>;
field4?: pb<4, uint_32>;
field5?: pb<5, bytes>;
}
export interface OperatorInfo {
operatorField?: pb<1, OperatorField1>;
}
export interface GroupChange {
groupUin?: pb<1, uint_32>;
flag?: pb<2, uint_32>;
memberUid?: pb<3, string>;
decreaseType?: pb<4, uint_32>;
operatorBytes?: pb<5, bytes>;
increaseType?: pb<6, uint_32>;
field7?: pb<7, bytes>;
}
export interface GroupAdminExtra {
adminUid?: pb<1, string>;
isPromote?: pb<2, bool>;
}
export interface GroupAdminBody {
extraDisable?: pb<1, GroupAdminExtra>;
extraEnable?: pb<2, GroupAdminExtra>;
}
export interface GroupAdmin {
groupUin?: pb<1, uint_32>;
flag?: pb<2, uint_32>;
isPromote?: pb<3, bool>;
body?: pb<4, GroupAdminBody>;
}
export interface InvitationInner {
groupUin?: pb<1, uint_32>;
field2?: pb<2, uint_32>;
field3?: pb<3, uint_32>;
field4?: pb<4, uint_32>;
targetUid?: pb<5, string>;
invitorUid?: pb<6, string>;
field7?: pb<7, uint_32>;
field9?: pb<9, uint_32>;
field10?: pb<10, bytes>;
field11?: pb<11, uint_32>;
field12?: pb<12, string>;
}
export interface InvitationInfo {
inner?: pb<1, InvitationInner>;
}
export interface GroupInvitation {
cmd?: pb<1, int_32>;
info?: pb<2, InvitationInfo>;
}
export interface GroupInvite {
groupUin?: pb<1, uint_32>;
field2?: pb<2, uint_32>;
field3?: pb<3, uint_32>;
field4?: pb<4, uint_32>;
invitorUid?: pb<5, string>;
hashes?: pb<6, bytes>;
}
export interface GroupJoin {
groupUin?: pb<1, uint_32>;
field2?: pb<2, uint_32>;
targetUid?: pb<3, string>;
field4?: pb<4, uint_32>;
field6?: pb<6, uint_32>;
field7?: pb<7, string>;
field8?: pb<8, uint_32>;
field9?: pb<9, bytes>;
}
export interface FriendRequestInfo {
targetUid?: pb<1, string>;
sourceUid?: pb<2, string>;
newSource?: pb<5, string>;
message?: pb<10, string>;
source?: pb<11, string>;
}
export interface FriendRequest {
info?: pb<1, FriendRequestInfo>;
}
export interface FriendRecallTipInfo {
tip?: pb<2, string>;
}
export interface FriendRecallInfo {
fromUid?: pb<1, string>;
toUid?: pb<2, string>;
clientSequence?: pb<3, uint_32>;
newId?: pb<4, uint_64>;
time?: pb<5, uint_32>;
random?: pb<6, uint_32>;
pkgNum?: pb<7, uint_32>;
pkgIndex?: pb<8, uint_32>;
divSeq?: pb<9, uint_32>;
tipInfo?: pb<13, FriendRecallTipInfo>;
}
export interface FriendRecall {
info?: pb<1, FriendRecallInfo>;
instId?: pb<2, uint_32>;
appId?: pb<3, uint_32>;
longMessageFlag?: pb<4, uint_32>;
reserved?: pb<5, bytes>;
}
// ── NewFriend (0x210 subType 179 + 226) ───────────────────────────
//
// Mutual-accept friend notice. Fires when:
// - bot sent a friend request and the other side accepted (179), or
// - the other side sent a request and bot accepted it (226).
// Both subTypes share this wire shape; field semantics follow
// `LagrangeDev/LagrangeGo` client/packets/pb/message/notify.proto.
export interface NewFriendInfo {
uid?: pb<1, string>;
field2?: pb<2, uint_32>;
time?: pb<3, uint_32>; // fixed32 on wire; uint_32 decoded value is the unix epoch
message?: pb<4, string>;
nickName?: pb<5, string>;
field6?: pb<6, uint_32>;
field7?: pb<7, uint_32>;
toUid?: pb<9, string>;
}
export interface NewFriend {
field1?: pb<1, uint_32>;
info?: pb<2, NewFriendInfo>;
}
// ── SelfJoinInGroup (PkgType 85) ──────────────────────────────────
//
// Fired when the bot itself was admitted into a group — typically the
// completion of an admin-approved join request or an accepted invite.
// Ported from `lagrange-python/pb/status/group.py:170 PBSelfJoinInGroup`.
export interface SelfJoinInGroup {
groupUin?: pb<1, uint_64>;
field2?: pb<2, uint_32>;
operatorUid?: pb<3, string>;
field4?: pb<4, uint_32>;
field6?: pb<6, uint_32>;
field7?: pb<7, string>;
}
export interface GroupMuteState {
targetUid?: pb<1, string>;
duration?: pb<2, uint_32>;
}
export interface GroupMuteData {
timestamp?: pb<1, uint_32>;
type?: pb<2, uint_32>;
state?: pb<3, GroupMuteState>;
}
export interface GroupMute {
groupUin?: pb<1, uint_32>;
subType?: pb<2, uint_32>;
field3?: pb<3, uint_32>;
operatorUid?: pb<4, string>;
data?: pb<5, GroupMuteData>;
}
export interface RecallMessage {
sequence?: pb<1, uint_32>;
time?: pb<2, uint_32>;
random?: pb<3, uint_32>;
type?: pb<4, uint_32>;
flag?: pb<5, uint_32>;
authorUid?: pb<6, string>;
}
export interface GroupRecallTipInfo {
tip?: pb<2, string>;
}
export interface GroupRecall {
operatorUid?: pb<1, string>;
recallMessages?: pb_repeated<3, RecallMessage>;
userDef?: pb<5, bytes>;
groupType?: pb<6, int_32>;
opType?: pb<7, int_32>;
tipInfo?: pb<9, GroupRecallTipInfo>;
}
export interface TemplParam {
name?: pb<1, string>;
value?: pb<2, string>;
}
export interface GeneralGrayTipInfo {
busiType?: pb<1, uint_64>;
busiId?: pb<2, uint_64>;
ctrlFlag?: pb<3, uint_32>;
c2cType?: pb<4, uint_32>;
serviceType?: pb<5, uint_32>;
templId?: pb<6, uint_64>;
msgTemplParam?: pb_repeated<7, TemplParam>;
content?: pb<8, string>;
}
export interface EssenceMessage {
groupUin?: pb<1, uint_32>;
msgSequence?: pb<2, uint_32>;
random?: pb<3, uint_32>;
setFlag?: pb<4, uint_32>;
memberUin?: pb<5, uint_32>;
operatorUin?: pb<6, uint_32>;
timestamp?: pb<7, uint_32>;
msgSequence2?: pb<8, uint_32>;
operatorNickname?: pb<9, string>;
memberNickname?: pb<10, string>;
setFlag2?: pb<11, uint_32>;
}
export interface NotifyMessageBody {
type?: pb<1, uint_32>;
groupUin?: pb<4, uint_32>;
eventParam?: pb<5, bytes>;
recall?: pb<11, GroupRecall>;
field13?: pb<13, uint_32>;
operatorUid?: pb<21, string>;
generalGrayTip?: pb<26, GeneralGrayTipInfo>;
essenceMessage?: pb<33, EssenceMessage>;
msgSequence?: pb<37, uint_32>;
field39?: pb<39, uint_32>;
}
// ─── Event0x2DC subType=16: GroupMsgEmojiLike ────────────────────────
export interface GroupReactionDataInnerDataTarget {
seq?: pb<1, uint_64>;
}
export interface GroupReactionDataContent {
code?: pb<1, string>;
count?: pb<3, uint_32>;
operatorUid?: pb<4, string>;
type?: pb<5, uint_32>;
}
export interface GroupReactionDataInnerData {
groupReactionTarget?: pb<2, GroupReactionDataInnerDataTarget>;
groupReactionDataContent?: pb<3, GroupReactionDataContent>;
}
export interface GroupReactionDataInner {
data?: pb<1, GroupReactionDataInnerData>;
}
export interface GroupReactionData {
data?: pb<1, GroupReactionDataInner>;
}
export interface GroupReactNotify {
groupUin?: pb<4, uint_64>;
field13?: pb<13, uint_32>;
groupReactionData?: pb<44, GroupReactionData>;
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,180 @@
// Proton (compile-time) form of bridge/proto/oidb.ts.
//
// The legacy file exports a `makeOidbBaseSchema(body)` factory that builds the
// OidbSvcTrpcTcpBase envelope at runtime; here that wrapper is expressed
// once as the generic `OidbBase<T>` interface. Every existing
// `makeOidbBaseSchema(InnerSchema)` call site becomes `OidbBase<Inner>`
// at the type level, and the proton plugin monomorphizes the codec
// per-instantiation at build time.
//
// `OidbBaseMeta` is the envelope-only view used by fire-and-check calls
// that want to peek at the error code without decoding the body.
import type { pb, pb_repeated, int_32, uint_32, uint_64, bytes } from '@snowluma/proton';
// ── OidbSvcTrpcTcpBase wrapper ──────────────────────────────────────
export interface OidbProperty {
key?: pb<1, string>;
value?: pb<2, bytes>;
}
export interface OidbBase<TBody> {
command?: pb<1, uint_32>;
subCommand?: pb<2, uint_32>;
errorCode?: pb<3, uint_32>;
body?: pb<4, TBody>;
errorMsg?: pb<5, string>;
properties?: pb_repeated<11, OidbProperty>;
reserved?: pb<12, int_32>;
}
/**
* Envelope-only view used by fire-and-check calls — proto3 wire format
* silently skips unknown fields, so decoding any OidbBase<T> message with
* this shape returns just the metadata and ignores the inner body.
*/
export interface OidbBaseMeta {
command?: pb<1, uint_32>;
subCommand?: pb<2, uint_32>;
errorCode?: pb<3, uint_32>;
errorMsg?: pb<5, string>;
reserved?: pb<12, int_32>;
}
// ── Friend list (0xFD4_1) ───────────────────────────────────────────
export interface OidbFriendProperty {
code?: pb<1, uint_32>;
value?: pb<2, string>;
}
export interface OidbFriendLayer1 {
properties?: pb_repeated<2, OidbFriendProperty>;
}
export interface OidbFriendAdditional {
type?: pb<1, uint_32>;
layer1?: pb<2, OidbFriendLayer1>;
}
export interface OidbFriend {
uid?: pb<1, string>;
customGroup?: pb<2, uint_32>;
uin?: pb<3, uint_32>;
additional?: pb_repeated<10001, OidbFriendAdditional>;
}
export interface OidbSvcTrpcTcp0xFD4_1ResponseUin {
uin?: pb<1, uint_32>;
}
export interface OidbSvcTrpcTcp0xFD4_1Response {
next?: pb<2, OidbSvcTrpcTcp0xFD4_1ResponseUin>;
displayFriendCount?: pb<3, uint_32>;
timestamp?: pb<6, uint_32>;
selfUin?: pb<7, uint_32>;
friends?: pb_repeated<101, OidbFriend>;
groups?: pb_repeated<102, OidbFriendProperty>;
}
// ── Group list (0xFE5_2) ────────────────────────────────────────────
export interface OidbSvcTrpcTcp0xFE5_2Member {
uid?: pb<2, string>;
}
export interface OidbSvcTrpcTcp0xFE5_2GroupInfo {
groupOwner?: pb<1, OidbSvcTrpcTcp0xFE5_2Member>;
createdTime?: pb<2, uint_32>;
memberMax?: pb<3, uint_32>;
memberCount?: pb<4, uint_32>;
groupName?: pb<5, string>;
description?: pb<18, string>;
question?: pb<19, string>;
announcement?: pb<30, string>;
}
export interface OidbSvcTrpcTcp0xFE5_2CustomInfo {
remark?: pb<3, string>;
}
export interface OidbSvcTrpcTcp0xFE5_2Group {
groupUin?: pb<3, uint_32>;
info?: pb<4, OidbSvcTrpcTcp0xFE5_2GroupInfo>;
customInfo?: pb<5, OidbSvcTrpcTcp0xFE5_2CustomInfo>;
}
export interface OidbSvcTrpcTcp0xFE5_2Response {
groups?: pb_repeated<2, OidbSvcTrpcTcp0xFE5_2Group>;
}
// ── Group member list (0xFE7_3) ─────────────────────────────────────
export interface OidbSvcTrpcTcp0xFE7_3Uin {
uid?: pb<2, string>;
uin?: pb<4, uint_32>;
}
export interface OidbSvcTrpcTcp0xFE7_3Card {
memberCard?: pb<2, string>;
}
export interface OidbSvcTrpcTcp0xFE7_3Level {
infos?: pb_repeated<1, uint_32>;
level?: pb<2, uint_32>;
}
export interface OidbSvcTrpcTcp0xFE7_3Member {
uin?: pb<1, OidbSvcTrpcTcp0xFE7_3Uin>;
memberName?: pb<10, string>;
specialTitle?: pb<17, string>;
memberCard?: pb<11, OidbSvcTrpcTcp0xFE7_3Card>;
level?: pb<12, OidbSvcTrpcTcp0xFE7_3Level>;
joinTimestamp?: pb<100, uint_32>;
lastMsgTimestamp?: pb<101, uint_32>;
shutUpTimestamp?: pb<102, uint_32>;
permission?: pb<107, uint_32>;
}
export interface OidbSvcTrpcTcp0xFE7_3Response {
groupUin?: pb<1, uint_32>;
members?: pb_repeated<2, OidbSvcTrpcTcp0xFE7_3Member>;
field3?: pb<3, uint_32>;
memberChangeSeq?: pb<5, uint_32>;
memberCardChangeSeq?: pb<6, uint_32>;
token?: pb<15, string>;
}
// ── Group request (0x10C0) ──────────────────────────────────────────
export interface OidbSvcTrpcTcp0x10C0ResponseUser {
uid?: pb<1, string>;
name?: pb<2, string>;
}
export interface OidbSvcTrpcTcp0x10C0ResponseGroup {
groupUin?: pb<1, uint_32>;
groupName?: pb<2, string>;
}
export interface OidbSvcTrpcTcp0x10C0ResponseRequest {
sequence?: pb<1, uint_64>;
eventType?: pb<2, uint_32>;
state?: pb<3, uint_32>;
group?: pb<4, OidbSvcTrpcTcp0x10C0ResponseGroup>;
target?: pb<5, OidbSvcTrpcTcp0x10C0ResponseUser>;
invitor?: pb<6, OidbSvcTrpcTcp0x10C0ResponseUser>;
operatorUser?: pb<7, OidbSvcTrpcTcp0x10C0ResponseUser>;
field9?: pb<9, string>;
comment?: pb<10, string>;
}
export interface OidbSvcTrpcTcp0x10C0Response {
requests?: pb_repeated<1, OidbSvcTrpcTcp0x10C0ResponseRequest>;
field2?: pb<2, uint_64>;
newLatestSeq?: pb<3, uint_64>;
field4?: pb<4, uint_32>;
field5?: pb<5, uint_64>;
field6?: pb<6, uint_32>;
}
+13 -19
View File
@@ -4,22 +4,19 @@
// thread the cookies into a qun.qq.com REST endpoint.
import type { Bridge } from '../bridge';
import { runOidb } from '../bridge-oidb';
import {
OidbClientKeyRespSchema,
OidbClientKeyReqSchema,
OidbGetPskeyReqSchema,
OidbGetPskeyRespSchema,
} from '../proto/oidb-action';
import { runOidb, makeOidbEnvelope, encodeOidbEnv, decodeOidbEnv } from '../bridge-oidb';
import type {
OidbClientKeyReq,
OidbClientKeyResp,
OidbGetPskeyReq,
OidbGetPskeyResp,
} from '../proto/proton/oidb-action';
import { RequestUtil } from '../web/request-util';
export async function forceFetchClientKey(bridge: Bridge) {
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x102a_1',
oidbCmd: 0x102A, subCmd: 1,
request: { schema: OidbClientKeyReqSchema, value: {} },
response: { schema: OidbClientKeyRespSchema },
});
const env = makeOidbEnvelope<OidbClientKeyReq>(0x102A, 1, {});
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x102a_1', encodeOidbEnv<OidbClientKeyReq>(env));
const resp = decodeOidbEnv<OidbClientKeyResp>(respBytes).body;
const clientKey = resp?.clientKey || '';
// keyIndex falls back to "19" — origin unknown but the value is what
@@ -34,12 +31,9 @@ export async function forceFetchClientKey(bridge: Bridge) {
}
export async function getPSkey(bridge: Bridge, domainList: string[]) {
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x102a_0',
oidbCmd: 0x102A, subCmd: 0,
request: { schema: OidbGetPskeyReqSchema, value: { domainList } },
response: { schema: OidbGetPskeyRespSchema },
});
const env = makeOidbEnvelope<OidbGetPskeyReq>(0x102A, 0, { domainList });
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x102a_0', encodeOidbEnv<OidbGetPskeyReq>(env));
const resp = decodeOidbEnv<OidbGetPskeyResp>(respBytes).body;
const domainPskeyMap = new Map<string, string>();
@@ -0,0 +1,29 @@
// Group album actions via web API
import type { Bridge } from '../bridge';
import { getGroupAlbumList, uploadImageToGroupAlbum } from '../web/group-album';
import { getCookies } from './cookies';
export async function getGroupAlbumListWeb(bridge: Bridge, groupId: number) {
const groupCode = groupId.toString();
const uin = bridge.identity.uin;
const cookieObject = await getCookies(bridge, 'qzone.qq.com');
const albumData = await getGroupAlbumList(cookieObject, groupCode, uin);
return albumData?.album || [];
}
export async function uploadImageToGroupAlbumWeb(
bridge: Bridge,
groupId: number,
albumId: string,
albumName: string,
filePath: string
): Promise<void> {
const groupCode = groupId.toString();
const uin = bridge.identity.uin;
const cookieObject = await getCookies(bridge, 'qzone.qq.com');
await uploadImageToGroupAlbum(cookieObject, groupCode, albumId, albumName, filePath, uin);
}
@@ -25,3 +25,8 @@ export {
getGroupNotice,
deleteGroupNoticeByFid,
} from './group-notice';
export {
getGroupAlbumListWeb,
uploadImageToGroupAlbumWeb,
} from './group-album';
+250
View File
@@ -0,0 +1,250 @@
import { RequestUtil, cookieToString, getBknFromCookie } from './request-util';
import { createHash } from 'crypto';
import { readFileSync, statSync, createReadStream, writeFileSync, unlinkSync } from 'fs';
import { basename, join } from 'path';
import { tmpdir } from 'os';
// 群相册信息
export interface GroupAlbumInfo {
id: string;
name: string;
picNum: number;
createTime: number;
[key: string]: any;
}
// 获取群相册列表返回
export interface GroupAlbumListRet {
album: GroupAlbumInfo[];
[key: string]: any;
}
// 相册媒体信息
export interface AlbumMediaInfo {
photoId: string;
url: string;
uploadTime: number;
[key: string]: any;
}
/**
* 获取群相册列表
*/
export async function getGroupAlbumList(
cookieObject: Record<string, string>,
groupId: string,
uin: string
): Promise<GroupAlbumListRet | undefined> {
if (!cookieObject || typeof cookieObject !== 'object') {
throw new Error('cookieObject is required');
}
const bkn = getBknFromCookie(cookieObject);
const url = `https://h5.qzone.qq.com/proxy/domain/u.photo.qzone.qq.com/cgi-bin/upp/qun_list_album_v2?${new URLSearchParams({
random: '7570',
g_tk: bkn,
format: 'json',
inCharset: 'utf-8',
outCharset: 'utf-8',
qua: 'V1_IPH_SQ_6.2.0_0_HDBM_T',
cmd: 'qunGetAlbumList',
qunId: groupId,
qunid: groupId,
start: '0',
num: '1000',
uin,
getMemberRole: '0',
}).toString()}`;
const ret = await RequestUtil.HttpGetJson<{ data: GroupAlbumListRet }>(
url,
'GET',
'',
{ Cookie: cookieToString(cookieObject) }
);
if (!ret || typeof ret !== 'object') {
throw new Error('invalid response from qzone api');
}
return ret.data;
}
/**
* 创建群相册上传会话
*/
async function createAlbumUploadSession(
groupId: string,
albumId: string,
albumName: string,
filePath: string,
skey: string,
pskey: string,
imgMd5: string,
uin: string
): Promise<string> {
const imgSize = statSync(filePath).size;
const imgName = basename(filePath);
const bkn = getBknFromCookie({ skey });
const timestamp = Math.floor(Date.now() / 1000);
const body = {
control_req: [{
uin,
token: { type: 4, data: pskey, appid: 5 },
appid: 'qun',
checksum: imgMd5,
check_type: 0,
file_len: imgSize,
env: { refer: 'qzone', deviceInfo: 'h5' },
model: 0,
biz_req: {
sPicTitle: imgName,
sPicDesc: '',
sAlbumName: albumName,
sAlbumID: albumId,
iAlbumTypeID: 0,
iBitmap: 0,
iUploadType: 0,
iUpPicType: 0,
iBatchID: timestamp,
sPicPath: '',
iPicWidth: 0,
iPicHight: 0,
iWaterType: 0,
iDistinctUse: 0,
iNeedFeeds: 1,
iUploadTime: timestamp,
mapExt: { appid: 'qun', userid: groupId },
stExtendInfo: { mapParams: { photo_num: '1', video_num: '0', batch_num: '1' } },
},
session: '',
asy_upload: 0,
cmd: 'FileUpload',
}],
};
const api = `https://h5.qzone.qq.com/webapp/json/sliceUpload/FileBatchControl/${imgMd5}?g_tk=${bkn}`;
const cookie = `p_uin=o${uin}; p_skey=${pskey}; skey=${skey}; uin=o${uin}`;
const response = await RequestUtil.HttpGetJson<{ data: { session: string }, ret: number, msg: string }>(
api,
'POST',
body,
{ Cookie: cookie, 'Content-Type': 'application/json' }
);
if (response.ret !== 0 || !response.data?.session) {
throw new Error(`创建上传会话失败: ${response.msg}`);
}
return response.data.session;
}
/**
* 修复后的上传图片分片方法
*/
async function uploadAlbumSlice(
session: string,
filePath: string,
// 移除 offset 和 chunkSize 参数,改为在内部控制
imgMd5: string,
skey: string,
pskey: string,
uin: string
): Promise<void> {
const img_size = statSync(filePath).size;
const slice_size = 16384; // 严格使用 16KB
const bkn = getBknFromCookie({ skey });
const cookie = `p_uin=o${uin}; p_skey=${pskey}; skey=${skey}; uin=o${uin}`;
const stream = createReadStream(filePath, { highWaterMark: slice_size });
let seq = 0;
let offset = 0;
for await (const chunk of stream) {
const end = Math.min(offset + chunk.length, img_size);
// 使用原生的 FormData 构建安全的 multipart 请求
const form = new FormData();
form.append('uin', uin);
form.append('appid', 'qun');
form.append('session', session);
form.append('offset', offset.toString());
form.append('data', new Blob([chunk as Buffer], { type: 'application/octet-stream' }), 'blob');
form.append('checksum', '');
form.append('check_type', '0');
form.append('retry', '0');
form.append('seq', seq.toString());
form.append('end', end.toString());
form.append('cmd', 'FileUpload');
form.append('slice_size', slice_size.toString());
form.append('biz_req.iUploadType', '0');
const api = `https://h5.qzone.qq.com/webapp/json/sliceUpload/FileUpload?seq=${seq}&retry=0&offset=${offset}&end=${end}&total=${img_size}&type=form&g_tk=${bkn}`;
// 放弃使用 HttpGetJson,改用原生 fetch,它能完美处理 FormData 和边界
const response = await fetch(api, {
method: 'POST',
headers: {
Cookie: cookie,
// 注意:不要手动设置 Content-Type,fetch 会自动加上带有正确 boundary 的 multipart/form-data
},
body: form,
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const post = await response.json() as { ret: number, msg: string };
if (post.ret !== 0) {
throw new Error(`分片 ${seq} 上传失败: ${post.msg}`);
}
offset += chunk.length;
seq++;
}
}
/**
* 上传图片到群相册
*/
export async function uploadImageToGroupAlbum(
cookieObject: Record<string, string>,
groupId: string,
albumId: string,
albumName: string,
filePath: string,
uin: string
): Promise<void> {
const { loadBinarySource } = await import('../highway/utils');
const loaded = await loadBinarySource(filePath, 'album image');
let tempFile: string | null = null;
let actualPath = filePath;
if (/^(https?:\/\/|base64:\/\/)/i.test(filePath)) {
tempFile = join(tmpdir(), `album_${Date.now()}_${Math.random().toString(36).slice(2)}.tmp`);
writeFileSync(tempFile, loaded.bytes);
actualPath = tempFile;
}
try {
const imgMd5 = createHash('md5').update(loaded.bytes).digest('hex');
// const imgSize = loaded.bytes.length;
const skey = cookieObject.skey || '';
const pskey = cookieObject.p_skey || '';
const session = await createAlbumUploadSession(groupId, albumId, albumName, actualPath, skey, pskey, imgMd5, uin);
await uploadAlbumSlice(session, actualPath, imgMd5, skey, pskey, uin);
} finally {
if (tempFile) {
try { unlinkSync(tempFile); } catch { /* ignore */ }
}
}
}
+7
View File
@@ -12,9 +12,11 @@ import { HookSession, type HookSessionDeps } from './hook-session';
import { PipeWatcher } from './pipe-watcher';
import { QqHookClient } from './qq-hook-client';
import type { HookProcessInfo } from './types';
import { probeQqLoginInfo, type QqPortLoginInfo } from './qq-port-probe';
export type { HookProcessInfo, HookProcessStatus } from './types';
export type { HookProcessBaseInfo } from './injector';
export type { QqPortLoginInfo } from './qq-port-probe';
export type HookManagerDeps = {
bridgeManager: BridgeManager;
@@ -147,6 +149,11 @@ export class HookManager {
return session.refresh();
}
async probeProcessLoginInfo(pid: number): Promise<QqPortLoginInfo | null> {
this.assertValidPid(pid);
return probeQqLoginInfo(pid);
}
dispose(): void {
if (this.disposed) return;
this.disposed = true;
+168
View File
@@ -0,0 +1,168 @@
import net from 'net';
import { exec } from 'child_process';
import { promisify } from 'util';
const execAsync = promisify(exec);
const PORT_RANGE_START = 9210;
const PORT_RANGE_END = 9219;
const PROBE_TIMEOUT_MS = 1000;
const CONNECTION_TIMEOUT_MS = 500;
export interface QqPortLoginInfo {
port: number;
uin: string;
uid?: string;
nickName?: string;
loggedIn: boolean;
}
interface JwtPayload {
errCode: number;
errMsg: string;
port: number;
uin?: string;
uid?: string;
nickName?: string;
data?: {
uin?: string;
url?: string;
};
iat: number;
}
function decodeJwt(token: string): JwtPayload | null {
try {
const parts = token.split('.');
if (parts.length !== 3) return null;
const payload = Buffer.from(parts[1], 'base64').toString('utf8');
return JSON.parse(payload);
} catch {
return null;
}
}
async function probePort(port: number): Promise<QqPortLoginInfo | null> {
return new Promise((resolve) => {
const client = new net.Socket();
const link = 'tencent://';
const payload = `POST /tencent HTTP/1.1\r\nHost: 127.0.0.1:${port}\r\nConnection: close\r\nContent-Length: ${link.length}\r\n\r\n${link}`;
let responseData = '';
let timer: NodeJS.Timeout;
const cleanup = () => {
clearTimeout(timer);
client.removeAllListeners();
client.destroy();
};
timer = setTimeout(() => {
cleanup();
resolve(null);
}, PROBE_TIMEOUT_MS);
client.setTimeout(CONNECTION_TIMEOUT_MS);
client.connect(port, '127.0.0.1', () => {
client.write(payload);
});
client.on('data', (data) => {
responseData += data.toString();
});
client.on('close', () => {
cleanup();
const jwtMatch = responseData.match(/eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/);
if (!jwtMatch) {
resolve(null);
return;
}
const decoded = decodeJwt(jwtMatch[0]);
if (!decoded || decoded.errCode !== 0) {
resolve(null);
return;
}
const uin = decoded.uin || decoded.data?.uin || '';
resolve({
port,
uin,
uid: decoded.uid,
nickName: decoded.nickName,
loggedIn: uin.length > 0,
});
});
client.on('error', () => {
cleanup();
resolve(null);
});
client.on('timeout', () => {
cleanup();
resolve(null);
});
});
}
async function getProcessPorts(pid: number): Promise<number[]> {
try {
if (process.platform === 'win32') {
const { stdout } = await execAsync(`netstat -ano | findstr ${pid}`);
const ports = new Set<number>();
const lines = stdout.split('\n');
for (const line of lines) {
const parts = line.trim().split(/\s+/);
if (parts.length < 5) continue;
const owningPid = parts[parts.length - 1];
if (owningPid !== String(pid)) continue;
const localAddr = parts[1];
const portMatch = localAddr.match(/:(\d+)$/);
if (!portMatch) continue;
const port = Number(portMatch[1]);
if (port >= PORT_RANGE_START && port <= PORT_RANGE_END) {
ports.add(port);
}
}
return Array.from(ports);
} else {
const { stdout } = await execAsync(`ss -tlnp | grep pid=${pid}`);
const ports = new Set<number>();
const lines = stdout.split('\n');
for (const line of lines) {
const match = line.match(/:(\d+)\s/);
if (match) {
const port = Number(match[1]);
if (port >= PORT_RANGE_START && port <= PORT_RANGE_END) {
ports.add(port);
}
}
}
return Array.from(ports);
}
} catch {
return [];
}
}
export async function probeQqLoginInfo(pid: number): Promise<QqPortLoginInfo | null> {
const ports = await getProcessPorts(pid);
if (ports.length === 0) {
for (let port = PORT_RANGE_START; port <= PORT_RANGE_END; port++) {
const info = await probePort(port);
if (info) return info;
}
return null;
}
for (const port of ports) {
const info = await probePort(port);
if (info) return info;
}
return null;
}
@@ -119,4 +119,4 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err));
}
});
}
}
@@ -0,0 +1,132 @@
import type { ApiHandler, ApiActionContext } from '../api-handler';
import { asNumber, asString } from '../api-handler';
import { RETCODE, failedResponse, okResponse } from '../types';
export function register(h: ApiHandler, ctx: ApiActionContext): void {
h.registerAction('get_group_album_list', async (params) => {
const groupId = asNumber(params.group_id);
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
try {
const albumList = await ctx.getGroupAlbumList(groupId);
return okResponse(albumList);
} catch (error) {
const message = error instanceof Error ? error.message : 'failed to get group album list';
return failedResponse(RETCODE.INTERNAL_ERROR, message);
}
});
h.registerAction('upload_image_to_qun_album', async (params) => {
const groupId = asNumber(params.group_id);
const albumId = asString(params.album_id);
const albumName = asString(params.album_name);
const file = asString(params.file);
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
if (!albumId) return failedResponse(RETCODE.BAD_REQUEST, 'album_id is required');
if (!albumName) return failedResponse(RETCODE.BAD_REQUEST, 'album_name is required');
if (!file) return failedResponse(RETCODE.BAD_REQUEST, 'file is required');
try {
await ctx.uploadImageToGroupAlbum(groupId, albumId, albumName, file);
return okResponse(null);
} catch (error) {
const message = error instanceof Error ? error.message : 'failed to upload image to group album';
return failedResponse(RETCODE.INTERNAL_ERROR, message);
}
});
h.registerAction('get_group_album_media_list', async (params) => {
const groupId = asNumber(params.group_id);
const albumId = asString(params.album_id);
const attachInfo = asString(params.attach_info) || '';
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
if (!albumId) return failedResponse(RETCODE.BAD_REQUEST, 'album_id is required');
try {
const mediaList = await ctx.getGroupAlbumMediaList(groupId, albumId, attachInfo);
return okResponse(mediaList);
} catch (error) {
const message = error instanceof Error ? error.message : 'failed to get group album media list';
return failedResponse(RETCODE.INTERNAL_ERROR, message);
}
});
h.registerAction('do_group_album_comment', async (params) => {
const groupId = asNumber(params.group_id);
const albumId = asString(params.album_id);
const lloc = asString(params.lloc);
const content = asString(params.content);
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
if (!albumId) return failedResponse(RETCODE.BAD_REQUEST, 'album_id is required');
if (!lloc) return failedResponse(RETCODE.BAD_REQUEST, 'lloc is required');
if (!content) return failedResponse(RETCODE.BAD_REQUEST, 'content is required');
try {
const comment = await ctx.commentGroupAlbumMedia(groupId, albumId, lloc, content);
return okResponse(comment);
} catch (error) {
const message = error instanceof Error ? error.message : 'failed to comment on album media';
return failedResponse(RETCODE.INTERNAL_ERROR, message);
}
});
h.registerAction('set_group_album_media_like', async (params) => {
const groupId = asNumber(params.group_id);
const albumId = asString(params.album_id);
const batchId = asString(params.batch_id);
const lloc = params.lloc ? asString(params.lloc) : undefined; // 可选参数
if (!groupId || !albumId || !batchId) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id, album_id and batch_id are required');
}
try {
const res = await ctx.likeGroupAlbumMedia(groupId, albumId, batchId, lloc, true);
return okResponse(res);
} catch (error) {
const message = error instanceof Error ? error.message : 'failed to set like on album media';
return failedResponse(RETCODE.INTERNAL_ERROR, message);
}
});
// 取消点赞群相册媒体
h.registerAction('cancel_group_album_media_like', async (params) => {
const groupId = asNumber(params.group_id);
const albumId = asString(params.album_id);
const batchId = asString(params.batch_id);
const lloc = params.lloc ? asString(params.lloc) : undefined; // 可选参数
if (!groupId || !albumId || !batchId) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id, album_id and batch_id are required');
}
try {
const res = await ctx.likeGroupAlbumMedia(groupId, albumId, batchId, lloc, false);
return okResponse(res);
} catch (error) {
const message = error instanceof Error ? error.message : 'failed to cancel like on album media';
return failedResponse(RETCODE.INTERNAL_ERROR, message);
}
});
h.registerAction('del_group_album_media', async (params) => {
const groupId = asNumber(params.group_id);
const albumId = asString(params.album_id);
const lloc = asString(params.lloc);
if (!groupId || !albumId || !lloc) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id, album_id and lloc are required');
}
try {
const res = await ctx.deleteGroupAlbumMedia(groupId, albumId, lloc);
return okResponse(res);
} catch (error) {
const message = error instanceof Error ? error.message : 'failed to delete album media';
return failedResponse(RETCODE.INTERNAL_ERROR, message);
}
});
}
+31
View File
@@ -15,6 +15,10 @@ import { register as registerGroupAdmin } from './actions/group-admin';
import { register as registerGroupFile } from './actions/group-file';
import { register as registerRequest } from './actions/request';
import { register as registerExtended } from './actions/extended';
import { register as registerGroupAlbum } from './actions/group-album';
import { WebHonorType } from '@/bridge/web/group-honor';
import { ClientKeyInfo } from '@/bridge/bridge';
export interface MessageSendResult {
messageId: number;
@@ -95,7 +99,33 @@ export interface ApiActionContext {
sendForwardMsg: (messages: JsonValue, groupId?: number) => Promise<{ forwardId: string }>;
getForwardMsg: (resId: string) => Promise<JsonObject[]>;
forwardSingleMsg: (messageId: number, target: { groupId?: number; userId?: number }) => Promise<{ messageId: number }>;
// Extended NapCat-compatible
setFriendRemark: (userId: number, remark: string) => Promise<void>;
setGroupRemark: (groupId: number, remark: string) => Promise<void>;
setGroupAvatar: (groupId: number, source: string) => Promise<void>;
setMsgEmojiLike: (messageId: number, emojiId: string, set: boolean) => Promise<void>;
markGroupMsgAsRead: (groupId: number, sequence: number) => Promise<void>;
markPrivateMsgAsRead: (userId: number, sequence: number) => Promise<void>;
setOnlineStatus: (status: number, extStatus?: number, batteryStatus?: number) => Promise<void>;
setProfile: (nickname?: string, personalNote?: string) => Promise<void>;
fetchCustomFace: (count?: number) => Promise<string[]>;
getEmojiLikes: (groupId: number, sequence: number, emojiId: string, emojiType?: number, count?: number, cookie?: string) => Promise<{ users: Array<{ uin: number }>, cookie: string, isLast: boolean }>;
// Web
getGroupHonorInfo: (groupId: number, type: WebHonorType | string) => Promise<any>;
getGroupEssenceAll: (groupId: number) => Promise<GroupEssenceMsgRet[]>;
getGroupAlbumList: (groupId: number) => Promise<any>;
uploadImageToGroupAlbum: (groupId: number, albumId: string, albumName: string, filePath: string) => Promise<void>;
getGroupAlbumMediaList: (groupId: number, albumId: string, attachInfo?: string) => Promise<any>;
commentGroupAlbumMedia: (groupId: number, albumId: string, lloc: string, content: string) => Promise<any>;
deleteGroupAlbumMedia: (groupId: number, albumId: string, lloc: string) => Promise<any>;
likeGroupAlbumMedia: (groupId: number, albumId: string, batchId: string, lloc: string | undefined, isLike: boolean) => Promise<any>;
sendGroupNotice: (groupId: number, content: string, options?: any) => Promise<any>;
getGroupNotice: (groupId: number) => Promise<any[]>;
deleteGroupNotice: (groupId: number, fid: string) => Promise<boolean>;
getCookiesStr: (domain: string) => Promise<string>;
getCsrfToken: () => Promise<number>;
getCredentials: (domain: string) => Promise<{ cookies: string; token: number; csrf_token: number }>;
forceFetchClientKey: () => Promise<ClientKeyInfo>;
// Media lookup (populated from previously dispatched message segments)
getImageInfo: (file: string) => Promise<JsonObject | null>;
getRecordInfo: (file: string) => Promise<JsonObject | null>;
@@ -117,6 +147,7 @@ export class ApiHandler {
registerGroupFile(this, context);
registerRequest(this, context);
registerExtended(this, context);
registerGroupAlbum(this, context);
}
registerAction(action: string, handler: ActionHandler): void {
@@ -54,6 +54,8 @@ async function elementToSegment(
const data: JsonObject = {
url,
file: element.fileId ?? '',
sub_type: element.subType ?? 0,
summary: element.summary ?? '',
};
if (mediaSegmentSink) mediaSegmentSink('image', element, data, isGroup, sessionId);
return { type: 'image', data };
@@ -162,6 +162,10 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
getForwardMsg: (resId) => getForwardMessage(ref, resId),
forwardSingleMsg: (messageId, target) => forwardSingleMessage(ref, messageId, target),
handleDeleteFriend: (userId, block) => bridge.deleteFriend(userId, !!block),
forceFetchClientKey: () => bridge.forceFetchClientKey(),
setFriendRemark: (userId, remark) => bridge.setFriendRemark(userId, remark),
setGroupRemark: (groupId, remark) => bridge.setGroupRemark(groupId, remark),
setGroupAvatar: (groupId, source) => bridge.setGroupAvatar(groupId, source),
getGroupFileCount: (groupId) => bridge.fetchGroupFileCount(groupId),
// Cross-store: looks up the meta then routes through Bridge.
@@ -174,6 +178,30 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
if (!meta.isGroup) throw new Error('emoji reactions are not supported on private messages');
await bridge.setGroupReaction(meta.targetId, meta.sequence, emojiId, set);
},
markGroupMsgAsRead: (groupId, sequence) => bridge.markGroupMsgAsRead(groupId, sequence),
markPrivateMsgAsRead: (userId, sequence) => bridge.markPrivateMsgAsRead(userId, sequence),
setOnlineStatus: (status: number, extStatus?: number, batteryStatus?: number) => bridge.setOnlineStatus(status, extStatus, batteryStatus),
setProfile: (nickname?: string, personalNote?: string) => bridge.setProfile(nickname, personalNote),
// Web-backed actions.
getGroupHonorInfo: (groupId: number, type: WebHonorType | string) => bridge.getGroupHonorInfo(groupId, type),
getGroupEssenceAll: (groupId) => bridge.getGroupEssenceAll(groupId),
getGroupAlbumList: (groupId) => bridge.getGroupAlbumList(groupId),
uploadImageToGroupAlbum: (groupId, albumId, albumName, filePath) => bridge.uploadImageToGroupAlbum(groupId, albumId, albumName, filePath),
getGroupAlbumMediaList: (groupId, albumId, attachInfo) => bridge.getGroupAlbumMediaList(groupId, albumId, attachInfo),
commentGroupAlbumMedia: (groupId, albumId, lloc, content) => bridge.commentGroupAlbumMedia(groupId, albumId, lloc, content),
deleteGroupAlbumMedia: (groupId, albumId, lloc) => bridge.deleteGroupAlbumMedia(groupId, albumId, lloc),
likeGroupAlbumMedia: (groupId, albumId, batchId, lloc, isLike) => bridge.likeGroupAlbumMedia(groupId, albumId, batchId, lloc, isLike),
sendGroupNotice: (groupId, content, options) => bridge.sendGroupNotice(groupId, content, options),
getGroupNotice: (groupId) => bridge.getGroupNotice(groupId),
deleteGroupNotice: (groupId, fid) => bridge.deleteGroupNotice(groupId, fid),
getCookiesStr: (domain) => bridge.getCookiesStr(domain),
getCsrfToken: () => bridge.getCsrfToken(),
getCredentials: (domain) => bridge.getCredentials(domain),
// Extended
fetchCustomFace: (count) => bridge.fetchCustomFace(count),
getEmojiLikes: (groupId, sequence, emojiId, emojiType, count, cookie) => bridge.getEmojiLikes(groupId, sequence, emojiId, emojiType, count, cookie),
// Media lookup.
getImageInfo: (file) => getCachedImageInfo(mediaStore, file),
@@ -336,6 +336,37 @@ async function segmentToElement(type: string, data: Record<string, unknown>, opt
// Anonymous flag — ignored during send, the protocol handles anonymity
return null;
}
case 'file': {
// OneBot11 file segment referencing a previously-uploaded file
// (returned by `upload_group_file` / `upload_private_file`).
// We deliberately do NOT support `{file: '/path'}` here because
// the upload pipeline is async and lives behind the bridge —
// the element-builder runs synchronously over the parsed
// message. Callers that want upload-and-send should use the
// dedicated `upload_*` actions which now publish the file in
// chat atomically (`actions/group-file.ts`).
const fileId = String(data.file_id ?? data.fileId ?? '').trim();
if (!fileId) {
log.warn('[MsgParser] file segment without file_id is unsupported (upload first via upload_group_file / upload_private_file)');
return null;
}
const fileName = String(data.name ?? data.filename ?? data.fileName ?? '').trim();
const fileSize = intOr(data.size ?? data.fileSize, 0);
const md5Hex = String(data.md5 ?? data.md5Hex ?? '').trim();
const sha1Hex = String(data.sha1 ?? data.sha1Hex ?? '').trim();
// file_hash is the c2c-file server-issued addon string — needed
// on the wire when re-sending a previously-uploaded c2c file.
// get_private_file_url callers already pass it through, so honour
// the same field naming here.
const fileHash = String(data.file_hash ?? data.fileHash ?? '').trim();
const elem: MessageElement = { type: 'file', fileId };
if (fileName) elem.fileName = fileName;
if (fileSize > 0) elem.fileSize = fileSize;
if (md5Hex) elem.md5Hex = md5Hex;
if (sha1Hex) elem.sha1Hex = sha1Hex;
if (fileHash) elem.fileHash = fileHash;
return elem;
}
default:
console.warn(`[MsgParser] unsupported segment type: ${type}`);
return null;
@@ -136,19 +136,80 @@ export async function sendPrivateMessage(
});
if (elements.length === 0) throw new Error('message is empty');
const receipt = await ref.bridge.sendPrivateMessage(userId, elements);
const messageId = hashMessageIdInt32(receipt.sequence, userId, PRIVATE_MESSAGE_EVENT);
// C2C `{type:'file'}` segments can't ride on the elems[] pipeline —
// c2c files live on `RichText.notOnlineFile`, parallel to elems
// (see `proto/proton/message.ts:notOnlineFile`). The element-builder
// explicitly drops them with a warn ("file send via elems[] is
// group-only"), so a private message that bundled a file alongside
// anything else used to either ship as "[空消息]" (only-file case,
// 0 elements after drop) or silently lose the file (mixed case).
//
// NapCat splits the same way (`dev/NapCatQQ/.../SendMsg.ts:404-415`):
// FILE / VIDEO / ARK / PTT each go in their own sendMsg call,
// never mixed with the regular elements. We only need it for file
// here — video/ARK/ptt already go through commonElem so the
// element-builder handles them inline.
const fileElements = elements.filter(e => e.type === 'file' && e.fileId);
const nonFileElements = elements.filter(e => e.type !== 'file');
if (fileElements.length !== elements.filter(e => e.type === 'file').length) {
log.warn('[OneBot] private file segment without file_id — skipped (upload first via upload_private_file)');
}
logSentMessage(false, userId, elements);
let lastReceipt: Awaited<ReturnType<typeof ref.bridge.sendPrivateMessage>> | undefined;
if (nonFileElements.length > 0) {
lastReceipt = await ref.bridge.sendPrivateMessage(userId, nonFileElements);
logSentMessage(false, userId, nonFileElements);
}
if (fileElements.length > 0) {
// C2C file send needs the recipient's UID — resolve once and reuse.
const userUid = await ref.bridge.resolveUserUid(userId);
if (!userUid) {
throw new Error(`c2c file send: could not resolve uid for user ${userId}`);
}
for (const fileEl of fileElements) {
// C2C file send requires fileSize/fileMd5/fileName to ride on the
// wire (NotOnlineFile inside msgContent). The OneBot caller
// usually only echoes the file_id from a previous
// `upload_private_file`, so look up the rest from the upload
// cache. Inline segment fields (md5/size/name) take precedence so
// a caller that already knows everything can bypass the cache.
const cached = ref.bridge.recallUploadedFile(fileEl.fileId!);
const fileMd5 = fileEl.md5Hex
? Buffer.from(fileEl.md5Hex, 'hex')
: (cached?.fileMd5 ?? new Uint8Array(0));
const fileSize = fileEl.fileSize ?? cached?.fileSize ?? 0;
// Fall back to a generic name — the QQ server resolves the
// file by fileUuid, not name, so a missing name only affects
// the chat bubble display.
const fileName = fileEl.fileName ?? cached?.fileName ?? 'file';
const fileHash = fileEl.fileHash ?? cached?.fileHash;
if (fileSize === 0 && !cached) {
log.warn(
'[OneBot] c2c file_id=%s sent without fileSize and no upload cache — recipient may see 0 B',
fileEl.fileId,
);
}
lastReceipt = await ref.bridge.sendC2cFileMessage(userId, userUid, {
fileId: fileEl.fileId!,
fileName,
fileSize,
fileMd5,
fileHash,
});
logSentMessage(false, userId, [fileEl]);
}
}
if (!lastReceipt) throw new Error('message is empty');
const messageId = hashMessageIdInt32(lastReceipt.sequence, userId, PRIVATE_MESSAGE_EVENT);
ref.cacheMessageMeta(messageId, {
isGroup: false,
targetId: userId,
sequence: receipt.sequence,
sequence: lastReceipt.sequence,
eventName: PRIVATE_MESSAGE_EVENT,
clientSequence: receipt.clientSequence,
random: receipt.random,
timestamp: receipt.timestamp,
clientSequence: lastReceipt.clientSequence,
random: lastReceipt.random,
timestamp: lastReceipt.timestamp,
});
return { messageId };
@@ -184,19 +245,60 @@ export async function sendGroupMessage(
});
if (elements.length === 0) throw new Error('message is empty');
const receipt = await ref.bridge.sendGroupMessage(groupId, elements);
const messageId = hashMessageIdInt32(receipt.sequence, groupId, GROUP_MESSAGE_EVENT);
// Group `{type:'file', file_id}` segments don't ride on the elems[]
// pipeline either. The QQ-NT server rejects PbSendMsg with a
// transElem(24) file payload (result=79); the correct send path is a
// dedicated OIDB call (`OidbSvcTrpcTcp.0x6d9_4`) that publishes a
// previously-uploaded file id as a chat bubble. Mirrors the c2c-file
// split below (private path) — both must be peeled off before the
// regular sendGroupMessage runs.
const fileElements = elements.filter(e => e.type === 'file' && e.fileId);
const nonFileElements = elements.filter(e => e.type !== 'file');
if (fileElements.length !== elements.filter(e => e.type === 'file').length) {
log.warn('[OneBot] group file segment without file_id — skipped (upload first via upload_group_file)');
}
logSentMessage(true, groupId, elements);
let lastReceipt: Awaited<ReturnType<typeof ref.bridge.sendGroupMessage>> | undefined;
if (nonFileElements.length > 0) {
lastReceipt = await ref.bridge.sendGroupMessage(groupId, nonFileElements);
logSentMessage(true, groupId, nonFileElements);
}
for (const fileEl of fileElements) {
// Group-file publish has no per-message sequence/random tuple to
// hash a messageId from — OIDB 0x6d9_4 is fire-and-forget on the
// wire. If this is the LAST element we still need a receipt so
// the OneBot caller can cache the id; synthesise one from the
// file_id hash + a fresh timestamp.
await ref.bridge.sendGroupFileMessage(groupId, fileEl.fileId!);
logSentMessage(true, groupId, [fileEl]);
if (!lastReceipt) {
// Use a hash of the fileId as a stable pseudo-id; this gets
// mixed with groupId in `hashMessageIdInt32` below.
let h = 0;
const s = fileEl.fileId ?? '';
for (let i = 0; i < s.length; i++) {
h = ((h << 5) - h + s.charCodeAt(i)) | 0;
}
lastReceipt = {
messageId: 0,
sequence: h & 0x7FFFFFFF,
clientSequence: 0,
random: h & 0x7FFFFFFF,
timestamp: Math.floor(Date.now() / 1000),
};
}
}
if (!lastReceipt) throw new Error('message is empty');
const messageId = hashMessageIdInt32(lastReceipt.sequence, groupId, GROUP_MESSAGE_EVENT);
ref.cacheMessageMeta(messageId, {
isGroup: true,
targetId: groupId,
sequence: receipt.sequence,
sequence: lastReceipt.sequence,
eventName: GROUP_MESSAGE_EVENT,
clientSequence: receipt.clientSequence,
random: receipt.random,
timestamp: receipt.timestamp,
clientSequence: lastReceipt.clientSequence,
random: lastReceipt.random,
timestamp: lastReceipt.timestamp,
});
return { messageId };
@@ -215,7 +317,11 @@ export async function sendGroupForwardMessage(
messages: JsonValue,
meta?: ForwardPreviewMeta,
): Promise<{ messageId: number; forwardId: string }> {
const nodes = await parseForwardNodes(ref, messages);
// Thread `groupId` into the parser so any nested forward inside a
// node's content uploads its inner forward against the same group
// namespace — otherwise the ARK card's res_id won't be resolvable
// when the recipient taps to expand.
const nodes = await parseForwardNodes(ref, messages, { groupId });
const forwardId = await ref.bridge.uploadForwardNodes(nodes, groupId);
const previewElement = buildForwardPreviewElement(forwardId, nodes, true, meta);
const receipt = await ref.bridge.sendGroupMessage(groupId, [previewElement]);
@@ -240,7 +346,7 @@ export async function sendPrivateForwardMessage(
messages: JsonValue,
meta?: ForwardPreviewMeta,
): Promise<{ messageId: number; forwardId: string }> {
const nodes = await parseForwardNodes(ref, messages);
const nodes = await parseForwardNodes(ref, messages, { userId });
// userId is plumbed through so inner image/record/video can be uploaded
// under the recipient's scene (otherwise the OIDB private-image upload
// has no target uid and the element builder bails).
@@ -267,7 +373,7 @@ export async function uploadForwardMessage(
messages: JsonValue,
groupId?: number,
): Promise<{ forwardId: string }> {
const nodes = await parseForwardNodes(ref, messages);
const nodes = await parseForwardNodes(ref, messages, { groupId });
// groupId controls the resId namespace (group vs private). Without it,
// a resId minted here is unusable when later sent into a group.
const forwardId = await ref.bridge.uploadForwardNodes(nodes, groupId);
@@ -526,6 +632,13 @@ function logSentMessage(isGroup: boolean, targetId: number, elements: MessageEle
case 'poke':
parts.push('[戳一戳]');
break;
case 'file':
// Avoid the misleading "[空消息]" the user previously saw when
// sending a file segment — the message is NOT empty, it's a
// file post. Show the name (or id as fallback) so the log
// reflects what actually went out.
parts.push(`[文件:${elem.fileName || elem.fileId || ''}]`);
break;
default:
break;
}
@@ -535,10 +648,49 @@ function logSentMessage(isGroup: boolean, targetId: number, elements: MessageEle
log.info(`${type} ${targetId} | 发送:${content}`);
}
// Cap forward nesting at the same depth NapCat uses
// (`SendMsg.ts:225-228`). QQ NT itself renders only a few levels of
// nested forward bubbles before collapsing into "查看更多" — going
// deeper just wastes long-msg uploads and increases the odds of one
// inner upload timing out and aborting the whole tree.
const MAX_FORWARD_DEPTH = 3;
interface ParseForwardOptions {
/** Destination group, when the parent forward is going to a group. */
groupId?: number;
/** Destination user, when the parent forward is going to a c2c peer. */
userId?: number;
/** Internal: current recursion depth. Callers should leave this 0. */
depth?: number;
}
/**
* Are all entries of this array `{type:'node'}` segments? Then `content`
* itself is a nested forward chain (vs a regular flat segment list).
* Mixed content (some nodes + some text/image) returns false: that's
* not a meaningful protocol shape, so we treat it as flat-segment and
* let the node entries fall through to parseMessage (which drops them
* with a warning).
*/
function isNestedNodeArray(value: JsonValue): boolean {
if (!Array.isArray(value) || value.length === 0) return false;
for (const item of value) {
const seg = asJsonObject(item);
if (!seg || String(seg.type ?? '') !== 'node') return false;
}
return true;
}
async function parseForwardNodes(
ref: OneBotInstanceContext,
messages: JsonValue,
options: ParseForwardOptions = {},
): Promise<ForwardNodePayload[]> {
const depth = options.depth ?? 0;
if (depth >= MAX_FORWARD_DEPTH) {
throw new Error(`forward nesting depth exceeds ${MAX_FORWARD_DEPTH}`);
}
if (!Array.isArray(messages)) {
throw new Error('forward messages must be an array');
}
@@ -590,10 +742,44 @@ async function parseForwardNodes(
const nickname = String(nodeData.nickname ?? nodeData.name ?? userUin);
const content = (nodeData.content ?? nodeData.message ?? '') as JsonValue;
const elements = await parseMessage(content, false);
if (elements.length === 0) throw new Error(`forward node content is empty: ${userUin}`);
nodes.push({ userUin, nickname, elements });
let elements: MessageElement[];
let innerForward: ForwardNodePayload[] | undefined;
if (isNestedNodeArray(content)) {
// Nested forward chain — `content` is itself a list of `{type:'node'}`
// segments. We recursively parse them into a sibling
// `ForwardNodePayload[]` and attach it to this node as `innerForward`.
// `uploadForwardNodes` then drives the recursive upload + ARK-preview
// generation + msgBody piggyback in one pass over the whole tree.
//
// Why hand it off instead of uploading here: NapCat (`dev/NapCatQQ/
// .../SendMsg.uploadForwardedNodesPacket`) carries every inner level's
// packetMsg up to the outermost long-msg upload as extra
// `actionCommand` slots, so the receiver gets the whole tree from one
// server fetch. That cross-layer piggyback needs the upload pipeline
// to own the recursion — doing it in `parseForwardNodes` would force
// each level to do its own independent long-msg upload, which is what
// the previous implementation did and what a NapCat-compatible
// receiver couldn't walk.
innerForward = await parseForwardNodes(ref, content, {
groupId: options.groupId,
userId: options.userId,
depth: depth + 1,
});
// Placeholder — `uploadForwardNodes` replaces these with a real
// forward-preview MessageElement once it has the inner res_id +
// uuid in hand.
elements = [];
} else {
elements = await parseMessage(content, false);
}
if (!innerForward && elements.length === 0) {
throw new Error(`forward node content is empty: ${userUin}`);
}
const node: ForwardNodePayload = { userUin, nickname, elements };
if (innerForward) node.innerForward = innerForward;
nodes.push(node);
}
if (nodes.length === 0) {
@@ -9,11 +9,20 @@ export async function handleGroupAddRequest(
// flag format: "add:groupId:uid" or "invite:groupId:uid" (from event-converter)
const parts = flag.split(':');
if (parts.length < 3) throw new Error('invalid group request flag');
const requestType = parts[0];
const groupId = parseInt(parts[1], 10);
const targetUid = parts.slice(2).join(':');
if (!groupId) throw new Error('invalid group_id in flag');
if (!targetUid) throw new Error('invalid request target in flag');
const requests = await bridge.fetchGroupRequests();
const matching = requests.find(r => r.groupId === groupId);
const matching = requests.find((r) => {
if (r.groupId !== groupId) return false;
if (requestType === 'add') return r.targetUid === targetUid;
if (requestType === 'invite') return r.invitorUid === targetUid;
return false;
}) || requests.find(r => r.groupId === groupId);
if (!matching) {
throw new Error('matching group request not found');
}
@@ -79,11 +79,8 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
onEvent(_event: JsonObject, _payload: DispatchPayload): void { /* no-op */ }
private startServer(): void {
const expectedPath = normalizePath(this.config.path ?? '/');
const accessToken = this.config.accessToken ?? '';
const server = createServer((req, res) => {
void this.handleRequest(expectedPath, accessToken, req, res);
void this.handleRequest(req, res);
});
this.server = server;
@@ -93,7 +90,7 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
this.name,
this.config.host ?? '0.0.0.0',
this.config.port,
expectedPath,
normalizePath(this.config.path ?? '/'),
);
});
server.on('error', (err) => {
@@ -103,7 +100,15 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
server.listen(this.config.port, this.config.host ?? '0.0.0.0');
}
private async handleRequest(expectedPath: string, accessToken: string, req: IncomingMessage, res: ServerResponse): Promise<void> {
private async handleRequest(req: IncomingMessage, res: ServerResponse): Promise<void> {
// Read `path` + `accessToken` fresh from `this.config` on every
// request so config hot-reloads (`reload()` overwrites `this.config`
// in place) take effect on the very next request without
// re-binding the listener. Matches the ws-server / http-post /
// ws-client adapters, which all read `this.config.accessToken`
// inline at the point of use.
const expectedPath = normalizePath(this.config.path ?? '/');
const accessToken = this.config.accessToken ?? '';
const parsedUrl = new URL(req.url ?? '/', 'http://127.0.0.1');
const incomingPath = parsedUrl.pathname;
@@ -143,19 +148,61 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
} else if (req.method === 'POST') {
const bodyContent = await readRequestBody(req);
if (bodyContent.trim()) {
try {
const parsedBody = JSON.parse(bodyContent);
if (typeof parsedBody === 'object' && parsedBody !== null && !Array.isArray(parsedBody)) {
if (parsedBody.action && !action) action = String(parsedBody.action);
if (parsedBody.params && typeof parsedBody.params === 'object' && !Array.isArray(parsedBody.params)) {
params = parsedBody.params as Record<string, unknown>;
} else {
params = parsedBody as Record<string, unknown>;
const contentType = req.headers['content-type'] ?? '';
if (contentType.includes('application/x-www-form-urlencoded')) {
const parsed = new URLSearchParams(bodyContent);
parsed.forEach((value, key) => {
try {
params[key] = JSON.parse(value);
} catch {
params[key] = value;
}
echo = parsedBody.echo;
});
if (params.action && !action) {
action = String(params.action);
delete params.action;
}
} catch {
writeJson(res, 400, { status: 'failed', retcode: 1400, data: null, wording: 'bad request: invalid json' });
if (params.echo !== undefined) {
echo = params.echo;
delete params.echo;
}
} else if (contentType.includes('application/json') || !contentType) {
try {
const parsedBody = JSON.parse(bodyContent);
if (typeof parsedBody === 'object' && parsedBody !== null && !Array.isArray(parsedBody)) {
if (parsedBody.action && !action) action = String(parsedBody.action);
if (parsedBody.params && typeof parsedBody.params === 'object' && !Array.isArray(parsedBody.params)) {
params = parsedBody.params as Record<string, unknown>;
} else {
params = parsedBody as Record<string, unknown>;
}
echo = parsedBody.echo;
}
} catch {
if (contentType.includes('application/json')) {
writeJson(res, 400, { status: 'failed', retcode: 1400, data: null, wording: 'bad request: invalid json' });
return;
}
// 无 content-type,JSON 失败则 fallback 到 urlencoded
const parsed = new URLSearchParams(bodyContent);
parsed.forEach((value, key) => {
try {
params[key] = JSON.parse(value);
} catch {
params[key] = value;
}
});
if (params.action && !action) {
action = String(params.action);
delete params.action;
}
if (params.echo !== undefined) {
echo = params.echo;
delete params.echo;
}
}
} else {
writeJson(res, 400, { status: 'failed', retcode: 1400, data: null, wording: `bad request: unsupported content-type: ${contentType}` });
return;
}
}
@@ -182,7 +229,16 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
}
function bindingSignature(net: HttpServerNetwork): string {
return `${net.host ?? '0.0.0.0'}:${net.port}${normalizePath(net.path ?? '/')}#${net.accessToken ?? ''}`;
// `accessToken` deliberately omitted: it's read per-request from
// `this.config`, so a token change doesn't need to re-bind the
// listener. Including it here would cause a `close()` + `listen()`
// round trip on every token edit — a needless port-rebind that, on
// some hosts, races with the OS releasing the port and lands the
// server in a half-broken state where the old token still
// authenticates because the EADDRINUSE-failing new server never
// replaced the old one. `host`/`port`/`path` still gate a restart
// because Node's HTTP `Server.listen()` binds the socket on those.
return `${net.host ?? '0.0.0.0'}:${net.port}${normalizePath(net.path ?? '/')}`;
}
function readRequestBody(req: IncomingMessage, maxBytes = 2 * 1024 * 1024): Promise<string> {
@@ -207,4 +263,4 @@ function writeJson(res: ServerResponse, statusCode: number, data: unknown): void
res.statusCode = statusCode;
res.setHeader('Content-Type', 'application/json; charset=utf-8');
res.end(JSON.stringify(data));
}
}
+15
View File
@@ -450,6 +450,21 @@ export async function initWebUI(
app.post('/api/processes/:pid/unload', processAction('unload', (pid) => hookManager!.unloadProcess(pid)));
app.post('/api/processes/:pid/refresh', processAction('refresh', (pid) => hookManager!.refreshProcess(pid)));
app.get('/api/processes/:pid/probe-login', async (c) => {
if (!hookManager) return c.json({ info: null, message: 'hook manager is not available' }, 503);
const pid = Number(c.req.param('pid'));
if (!Number.isInteger(pid) || pid <= 0 || pid > MAX_PID) {
return c.json({ info: null, message: 'invalid pid' }, 400);
}
try {
const info = await hookManager.probeProcessLoginInfo(pid);
return c.json({ info });
} catch (err) {
log.warn('probe-login pid=%d failed: %s', pid, err instanceof Error ? err.message : String(err));
return c.json({ info: null, message: '探测失败' }, 500);
}
});
app.get('/api/config/:uin', (c) => {
const uin = c.req.param('uin');
if (!UIN_REGEX.test(uin)) return c.json({ message: 'invalid uin' }, 400);
+19
View File
@@ -24,6 +24,19 @@ export interface MockBridge {
fetchGroupMemberList: ReturnType<typeof vi.fn>;
fetchUserProfile: ReturnType<typeof vi.fn>;
resolveUserUid: ReturnType<typeof vi.fn>;
// High-level message senders. Default to no-op resolves so actions
// that fire off a follow-up chat message after their main work
// (e.g. `upload_group_file` → `sendGroupFileMessage` to publish the
// file in chat) don't crash test setups that don't care about it.
sendGroupMessage: ReturnType<typeof vi.fn>;
sendPrivateMessage: ReturnType<typeof vi.fn>;
sendC2cFileMessage: ReturnType<typeof vi.fn>;
sendGroupFileMessage: ReturnType<typeof vi.fn>;
// Uploaded-file metadata cache helpers — actions like uploadGroupFile
// / uploadPrivateFile call these to remember the upload, so tests
// covering those code paths get a default-no-op shim.
rememberUploadedFile: ReturnType<typeof vi.fn>;
recallUploadedFile: ReturnType<typeof vi.fn>;
}
export function mockBridge(overrides: Partial<MockBridge> = {}): MockBridge {
@@ -49,6 +62,12 @@ export function mockBridge(overrides: Partial<MockBridge> = {}): MockBridge {
fetchGroupMemberList: vi.fn(async () => []),
fetchUserProfile: vi.fn(async () => ({ uid: 'profile-uid' })),
resolveUserUid: vi.fn(async () => 'resolved-uid'),
sendGroupMessage: vi.fn(async () => ({ messageId: 1, sequence: 1, clientSequence: 0, random: 1, timestamp: 0 })),
sendPrivateMessage: vi.fn(async () => ({ messageId: 1, sequence: 1, clientSequence: 0, random: 1, timestamp: 0 })),
sendC2cFileMessage: vi.fn(async () => ({ messageId: 1, sequence: 1, clientSequence: 0, random: 1, timestamp: 0 })),
sendGroupFileMessage: vi.fn(async () => undefined),
rememberUploadedFile: vi.fn(),
recallUploadedFile: vi.fn(() => undefined),
...overrides,
};
}
+92 -46
View File
@@ -1,19 +1,38 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '../../src/bridge/proto/proton/oidb';
import type {
OidbStrangerStatusResp,
OidbAiVoiceListResp,
OidbAiVoiceResp,
} from '../../src/bridge/proto/proton/oidb-action';
// Same stub-the-oidb-runner pattern as actions/group-admin.test.ts —
// we don't care about wire bytes, just that each function targets the
// right cmd / subCmd / schema.
vi.mock('../../src/bridge/bridge-oidb', () => ({
runOidb: vi.fn(async () => ({})),
}));
// `encodeOidbEnv` / `decodeOidbEnv` are proton-bound pass-through wrappers
// that the plugin substitutes at the call site with the inlined codec, so
// mocking them on the module object is a no-op. The only mockable point
// is `runOidb` (non-generic, untouched by proton) returning real bytes
// that the production-side codec then decodes. `makeOidbEnvelope` is a
// pure TS helper, so its mock works for introspection.
vi.mock('../../src/bridge/bridge-oidb', async () => {
const actual = await vi.importActual<typeof import('../../src/bridge/bridge-oidb')>(
'../../src/bridge/bridge-oidb',
);
return {
...actual,
runOidb: vi.fn(async () => new Uint8Array()),
makeOidbEnvelope: vi.fn((_oidbCmd, _subCmd, body) => ({ body })),
};
});
import * as oidb from '../../src/bridge/bridge-oidb';
import * as extras from '../../src/bridge/actions/extras';
import * as schemas from '../../src/bridge/proto/oidb-action';
import { mockBridge } from './_helpers';
describe('actions/extras / group todo (0xF90)', () => {
beforeEach(() => vi.mocked(oidb.runOidb).mockClear());
beforeEach(() => {
vi.mocked(oidb.runOidb).mockClear();
vi.mocked(oidb.makeOidbEnvelope).mockClear();
});
it.each([
['setGroupTodo', extras.setGroupTodo, 'OidbSvcTrpcTcp.0xf90_1', 1],
@@ -22,32 +41,41 @@ describe('actions/extras / group todo (0xF90)', () => {
] as const)('%s dispatches the right subCmd with shared body', async (_name, fn, cmd, subCmd) => {
const bridge = mockBridge();
await fn(bridge as any, 12345, 9876543210n);
const call = vi.mocked(oidb.runOidb).mock.calls[0]![1];
expect(call.cmd).toBe(cmd);
expect(call.oidbCmd).toBe(0xF90);
expect(call.subCmd).toBe(subCmd);
expect(call.request.schema).toBe(schemas.OidbGroupTodoSchema);
expect(call.request.value).toEqual({ groupUin: 12345, msgSeq: 9876543210n });
const [, runCmd] = vi.mocked(oidb.runOidb).mock.calls[0]!;
expect(runCmd).toBe(cmd);
const [oidbCmd, sub, body] = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]!;
expect(oidbCmd).toBe(0xF90);
expect(sub).toBe(subCmd);
expect(body).toEqual({ groupUin: 12345, msgSeq: 9876543210n });
});
});
describe('actions/extras / getStrangerStatus (0xFE1_2)', () => {
beforeEach(() => vi.mocked(oidb.runOidb).mockClear());
beforeEach(() => {
vi.mocked(oidb.runOidb).mockReset();
vi.mocked(oidb.runOidb).mockResolvedValue(new Uint8Array());
vi.mocked(oidb.makeOidbEnvelope).mockClear();
});
it('issues the FE1_2 query with key=27372', async () => {
const bridge = mockBridge();
vi.mocked(oidb.runOidb).mockResolvedValueOnce({ data: { status: { value: 5n } } } as any);
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
protobuf_encode<OidbBase<OidbStrangerStatusResp>>({ body: { data: { status: { value: 5n } } } }),
);
await extras.getStrangerStatus(bridge as any, 100200);
const call = vi.mocked(oidb.runOidb).mock.calls[0]![1];
expect(call.cmd).toBe('OidbSvcTrpcTcp.0xfe1_2');
expect(call.oidbCmd).toBe(0xFE1);
expect(call.subCmd).toBe(2);
expect(call.request.value).toMatchObject({ uin: 100200, key: [{ key: 27372 }] });
const [, runCmd] = vi.mocked(oidb.runOidb).mock.calls[0]!;
expect(runCmd).toBe('OidbSvcTrpcTcp.0xfe1_2');
const [oidbCmd, sub, body] = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]!;
expect(oidbCmd).toBe(0xFE1);
expect(sub).toBe(2);
expect(body).toMatchObject({ uin: 100200, key: [{ key: 27372 }] });
});
it('low-band values (≤10) map to status*10 with ext_status=0', async () => {
const bridge = mockBridge();
vi.mocked(oidb.runOidb).mockResolvedValueOnce({ data: { status: { value: 7n } } } as any);
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
protobuf_encode<OidbBase<OidbStrangerStatusResp>>({ body: { data: { status: { value: 7n } } } }),
);
expect(await extras.getStrangerStatus(bridge as any, 1)).toEqual({ status: 70, ext_status: 0 });
});
@@ -56,7 +84,9 @@ describe('actions/extras / getStrangerStatus (0xFE1_2)', () => {
// value 0x42F100: bits 8-15 (the 0xff00 mask) = 0xF100;
// bits 16-23 (>>16 & 0xff) = 0x42.
// ext_status = 0xF100 + 0x42 = 0xF142.
vi.mocked(oidb.runOidb).mockResolvedValueOnce({ data: { status: { value: 0x42F100n } } } as any);
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
protobuf_encode<OidbBase<OidbStrangerStatusResp>>({ body: { data: { status: { value: 0x42F100n } } } }),
);
const status = await extras.getStrangerStatus(bridge as any, 1);
expect(status).toEqual({ status: 10, ext_status: 0xF142 });
});
@@ -69,58 +99,74 @@ describe('actions/extras / getStrangerStatus (0xFE1_2)', () => {
it('returns null when the server omits the status field', async () => {
const bridge = mockBridge();
vi.mocked(oidb.runOidb).mockResolvedValueOnce({} as any);
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
protobuf_encode<OidbBase<OidbStrangerStatusResp>>({ body: {} }),
);
expect(await extras.getStrangerStatus(bridge as any, 1)).toBeNull();
});
});
describe('actions/extras / AI voice (0x929D / 0x929B)', () => {
beforeEach(() => vi.mocked(oidb.runOidb).mockClear());
beforeEach(() => {
vi.mocked(oidb.runOidb).mockReset();
vi.mocked(oidb.runOidb).mockResolvedValue(new Uint8Array());
vi.mocked(oidb.makeOidbEnvelope).mockClear();
});
it('fetchAiVoiceList sends 0x929D_0 and returns server content verbatim', async () => {
const bridge = mockBridge();
const fake = [
{ category: 'cute', voices: [{ voiceId: 'v1', voiceDisplayName: 'V1', voiceExampleUrl: 'http://x' }] },
];
vi.mocked(oidb.runOidb).mockResolvedValueOnce({ content: fake } as any);
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
protobuf_encode<OidbBase<OidbAiVoiceListResp>>({ body: { content: fake } } as any),
);
const out = await extras.fetchAiVoiceList(bridge as any, 4242, extras.AiVoiceChatType.Sound);
expect(out).toEqual(fake);
const call = vi.mocked(oidb.runOidb).mock.calls[0]![1];
expect(call.cmd).toBe('OidbSvcTrpcTcp.0x929d_0');
expect(call.request.value).toEqual({ groupUin: 4242, chatType: 1 });
const [, runCmd] = vi.mocked(oidb.runOidb).mock.calls[0]!;
expect(runCmd).toBe('OidbSvcTrpcTcp.0x929d_0');
const body = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2];
expect(body).toEqual({ groupUin: 4242, chatType: 1 });
});
it('fetchAiVoiceList returns [] when server replies with no content', async () => {
const bridge = mockBridge();
vi.mocked(oidb.runOidb).mockResolvedValueOnce({} as any);
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
protobuf_encode<OidbBase<OidbAiVoiceListResp>>({ body: {} }),
);
const out = await extras.fetchAiVoiceList(bridge as any, 1, 1 as any);
expect(out).toEqual([]);
});
it('fetchAiVoice retries while msgInfo is empty, returns the first IndexNode it sees', async () => {
const bridge = mockBridge();
const node = { fileUuid: 'uuid-1', subType: 0 };
// subType is non-zero so proto3 doesn't omit it from the wire (the
// re-decoded object must include the field for the matcher to spot it).
const node = { fileUuid: 'uuid-1', subType: 1 };
vi.mocked(oidb.runOidb)
.mockResolvedValueOnce({ statusCode: 2 } as any)
.mockResolvedValueOnce({ msgInfo: { msgInfoBody: [] } } as any)
.mockResolvedValueOnce({ msgInfo: { msgInfoBody: [{ index: node }] } } as any);
.mockResolvedValueOnce(protobuf_encode<OidbBase<OidbAiVoiceResp>>({ body: { statusCode: 2 } }))
.mockResolvedValueOnce(protobuf_encode<OidbBase<OidbAiVoiceResp>>({ body: { msgInfo: { msgInfoBody: [] } } as any }))
.mockResolvedValueOnce(protobuf_encode<OidbBase<OidbAiVoiceResp>>({ body: { msgInfo: { msgInfoBody: [{ index: node }] } } as any }));
const out = await extras.fetchAiVoice(bridge as any, 100, 'voice-id', 'hi', extras.AiVoiceChatType.Sound);
expect(out).toBe(node);
expect(out).toMatchObject(node);
expect(vi.mocked(oidb.runOidb)).toHaveBeenCalledTimes(3);
const call = vi.mocked(oidb.runOidb).mock.calls[0]![1];
expect(call.cmd).toBe('OidbSvcTrpcTcp.0x929b_0');
expect(call.request.value).toMatchObject({
const [, runCmd] = vi.mocked(oidb.runOidb).mock.calls[0]!;
expect(runCmd).toBe('OidbSvcTrpcTcp.0x929b_0');
const body = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2] as any;
expect(body).toMatchObject({
groupUin: 100, voiceId: 'voice-id', text: 'hi', chatType: 1,
});
// sessionId is randomized but must be a uint32.
expect((call.request.value as any).session.sessionId).toBeTypeOf('number');
expect((call.request.value as any).session.sessionId).toBeGreaterThanOrEqual(0);
expect((call.request.value as any).session.sessionId).toBeLessThanOrEqual(0xFFFFFFFF);
expect(body.session.sessionId).toBeTypeOf('number');
expect(body.session.sessionId).toBeGreaterThanOrEqual(0);
expect(body.session.sessionId).toBeLessThanOrEqual(0xFFFFFFFF);
});
it('fetchAiVoice throws after exhausting the retry budget', async () => {
const bridge = mockBridge();
vi.mocked(oidb.runOidb).mockResolvedValue({ statusCode: 1 } as any);
vi.mocked(oidb.runOidb).mockResolvedValue(
protobuf_encode<OidbBase<OidbAiVoiceResp>>({ body: { statusCode: 1 } }),
);
await expect(extras.fetchAiVoice(bridge as any, 1, 'v', 't', 1 as any, 3)).rejects.toThrow(
/AI voice synthesis did not complete/,
);
@@ -131,11 +177,11 @@ describe('actions/extras / AI voice (0x929D / 0x929B)', () => {
const bridge = mockBridge();
const node = { fileUuid: 'uuid', subType: 0 };
vi.mocked(oidb.runOidb)
.mockResolvedValueOnce({} as any)
.mockResolvedValueOnce({ msgInfo: { msgInfoBody: [{ index: node }] } } as any);
.mockResolvedValueOnce(protobuf_encode<OidbBase<OidbAiVoiceResp>>({ body: {} }))
.mockResolvedValueOnce(protobuf_encode<OidbBase<OidbAiVoiceResp>>({ body: { msgInfo: { msgInfoBody: [{ index: node }] } } as any }));
await extras.fetchAiVoice(bridge as any, 1, 'v', 't', 1 as any);
const first = (vi.mocked(oidb.runOidb).mock.calls[0]![1].request.value as any).session.sessionId;
const second = (vi.mocked(oidb.runOidb).mock.calls[1]![1].request.value as any).session.sessionId;
const first = (vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2] as any).session.sessionId;
const second = (vi.mocked(oidb.makeOidbEnvelope).mock.calls[1]![2] as any).session.sessionId;
expect(first).toBe(second);
});
});
@@ -0,0 +1,168 @@
// Regression coverage for the file-inside-send_forward_msg bug.
//
// Symptom: caller put `{type:'file', file_id}` inside a forward node;
// the element-builder dropped it (`[ElemBuilder] BUG: {type:"file"}
// reached element-builder — must be split out at the OneBot layer`)
// because the live-send paths route files through dedicated methods
// (sendC2cFileMessage / sendGroupFileMessage), and the forward
// builder was naïvely calling buildSendElems with the same ctx. The
// forward upload succeeded but the bubble shipped without the file
// element.
//
// Fix: forward upload passes `forwardFake: true` on the SendContext.
// The element-builder honours that flag by emitting the receive-side
// shapes:
// * group file → transElem(elemType=24, GroupFileExtra)
// * c2c file → handled at the forward-builder level, written into
// `body.msgContent` as FileExtra { file: NotOnlineFile }
//
// These shapes are RECEIVE-side: the QQ-NT live-send pipeline rejects
// transElem(24) (result=79), but the long-msg upload service stores the
// gzipped protobuf verbatim and the recipient's msg-push decoder pulls
// the file entity back out via the normal path (rich-body-decoder.ts).
// Mirrors NapCat's `PacketMsgFileElement.{buildElement,buildContent}`
// split.
import { describe, it, expect, vi } from 'vitest';
vi.mock('../../src/bridge/bridge-oidb', () => ({
runOidb: vi.fn(async () => new Uint8Array()),
makeOidbEnvelope: vi.fn((_oidbCmd, _subCmd, body) => ({ body })),
encodeOidbEnv: vi.fn(() => new Uint8Array()),
decodeOidbEnv: vi.fn(() => ({ body: {} })),
}));
// `vi.mock` factories are hoisted above the imports — declare the spy
// inside a `vi.hoisted` block so it's available at the same moment.
// Declare parameter types on the fn so `mock.calls[0]` infers a tuple
// of [elements, ctx] instead of `[]`, which makes the destructuring
// a tsc error under strict tuple checking on CI.
const { buildSendElemsMock } = vi.hoisted(() => ({
buildSendElemsMock: vi.fn(async (_elements: unknown[], _ctx?: Record<string, unknown>) => []),
}));
vi.mock('../../src/bridge/element-builder', () => ({
buildSendElems: buildSendElemsMock,
}));
import { protoEncode } from '../../src/protobuf/decode';
import { SendLongMsgRespSchema } from '../../src/bridge/proto/longmsg';
import * as forward from '../../src/bridge/actions/forward';
import { mockBridge } from './_helpers';
function uploadResponseWithResId(resId: string) {
const encoded = protoEncode({ result: { resId } }, SendLongMsgRespSchema);
return {
success: true,
gotResponse: true,
errorCode: 0,
errorMessage: '',
responseData: Buffer.from(encoded),
};
}
describe('actions/forward — file segment inside forward node', () => {
it('group forward sets forwardFake:true on the SendContext so transElem(24) is emitted', async () => {
// Group case: the file element rides on elems[] as transElem(24).
// The element-builder receives ctx.forwardFake=true so it knows to
// emit the receive-side shape instead of dropping the segment.
buildSendElemsMock.mockClear();
const bridge = mockBridge({
sendRawPacket: vi.fn(async () => uploadResponseWithResId('res-grp-file')) as any,
});
await forward.uploadForwardNodes(bridge as any, [
{
userUin: 10001,
nickname: 'alice',
elements: [{ type: 'file', fileId: 'gfid-1', fileName: 'a.txt', fileSize: 99 } as any],
},
], 12345);
expect(buildSendElemsMock).toHaveBeenCalled();
const [, ctx] = buildSendElemsMock.mock.calls[0]!;
expect(ctx).toMatchObject({ groupId: 12345, forwardFake: true });
});
it('c2c forward writes the file as msgContent (FileExtra { file: NotOnlineFile })', async () => {
// Private case: c2c files live on `body.msgContent`, not in elems[].
// The forward-builder pulls the file segment off and synthesises a
// FileExtra payload so the recipient's decoder (which reads
// msgContent first) renders the file bubble.
buildSendElemsMock.mockClear();
let captured: Uint8Array | undefined;
const bridge = mockBridge({
sendRawPacket: vi.fn(async (_cmd: string, body: Uint8Array) => {
captured = body;
return uploadResponseWithResId('res-c2c-file');
}) as any,
// Inline fields cover everything we need; cache lookup must not be
// required for the path to work.
recallUploadedFile: vi.fn(() => undefined),
});
await forward.uploadForwardNodes(bridge as any, [
{
userUin: 10001,
nickname: 'alice',
elements: [{
type: 'file',
fileId: 'pfid-1',
fileName: 'invoice.pdf',
fileSize: 4096,
md5Hex: 'aabbccddeeff00112233445566778899',
fileHash: 'srv-hash-abc',
} as any],
},
], undefined, 67890);
expect(buildSendElemsMock).toHaveBeenCalled();
const [, ctx] = buildSendElemsMock.mock.calls[0]!;
expect(ctx).toMatchObject({ forwardFake: true });
expect(ctx?.groupId).toBeUndefined();
// Spot-check that the upload body carries the file metadata. The
// payload is gzipped + protobuf-wrapped, so we just verify the
// raw filename string survived — that's enough to confirm the
// FileExtra branch ran (a "missing file" regression would drop
// these bytes entirely).
expect(captured).toBeDefined();
const flat = Buffer.from(captured!).toString('binary');
// The filename gets gzipped, so we can't substring-search; instead
// assert the body is large enough that the FileExtra wasn't elided.
// (A name-only forward with no msgContent runs ~80-100 bytes; with
// the FileExtra blob it's noticeably larger.)
expect(flat.length).toBeGreaterThan(80);
});
it('c2c forward falls back to the upload metadata cache when inline fields are missing', async () => {
// The OneBot caller often passes only `file_id` — the rest comes
// from the bridge's uploaded-file cache. This is the same
// hydration path send_private_msg uses; the forward builder must
// honour it too or every cached-only forward ships a 0 B bubble.
buildSendElemsMock.mockClear();
const recallUploadedFile = vi.fn((id: string) => id === 'pfid-cached' ? {
fileId: 'pfid-cached',
scope: 'private' as const,
userId: 67890,
fileName: 'cached-name.zip',
fileSize: 8192,
fileMd5: Buffer.from('ffeeddccbbaa99887766554433221100', 'hex'),
fileSha1: new Uint8Array(20),
fileHash: 'cached-hash',
rememberedAt: 0,
} : undefined);
const bridge = mockBridge({
sendRawPacket: vi.fn(async () => uploadResponseWithResId('res-cache')) as any,
recallUploadedFile,
});
await forward.uploadForwardNodes(bridge as any, [{
userUin: 10001,
nickname: 'alice',
elements: [{ type: 'file', fileId: 'pfid-cached' } as any],
}], undefined, 67890);
expect(recallUploadedFile).toHaveBeenCalledWith('pfid-cached');
});
});
+50 -1
View File
@@ -1,7 +1,10 @@
import { describe, it, expect, vi } from 'vitest';
vi.mock('../../src/bridge/bridge-oidb', () => ({
runOidb: vi.fn(async () => ({})),
runOidb: vi.fn(async () => new Uint8Array()),
makeOidbEnvelope: vi.fn((_oidbCmd, _subCmd, body) => ({ body })),
encodeOidbEnv: vi.fn(() => new Uint8Array()),
decodeOidbEnv: vi.fn(() => ({ body: {} })),
}));
// element-builder reaches into protoEncode with element-specific schemas
@@ -101,4 +104,50 @@ describe('actions/forward', () => {
await expect(forward.fetchForwardNodes(bridge as any, 'cold-cache-miss'))
.rejects.toThrow(/download forward message failed|down/);
});
it('uploadForwardNodes recursively uploads nested innerForward chains (NapCat piggyback model)', async () => {
// Regression: nested forward needs the inner chain to be uploaded
// first (so we have its res_id for the outer ARK preview), AND
// the inner level's msgBody to be carried up to the outermost
// long-msg upload as an extra `actionCommand` slot keyed on a
// uuid. Matches `dev/NapCatQQ/.../SendMsg.uploadForwardedNodesPacket`
// — the receiver gets the whole tree from a single fetch instead
// of resolving each layer's res_id separately.
const responses = ['inner-res', 'outer-res'];
const sendRawPacket = vi.fn(async () => uploadResponseWithResId(responses.shift()!)) as any;
const bridge = mockBridge({ sendRawPacket });
const resId = await forward.uploadForwardNodes(bridge as any, [
{
userUin: 111,
nickname: 'outer',
elements: [],
innerForward: [
{ userUin: 222, nickname: 'inner', elements: [{ type: 'text', text: 'hi' }] },
],
},
]);
// Two server roundtrips: one for the inner chain, then one for
// the outer (which piggybacks the inner msgBody onto its actions
// array). The outer res_id is what the caller gets back.
expect(resId).toBe('outer-res');
expect(sendRawPacket).toHaveBeenCalledTimes(2);
});
it('uploadForwardNodes leaves flat (non-nested) sends at a single roundtrip', async () => {
// Backwards-compat: the common case (no inner forward) must still
// be one SsoSendLongMsg call. Without this we'd double upload
// every regular forward send.
const sendRawPacket = vi.fn(async () => uploadResponseWithResId('flat-res')) as any;
const bridge = mockBridge({ sendRawPacket });
const resId = await forward.uploadForwardNodes(bridge as any, [
{ userUin: 10001, nickname: 'a', elements: [{ type: 'text', text: 'hello' }] },
{ userUin: 10002, nickname: 'b', elements: [{ type: 'text', text: 'world' }] },
]);
expect(resId).toBe('flat-res');
expect(sendRawPacket).toHaveBeenCalledOnce();
});
});
+19 -11
View File
@@ -1,7 +1,10 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
vi.mock('../../src/bridge/bridge-oidb', () => ({
runOidb: vi.fn(async () => ({})),
runOidb: vi.fn(async () => new Uint8Array()),
makeOidbEnvelope: vi.fn((_oidbCmd, _subCmd, body) => ({ body })),
encodeOidbEnv: vi.fn(() => new Uint8Array()),
decodeOidbEnv: vi.fn(() => ({ body: {} })),
}));
import * as oidb from '../../src/bridge/bridge-oidb';
@@ -11,31 +14,35 @@ import { mockBridge } from './_helpers';
describe('actions/friend', () => {
beforeEach(() => {
vi.mocked(oidb.runOidb).mockClear();
vi.mocked(oidb.makeOidbEnvelope).mockClear();
vi.mocked(oidb.encodeOidbEnv).mockClear();
vi.mocked(oidb.decodeOidbEnv).mockClear();
});
it('setFriendAddRequest: numeric input is treated as UIN and resolved', async () => {
const bridge = mockBridge();
await friend.setFriendAddRequest(bridge as any, '10001', true);
expect(bridge.resolveUserUid).toHaveBeenCalledWith(10001);
const call = vi.mocked(oidb.runOidb).mock.calls[0]![1];
expect(call.request.value).toMatchObject({ accept: 3, targetUid: 'resolved-uid' });
const body = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2];
expect(body).toMatchObject({ accept: 3, targetUid: 'resolved-uid' });
});
it('setFriendAddRequest: non-numeric flag is forwarded as-is', async () => {
const bridge = mockBridge();
await friend.setFriendAddRequest(bridge as any, 'flag-abc', false);
expect(bridge.resolveUserUid).not.toHaveBeenCalled();
const call = vi.mocked(oidb.runOidb).mock.calls[0]![1];
expect(call.request.value).toMatchObject({ accept: 5, targetUid: 'flag-abc' });
const body = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2];
expect(body).toMatchObject({ accept: 5, targetUid: 'flag-abc' });
});
it('deleteFriend resolves UID, calls 0x126b_0, and triggers a friend-list refresh', async () => {
const bridge = mockBridge();
await friend.deleteFriend(bridge as any, 10001, true);
expect(bridge.resolveUserUid).toHaveBeenCalledWith(10001);
const call = vi.mocked(oidb.runOidb).mock.calls[0]![1];
expect(call.cmd).toBe('OidbSvcTrpcTcp.0x126b_0');
expect((call.request.value as any).field1.block).toBe(true);
const [, cmd] = vi.mocked(oidb.runOidb).mock.calls[0]!;
expect(cmd).toBe('OidbSvcTrpcTcp.0x126b_0');
const body = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2];
expect((body as any).field1.block).toBe(true);
expect(bridge.fetchFriendList).toHaveBeenCalled();
});
@@ -50,8 +57,9 @@ describe('actions/friend', () => {
it('setFriendRemark resolves UID and sends 0xb6e_2', async () => {
const bridge = mockBridge();
await friend.setFriendRemark(bridge as any, 10001, 'best-friend');
const call = vi.mocked(oidb.runOidb).mock.calls[0]![1];
expect(call.cmd).toBe('OidbSvcTrpcTcp.0xb6e_2');
expect(call.request.value).toMatchObject({ targetUid: 'resolved-uid', remark: 'best-friend' });
const [, cmd] = vi.mocked(oidb.runOidb).mock.calls[0]!;
expect(cmd).toBe('OidbSvcTrpcTcp.0xb6e_2');
const body = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2];
expect(body).toMatchObject({ targetUid: 'resolved-uid', remark: 'best-friend' });
});
});
+50 -29
View File
@@ -1,10 +1,24 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '../../src/bridge/proto/proton/oidb';
import type { Oidb0x8a7Resp } from '../../src/bridge/proto/proton/oidb-action';
// Stub the OIDB shim so we can assert WHICH command + payload each
// action constructs without booting a real Bridge / native pipe.
vi.mock('../../src/bridge/bridge-oidb', () => ({
runOidb: vi.fn(async () => ({})),
}));
// `encodeOidbEnv` / `decodeOidbEnv` are proton-bound pass-through wrappers
// that the plugin substitutes at the call site with the inlined codec, so
// mocking them on the module object is a no-op. The only mockable point
// is `runOidb` (non-generic, untouched by proton) returning real bytes
// that the production-side codec then decodes. `makeOidbEnvelope` is a
// pure TS helper, so its mock works for introspection.
vi.mock('../../src/bridge/bridge-oidb', async () => {
const actual = await vi.importActual<typeof import('../../src/bridge/bridge-oidb')>(
'../../src/bridge/bridge-oidb',
);
return {
...actual,
runOidb: vi.fn(async () => new Uint8Array()),
makeOidbEnvelope: vi.fn((_oidbCmd, _subCmd, body) => ({ body })),
};
});
import * as oidb from '../../src/bridge/bridge-oidb';
import * as admin from '../../src/bridge/actions/group-admin';
@@ -12,7 +26,9 @@ import { mockBridge } from './_helpers';
describe('actions/group-admin', () => {
beforeEach(() => {
vi.mocked(oidb.runOidb).mockClear();
vi.mocked(oidb.runOidb).mockReset();
vi.mocked(oidb.runOidb).mockResolvedValue(new Uint8Array());
vi.mocked(oidb.makeOidbEnvelope).mockClear();
});
it('muteGroupMember resolves UID and dispatches 0x1253_1', async () => {
@@ -20,11 +36,12 @@ describe('actions/group-admin', () => {
await admin.muteGroupMember(bridge as any, 12345, 67890, 600);
expect(bridge.resolveUserUid).toHaveBeenCalledWith(67890, 12345);
expect(oidb.runOidb).toHaveBeenCalledOnce();
const call = vi.mocked(oidb.runOidb).mock.calls[0]![1];
expect(call.cmd).toBe('OidbSvcTrpcTcp.0x1253_1');
expect(call.oidbCmd).toBe(0x1253);
expect(call.subCmd).toBe(1);
expect(call.request.value).toMatchObject({
const [, cmd] = vi.mocked(oidb.runOidb).mock.calls[0]!;
expect(cmd).toBe('OidbSvcTrpcTcp.0x1253_1');
const [oidbCmd, subCmd, body] = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]!;
expect(oidbCmd).toBe(0x1253);
expect(subCmd).toBe(1);
expect(body).toMatchObject({
groupUin: 12345,
type: 1,
body: { targetUid: 'resolved-uid', duration: 600 },
@@ -34,13 +51,13 @@ describe('actions/group-admin', () => {
it('muteGroupAll flips the muteState flag based on enable', async () => {
const bridge = mockBridge();
await admin.muteGroupAll(bridge as any, 12345, true);
expect(vi.mocked(oidb.runOidb).mock.calls[0]![1].request.value).toMatchObject({
expect(vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2]).toMatchObject({
groupUin: 12345,
muteState: { state: 0xFFFFFFFF },
});
await admin.muteGroupAll(bridge as any, 12345, false);
expect(vi.mocked(oidb.runOidb).mock.calls[1]![1].request.value).toMatchObject({
expect(vi.mocked(oidb.makeOidbEnvelope).mock.calls[1]![2]).toMatchObject({
muteState: { state: 0 },
});
});
@@ -49,7 +66,7 @@ describe('actions/group-admin', () => {
const bridge = mockBridge();
await admin.kickGroupMember(bridge as any, 12345, 67890, true, 'bad behaviour');
expect(bridge.resolveUserUid).toHaveBeenCalledWith(67890, 12345);
expect(vi.mocked(oidb.runOidb).mock.calls[0]![1].request.value).toMatchObject({
expect(vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2]).toMatchObject({
groupUin: 12345,
targetUid: 'resolved-uid',
rejectAddRequest: true,
@@ -65,7 +82,7 @@ describe('actions/group-admin', () => {
await admin.kickGroupMembers(bridge as any, 12345, [11, 22], false);
expect(bridge.resolveUserUid).toHaveBeenCalledTimes(2);
const payload: any = vi.mocked(oidb.runOidb).mock.calls[0]![1].request.value;
const payload: any = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2];
expect(payload.targetUids).toEqual(['uid-a', 'uid-b']);
expect(payload.rejectAddRequest).toBe(0);
});
@@ -73,15 +90,15 @@ describe('actions/group-admin', () => {
it('leaveGroup sends 0x1097_1 with the groupUin', async () => {
const bridge = mockBridge();
await admin.leaveGroup(bridge as any, 12345);
const call = vi.mocked(oidb.runOidb).mock.calls[0]![1];
expect(call.cmd).toBe('OidbSvcTrpcTcp.0x1097_1');
expect(call.request.value).toMatchObject({ groupUin: 12345 });
const [, cmd] = vi.mocked(oidb.runOidb).mock.calls[0]!;
expect(cmd).toBe('OidbSvcTrpcTcp.0x1097_1');
expect(vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2]).toMatchObject({ groupUin: 12345 });
});
it('setGroupAdmin resolves UID and sends 0x1096_1', async () => {
const bridge = mockBridge();
await admin.setGroupAdmin(bridge as any, 12345, 67890, true);
expect(vi.mocked(oidb.runOidb).mock.calls[0]![1].request.value).toMatchObject({
expect(vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2]).toMatchObject({
groupUin: 12345, uid: 'resolved-uid', isAdmin: true,
});
});
@@ -95,7 +112,7 @@ describe('actions/group-admin', () => {
await admin.setGroupAddOption(bridge as any, 1, 2);
await admin.setGroupSearch(bridge as any, 1);
const cmds = vi.mocked(oidb.runOidb).mock.calls.map(call => call[1].cmd);
const cmds = vi.mocked(oidb.runOidb).mock.calls.map(call => call[1]);
expect(cmds).toEqual([
'OidbSvcTrpcTcp.0x8fc_3',
'OidbSvcTrpcTcp.0x89a_15',
@@ -111,27 +128,27 @@ describe('actions/group-admin', () => {
await admin.setGroupAddRequest(bridge as any, 12345, 5, 1, true, 'ok', false);
await admin.setGroupAddRequest(bridge as any, 12345, 5, 1, false, 'no', true);
const cmds = vi.mocked(oidb.runOidb).mock.calls.map(call => call[1].cmd);
const cmds = vi.mocked(oidb.runOidb).mock.calls.map(call => call[1]);
expect(cmds).toEqual([
'OidbSvcTrpcTcp.0x10c8_1',
'OidbSvcTrpcTcp.0x10c8_2',
]);
const firstBody: any = vi.mocked(oidb.runOidb).mock.calls[0]![1].request.value;
const firstBody: any = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2];
expect(firstBody.accept).toBe(1);
expect(firstBody.body.message).toBe('ok');
const secondBody: any = vi.mocked(oidb.runOidb).mock.calls[1]![1].request.value;
const secondBody: any = vi.mocked(oidb.makeOidbEnvelope).mock.calls[1]![2];
expect(secondBody.accept).toBe(2);
});
it('getGroupAtAllRemain decodes the response and converts BigInts', async () => {
const bridge = mockBridge();
vi.mocked(oidb.runOidb).mockResolvedValueOnce({
canAtAll: 1,
groupRemain: 12n,
uinRemain: 5n,
});
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
protobuf_encode<OidbBase<Oidb0x8a7Resp>>({
body: { canAtAll: true, groupRemain: 12, uinRemain: 5 } as any,
}),
);
const out = await admin.getGroupAtAllRemain(bridge as any, 12345);
expect(out).toEqual({
can_at_all: true,
@@ -142,7 +159,11 @@ describe('actions/group-admin', () => {
it('getGroupAtAllRemain throws when the response is empty', async () => {
const bridge = mockBridge();
vi.mocked(oidb.runOidb).mockResolvedValueOnce(null);
// An empty OidbBase envelope (no body) — production code sees `body`
// undefined and throws the "empty" error.
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
protobuf_encode<OidbBase<Oidb0x8a7Resp>>({}),
);
await expect(admin.getGroupAtAllRemain(bridge as any, 12345)).rejects.toThrow(/empty/);
});
});
+349 -67
View File
@@ -1,8 +1,30 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '../../src/bridge/proto/proton/oidb';
import type {
OidbGroupFileCountViewResp,
OidbGroupFileResp,
OidbGroupFileViewResp,
OidbPrivateFileUploadResp,
OidbGroupFileFolderResp,
NTV2RichMediaResp,
} from '../../src/bridge/proto/proton/oidb-action';
vi.mock('../../src/bridge/bridge-oidb', () => ({
runOidb: vi.fn(async () => ({})),
}));
// `encodeOidbEnv` / `decodeOidbEnv` are proton-bound pass-through wrappers
// (substituted at the call site with the inlined codec). Mocking them on
// the module object is a no-op — proton has already inlined the call.
// We mock `runOidb` (non-generic, proton leaves it alone) to return real
// proton-encoded bytes, which the production-side codec then decodes.
vi.mock('../../src/bridge/bridge-oidb', async () => {
const actual = await vi.importActual<typeof import('../../src/bridge/bridge-oidb')>(
'../../src/bridge/bridge-oidb',
);
return {
...actual,
runOidb: vi.fn(async () => new Uint8Array()),
makeOidbEnvelope: vi.fn((_oidbCmd, _subCmd, body) => ({ body })),
};
});
vi.mock('../../src/bridge/highway/highway-client', () => ({
fetchHighwaySession: vi.fn(async () => ({})),
@@ -27,36 +49,45 @@ import { mockBridge } from './_helpers';
describe('actions/group-file', () => {
beforeEach(() => {
vi.mocked(oidb.runOidb).mockReset();
vi.mocked(oidb.runOidb).mockResolvedValue({});
vi.mocked(oidb.runOidb).mockResolvedValue(new Uint8Array());
vi.mocked(oidb.makeOidbEnvelope).mockClear();
vi.mocked(highwayClient.fetchHighwaySession).mockClear();
vi.mocked(highwayClient.uploadHighwayHttp).mockClear();
});
it('fetchGroupFileCount returns { fileCount, maxCount } from the OIDB response', async () => {
const bridge = mockBridge();
vi.mocked(oidb.runOidb).mockResolvedValueOnce({
count: { fileCount: 42, maxCount: 1000 },
});
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
protobuf_encode<OidbBase<OidbGroupFileCountViewResp>>({
body: { count: { fileCount: 42, maxCount: 1000 } },
}),
);
const out = await groupFile.fetchGroupFileCount(bridge as any, 12345);
expect(out).toEqual({ fileCount: 42, maxCount: 1000 });
});
it('fetchGroupFileCount falls back to defaults on partial response', async () => {
const bridge = mockBridge();
vi.mocked(oidb.runOidb).mockResolvedValueOnce({ count: {} });
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
protobuf_encode<OidbBase<OidbGroupFileCountViewResp>>({ body: { count: {} } }),
);
const out = await groupFile.fetchGroupFileCount(bridge as any, 12345);
expect(out).toEqual({ fileCount: 0, maxCount: 10000 });
});
it('uploadGroupFile skips highway when boolFileExist is true', async () => {
const bridge = mockBridge();
vi.mocked(oidb.runOidb).mockResolvedValueOnce({
upload: {
retCode: 0,
fileId: 'fid-xyz',
boolFileExist: true,
},
});
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
protobuf_encode<OidbBase<OidbGroupFileResp>>({
body: {
upload: {
// retCode 0 omitted by proto3 — production only checks against nonzero
fileId: 'fid-xyz',
boolFileExist: true,
},
} as any,
}),
);
const out = await groupFile.uploadGroupFile(bridge as any, 12345, '/path/file.bin');
expect(out).toEqual({ fileId: 'fid-xyz' });
expect(highwayClient.fetchHighwaySession).not.toHaveBeenCalled();
@@ -65,17 +96,21 @@ describe('actions/group-file', () => {
it('uploadGroupFile runs highway PUT when boolFileExist is false', async () => {
const bridge = mockBridge();
vi.mocked(oidb.runOidb).mockResolvedValueOnce({
upload: {
retCode: 0,
fileId: 'fid-xyz',
boolFileExist: false,
uploadIp: '1.2.3.4',
uploadPort: 8080,
fileKey: new Uint8Array([9]),
checkKey: new Uint8Array([8]),
},
});
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
protobuf_encode<OidbBase<OidbGroupFileResp>>({
body: {
upload: {
fileId: 'fid-xyz',
// boolFileExist is the proto3 default (false) — omit, production
// sees undefined which the helper treats as "must upload via highway".
uploadIp: '1.2.3.4',
uploadPort: 8080,
fileKey: new Uint8Array([9]),
checkKey: new Uint8Array([8]),
},
} as any,
}),
);
await groupFile.uploadGroupFile(bridge as any, 12345, '/path/file.bin');
expect(highwayClient.fetchHighwaySession).toHaveBeenCalledOnce();
expect(highwayClient.uploadHighwayHttp).toHaveBeenCalledOnce();
@@ -83,20 +118,120 @@ describe('actions/group-file', () => {
it('uploadGroupFile throws on missing upload response', async () => {
const bridge = mockBridge();
vi.mocked(oidb.runOidb).mockResolvedValueOnce({});
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
protobuf_encode<OidbBase<OidbGroupFileResp>>({ body: {} }),
);
await expect(groupFile.uploadGroupFile(bridge as any, 12345, '/path/file.bin'))
.rejects.toThrow(/response missing/);
});
it('uploadGroupFile bubbles up OIDB retCode errors', async () => {
const bridge = mockBridge();
vi.mocked(oidb.runOidb).mockResolvedValueOnce({
upload: { retCode: 999, retMsg: 'quota exceeded' },
});
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
protobuf_encode<OidbBase<OidbGroupFileResp>>({
body: { upload: { retCode: 999, retMsg: 'quota exceeded' } as any },
}),
);
await expect(groupFile.uploadGroupFile(bridge as any, 12345, '/path/file.bin'))
.rejects.toThrow(/code=999/);
});
it('uploadGroupFile publishes the file via OIDB 0x6d9_4 after upload (the "empty message" regression)', async () => {
// Reproduces the bug report: OIDB upload + highway PUT alone only
// stage the bytes on QQ's side; without the trailing 0x6d9_4 OIDB
// call the file never appears in the chat. Earlier attempts used
// PbSendMsg with a transElem(24) but the QQ-NT server rejects that
// with result=79 (transElem(24) is a receive-side decoding shape,
// not a send-side one). Asserts that `bridge.sendGroupFileMessage`
// is invoked with the uploaded fileId.
const bridge = mockBridge();
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
protobuf_encode<OidbBase<OidbGroupFileResp>>({
body: { upload: { fileId: 'fid-pub', boolFileExist: true } as any },
}),
);
await groupFile.uploadGroupFile(bridge as any, 12345, '/path/some-file.bin', 'mynote.txt');
expect(bridge.sendGroupFileMessage).toHaveBeenCalledOnce();
const [groupId, fileId] = bridge.sendGroupFileMessage.mock.calls[0]!;
expect(groupId).toBe(12345);
expect(fileId).toBe('fid-pub');
// sendGroupMessage must NOT be touched — the previous wire shape
// (PbSendMsg w/ transElem(24)) is the bug we're guarding against.
expect(bridge.sendGroupMessage).not.toHaveBeenCalled();
});
it('uploadGroupFile skips the chat post when uploadFile=false', async () => {
const bridge = mockBridge();
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
protobuf_encode<OidbBase<OidbGroupFileResp>>({
body: { upload: { fileId: 'fid-skip', boolFileExist: true } as any },
}),
);
await groupFile.uploadGroupFile(bridge as any, 12345, '/path/file.bin', '', '/', false);
expect(bridge.sendGroupFileMessage).not.toHaveBeenCalled();
});
it('uploadGroupFile returns success even when the chat post fails (file is still uploaded)', async () => {
const bridge = mockBridge();
vi.mocked(bridge.sendGroupFileMessage).mockRejectedValueOnce(new Error('message rejected'));
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
protobuf_encode<OidbBase<OidbGroupFileResp>>({
body: { upload: { fileId: 'fid-tolerant', boolFileExist: true } as any },
}),
);
const out = await groupFile.uploadGroupFile(bridge as any, 12345, '/path/file.bin');
expect(out).toEqual({ fileId: 'fid-tolerant' });
expect(bridge.sendGroupFileMessage).toHaveBeenCalledOnce();
});
it('uploadGroupFile caches the upload metadata for later resend by file_id', async () => {
// After upload, a later `send_group_msg` carrying just the file_id
// needs to recover the name/size/md5 from somewhere. Production
// populates `bridge.rememberUploadedFile` with the full tuple.
const bridge = mockBridge();
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
protobuf_encode<OidbBase<OidbGroupFileResp>>({
body: { upload: { fileId: 'fid-cached', boolFileExist: true } as any },
}),
);
await groupFile.uploadGroupFile(bridge as any, 12345, '/path/x.bin', 'x.bin');
expect(bridge.rememberUploadedFile).toHaveBeenCalledOnce();
const [meta] = bridge.rememberUploadedFile.mock.calls[0]!;
expect(meta).toMatchObject({
fileId: 'fid-cached',
scope: 'group',
groupId: 12345,
fileName: 'x.bin',
});
});
it('sendGroupFileMessage hits OIDB 0x6d9_4 with the right body', async () => {
// Direct cover of the new bridge method. The previous send-shape
// (PbSendMsg + transElem(24)) failed with result=79; this is the
// Lagrange-V2-mirrored fix.
const bridge = mockBridge();
vi.mocked(oidb.runOidb).mockResolvedValueOnce(new Uint8Array());
await groupFile.sendGroupFileMessage(bridge as any, 12345, 'fid-publish');
expect(oidb.runOidb).toHaveBeenCalledOnce();
const [, cmd] = vi.mocked(oidb.runOidb).mock.calls[0]!;
expect(cmd).toBe('OidbSvcTrpcTcp.0x6d9_4');
// The envelope wraps a `{body: {groupUin, type=2, info: {busiType=102, fileId, ...}}}`.
expect(oidb.makeOidbEnvelope).toHaveBeenCalledWith(
0x6D9, 4,
expect.objectContaining({
body: expect.objectContaining({
groupUin: 12345,
type: 2,
info: expect.objectContaining({
busiType: 102,
fileId: 'fid-publish',
field5: true,
}),
}),
}),
);
});
it('uploadPrivateFile resolves both target + self UID before OIDB call', async () => {
const bridge = mockBridge({
identity: {
@@ -111,26 +246,164 @@ describe('actions/group-file', () => {
vi.mocked(bridge.resolveUserUid)
.mockResolvedValueOnce('target-uid') // target user
.mockResolvedValueOnce('self-uid-resolved'); // self fallback
vi.mocked(oidb.runOidb).mockResolvedValueOnce({
upload: { retCode: 0, uuid: 'fid', fileAddon: 'hash', boolFileExist: true },
});
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
protobuf_encode<OidbBase<OidbPrivateFileUploadResp>>({
body: { upload: { uuid: 'fid', fileAddon: 'hash', boolFileExist: true } as any },
}),
);
const out = await groupFile.uploadPrivateFile(bridge as any, 67890, '/path/file');
expect(out).toEqual({ fileId: 'fid', fileHash: 'hash' });
expect(bridge.resolveUserUid).toHaveBeenCalledTimes(2);
});
it('uploadPrivateFile publishes the file via sendC2cFileMessage after upload', async () => {
// C2C files use `RichText.notOnlineFile` (not in the elems array),
// so `uploadPrivateFile` calls the dedicated `sendC2cFileMessage`
// path on the bridge rather than `sendPrivateMessage`. Same bug
// class as the group case — without this the recipient sees no
// message even though the bytes are on the server.
const bridge = mockBridge();
vi.mocked(bridge.resolveUserUid).mockResolvedValueOnce('target-uid');
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
protobuf_encode<OidbBase<OidbPrivateFileUploadResp>>({
body: { upload: { uuid: 'pfid', fileAddon: 'phash', boolFileExist: true } as any },
}),
);
await groupFile.uploadPrivateFile(bridge as any, 67890, '/path/private-file.bin', 'doc.pdf');
expect(bridge.sendC2cFileMessage).toHaveBeenCalledOnce();
const [userUin, userUid, info] = bridge.sendC2cFileMessage.mock.calls[0]!;
expect(userUin).toBe(67890);
expect(userUid).toBe('target-uid');
expect(info).toMatchObject({ fileId: 'pfid', fileName: 'doc.pdf', fileHash: 'phash' });
expect(bridge.sendPrivateMessage).not.toHaveBeenCalled();
});
it('uploadPrivateFile caches the upload metadata for later resend by file_id', async () => {
// C2C file resend (send_private_msg with just file_id) was the
// "sends a 0 B file" bug: the wire packet needs fileSize/fileMd5/
// fileName/fileHash, but the OneBot caller only knows the file_id.
// Caching the upload tuple lets the OneBot send-message path
// recover the rest via `bridge.recallUploadedFile(fileId)`.
const bridge = mockBridge();
vi.mocked(bridge.resolveUserUid).mockResolvedValueOnce('target-uid');
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
protobuf_encode<OidbBase<OidbPrivateFileUploadResp>>({
body: { upload: { uuid: 'pfid-cache', fileAddon: 'addon-hash', boolFileExist: true } as any },
}),
);
await groupFile.uploadPrivateFile(bridge as any, 67890, '/path/cache-me.txt', 'cache-me.txt');
expect(bridge.rememberUploadedFile).toHaveBeenCalledOnce();
const [meta] = bridge.rememberUploadedFile.mock.calls[0]!;
expect(meta).toMatchObject({
fileId: 'pfid-cache',
scope: 'private',
userId: 67890,
fileName: 'cache-me.txt',
fileHash: 'addon-hash',
});
});
it('uploadPrivateFile skips the chat post when uploadFile=false', async () => {
const bridge = mockBridge();
vi.mocked(bridge.resolveUserUid).mockResolvedValueOnce('target-uid');
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
protobuf_encode<OidbBase<OidbPrivateFileUploadResp>>({
body: { upload: { uuid: 'pfid', fileAddon: 'phash', boolFileExist: true } as any },
}),
);
await groupFile.uploadPrivateFile(bridge as any, 67890, '/path/file', '', false);
expect(bridge.sendC2cFileMessage).not.toHaveBeenCalled();
});
it('uploadPrivateFile reads host from rtpMediaPlatformUploadAddress[0].inIP when populated', async () => {
// The 2026 QQ-NT server rollout moved the upload host out of the
// legacy `uploadIp` (field 60) string into the new
// `rtpMediaPlatformUploadAddress` (field 210, repeated IPv4 message).
// Mirrors acidify's `UploadPrivateFile.kt` consumer logic — read
// `inIP` (LAN, same DC as the OIDB endpoint) and pair with `inPort`.
// The int is little-endian-packed: 0x0101A8C0 → 192.168.1.1.
const bridge = mockBridge();
vi.mocked(bridge.resolveUserUid).mockResolvedValueOnce('target-uid');
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
protobuf_encode<OidbBase<OidbPrivateFileUploadResp>>({
body: {
upload: {
uuid: 'pfid',
fileAddon: 'phash',
// boolFileExist defaults to false — forces highway path
// 192.168.1.1 little-endian packed = (1 << 24) | (1 << 16) | (168 << 8) | 192 = 16885952
rtpMediaPlatformUploadAddress: [
{ outIP: 0, outPort: 0, inIP: 16885952, inPort: 8080, iPType: 1 },
],
mediaPlatformUploadKey: new Uint8Array([1, 2, 3]),
} as any,
},
}),
);
await groupFile.uploadPrivateFile(bridge as any, 67890, '/path/file.bin');
expect(highwayClient.uploadHighwayHttp).toHaveBeenCalledOnce();
});
it('uploadPrivateFile falls back to uploadDomain when uploadIp is empty', async () => {
// Regression: the server has been observed in the wild returning the
// highway host in `uploadDomain` (field 70) instead of `uploadIp`
// (field 60), causing "private file upload host is invalid". The
// helper should walk the parallel host fields rather than dying on
// a single missing slot. Cross-referenced against napcat's proto
// (`Oidb.0XE37_800.ts` ApplyUploadRespV3) — fields 60/70/130/150/160
// all carry plausible host values from the same server endpoint.
const bridge = mockBridge();
vi.mocked(bridge.resolveUserUid).mockResolvedValueOnce('target-uid');
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
protobuf_encode<OidbBase<OidbPrivateFileUploadResp>>({
body: {
upload: {
uuid: 'pfid',
fileAddon: 'phash',
// boolFileExist defaults to false (proto3) — forces the
// highway path where the host fields actually matter.
uploadDomain: 'upload.qpic.cn',
uploadPort: 8080,
mediaPlatformUploadKey: new Uint8Array([1, 2, 3]),
} as any,
},
}),
);
await groupFile.uploadPrivateFile(bridge as any, 67890, '/path/file.bin');
expect(highwayClient.uploadHighwayHttp).toHaveBeenCalledOnce();
});
it('uploadPrivateFile throws "host is invalid" only when every host field is empty', async () => {
// The diagnostic warn-log lists every host slot to help users
// report which one the server actually populated; this test just
// asserts that the throw still fires when none of them carry a
// value (boolFileExist=false + no usable host).
const bridge = mockBridge();
vi.mocked(bridge.resolveUserUid).mockResolvedValueOnce('target-uid');
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
protobuf_encode<OidbBase<OidbPrivateFileUploadResp>>({
body: { upload: { uuid: 'pfid', fileAddon: 'phash', uploadPort: 8080 } as any },
}),
);
await expect(groupFile.uploadPrivateFile(bridge as any, 67890, '/path/file.bin'))
.rejects.toThrow(/upload host is invalid/);
});
it('fetchGroupFiles paginates files + folders out of OIDB items', async () => {
const bridge = mockBridge();
vi.mocked(oidb.runOidb).mockResolvedValueOnce({
list: {
retCode: 0,
isEnd: true,
items: [
{ type: 1, fileInfo: { fileId: 'f1', fileName: 'a.txt', uploaderUin: 1, uploaderName: 'alice' } },
{ type: 2, folderInfo: { folderId: 'd1', folderName: 'dir', creatorUin: 2, creatorName: 'bob' } },
],
},
});
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
protobuf_encode<OidbBase<OidbGroupFileViewResp>>({
body: {
list: {
isEnd: true,
items: [
{ type: 1, fileInfo: { fileId: 'f1', fileName: 'a.txt', uploaderUin: 1, uploaderName: 'alice' } },
{ type: 2, folderInfo: { folderId: 'd1', folderName: 'dir', creatorUin: 2, creatorName: 'bob' } },
],
} as any,
},
}),
);
const out = await groupFile.fetchGroupFiles(bridge as any, 12345);
expect(out.files).toHaveLength(1);
expect(out.files[0]).toMatchObject({ fileId: 'f1', fileName: 'a.txt', uploader: 1, uploaderName: 'alice' });
@@ -140,22 +413,27 @@ describe('actions/group-file', () => {
it('fetchGroupFileUrl builds the https URL from downloadDns + hex-encoded path', async () => {
const bridge = mockBridge();
vi.mocked(oidb.runOidb).mockResolvedValueOnce({
download: {
retCode: 0,
downloadDns: 'cdn.example.com',
downloadUrl: new Uint8Array([0x01, 0x02]),
},
});
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
protobuf_encode<OidbBase<OidbGroupFileResp>>({
body: {
download: {
downloadDns: 'cdn.example.com',
downloadUrl: new Uint8Array([0x01, 0x02]),
} as any,
},
}),
);
const url = await groupFile.fetchGroupFileUrl(bridge as any, 12345, 'fid-xyz');
expect(url).toBe('https://cdn.example.com/ftn_handler/0102/?fname=fid-xyz');
});
it('fetchGroupFileUrl throws when response is missing dns or url', async () => {
const bridge = mockBridge();
vi.mocked(oidb.runOidb).mockResolvedValueOnce({
download: { retCode: 0 },
});
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
protobuf_encode<OidbBase<OidbGroupFileResp>>({
body: { download: {} as any },
}),
);
await expect(groupFile.fetchGroupFileUrl(bridge as any, 12345, 'fid-xyz'))
.rejects.toThrow(/invalid/);
});
@@ -163,34 +441,38 @@ describe('actions/group-file', () => {
it('deleteGroupFile / moveGroupFile dispatch the right sub-commands', async () => {
const bridge = mockBridge();
vi.mocked(oidb.runOidb)
.mockResolvedValueOnce({ delete: { retCode: 0 } })
.mockResolvedValueOnce({ move: { retCode: 0 } });
.mockResolvedValueOnce(protobuf_encode<OidbBase<OidbGroupFileResp>>({ body: { delete: {} as any } }))
.mockResolvedValueOnce(protobuf_encode<OidbBase<OidbGroupFileResp>>({ body: { move: {} as any } }));
await groupFile.deleteGroupFile(bridge as any, 12345, 'fid');
await groupFile.moveGroupFile(bridge as any, 12345, 'fid', '/a', '/b');
expect(vi.mocked(oidb.runOidb).mock.calls.map(c => c[1].subCmd)).toEqual([3, 5]);
expect(vi.mocked(oidb.makeOidbEnvelope).mock.calls.map(c => c[1])).toEqual([3, 5]);
});
it('createGroupFileFolder / deleteGroupFileFolder / renameGroupFileFolder dispatch 0x6d7 family', async () => {
const bridge = mockBridge();
vi.mocked(oidb.runOidb)
.mockResolvedValueOnce({ create: { retcode: 0 } })
.mockResolvedValueOnce({ delete: { retcode: 0 } })
.mockResolvedValueOnce({ rename: { retcode: 0 } });
.mockResolvedValueOnce(protobuf_encode<OidbBase<OidbGroupFileFolderResp>>({ body: { create: {} as any } }))
.mockResolvedValueOnce(protobuf_encode<OidbBase<OidbGroupFileFolderResp>>({ body: { delete: {} as any } }))
.mockResolvedValueOnce(protobuf_encode<OidbBase<OidbGroupFileFolderResp>>({ body: { rename: {} as any } }));
await groupFile.createGroupFileFolder(bridge as any, 1, 'folder');
await groupFile.deleteGroupFileFolder(bridge as any, 1, 'fid');
await groupFile.renameGroupFileFolder(bridge as any, 1, 'fid', 'newname');
expect(vi.mocked(oidb.runOidb).mock.calls.map(c => c[1].oidbCmd)).toEqual([0x6D7, 0x6D7, 0x6D7]);
expect(vi.mocked(oidb.makeOidbEnvelope).mock.calls.map(c => c[0])).toEqual([0x6D7, 0x6D7, 0x6D7]);
});
it('fetch*UrlByNode builds https://domain/path?rkey from the NTV2 response', async () => {
const bridge = mockBridge();
vi.mocked(oidb.runOidb).mockResolvedValue({
respHead: { retCode: 0 },
download: {
info: { domain: 'media.example.com', urlPath: '/path/x' },
rKeyParam: '?rkey=abc',
},
});
vi.mocked(oidb.runOidb).mockResolvedValue(
protobuf_encode<OidbBase<NTV2RichMediaResp>>({
body: {
respHead: {},
download: {
info: { domain: 'media.example.com', urlPath: '/path/x' },
rKeyParam: '?rkey=abc',
} as any,
} as any,
}),
);
const url = await groupFile.fetchGroupVideoUrlByNode(bridge as any, 12345, { fileUuid: 'uuid' });
expect(url).toBe('https://media.example.com/path/x?rkey=abc');
});
@@ -1,7 +1,10 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
vi.mock('../../src/bridge/bridge-oidb', () => ({
runOidb: vi.fn(async () => ({})),
runOidb: vi.fn(async () => new Uint8Array()),
makeOidbEnvelope: vi.fn((_oidbCmd, _subCmd, body) => ({ body })),
encodeOidbEnv: vi.fn(() => new Uint8Array()),
decodeOidbEnv: vi.fn(() => ({ body: {} })),
}));
import * as oidb from '../../src/bridge/bridge-oidb';
@@ -11,6 +14,9 @@ import { mockBridge } from './_helpers';
describe('actions/group-message', () => {
beforeEach(() => {
vi.mocked(oidb.runOidb).mockClear();
vi.mocked(oidb.makeOidbEnvelope).mockClear();
vi.mocked(oidb.encodeOidbEnv).mockClear();
vi.mocked(oidb.decodeOidbEnv).mockClear();
});
it('recallGroupMessage sends to SsoGroupRecallMsg with the group sequence', async () => {
@@ -59,7 +65,7 @@ describe('actions/group-message', () => {
const bridge = mockBridge();
await msg.setGroupEssence(bridge as any, 12345, 5, 7, true);
await msg.setGroupEssence(bridge as any, 12345, 5, 7, false);
const cmds = vi.mocked(oidb.runOidb).mock.calls.map(c => c[1].cmd);
const cmds = vi.mocked(oidb.runOidb).mock.calls.map(c => c[1]);
expect(cmds).toEqual(['OidbSvcTrpcTcp.0xeac_1', 'OidbSvcTrpcTcp.0xeac_2']);
});
});
+42 -17
View File
@@ -1,8 +1,25 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '../../src/bridge/proto/proton/oidb';
import type { Oidb0x9083Resp } from '../../src/bridge/proto/proton/oidb-action';
vi.mock('../../src/bridge/bridge-oidb', () => ({
runOidb: vi.fn(async () => ({})),
}));
// `encodeOidbEnv` / `decodeOidbEnv` are proton-bound pass-through wrappers
// that the plugin substitutes at the call site for the inlined codec.
// That means production calls to them NEVER hit the imported function —
// mocking them on the module object is a no-op. The only mockable point
// is `runOidb` (non-generic, untouched by proton) returning real bytes
// that the production-side codec actually decodes. `makeOidbEnvelope` is
// a pure TS helper, so its mock works for introspection.
vi.mock('../../src/bridge/bridge-oidb', async () => {
const actual = await vi.importActual<typeof import('../../src/bridge/bridge-oidb')>(
'../../src/bridge/bridge-oidb',
);
return {
...actual,
runOidb: vi.fn(async () => new Uint8Array()),
makeOidbEnvelope: vi.fn((_oidbCmd, _subCmd, body) => ({ body })),
};
});
import * as oidb from '../../src/bridge/bridge-oidb';
import * as inter from '../../src/bridge/actions/interaction';
@@ -11,45 +28,51 @@ import { mockBridge } from './_helpers';
describe('actions/interaction', () => {
beforeEach(() => {
vi.mocked(oidb.runOidb).mockReset();
vi.mocked(oidb.runOidb).mockResolvedValue({});
vi.mocked(oidb.runOidb).mockResolvedValue(new Uint8Array());
vi.mocked(oidb.makeOidbEnvelope).mockClear();
});
it('sendPoke group: groupUin set, friendUin=0', async () => {
const bridge = mockBridge();
await inter.sendPoke(bridge as any, true, 12345, 67890);
const call = vi.mocked(oidb.runOidb).mock.calls[0]![1];
expect(call.request.value).toMatchObject({ uin: 67890, groupUin: 12345, friendUin: 0 });
const body = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2];
expect(body).toMatchObject({ uin: 67890, groupUin: 12345, friendUin: 0 });
});
it('sendPoke friend: friendUin set, groupUin=0, targetUin defaults to peer', async () => {
const bridge = mockBridge();
await inter.sendPoke(bridge as any, false, 67890);
const call = vi.mocked(oidb.runOidb).mock.calls[0]![1];
expect(call.request.value).toMatchObject({ uin: 67890, groupUin: 0, friendUin: 67890 });
const body = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2];
expect(body).toMatchObject({ uin: 67890, groupUin: 0, friendUin: 67890 });
});
it('sendLike forwards target + count to 0x7e5_104', async () => {
const bridge = mockBridge();
await inter.sendLike(bridge as any, 10001, 3);
const call = vi.mocked(oidb.runOidb).mock.calls[0]![1];
expect(call.cmd).toBe('OidbSvcTrpcTcp.0x7e5_104');
expect(call.request.value).toMatchObject({ targetUin: 10001, count: 3 });
const [, cmd] = vi.mocked(oidb.runOidb).mock.calls[0]!;
expect(cmd).toBe('OidbSvcTrpcTcp.0x7e5_104');
const body = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2];
expect(body).toMatchObject({ targetUin: 10001, count: 3 });
});
it('setGroupReaction picks _1 for set and _2 for unset', async () => {
const bridge = mockBridge();
await inter.setGroupReaction(bridge as any, 12345, 99, '128516', true);
await inter.setGroupReaction(bridge as any, 12345, 99, '128516', false);
const cmds = vi.mocked(oidb.runOidb).mock.calls.map(c => c[1].cmd);
const cmds = vi.mocked(oidb.runOidb).mock.calls.map(c => c[1]);
expect(cmds).toEqual(['OidbSvcTrpcTcp.0x9082_1', 'OidbSvcTrpcTcp.0x9082_2']);
});
it('getEmojiLikes decodes user list, base64-encodes cookie, and reports isLast', async () => {
const bridge = mockBridge();
vi.mocked(oidb.runOidb).mockResolvedValueOnce({
inner: { userInfo: { uin: 10001 } },
cookie: new Uint8Array([0xCA, 0xFE]),
});
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
protobuf_encode<OidbBase<Oidb0x9083Resp>>({
body: {
inner: { userInfo: { uin: 10001n } },
cookie: new Uint8Array([0xCA, 0xFE]),
} as any,
}),
);
const out = await inter.getEmojiLikes(bridge as any, 12345, 99, '128516');
expect(out.users).toEqual([{ uin: 10001 }]);
expect(out.cookie).toBe(Buffer.from([0xCA, 0xFE]).toString('base64'));
@@ -58,7 +81,9 @@ describe('actions/interaction', () => {
it('getEmojiLikes reports isLast=true when no cookie comes back', async () => {
const bridge = mockBridge();
vi.mocked(oidb.runOidb).mockResolvedValueOnce({});
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
protobuf_encode<OidbBase<Oidb0x9083Resp>>({ body: {} }),
);
const out = await inter.getEmojiLikes(bridge as any, 12345, 99, '128516');
expect(out.users).toEqual([]);
expect(out.isLast).toBe(true);
+38 -13
View File
@@ -1,8 +1,26 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '../../src/bridge/proto/proton/oidb';
import type {
Oidb0x990Resp,
Oidb0x112eResp,
} from '../../src/bridge/proto/proton/oidb-action';
vi.mock('../../src/bridge/bridge-oidb', () => ({
runOidb: vi.fn(async () => ({})),
}));
// `encodeOidbEnv` / `decodeOidbEnv` are proton-bound pass-through wrappers
// — the plugin substitutes them at the call site with the inlined codec,
// so mocking them on the module object is a no-op. We mock `runOidb`
// (non-generic, untouched by proton) to return real proton-encoded bytes
// that the production-side codec then actually decodes.
vi.mock('../../src/bridge/bridge-oidb', async () => {
const actual = await vi.importActual<typeof import('../../src/bridge/bridge-oidb')>(
'../../src/bridge/bridge-oidb',
);
return {
...actual,
runOidb: vi.fn(async () => new Uint8Array()),
makeOidbEnvelope: vi.fn((_oidbCmd, _subCmd, body) => ({ body })),
};
});
import * as oidb from '../../src/bridge/bridge-oidb';
import * as misc from '../../src/bridge/actions/misc';
@@ -11,21 +29,26 @@ import { mockBridge } from './_helpers';
describe('actions/misc', () => {
beforeEach(() => {
vi.mocked(oidb.runOidb).mockReset();
vi.mocked(oidb.runOidb).mockResolvedValue({});
vi.mocked(oidb.runOidb).mockResolvedValue(new Uint8Array());
vi.mocked(oidb.makeOidbEnvelope).mockClear();
});
it('translateEn2Zh returns dstWords when present', async () => {
const bridge = mockBridge();
vi.mocked(oidb.runOidb).mockResolvedValueOnce({
translateResp: { dstWords: ['你好', '世界'] },
});
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
protobuf_encode<OidbBase<Oidb0x990Resp>>({
body: { translateResp: { dstWords: ['你好', '世界'] } } as any,
}),
);
const out = await misc.translateEn2Zh(bridge as any, ['hello', 'world']);
expect(out).toEqual(['你好', '世界']);
});
it('translateEn2Zh throws on empty response', async () => {
const bridge = mockBridge();
vi.mocked(oidb.runOidb).mockResolvedValueOnce({});
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
protobuf_encode<OidbBase<Oidb0x990Resp>>({ body: {} }),
);
await expect(misc.translateEn2Zh(bridge as any, ['hello']))
.rejects.toThrow(/empty/);
});
@@ -60,9 +83,11 @@ describe('actions/misc', () => {
it('clickInlineKeyboardButton returns shaped result', async () => {
const bridge = mockBridge();
vi.mocked(oidb.runOidb).mockResolvedValueOnce({
result: 1, errMsg: 'ok', promptText: 'hi',
});
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
protobuf_encode<OidbBase<Oidb0x112eResp>>({
body: { result: 1, errMsg: 'ok', promptText: 'hi' } as any,
}),
);
const out = await misc.clickInlineKeyboardButton(bridge as any, 1, 2, 'btn', 'data', 100);
expect(out).toMatchObject({ result: 1, errMsg: 'ok', promptText: 'hi', status: 0 });
});
@@ -70,7 +95,7 @@ describe('actions/misc', () => {
it('sendGroupSign dispatches to 0xEB7_1', async () => {
const bridge = mockBridge();
await misc.sendGroupSign(bridge as any, 12345);
const call = vi.mocked(oidb.runOidb).mock.calls[0]![1];
expect(call.cmd).toBe('OidbSvcTrpcTcp.0xEB7_1');
const [, cmd] = vi.mocked(oidb.runOidb).mock.calls[0]!;
expect(cmd).toBe('OidbSvcTrpcTcp.0xEB7_1');
});
});
+49 -22
View File
@@ -1,8 +1,26 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '../../src/bridge/proto/proton/oidb';
import type {
Oidb0x7edResp,
Oidb0xe17Resp,
} from '../../src/bridge/proto/proton/oidb-action';
vi.mock('../../src/bridge/bridge-oidb', () => ({
runOidb: vi.fn(async () => ({})),
}));
// `encodeOidbEnv` / `decodeOidbEnv` are proton-bound pass-through wrappers
// (substituted at the call site with the inlined codec). Mocking them on
// the module object is a no-op — proton has already inlined the call.
// We mock `runOidb` (non-generic) to return real proton-encoded bytes
// that the production-side codec actually decodes.
vi.mock('../../src/bridge/bridge-oidb', async () => {
const actual = await vi.importActual<typeof import('../../src/bridge/bridge-oidb')>(
'../../src/bridge/bridge-oidb',
);
return {
...actual,
runOidb: vi.fn(async () => new Uint8Array()),
makeOidbEnvelope: vi.fn((_oidbCmd, _subCmd, body) => ({ body })),
};
});
vi.mock('../../src/bridge/highway/highway-client', () => ({
fetchHighwaySession: vi.fn(async () => ({})),
@@ -23,7 +41,8 @@ import { mockBridge } from './_helpers';
describe('actions/profile', () => {
beforeEach(() => {
vi.mocked(oidb.runOidb).mockReset();
vi.mocked(oidb.runOidb).mockResolvedValue({});
vi.mocked(oidb.runOidb).mockResolvedValue(new Uint8Array());
vi.mocked(oidb.makeOidbEnvelope).mockClear();
vi.mocked(highwayClient.fetchHighwaySession).mockClear();
vi.mocked(highwayClient.uploadHighwayHttp).mockClear();
});
@@ -93,23 +112,23 @@ describe('actions/profile', () => {
const bridge = mockBridge();
await profile.setProfile(bridge as any, 'New Nick');
expect(oidb.runOidb).toHaveBeenCalledOnce();
const call = vi.mocked(oidb.runOidb).mock.calls[0]![1];
expect((call.request.value as any).stringProfiles).toEqual([{ fieldId: 20002, value: 'New Nick' }]);
const body = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2];
expect((body as any).stringProfiles).toEqual([{ fieldId: 20002, value: 'New Nick' }]);
});
it('setSelfLongNick wraps the long nick in profile tag 102', async () => {
const bridge = mockBridge();
await profile.setSelfLongNick(bridge as any, 'hello world');
const call = vi.mocked(oidb.runOidb).mock.calls[0]![1];
expect((call.request.value as any).profile).toEqual({ tag: 102, value: 'hello world' });
const body = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2];
expect((body as any).profile).toEqual({ tag: 102, value: 'hello world' });
});
it('setInputStatus resolves UID first and sends 0xcd4_1', async () => {
const bridge = mockBridge();
await profile.setInputStatus(bridge as any, 10001, 1);
expect(bridge.resolveUserUid).toHaveBeenCalledWith(10001);
const call = vi.mocked(oidb.runOidb).mock.calls[0]![1];
expect(call.cmd).toBe('OidbSvcTrpcTcp.0xcd4_1');
const [, cmd] = vi.mocked(oidb.runOidb).mock.calls[0]!;
expect(cmd).toBe('OidbSvcTrpcTcp.0xcd4_1');
});
it('setAvatar loads bytes and pushes through the highway upload path (cmd 90)', async () => {
@@ -155,14 +174,18 @@ describe('actions/profile', () => {
it('getProfileLike (self): resolves self UID, returns formatted favorite + vote info', async () => {
const bridge = mockBridge();
vi.mocked(oidb.runOidb).mockResolvedValueOnce({
userLikeInfos: [{
uid: 'u',
time: 1700000000n,
favoriteInfo: { totalCount: 5, lastTime: 1n, newCount: 1 },
voteInfo: { totalCount: 7, newCount: 2, lastTime: 2n },
}],
});
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
protobuf_encode<OidbBase<Oidb0x7edResp>>({
body: {
userLikeInfos: [{
uid: 'u',
time: 1700000000n,
favoriteInfo: { totalCount: 5, lastTime: 1n, newCount: 1 },
voteInfo: { totalCount: 7, newCount: 2, lastTime: 2n },
}],
} as any,
}),
);
const out = await profile.getProfileLike(bridge as any);
expect(out.favoriteInfo.total_count).toBe(5);
expect(out.voteInfo.total_count).toBe(7);
@@ -170,15 +193,19 @@ describe('actions/profile', () => {
it('getProfileLike throws on empty result', async () => {
const bridge = mockBridge();
vi.mocked(oidb.runOidb).mockResolvedValueOnce({ userLikeInfos: [] });
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
protobuf_encode<OidbBase<Oidb0x7edResp>>({ body: { userLikeInfos: [] } as any }),
);
await expect(profile.getProfileLike(bridge as any)).rejects.toThrow(/empty/);
});
it('getUnidirectionalFriendList parses the embedded JSON body', async () => {
const bridge = mockBridge();
vi.mocked(oidb.runOidb).mockResolvedValueOnce({
jsonBody: JSON.stringify({ rpt_block_list: [{ uin: 10001 }, { uin: 10002 }] }),
});
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
protobuf_encode<OidbBase<Oidb0xe17Resp>>({
body: { jsonBody: JSON.stringify({ rpt_block_list: [{ uin: 10001 }, { uin: 10002 }] }) } as any,
}),
);
const out = await profile.getUnidirectionalFriendList(bridge as any);
expect(out).toEqual([{ uin: 10001 }, { uin: 10002 }]);
});
@@ -2,6 +2,7 @@ import { describe, expect, it, vi } from 'vitest';
import type { SendPacketResult } from '../src/protocol/packet-sender';
import { protoDecode, protoEncode } from '../src/protobuf/decode';
import { SendMessageRequestSchema, SendMessageResponseSchema } from '../src/bridge/proto/action';
import { FileExtraSchema } from '../src/bridge/proto/message';
vi.mock('../src/bridge/element-builder', () => ({
buildSendElems: vi.fn(async () => [{ text: { str: 'stub media elem' } }]),
@@ -47,4 +48,81 @@ describe('Bridge private media routing', () => {
uid: 'u_peer_12345',
});
});
it('sendC2cFileMessage uses trans0x211 routing + msgContent FileExtra (NOT richText.notOnlineFile)', async () => {
// Regression: c2c file messages route through `trans0x211 { ccCmd:
// 4, uid }` (RoutingHead field 15), not `c2c { uin, uid }`. The
// file metadata lives in `MessageBody.msgContent` (a serialised
// `FileExtra { file: NotOnlineFile }`), not in `richText.notOnlineFile`.
// Confirmed against `dev/Lagrange.Core/.../MessagePacker.cs:
// BuildPacketBase` + `FileEntity.PackMessageContent`. Previous
// implementation wrote c2c routing + richText.notOnlineFile +
// c2cCmd=11 — the QQ-NT server rejected every c2c file send.
const { Bridge } = await import('../src/bridge/bridge');
const { IdentityService } = await import('../src/bridge/identity-service');
class TestBridge extends Bridge {
capturedBody: Uint8Array | null = null;
override async sendRawPacket(_cmd: string, body: Uint8Array): Promise<SendPacketResult> {
this.capturedBody = body;
return {
success: true, gotResponse: true, errorCode: 0, errorMessage: '',
responseData: Buffer.from(protoEncode({
result: 0, privateSequence: 88, timestamp1: 1710000000,
}, SendMessageResponseSchema)),
};
}
}
const bridge = new TestBridge(IdentityService.memory('10000'));
const fileMd5 = new Uint8Array([0xde, 0xad, 0xbe, 0xef]);
await bridge.sendC2cFileMessage(67890, 'u_peer_xyz', {
fileId: 'uuid-abc-123',
fileName: 'doc.txt',
fileSize: 1024,
fileMd5,
fileHash: 'hash-xyz',
});
const request = protoDecode(bridge.capturedBody as Uint8Array, SendMessageRequestSchema);
// Routing: must be trans0x211 with ccCmd=4 + uid, no c2c slot.
expect(request?.routingHead?.trans0x211).toMatchObject({
ccCmd: 4,
uid: 'u_peer_xyz',
});
expect(request?.routingHead?.c2c).toBeUndefined();
// Body: msgContent carries the FileExtra; richText is absent (no
// elems, no notOnlineFile slot — both lived on the wrong place).
expect(request?.messageBody?.msgContent).toBeInstanceOf(Uint8Array);
expect(request?.messageBody?.richText).toBeUndefined();
// Decode the msgContent and verify the NotOnlineFile fields land
// at the correct tags (Lagrange's NotOnlineFile schema, not the
// dead FileExtraInfo one).
const fileExtra = protoDecode(
request!.messageBody!.msgContent as Uint8Array,
FileExtraSchema,
);
expect(fileExtra?.file).toMatchObject({
fileUuid: 'uuid-abc-123',
fileName: 'doc.txt',
fileSize: 1024n,
fileHash: 'hash-xyz',
subcmd: 1, // server-required intake validator field
// dangerEvel and fileType are 0 — proto3 omits zero values on
// the wire, so they're not asserted here (matches Lagrange's
// behaviour: it sets `DangerEvel = 0` but protobuf-net also
// skips serialising default ints).
});
expect(fileExtra?.file?.fileMd5).toEqual(fileMd5);
// expireTime is now+7d; just sanity-check it landed (non-zero, plausible)
expect(fileExtra?.file?.expireTime).toBeGreaterThan(Math.floor(Date.now() / 1000));
// c2cCmd is left at 0 / undefined — the old `c2cCmd=11` was a
// stale go-cqhttp value the QQ-NT server doesn't recognise on the
// c2c-file path.
expect(request?.contentHead?.c2cCmd ?? 0).toBe(0);
});
});
@@ -92,3 +92,29 @@ describe('element-builder / commonElem.businessType per scene', () => {
});
});
});
describe('element-builder / file element is no longer carried in elems[]', () => {
// Regression for the `result=79` class: previously the element-builder
// emitted a `transElem(elemType=24, ...)` for `{type:'file'}` segments
// and the QQ-NT server rejected the outgoing PbSendMsg with that wire
// shape. The fix moves group-file publishing onto a dedicated OIDB
// call (`OidbSvcTrpcTcp.0x6d9_4`), driven from the OneBot layer in
// `modules/message-actions.ts::sendGroupMessage` after the file
// segment is split off. The element-builder therefore must NOT emit
// any element for `{type:'file'}` anymore — if it does, the message
// ships with a transElem(24) payload and result=79 returns.
it('produces an empty elems[] for a {type:"file"} segment (must be split out at OneBot layer)', async () => {
const result = await buildSendElems(
[{
type: 'file',
fileId: 'fid-abc',
fileName: 'doc.txt',
fileSize: 123,
md5Hex: 'aabbccddeeff00112233445566778899',
sha1Hex: '0102030405060708090a0b0c0d0e0f1011121314',
} as any],
{ bridge: fakeBridge, groupId: 12345 },
);
expect(result).toEqual([]);
});
});
@@ -343,6 +343,8 @@ describe('convertEvent — message elements (13 segment types)', () => {
expect(seg.type).toBe('image');
expect((seg.data as Record<string, unknown>).url).toBe('http://resolved');
expect((seg.data as Record<string, unknown>).file).toBe('fid');
expect((seg.data as Record<string, unknown>).sub_type).toBe(0);
expect((seg.data as Record<string, unknown>).summary).toBe('');
});
it('image without resolver uses element.imageUrl', async () => {
@@ -350,6 +352,25 @@ describe('convertEvent — message elements (13 segment types)', () => {
expect((seg.data as Record<string, unknown>).url).toBe('http://x');
});
it('image: forwards optional sub_type and summary for custom emoji/stickers', async () => {
const seg = await segment({
type: 'image',
fileId: 'fid',
imageUrl: 'http://x',
subType: 1,
summary: '[动画表情]',
});
expect(seg).toEqual({
type: 'image',
data: {
url: 'http://x',
file: 'fid',
sub_type: 1,
summary: '[动画表情]',
},
});
});
it('at: targetUin -> qq string', async () => {
const seg = await segment({ type: 'at', targetUin: PEER_UIN });
expect(seg).toEqual({ type: 'at', data: { qq: String(PEER_UIN) } });
@@ -90,6 +90,21 @@ describe('video-upload', () => {
expect((uploadInfo[1] as any).fileInfo.type.type).toBe(1); // pic (thumb)
});
it('main video carries the real `time` (duration in seconds) — regression: was 0', async () => {
// NTV2 server bakes the `time` field into the resulting MsgInfo
// bytes that ride along as `commonElem.pbElem`; the receiver
// reads it back via `VideoFile.fileTime` and renders it as the
// playable duration. NapCat ships `time: 0` only because it sits
// on top of QQ-NT's IPC layer which patches the value in before
// the wire send; we're a protocol-direct client (same position
// as acidify) and must populate it ourselves. Without this the
// receiver shows "00:00" on every video the bot sends.
await uploadVideoMsgInfo({} as any, true, 12345, FINGERPRINT);
const uploadInfo = vi.mocked(pipeline.runNtv2Upload).mock.calls[0]![0].uploadInfo;
expect((uploadInfo[0] as any).fileInfo.time).toBe(10); // matches FINGERPRINT.duration
expect((uploadInfo[1] as any).fileInfo.time).toBe(0); // thumb stays at 0 (matches acidify)
});
it('thumb falls back to a synthesized 1x1 PNG with real bytes', async () => {
await uploadVideoMsgInfo({} as any, true, 12345, FINGERPRINT);
const uploads = vi.mocked(pipeline.runNtv2Upload).mock.calls[0]![0].uploads;
@@ -0,0 +1,149 @@
// Tests for HTTP server adapter content-type parsing (POST body).
// Covers: application/x-www-form-urlencoded, application/json,
// no content-type fallback, and unsupported content-type rejection.
import { describe, expect, it, vi, beforeAll, afterAll } from 'vitest';
import http from 'http';
import { HttpServerAdapter } from '../src/onebot/network/http-server-adapter';
import type { NetworkAdapterContext } from '../src/onebot/network/adapter';
import type { HttpServerNetwork } from '../src/onebot/types';
// ─── Helpers ───
function fakeCtx(handleFn: (action: string, params: Record<string, unknown>) => unknown): NetworkAdapterContext {
return {
uin: '10001',
api: {
handle: vi.fn(async (action: string, params: Record<string, unknown>) => {
const data = handleFn(action, params);
return { status: 'ok', retcode: 0, data };
}),
} as any,
buildLifecycleEvent: vi.fn(() => ({})),
buildHeartbeatEvent: vi.fn(() => ({})),
};
}
function post(port: number, path: string, body: string, headers: Record<string, string> = {}): Promise<{ status: number; body: any }> {
return new Promise((resolve, reject) => {
const req = http.request({ hostname: '127.0.0.1', port, path, method: 'POST', headers }, (res) => {
const chunks: Buffer[] = [];
res.on('data', (c) => chunks.push(c));
res.on('end', () => {
const raw = Buffer.concat(chunks).toString('utf8');
try {
resolve({ status: res.statusCode!, body: JSON.parse(raw) });
} catch {
resolve({ status: res.statusCode!, body: raw });
}
});
});
req.on('error', reject);
req.end(body);
});
}
// ─── Tests ───
describe('HttpServerAdapter content-type parsing', () => {
let adapter: HttpServerAdapter;
let handleFn: ReturnType<typeof vi.fn<(action: string, params: Record<string, unknown>) => unknown>>;
const PORT = 19876;
beforeAll(async () => {
handleFn = vi.fn((_action: string, params: Record<string, unknown>) => params);
const ctx = fakeCtx(handleFn);
const config: HttpServerNetwork = { name: 'test-http', port: PORT, enabled: true, messageFormat: 'array', reportSelfMessage: false };
adapter = new HttpServerAdapter('test-http', config, ctx);
adapter.open();
// Wait for server to be listening
await new Promise((resolve) => setTimeout(resolve, 100));
});
afterAll(() => {
adapter.close();
});
it('should parse application/json body', async () => {
const res = await post(PORT, '/send_message', JSON.stringify({ params: { group_id: 123, message: 'hi' } }), {
'content-type': 'application/json',
});
expect(res.status).toBe(200);
expect(res.body.status).toBe('ok');
expect(handleFn).toHaveBeenCalledWith('send_message', { group_id: 123, message: 'hi' });
});
it('should parse application/x-www-form-urlencoded body', async () => {
handleFn.mockClear();
const body = 'group_id=456&message=hello';
const res = await post(PORT, '/send_message', body, {
'content-type': 'application/x-www-form-urlencoded',
});
expect(res.status).toBe(200);
expect(res.body.status).toBe('ok');
expect(handleFn).toHaveBeenCalledWith('send_message', { group_id: 456, message: 'hello' });
});
it('should JSON-parse values in urlencoded body', async () => {
handleFn.mockClear();
const body = 'user_id=789&data={"nested":true}';
const res = await post(PORT, '/get_info', body, {
'content-type': 'application/x-www-form-urlencoded',
});
expect(res.status).toBe(200);
expect(handleFn).toHaveBeenCalledWith('get_info', { user_id: 789, data: { nested: true } });
});
it('should extract action from urlencoded body when path has no action', async () => {
handleFn.mockClear();
const body = 'action=get_status&key=value';
const res = await post(PORT, '/', body, {
'content-type': 'application/x-www-form-urlencoded',
});
expect(res.status).toBe(200);
expect(handleFn).toHaveBeenCalledWith('get_status', { key: 'value' });
});
it('should extract echo from urlencoded body', async () => {
handleFn.mockClear();
const body = 'action=test_action&echo=12345&foo=bar';
const res = await post(PORT, '/', body, {
'content-type': 'application/x-www-form-urlencoded',
});
expect(res.status).toBe(200);
expect(res.body.echo).toBe(12345);
expect(handleFn).toHaveBeenCalledWith('test_action', { foo: 'bar' });
});
it('should reject unsupported content-type with 400', async () => {
const res = await post(PORT, '/send_message', '<xml></xml>', {
'content-type': 'application/xml',
});
expect(res.status).toBe(400);
expect(res.body.wording).toContain('unsupported content-type');
});
it('should reject invalid JSON with explicit application/json content-type', async () => {
const res = await post(PORT, '/send_message', 'not-json{{{', {
'content-type': 'application/json',
});
expect(res.status).toBe(400);
expect(res.body.wording).toContain('invalid json');
});
it('should fallback to urlencoded when no content-type and body is not valid JSON', async () => {
handleFn.mockClear();
const body = 'action=fallback_action&param1=value1';
const res = await post(PORT, '/', body, {});
expect(res.status).toBe(200);
expect(handleFn).toHaveBeenCalledWith('fallback_action', { param1: 'value1' });
});
it('should parse JSON when no content-type and body is valid JSON', async () => {
handleFn.mockClear();
const body = JSON.stringify({ action: 'json_action', params: { x: 1 } });
const res = await post(PORT, '/', body, {});
expect(res.status).toBe(200);
expect(handleFn).toHaveBeenCalledWith('json_action', { x: 1 });
});
});
@@ -0,0 +1,141 @@
// Hot-reload tests for HttpServerAdapter — pins the contract that
// `reload({ accessToken: <new> })` must take effect on the very next
// request without the listener being torn down. Earlier the adapter
// captured `accessToken` into a `startServer()` closure and relied on
// `bindingSignature` to trigger a `close()` + `open()` round-trip on
// token change; that race-prone path is gone and `handleRequest` now
// reads `this.config.accessToken` per request.
import { describe, expect, it, vi, afterEach } from 'vitest';
import http from 'http';
import type { AddressInfo } from 'net';
import { HttpServerAdapter } from '../src/onebot/network/http-server-adapter';
import { NetworkReloadType, type NetworkAdapterContext } from '../src/onebot/network/adapter';
import type { HttpServerNetwork } from '../src/onebot/types';
function fakeCtx(): NetworkAdapterContext {
return {
uin: '10001',
api: {
handle: vi.fn(async () => ({ status: 'ok', retcode: 0, data: { online: true } })),
} as any,
buildLifecycleEvent: vi.fn(() => ({})),
buildHeartbeatEvent: vi.fn(() => ({})),
};
}
function get(port: number, path: string, headers: Record<string, string> = {}): Promise<{ status: number }> {
return new Promise((resolve, reject) => {
const req = http.request(
{ hostname: '127.0.0.1', port, path, method: 'GET', headers },
(res) => {
res.on('data', () => { /* drain */ });
res.on('end', () => resolve({ status: res.statusCode! }));
},
);
req.on('error', reject);
req.end();
});
}
// Wait until the underlying http.Server has bound its port; tests that
// hit the socket too early get ECONNREFUSED on slow CI hosts.
async function waitForListen(adapter: HttpServerAdapter): Promise<number> {
for (let i = 0; i < 50; i++) {
const server = (adapter as any).server as http.Server | null;
const addr = server?.address() as AddressInfo | null | undefined;
if (addr && typeof addr === 'object') return addr.port;
await new Promise((r) => setTimeout(r, 20));
}
throw new Error('http server never started listening');
}
describe('HttpServerAdapter — accessToken hot reload', () => {
let adapter: HttpServerAdapter | null = null;
afterEach(() => {
adapter?.close();
adapter = null;
});
it('a swapped accessToken authorizes the new token on the next request — no listener re-bind', async () => {
const ctx = fakeCtx();
// port=0 → OS-assigned; the swap proves no re-bind happens because
// a re-bind would land on a different port and `waitForListen`
// would diverge from the original.
const config: HttpServerNetwork = {
name: 'hot', port: 0, enabled: true, accessToken: 'tok-1',
messageFormat: 'array', reportSelfMessage: false,
};
adapter = new HttpServerAdapter('hot', config, ctx);
adapter.open();
const portBefore = await waitForListen(adapter);
// Sanity: old token authorizes, anything else 401s.
expect((await get(portBefore, '/', { authorization: 'Bearer tok-1' })).status).toBe(200);
expect((await get(portBefore, '/', { authorization: 'Bearer tok-2' })).status).toBe(401);
// Hot-swap the token.
await adapter.reload({ ...config, accessToken: 'tok-2' });
// Same port (no re-bind) — and the new token must take effect on
// the very next request.
const portAfter = ((adapter as any).server as http.Server).address() as AddressInfo;
expect(portAfter.port).toBe(portBefore);
expect((await get(portBefore, '/', { authorization: 'Bearer tok-1' })).status).toBe(401);
expect((await get(portBefore, '/', { authorization: 'Bearer tok-2' })).status).toBe(200);
});
it('clearing accessToken to empty disables auth on the next request', async () => {
const ctx = fakeCtx();
const config: HttpServerNetwork = {
name: 'hot-clear', port: 0, enabled: true, accessToken: 'tok-1',
messageFormat: 'array', reportSelfMessage: false,
};
adapter = new HttpServerAdapter('hot-clear', config, ctx);
adapter.open();
const port = await waitForListen(adapter);
expect((await get(port, '/')).status).toBe(401); // no token header → 401
await adapter.reload({ ...config, accessToken: '' });
expect((await get(port, '/')).status).toBe(200); // auth disabled
});
it('setting accessToken from empty enforces auth on the next request', async () => {
const ctx = fakeCtx();
const config: HttpServerNetwork = {
name: 'hot-add', port: 0, enabled: true,
messageFormat: 'array', reportSelfMessage: false,
};
adapter = new HttpServerAdapter('hot-add', config, ctx);
adapter.open();
const port = await waitForListen(adapter);
expect((await get(port, '/')).status).toBe(200); // no auth configured
await adapter.reload({ ...config, accessToken: 'tok-new' });
expect((await get(port, '/')).status).toBe(401); // auth now required
expect((await get(port, '/', { authorization: 'Bearer tok-new' })).status).toBe(200);
});
it('changing only accessToken returns NetworkReloadType.Normal — no Reopened/Closed', async () => {
const ctx = fakeCtx();
const config: HttpServerNetwork = {
name: 'hot-type', port: 0, enabled: true, accessToken: 'a',
messageFormat: 'array', reportSelfMessage: false,
};
adapter = new HttpServerAdapter('hot-type', config, ctx);
adapter.open();
await waitForListen(adapter);
const reloadType = await adapter.reload({ ...config, accessToken: 'b' });
// Without re-binding, the adapter reports `Normal` — anything but
// `Reopened` / `Closed` is acceptable; we mostly care that nothing
// touched the listener.
expect(reloadType).toBe(NetworkReloadType.Normal);
});
});
@@ -437,4 +437,48 @@ describe('parseMessage', () => {
expect(result).toEqual([]);
});
});
describe('file segment', () => {
// Closes the parser-side of the "upload says ok but message is
// empty" bug. Before this, `{type:'file', file_id:'…'}` segments
// fell through to the default warn-and-drop branch — which made
// `send_msg([{type:'file', file_id:'<uploaded>'}])` produce either
// a "message is empty" error or, when mixed with text, a message
// with the file segment quietly missing.
it('parses {type:"file", file_id:"x"} into a file MessageElement', async () => {
const result = await parseMessage(
[{ type: 'file', data: { file_id: 'fid-1', name: 'a.zip', size: 123 } } as any],
false,
);
expect(result).toEqual([
{ type: 'file', fileId: 'fid-1', fileName: 'a.zip', fileSize: 123 },
]);
});
it('drops a file segment with no file_id (upload-first contract)', async () => {
// Path-only segments aren't supported here — callers must
// upload via `upload_group_file` / `upload_private_file` first
// to obtain a file_id. Dropping with a warning is preferable
// to silently kicking off an upload from inside the message
// parser, which can't fail loudly without changing call sites.
const result = await parseMessage(
[{ type: 'file', data: { file: '/local/path/a.bin' } } as any],
false,
);
expect(result).toEqual([]);
});
it('accepts fileId / filename / fileName / md5 / sha1 aliases', async () => {
const result = await parseMessage(
[{
type: 'file',
data: { fileId: 'fid-2', filename: 'b.zip', fileSize: 456, md5: 'AB', sha1: 'CD' },
} as any],
false,
);
expect(result).toEqual([
{ type: 'file', fileId: 'fid-2', fileName: 'b.zip', fileSize: 456, md5Hex: 'AB', sha1Hex: 'CD' },
]);
});
});
});
+252 -1
View File
@@ -1,12 +1,33 @@
import { describe, expect, it } from 'vitest';
import { protobuf_encode } from '@snowluma/proton';
import { parseMsgPush, MSG_PUSH_CMD } from '../src/bridge/msg-push';
import { IdentityService } from '../src/bridge/identity-service';
import type { GroupMemberInfo, QQGroupInfo } from '../src/bridge/qq-info';
import { PushMsgSchema } from '../src/bridge/proto/message';
import { GroupChangeSchema, OperatorInfoSchema } from '../src/bridge/proto/notify';
import type { GroupMemberJoin } from '../src/bridge/events';
// Proton's call-site analyzer keys off the literal type identifier
// printed in `protobuf_encode<X>` — it walks imports by *original*
// name (not alias). If both `import { X } from 'proto/notify'` and
// `import { X as Y } from 'events'` appear, the analyzer's import
// resolver picks up the second one and the proton-side definition
// loses, so call sites referencing `X` go un-replaced. Side-step by
// re-aliasing the event-side type's *source* (not just the local
// name) — we don't need to import it directly since assertions can
// inline-extract the kind.
import type {
NewFriend, FriendRecall, SelfJoinInGroup,
} from '../src/bridge/proto/proton/notify';
import type {
GroupMemberJoin, FriendAddEvent, QQEventVariant,
} from '../src/bridge/events';
// Local alias for the event-side recall type — derived via Extract so
// we avoid an `import { FriendRecall as X }` that collides with the
// proton import above.
type FriendRecallEvent = Extract<QQEventVariant, { kind: 'friend_recall' }>;
import type { PacketInfo } from '../src/protocol/types';
import { protoEncode } from '../src/protobuf/decode';
import { subscribeLogs } from '../src/utils/logger';
const SELF_UIN = '10001';
const GROUP_ID = 123456789;
@@ -98,3 +119,233 @@ describe('parseMsgPush group member increase', () => {
expect(event.operatorUid).toBe(operator.uid);
});
});
describe('parseMsgPush Event0x210 subType=38 (acknowledged-but-silent)', () => {
// Tracked back to the stock-QQ-android decompiled decoder
// `com.tencent.imcore.message.ext.codec.decoder.msgType0x210.SubType0x26`
// — it's the QQ-client-internal "troop shortcut bar" / discussion
// app state push (badge counts + in-app tips), not a chat event.
// We acknowledge it via `Event0x210SubType.GroupAppStatePush` and
// drop silently — no OneBot-level event, and — critically —
// **no** "unknown subType=38" fallback log spam anymore.
function makeEvent0x210Packet(subType: number, content = new Uint8Array(0)): PacketInfo {
const body = protoEncode({
message: {
responseHead: { fromUin: 22222, type: 0, sigMap: 0 },
// 528 = Event0x210
contentHead: { msgType: 528, subType, timestamp: 1710000000 },
body: { msgContent: content },
},
status: 0,
} as any, PushMsgSchema);
return {
pid: 1, uin: SELF_UIN, serviceCmd: MSG_PUSH_CMD, seqId: 1,
retCode: 0, fromClient: false, body,
};
}
it('returns [] for subType 38 without falling through to the MsgPush.Unknown log', () => {
const captured: string[] = [];
const unsubscribe = subscribeLogs((entry) => {
// Only care about the spam that the prior implementation produced
// ("MsgPush.Unknown" with subType=38). Other modules log freely
// during identity setup etc., we ignore them.
if (entry.scope === 'MsgPush.Unknown' && /subType=38/.test(entry.message)) {
captured.push(entry.message);
}
});
try {
const events = parseMsgPush(makeEvent0x210Packet(38), makeIdentity());
expect(events).toEqual([]);
expect(captured).toEqual([]); // no "unknown subType=38" debug log
} finally {
unsubscribe();
}
});
it('still flags genuinely-unknown subTypes via MsgPush.Unknown (regression guard)', () => {
// Counterpart to the silent-on-38 case: anything we *haven't*
// claimed in the enum should still hit the fallback so it's
// visible to whoever's tailing debug logs.
const captured: string[] = [];
const unsubscribe = subscribeLogs((entry) => {
if (entry.scope === 'MsgPush.Unknown' && /subType=999/.test(entry.message)) {
captured.push(entry.message);
}
});
try {
parseMsgPush(makeEvent0x210Packet(999), makeIdentity());
expect(captured.length).toBeGreaterThan(0);
} finally {
unsubscribe();
}
});
});
// ── P1 coverage extension: subTypes confirmed by LagrangeGo / acidify
// that we were previously dropping into the "unknown" fallback. ──
function makeEvent0x210PacketAny(subType: number, content: Uint8Array): PacketInfo {
const body = protoEncode({
message: {
responseHead: { fromUin: 22222, type: 0, sigMap: 0 },
contentHead: { msgType: 528, subType, timestamp: 1710000000 },
body: { msgContent: content },
},
status: 0,
} as any, PushMsgSchema);
return {
pid: 1, uin: SELF_UIN, serviceCmd: MSG_PUSH_CMD, seqId: 1,
retCode: 0, fromClient: false, body,
};
}
describe('parseMsgPush Event0x210 subType=179/226 (NewFriend → friend_add)', () => {
// 179 fires when bot sent a request and other side accepted; 226
// when bot accepted other side's request. Both share the
// `NewFriend` wire shape (LagrangeGo registers both via
// case-fallthrough in `client/listener.go:248`). We surface them
// identically as `kind: 'friend_add'`.
function makeNewFriendPacket(subType: 179 | 226, friendUid: string, time = 1710000000): PacketInfo {
const content = protobuf_encode<NewFriend>({
field1: 0,
info: { uid: friendUid, time, message: 'hello', nickName: 'Alice' },
});
return makeEvent0x210PacketAny(subType, content);
}
it('emits friend_add for subType 179', () => {
const member = makeGroupMember(99999, 'u_new_friend');
const [event] = parseMsgPush(
makeNewFriendPacket(179, member.uid),
makeIdentity([member]),
) as FriendAddEvent[];
expect(event.kind).toBe('friend_add');
expect(event.userUin).toBe(99999);
expect(event.time).toBe(1710000000);
});
it('emits friend_add for subType 226 (same wire shape, different surface)', () => {
const member = makeGroupMember(88888, 'u_other_friend');
const [event] = parseMsgPush(
makeNewFriendPacket(226, member.uid),
makeIdentity([member]),
) as FriendAddEvent[];
expect(event.kind).toBe('friend_add');
expect(event.userUin).toBe(88888);
});
it('falls back to the packet routingHead.fromUin when the uid is not in the local cache', () => {
// No member registered for `u_unknown_uid`, but the packet itself
// carries the new friend's uin on `fromUin` (22222 in
// makeEvent0x210PacketAny). That's the wire-level convention
// (LagrangeGo emits unconditionally then calls `ResolveUin` post
// hoc, see `client/listener.go:259`). Without the fallback the
// event would either drop or surface `user_id: 0`, both of which
// confuse OneBot consumers.
const [event] = parseMsgPush(
makeNewFriendPacket(179, 'u_unknown_uid'),
makeIdentity(),
) as FriendAddEvent[];
expect(event.kind).toBe('friend_add');
expect(event.userUin).toBe(22222); // the packet's fromUin
});
});
describe('parseMsgPush Event0x210 subType=139 (self-recall direction)', () => {
// 138 = friend recalled their own message sent to bot
// (peer in friend_recall event = fromUid)
// 139 = bot recalled own message sent to friend
// (peer in friend_recall event = toUid)
// Same wire shape; the subType is the direction discriminator.
// Acidify makes the same split in `parseFriendRecall:380`. Without
// 139, self-recalls used to fall through and disappear.
function makeFriendRecallPacket(subType: 138 | 139, fromUid: string, toUid: string): PacketInfo {
const content = protobuf_encode<FriendRecall>({
info: {
fromUid, toUid, clientSequence: 4242, newId: 0n,
time: 1710000000, random: 0, pkgNum: 1, pkgIndex: 0, divSeq: 1,
},
});
return makeEvent0x210PacketAny(subType, content);
}
it('subType 138 keeps fromUid as the resolved peer (other recalled their own msg to us)', () => {
const friend = makeGroupMember(77777, 'u_friend');
const [event] = parseMsgPush(
makeFriendRecallPacket(138, friend.uid, 'u_self'),
makeIdentity([friend]),
) as FriendRecallEvent[];
expect(event.kind).toBe('friend_recall');
expect(event.userUin).toBe(77777);
expect(event.msgSeq).toBe(4242);
});
it('subType 139 picks toUid as the peer (we recalled our msg sent to friend)', () => {
const friend = makeGroupMember(77777, 'u_friend');
const [event] = parseMsgPush(
makeFriendRecallPacket(139, 'u_self', friend.uid),
makeIdentity([friend]),
) as FriendRecallEvent[];
expect(event.kind).toBe('friend_recall');
expect(event.userUin).toBe(77777); // resolved from toUid (the friend), not fromUid (us)
});
});
describe('parseMsgPush PkgType 85 (bot self-joined a group)', () => {
// PkgType 33 (GroupMemberIncreaseNotice) fires for *other* members
// joining; the bot's own join after `set_group_add_request` approval
// / invite-accept arrives at 85 instead. We surface it as
// `group_member_join` with `userUin = selfUin` so the OneBot
// converter naturally produces `notice.group_increase`.
function makeSelfJoinPacket(groupId: number, operatorUid = ''): PacketInfo {
const content = protobuf_encode<SelfJoinInGroup>({
groupUin: BigInt(groupId),
field2: 1,
operatorUid,
field4: 0,
field6: 48,
field7: '',
});
const body = protoEncode({
message: {
responseHead: { fromUin: groupId, type: 0, sigMap: 0 },
contentHead: { msgType: 85, subType: 0, timestamp: 1710000000 },
body: { msgContent: content },
},
status: 0,
} as any, PushMsgSchema);
return {
pid: 1, uin: SELF_UIN, serviceCmd: MSG_PUSH_CMD, seqId: 1,
retCode: 0, fromClient: false, body,
};
}
it('emits group_member_join with userUin == selfUin', () => {
const [event] = parseMsgPush(
makeSelfJoinPacket(GROUP_ID),
makeIdentity(),
) as GroupMemberJoin[];
expect(event.kind).toBe('group_member_join');
expect(event.groupId).toBe(GROUP_ID);
expect(event.userUin).toBe(Number(SELF_UIN));
});
it('resolves operator uid through identity when present', () => {
const admin = makeGroupMember(11111, 'u_admin');
const [event] = parseMsgPush(
makeSelfJoinPacket(GROUP_ID, admin.uid),
makeIdentity([admin]),
) as GroupMemberJoin[];
expect(event.operatorUin).toBe(admin.uin);
expect(event.operatorUid).toBe(admin.uid);
});
});
@@ -0,0 +1,220 @@
// Regression coverage for nested forward (forward-inside-forward).
//
// `parseForwardNodes` detects an all-`{type:'node'}` content array,
// recursively builds the inner `ForwardNodePayload[]`, and attaches it
// to the outer node as `innerForward`. `uploadForwardNodes` then drives
// the recursive long-msg upload + ARK-preview generation + msgBody
// piggyback in one pass over the tree — modelled on NapCat's
// `uploadForwardedNodesPacket` (`dev/NapCatQQ/.../SendMsg.ts:208`).
//
// These tests stub `bridge.uploadForwardNodes` so we can inspect the
// payload that the upload pipeline receives: outer nodes carry an
// `innerForward` field holding the parsed inner chain, and the
// upload helper is invoked exactly ONCE (the recursive walk happens
// inside the real implementation; mocks see only the top call).
import { describe, expect, it, vi } from 'vitest';
import type { BridgeInterface } from '../../src/bridge/bridge-interface';
import type { OneBotInstanceContext } from '../../src/onebot/instance-context';
import {
sendGroupForwardMessage,
sendPrivateForwardMessage,
} from '../../src/onebot/modules/message-actions';
function fakeBridge(overrides: Partial<BridgeInterface> = {}): BridgeInterface {
return new Proxy(overrides as BridgeInterface, {
get(target, prop) {
if (prop in target) return (target as any)[prop];
throw new Error(`fakeBridge: '${String(prop)}' was not stubbed for this test`);
},
});
}
function makeCtx(bridge: BridgeInterface): OneBotInstanceContext {
return {
uin: '10001',
bridge,
messageStore: { findEvent: () => null } as any,
cacheMessageMeta: vi.fn(),
mediaStore: {} as any,
musicSignUrl: '',
} as unknown as OneBotInstanceContext;
}
describe('forward — nested {type:"node"} content', () => {
it('group: nested forward attaches inner chain to outer node via `innerForward`', async () => {
// Single upload call, but the outer payload now carries an
// `innerForward` field with the recursively-parsed inner chain.
// The real `uploadForwardNodes` (the production module) walks
// that tree and does the recursive long-msg uploads with NapCat
// piggyback — we're just testing the parse-side handoff here.
const uploadForwardNodes = vi.fn(async (_nodes: any[], _groupId?: number, _userId?: number) => 'OUTER_RESID');
const sendGroupMessage = vi.fn(async () => ({
messageId: 1, sequence: 100, clientSequence: 0, random: 1, timestamp: 1700000000,
}));
const bridge = fakeBridge({ uploadForwardNodes, sendGroupMessage } as any);
const ctx = makeCtx(bridge);
const messages = [{
type: 'node',
data: {
user_id: 111, nickname: 'outer',
content: [{
type: 'node',
data: {
user_id: 222, nickname: 'inner',
content: [{ type: 'text', data: { text: 'hello from inner' } }],
},
}],
},
}];
const result = await sendGroupForwardMessage(ctx, 12345, messages as any);
// Exactly one upload call: the production-side recursive walker
// owns the inner upload, the OneBot parser just hands off the tree.
expect(uploadForwardNodes).toHaveBeenCalledOnce();
const [outerNodes, outerGroupId] = uploadForwardNodes.mock.calls[0]!;
expect(outerGroupId).toBe(12345);
const outerNode = (outerNodes as any[])[0]!;
expect(outerNode.userUin).toBe(111);
// Outer node's `elements` is empty — the upload pipeline replaces
// it with the real ARK preview once it has the inner res_id.
expect(outerNode.elements).toEqual([]);
// The inner chain rides along as `innerForward`.
expect(Array.isArray(outerNode.innerForward)).toBe(true);
expect(outerNode.innerForward).toHaveLength(1);
expect(outerNode.innerForward[0]).toMatchObject({
userUin: 222,
nickname: 'inner',
elements: [{ type: 'text', text: 'hello from inner' }],
});
expect(result.forwardId).toBe('OUTER_RESID');
expect(sendGroupMessage).toHaveBeenCalledOnce();
});
it('private: nested forward threads userId into uploadForwardNodes', async () => {
// Same shape but routed via sendPrivateForwardMessage. The c2c path
// passes `userId` instead of `groupId` so the upload pipeline can
// pick up the recipient's UID scene for any inner media element.
const uploadForwardNodes = vi.fn(async (_nodes: any[], _groupId?: number, _userId?: number) => 'RESID');
const sendPrivateMessage = vi.fn(async () => ({
messageId: 1, sequence: 100, clientSequence: 0, random: 1, timestamp: 1700000000,
}));
const bridge = fakeBridge({ uploadForwardNodes, sendPrivateMessage } as any);
const ctx = makeCtx(bridge);
const messages = [{
type: 'node',
data: {
user_id: 111, nickname: 'outer',
content: [{
type: 'node',
data: {
user_id: 222, nickname: 'inner',
content: [{ type: 'text', data: { text: 'hi' } }],
},
}],
},
}];
await sendPrivateForwardMessage(ctx, 67890, messages as any);
// Single call, c2c-scoped (groupId undefined, userId = recipient).
expect(uploadForwardNodes).toHaveBeenCalledOnce();
const call = uploadForwardNodes.mock.calls[0]!;
expect(call[1]).toBeUndefined();
expect(call[2]).toBe(67890);
// Inner chain attached via `innerForward`.
const outerNode = (call[0] as any[])[0]!;
expect(outerNode.innerForward).toHaveLength(1);
expect(outerNode.innerForward[0]!.userUin).toBe(222);
});
it('rejects nesting deeper than 3 levels', async () => {
// Build a 4-level nested chain. NapCat caps at 3 too, going further
// wastes long-msg uploads and risks one inner upload timing out
// and aborting the whole tree. Better to fail loud here.
const uploadForwardNodes = vi.fn(async (_nodes: any[], _groupId?: number, _userId?: number) => 'X');
const sendGroupMessage = vi.fn(async () => ({
messageId: 1, sequence: 100, clientSequence: 0, random: 1, timestamp: 0,
}));
const bridge = fakeBridge({ uploadForwardNodes, sendGroupMessage } as any);
const ctx = makeCtx(bridge);
function wrap(content: any, depth: number): any {
if (depth === 0) return [{ type: 'text', data: { text: 'leaf' } }];
return [{
type: 'node',
data: { user_id: 100 + depth, nickname: `lvl-${depth}`, content: wrap(content, depth - 1) },
}];
}
await expect(
sendGroupForwardMessage(ctx, 12345, wrap(null, 4) as any),
).rejects.toThrow(/depth/);
});
it('flat content (no nesting) still goes through the unchanged path', async () => {
// Backwards-compat: a single-level forward with plain text nodes
// calls uploadForwardNodes exactly once and never touches the
// recursive branch.
const uploadForwardNodes = vi.fn(async (_nodes: any[], _groupId?: number, _userId?: number) => 'RES');
const sendGroupMessage = vi.fn(async () => ({
messageId: 1, sequence: 100, clientSequence: 0, random: 1, timestamp: 0,
}));
const bridge = fakeBridge({ uploadForwardNodes, sendGroupMessage } as any);
const ctx = makeCtx(bridge);
const messages = [
{ type: 'node', data: { user_id: 111, nickname: 'a', content: [{ type: 'text', data: { text: 'one' } }] } },
{ type: 'node', data: { user_id: 222, nickname: 'b', content: [{ type: 'text', data: { text: 'two' } }] } },
];
await sendGroupForwardMessage(ctx, 12345, messages as any);
expect(uploadForwardNodes).toHaveBeenCalledOnce();
const [nodes] = uploadForwardNodes.mock.calls[0]!;
expect((nodes as any[])).toHaveLength(2);
expect((nodes as any[])[0]!.elements).toEqual([{ type: 'text', text: 'one' }]);
expect((nodes as any[])[1]!.elements).toEqual([{ type: 'text', text: 'two' }]);
});
it('mixed content (some {type:"node"} + non-node) falls back to flat parsing — does NOT recurse', async () => {
// Recursion only kicks in when *all* content entries are nodes —
// mixed content is ambiguous (do the non-node parts belong to the
// outer node or are they parallel siblings?), so we keep the legacy
// behaviour and let parseMessage handle it. Non-node parts come
// through, node parts get parsed via `case 'node':` and then
// dropped by element-builder. A user who wants nested forward
// should pass a pure node list.
const uploadForwardNodes = vi.fn(async (_nodes: any[], _groupId?: number, _userId?: number) => 'RES');
const sendGroupMessage = vi.fn(async () => ({
messageId: 1, sequence: 100, clientSequence: 0, random: 1, timestamp: 0,
}));
const bridge = fakeBridge({ uploadForwardNodes, sendGroupMessage } as any);
const ctx = makeCtx(bridge);
const messages = [{
type: 'node',
data: {
user_id: 111, nickname: 'mixed',
content: [
{ type: 'text', data: { text: 'a sibling' } },
{ type: 'node', data: { user_id: 222, content: [{ type: 'text', data: { text: 'lost' } }] } },
],
},
}];
await sendGroupForwardMessage(ctx, 12345, messages as any);
expect(uploadForwardNodes).toHaveBeenCalledOnce();
// Only the text element survives — the legacy "node MessageElement"
// that parseMessage produces is opaque to the element-builder.
const [nodes] = uploadForwardNodes.mock.calls[0]!;
const elements = (nodes as any[])[0]!.elements;
expect(elements.some((e: any) => e.type === 'text' && e.text === 'a sibling')).toBe(true);
});
});
@@ -0,0 +1,67 @@
import { describe, expect, it, vi } from 'vitest';
import { handleGroupAddRequest } from '../../src/onebot/modules/request-actions';
import type { BridgeInterface } from '../../src/bridge/bridge-interface';
import type { GroupRequestInfo } from '../../src/bridge/qq-info';
function fakeBridge(overrides: Partial<BridgeInterface> = {}): BridgeInterface {
return new Proxy(overrides as BridgeInterface, {
get(target, prop) {
if (prop in target) return (target as any)[prop];
throw new Error(`fakeBridge: '${String(prop)}' was not stubbed`);
},
});
}
function fakeRequest(overrides: Partial<GroupRequestInfo> = {}): GroupRequestInfo {
return {
groupId: 999,
groupName: 'g',
targetUid: 'u_t',
targetUin: 5555,
targetName: 'target',
invitorUid: 'u_i',
invitorUin: 7777,
invitorName: 'inviter',
operatorUid: 'u_o',
operatorUin: 8888,
operatorName: 'op',
sequence: 42,
state: 1,
eventType: 7,
comment: 'pls',
filtered: false,
...overrides,
};
}
describe('onebot/modules/request-actions / handleGroupAddRequest', () => {
it('matches add requests by groupId and targetUid', async () => {
const setGroupAddRequest = vi.fn(async () => {});
const bridge = fakeBridge({
fetchGroupRequests: vi.fn(async () => [
fakeRequest({ groupId: 999, targetUid: 'u_t', sequence: 42, eventType: 7, filtered: false }),
]),
setGroupAddRequest: setGroupAddRequest as any,
});
await handleGroupAddRequest(bridge, 'add:999:u_t', true, 'ok');
expect(setGroupAddRequest).toHaveBeenCalledOnce();
expect(setGroupAddRequest).toHaveBeenCalledWith(999, 42, 7, true, 'ok', false);
});
it('matches invite requests by groupId and invitorUid', async () => {
const setGroupAddRequest = vi.fn(async () => {});
const bridge = fakeBridge({
fetchGroupRequests: vi.fn(async () => [
fakeRequest({ groupId: 999, invitorUid: 'u_i', sequence: 97, eventType: 8, filtered: false }),
]),
setGroupAddRequest: setGroupAddRequest as any,
});
await handleGroupAddRequest(bridge, 'invite:999:u_i', false, 'no');
expect(setGroupAddRequest).toHaveBeenCalledOnce();
expect(setGroupAddRequest).toHaveBeenCalledWith(999, 97, 8, false, 'no', false);
});
});
@@ -0,0 +1,123 @@
// Regression coverage for the group-file-in-send_group_msg bug.
//
// Symptom in the wild: bot uploaded a group file via `upload_group_file`,
// then sent `{type:'file', file_id}` through `send_group_msg`; the
// element-builder wrapped it as `transElem(elemType=24, ...)` inside
// `richText.elems` and shipped a regular `MessageSvc.PbSendMsg`. The
// QQ-NT server rejected the message with `result=79` because that wire
// shape is RECEIVE-side only (rich-body-decoder unpacks it into a
// FileEntity for inbound messages, but the server's intake validator
// flags it on the send side).
//
// Fix: split file segments off at the OneBot layer (same pattern as
// the c2c-file split for private messages) and dispatch through
// `bridge.sendGroupFileMessage`, which calls dedicated OIDB
// `OidbSvcTrpcTcp.0x6d9_4` — Lagrange.Core V2's
// `GroupSendFileService.cs`.
import { describe, expect, it, vi } from 'vitest';
import type { BridgeInterface } from '../../src/bridge/bridge-interface';
import type { OneBotInstanceContext } from '../../src/onebot/instance-context';
import { sendGroupMessage } from '../../src/onebot/modules/message-actions';
function fakeBridge(overrides: Partial<BridgeInterface> = {}): BridgeInterface {
return new Proxy(overrides as BridgeInterface, {
get(target, prop) {
if (prop in target) return (target as any)[prop];
throw new Error(`fakeBridge: '${String(prop)}' was not stubbed for this test`);
},
});
}
function makeCtx(bridge: BridgeInterface): OneBotInstanceContext {
return {
uin: '10001',
bridge,
messageStore: { findEvent: () => null, resolveReplySequence: () => 0 } as any,
cacheMessageMeta: vi.fn(),
mediaStore: {} as any,
musicSignUrl: '',
} as unknown as OneBotInstanceContext;
}
const goodReceipt = {
messageId: 1, sequence: 100, clientSequence: 0, random: 1, timestamp: 1700000000,
};
describe('send_group_msg with {type:"file"} segment', () => {
it('file-only message routes through sendGroupFileMessage (not sendGroupMessage_bridge)', async () => {
// Pure-file case — the elems[] path used to ship a transElem(24)
// and got result=79. The dedicated OIDB-0x6d9_4 route must take
// over for group file publishing.
const sendGroupMessage_bridge = vi.fn();
// Declare params on the fn so `mock.calls[0]` infers a tuple of
// [groupId, fileId] instead of `[]` (which makes the destructuring
// a tsc error under noUncheckedIndexedAccess).
const sendGroupFileMessage = vi.fn(async (_groupId: number, _fileId: string) => undefined);
const bridge = fakeBridge({
sendGroupMessage: sendGroupMessage_bridge,
sendGroupFileMessage,
resolveUserUid: vi.fn(),
} as any);
const ctx = makeCtx(bridge);
await sendGroupMessage(ctx, 12345, [{
type: 'file', data: { file_id: 'gfid-abc', name: 'doc.txt', size: 123 },
}] as any, false);
expect(sendGroupFileMessage).toHaveBeenCalledOnce();
expect(sendGroupMessage_bridge).not.toHaveBeenCalled();
const [groupId, fileId] = sendGroupFileMessage.mock.calls[0]!;
expect(groupId).toBe(12345);
expect(fileId).toBe('gfid-abc');
});
it('mixed text + file splits across two sends (text via elems[], file via OIDB)', async () => {
const sendGroupMessage_bridge = vi.fn(async (_gid: number, _elements: any[]) => goodReceipt);
const sendGroupFileMessage = vi.fn(async (_groupId: number, _fileId: string) => undefined);
const bridge = fakeBridge({
sendGroupMessage: sendGroupMessage_bridge,
sendGroupFileMessage,
resolveUserUid: vi.fn(async () => 'u_peer'),
} as any);
const ctx = makeCtx(bridge);
await sendGroupMessage(ctx, 12345, [
{ type: 'text', data: { text: 'here is the file:' } },
{ type: 'file', data: { file_id: 'gfid-xyz', name: 'pkg.zip' } },
] as any, false);
expect(sendGroupMessage_bridge).toHaveBeenCalledOnce();
expect(sendGroupFileMessage).toHaveBeenCalledOnce();
const [textGid, textElements] = sendGroupMessage_bridge.mock.calls[0]!;
expect(textGid).toBe(12345);
expect(textElements).toEqual([{ type: 'text', text: 'here is the file:' }]);
const [fileGid, fileFileId] = sendGroupFileMessage.mock.calls[0]!;
expect(fileGid).toBe(12345);
expect(fileFileId).toBe('gfid-xyz');
});
it('file segment without file_id is skipped (with a warn-level log)', async () => {
// Same upload-by-reference contract as the c2c file path —
// missing file_id means there's nothing to publish.
const sendGroupMessage_bridge = vi.fn(async (_gid: number, _elements: any[]) => goodReceipt);
const sendGroupFileMessage = vi.fn();
const bridge = fakeBridge({
sendGroupMessage: sendGroupMessage_bridge,
sendGroupFileMessage,
resolveUserUid: vi.fn(),
} as any);
const ctx = makeCtx(bridge);
await sendGroupMessage(ctx, 12345, [
{ type: 'text', data: { text: 'with bad file segment' } },
{ type: 'file', data: {} }, // no file_id
] as any, false);
expect(sendGroupMessage_bridge).toHaveBeenCalledOnce();
expect(sendGroupFileMessage).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,236 @@
// Regression coverage for the c2c-file-in-send_private_msg bug.
//
// Symptom in the wild: bot called `send_private_msg` with a
// `{type:'file', file_id}` segment; the OneBot module passed it
// straight to `bridge.sendPrivateMessage(userId, [fileElement])`;
// `buildSendElems` warned ("file send via elems[] is group-only")
// and dropped it; the resulting wire send had 0 elems and the chat
// rendered "[空消息]".
//
// Fix: c2c file segments are split out at the OneBot layer in
// `sendPrivateMessage` and dispatched through `bridge.sendC2cFileMessage`
// (which writes `RichText.notOnlineFile`, the correct wire slot for
// c2c files). Matches NapCat's `SendMsg.ts:404-415` which splits
// FILE / VIDEO / ARK / PTT into their own sendMsg calls and never
// mixes them with the regular elems[] batch.
import { describe, expect, it, vi } from 'vitest';
import type { BridgeInterface } from '../../src/bridge/bridge-interface';
import type { OneBotInstanceContext } from '../../src/onebot/instance-context';
import { sendPrivateMessage } from '../../src/onebot/modules/message-actions';
function fakeBridge(overrides: Partial<BridgeInterface> = {}): BridgeInterface {
return new Proxy(overrides as BridgeInterface, {
get(target, prop) {
if (prop in target) return (target as any)[prop];
throw new Error(`fakeBridge: '${String(prop)}' was not stubbed for this test`);
},
});
}
function makeCtx(bridge: BridgeInterface): OneBotInstanceContext {
return {
uin: '10001',
bridge,
messageStore: { findEvent: () => null } as any,
cacheMessageMeta: vi.fn(),
mediaStore: {} as any,
musicSignUrl: '',
} as unknown as OneBotInstanceContext;
}
const goodReceipt = {
messageId: 1, sequence: 100, clientSequence: 0, random: 1, timestamp: 1700000000,
};
describe('send_private_msg with {type:"file"} segment', () => {
it('file-only message routes through sendC2cFileMessage (not sendPrivateMessage)', async () => {
// Pure-file case — the elems[] path would have dropped this entirely
// and shipped "[空消息]". The c2c file route must take over.
const sendPrivateMessage_bridge = vi.fn();
const sendC2cFileMessage = vi.fn(async (_uin: number, _uid: string, _info: any) => goodReceipt);
const resolveUserUid = vi.fn(async () => 'u_peer');
const recallUploadedFile = vi.fn(() => undefined);
const bridge = fakeBridge({
sendPrivateMessage: sendPrivateMessage_bridge,
sendC2cFileMessage,
resolveUserUid,
recallUploadedFile,
} as any);
const ctx = makeCtx(bridge);
await sendPrivateMessage(ctx, 67890, [{
type: 'file',
data: { file_id: 'uuid-abc', name: 'doc.txt', size: 123, md5: '00112233' },
}] as any, false);
expect(sendC2cFileMessage).toHaveBeenCalledOnce();
expect(sendPrivateMessage_bridge).not.toHaveBeenCalled();
const [uin, uid, info] = sendC2cFileMessage.mock.calls[0]!;
expect(uin).toBe(67890);
expect(uid).toBe('u_peer');
expect(info).toMatchObject({
fileId: 'uuid-abc',
fileName: 'doc.txt',
fileSize: 123,
});
// md5 decoded from hex (4 bytes for '00112233')
expect(info.fileMd5).toEqual(Buffer.from('00112233', 'hex'));
});
it('file-only with just file_id hydrates fileName/size/md5 from the upload cache', async () => {
// Reproduces the "0 B file" bug: a caller passes only `file_id` from
// a previous upload_private_file, with no size/md5/name. Without
// the cache lookup the wire packet ships fileSize=0/md5=empty and
// the recipient sees a 0-byte file. With the cache we recover the
// real tuple.
const sendC2cFileMessage = vi.fn(async (_uin: number, _uid: string, _info: any) => goodReceipt);
const recallUploadedFile = vi.fn((id: string) => id === 'uuid-cached' ? {
fileId: 'uuid-cached',
scope: 'private' as const,
userId: 67890,
fileName: 'real-doc.pdf',
fileSize: 4096,
fileMd5: Buffer.from('aabbccddeeff', 'hex'),
fileSha1: new Uint8Array(20),
fileHash: 'srv-hash',
rememberedAt: 0,
} : undefined);
const bridge = fakeBridge({
sendPrivateMessage: vi.fn(),
sendC2cFileMessage,
resolveUserUid: vi.fn(async () => 'u_peer'),
recallUploadedFile,
} as any);
const ctx = makeCtx(bridge);
await sendPrivateMessage(ctx, 67890, [{
type: 'file', data: { file_id: 'uuid-cached' },
}] as any, false);
expect(sendC2cFileMessage).toHaveBeenCalledOnce();
const [, , info] = sendC2cFileMessage.mock.calls[0]!;
expect(info).toMatchObject({
fileId: 'uuid-cached',
fileName: 'real-doc.pdf',
fileSize: 4096,
fileHash: 'srv-hash',
});
expect(info.fileMd5).toEqual(Buffer.from('aabbccddeeff', 'hex'));
});
it('inline segment fields take precedence over the upload cache', async () => {
// If the caller threads the metadata inline (e.g. they tracked the
// upload response themselves), honour that over the cache so a
// refresh of an evicted file still works.
const sendC2cFileMessage = vi.fn(async (_uin: number, _uid: string, _info: any) => goodReceipt);
const recallUploadedFile = vi.fn(() => ({
fileId: 'uuid-x',
scope: 'private' as const,
userId: 67890,
fileName: 'stale-cache-name.txt',
fileSize: 99,
fileMd5: new Uint8Array(16),
fileSha1: new Uint8Array(20),
fileHash: 'stale-hash',
rememberedAt: 0,
}));
const bridge = fakeBridge({
sendPrivateMessage: vi.fn(),
sendC2cFileMessage,
resolveUserUid: vi.fn(async () => 'u_peer'),
recallUploadedFile,
} as any);
const ctx = makeCtx(bridge);
await sendPrivateMessage(ctx, 67890, [{
type: 'file', data: { file_id: 'uuid-x', name: 'inline.txt', size: 200, md5: '11223344', file_hash: 'inline-hash' },
}] as any, false);
const [, , info] = sendC2cFileMessage.mock.calls[0]!;
expect(info).toMatchObject({
fileName: 'inline.txt',
fileSize: 200,
fileHash: 'inline-hash',
});
expect(info.fileMd5).toEqual(Buffer.from('11223344', 'hex'));
});
it('mixed file + text splits across two sends (text first, file second)', async () => {
const sendPrivateMessage_bridge = vi.fn(async (_uin: number, _elements: any[]) => goodReceipt);
const sendC2cFileMessage = vi.fn(async (_uin: number, _uid: string, _info: any) => goodReceipt);
const resolveUserUid = vi.fn(async () => 'u_peer');
const bridge = fakeBridge({
sendPrivateMessage: sendPrivateMessage_bridge,
sendC2cFileMessage,
resolveUserUid,
recallUploadedFile: vi.fn(() => undefined),
} as any);
const ctx = makeCtx(bridge);
await sendPrivateMessage(ctx, 67890, [
{ type: 'text', data: { text: 'here is the file:' } },
{ type: 'file', data: { file_id: 'uuid-xyz', name: 'pkg.zip' } },
] as any, false);
expect(sendPrivateMessage_bridge).toHaveBeenCalledOnce();
expect(sendC2cFileMessage).toHaveBeenCalledOnce();
// Text goes via the elems[] pipeline.
const [textUin, textElements] = sendPrivateMessage_bridge.mock.calls[0]!;
expect(textUin).toBe(67890);
expect(textElements).toEqual([{ type: 'text', text: 'here is the file:' }]);
// File goes via the dedicated c2c-file API.
const [fileUin, fileUid, fileInfo] = sendC2cFileMessage.mock.calls[0]!;
expect(fileUin).toBe(67890);
expect(fileUid).toBe('u_peer');
expect(fileInfo).toMatchObject({ fileId: 'uuid-xyz', fileName: 'pkg.zip' });
});
it('file segment without file_id is skipped (with a warn-level log)', async () => {
// OneBot11 file segments are upload-by-reference — without a
// file_id there's nothing to send. Previously these slipped
// through to the elems[] path and shipped empty messages.
const sendPrivateMessage_bridge = vi.fn(async (_uin: number, _elements: any[]) => goodReceipt);
const sendC2cFileMessage = vi.fn();
const bridge = fakeBridge({
sendPrivateMessage: sendPrivateMessage_bridge,
sendC2cFileMessage,
resolveUserUid: vi.fn(),
recallUploadedFile: vi.fn(() => undefined),
} as any);
const ctx = makeCtx(bridge);
await sendPrivateMessage(ctx, 67890, [
{ type: 'text', data: { text: 'with bad file segment' } },
{ type: 'file', data: {} }, // no file_id
] as any, false);
// Text still went out, file dropped (no c2c file call).
expect(sendPrivateMessage_bridge).toHaveBeenCalledOnce();
expect(sendC2cFileMessage).not.toHaveBeenCalled();
});
it('throws when uid cannot be resolved for a file-only message', async () => {
// C2C file send requires the recipient's UID for the RichText.
// notOnlineFile routing. If lookup fails we can't proceed —
// surfacing the error is better than shipping a c2c send with
// an empty uid.
const sendC2cFileMessage = vi.fn();
const bridge = fakeBridge({
sendPrivateMessage: vi.fn(),
sendC2cFileMessage,
resolveUserUid: vi.fn(async () => ''), // intentional empty
recallUploadedFile: vi.fn(() => undefined),
} as any);
const ctx = makeCtx(bridge);
await expect(sendPrivateMessage(ctx, 67890, [
{ type: 'file', data: { file_id: 'uuid-orphan', name: 'x.txt' } },
] as any, false)).rejects.toThrow(/could not resolve uid/);
expect(sendC2cFileMessage).not.toHaveBeenCalled();
});
});
+815
View File
@@ -0,0 +1,815 @@
// Proof-of-concept: verify that codec generated by @snowluma/proton's Vite
// plugin produces wire bytes byte-identical to the legacy runtime schema
// encoder for the same input. If this passes, the migration pattern is sound
// for the schemas covered here.
import { describe, it, expect } from 'vitest';
import { protobuf_encode, protobuf_decode } from '@snowluma/proton';
import { protoEncode, protoDecode } from '../src/protobuf/decode';
import {
SendLongMsgRespSchema,
SendLongMsgReqSchema,
RecvLongMsgReqSchema,
RecvLongMsgRespSchema,
LongMsgSettingsSchema,
LongMsgResultSchema,
} from '../src/bridge/proto/longmsg';
import {
TextElemSchema,
NotOnlineImageSchema,
ExtraInfoSchema,
SrcMsgSchema,
ElemSchema,
MsgInfoSchema,
} from '../src/bridge/proto/element';
import {
ResponseHeadSchema,
PushMsgBodySchema,
PushMsgSchema,
} from '../src/bridge/proto/message';
import {
GroupChangeSchema,
GroupAdminSchema,
NotifyMessageBodySchema,
GroupReactNotifySchema,
FriendRequestSchema,
GroupJoinSchema,
} from '../src/bridge/proto/notify';
import {
RoutingHeadSchema,
SendMessageRequestSchema,
SendMessageResponseSchema,
MentionExtraSendSchema,
MarkdownDataSchema,
} from '../src/bridge/proto/action';
import {
HttpConn0x6FF501RequestSchema,
HttpConn0x6FF501ResponseSchema,
ReqDataHighwayHeadSchema,
NTV2RichMediaHighwayExtSchema,
FileUploadExtSchema,
} from '../src/bridge/proto/highway';
import { makeOidbBaseSchema, OidbSvcTrpcTcp0xFE5_2ResponseSchema } from '../src/bridge/proto/oidb';
import { makeOidbEnvelope, encodeOidbEnv, decodeOidbEnv } from '../src/bridge/bridge-oidb';
import {
GetMediaListRequestSchema,
DoQunCommentRequestSchema,
DoQunLikeRequestSchema,
DeleteMediasRequestSchema,
DeleteMediasResponseSchema,
} from '../src/bridge/proto/oidb-action';
import type {
SendLongMsgResp,
SendLongMsgReq,
RecvLongMsgReq,
RecvLongMsgResp,
LongMsgSettings,
LongMsgResult,
} from '../src/bridge/proto/proton/longmsg';
import type {
TextElem,
NotOnlineImage,
ExtraInfo,
SrcMsg,
Elem,
MsgInfo,
} from '../src/bridge/proto/proton/element';
import type {
ResponseHead,
PushMsgBody,
PushMsg,
} from '../src/bridge/proto/proton/message';
import type {
GroupChange,
GroupAdmin,
NotifyMessageBody,
GroupReactNotify,
FriendRequest as FriendRequestNotify,
GroupJoin,
} from '../src/bridge/proto/proton/notify';
import type {
RoutingHead,
SendMessageRequest,
SendMessageResponse,
MentionExtraSend,
MarkdownData,
} from '../src/bridge/proto/proton/action';
import type {
HttpConn0x6FF501Request,
HttpConn0x6FF501Response,
ReqDataHighwayHead,
NTV2RichMediaHighwayExt,
FileUploadExt,
} from '../src/bridge/proto/proton/highway';
import type {
OidbBase,
OidbSvcTrpcTcp0xFE5_2Response,
} from '../src/bridge/proto/proton/oidb';
import type {
GetMediaListRequest,
DoQunCommentRequest,
DoQunLikeRequest,
DeleteMediasRequest,
DeleteMediasResponse,
} from '../src/bridge/proto/proton/oidb-action';
function hex(buf: Uint8Array): string {
return Buffer.from(buf).toString('hex');
}
describe('proton ↔ legacy parity (longmsg subset)', () => {
it('encodes LongMsgSettings identically', () => {
const data: LongMsgSettings = { field1: 1, field2: 2, field3: 3, field4: 4 };
const legacy = protoEncode(data as any, LongMsgSettingsSchema);
const proton = protobuf_encode<LongMsgSettings>(data);
expect(hex(proton)).toBe(hex(legacy));
});
it('encodes SendLongMsgResp (nested message) identically', () => {
const data: SendLongMsgResp = { result: { resId: 'res-001' } };
const legacy = protoEncode(data as any, SendLongMsgRespSchema);
const proton = protobuf_encode<SendLongMsgResp>(data);
expect(hex(proton)).toBe(hex(legacy));
});
it('encodes SendLongMsgReq with bytes + nested + settings identically', () => {
// NOTE: all numeric fields are non-zero — proton follows proto3 semantics
// and omits default-valued fields from the wire, whereas the legacy runtime
// encoder always writes them. Parity is therefore only expected when no
// numeric field equals its default. See the explicit divergence test below.
const data: SendLongMsgReq = {
info: {
type: 1,
uid: { uid: 'u_test' },
groupUin: 123456,
payload: new Uint8Array([0xde, 0xad, 0xbe, 0xef]),
},
settings: { field1: 4, field2: 1, field3: 7, field4: 2 },
};
const legacy = protoEncode(data as any, SendLongMsgReqSchema);
const proton = protobuf_encode<SendLongMsgReq>(data);
expect(hex(proton)).toBe(hex(legacy));
});
it('encodes RecvLongMsgReq with bool field identically', () => {
const data: RecvLongMsgReq = {
info: { uid: { uid: 'u_recv' }, resId: 'r-9', acquire: true },
settings: { field1: 4, field2: 1, field3: 7, field4: 2 },
};
const legacy = protoEncode(data as any, RecvLongMsgReqSchema);
const proton = protobuf_encode<RecvLongMsgReq>(data);
expect(hex(proton)).toBe(hex(legacy));
});
it('encodes RecvLongMsgResp (with bytes payload) identically', () => {
const data: RecvLongMsgResp = {
result: { resId: 'r-1', payload: new Uint8Array([1, 2, 3, 4, 5]) },
settings: { field1: 4, field2: 1, field3: 7, field4: 2 },
};
const legacy = protoEncode(data as any, RecvLongMsgRespSchema);
const proton = protobuf_encode<RecvLongMsgResp>(data);
expect(hex(proton)).toBe(hex(legacy));
});
// ── element.ts coverage ─────────────────────────────────────────────
it('encodes TextElem (only primitive bytes + strings) identically', () => {
const data: TextElem = {
str: 'hello',
link: 'https://example.com',
attr6Buf: new Uint8Array([1, 2, 3]),
buf: new Uint8Array([0xff, 0xee]),
};
const legacy = protoEncode(data as any, TextElemSchema);
const proton = protobuf_encode<TextElem>(data);
expect(hex(proton)).toBe(hex(legacy));
});
it('encodes NotOnlineImage with nested PbReserve identically', () => {
const data: NotOnlineImage = {
filePath: 'pic.jpg',
fileLen: 12345,
picMd5: new Uint8Array([0x11, 0x22, 0x33, 0x44]),
picHeight: 600,
picWidth: 800,
resId: 'res-abc',
original: 1,
bigUrl: 'https://q.qq.com/big/abc',
bizType: 5,
pbRes: {
subType: 1,
summary: '[picture]',
field10: 7,
field20: { field1: 1, field2: 'inner', field3: 2, field4: 3, field5: 4, field7: 'tail' },
url: 'https://q.qq.com/abc',
md5Str: 'abc123',
},
};
const legacy = protoEncode(data as any, NotOnlineImageSchema);
const proton = protobuf_encode<NotOnlineImage>(data);
expect(hex(proton)).toBe(hex(legacy));
});
it('encodes ExtraInfo (mix of bytes + int32 + uint64) identically', () => {
const data: ExtraInfo = {
nick: new Uint8Array([0x41, 0x42]),
groupCard: new Uint8Array([0x43]),
level: 7,
flags: 1,
groupMask: 2,
msgTailId: 3,
uin: 10001n,
msgStateFlag: 4,
};
const legacy = protoEncode(data as any, ExtraInfoSchema);
const proton = protobuf_encode<ExtraInfo>(data);
expect(hex(proton)).toBe(hex(legacy));
});
it('encodes SrcMsg with repeated_uint32 + repeated_bytes identically', () => {
const data: SrcMsg = {
origSeqs: [100, 200, 300, 400],
senderUin: 10001n,
time: 1234567890,
flag: 1,
elemsRaw: [new Uint8Array([1, 2]), new Uint8Array([3, 4]), new Uint8Array([5, 6])],
type: 1,
toUin: 20002n,
};
const legacy = protoEncode(data as any, SrcMsgSchema);
const proton = protobuf_encode<SrcMsg>(data);
expect(hex(proton)).toBe(hex(legacy));
});
it('encodes Elem (oneOf-style union) identically across multiple shapes', () => {
const textOnly: Elem = { text: { str: 'hi', link: 'lnk' } };
expect(hex(protobuf_encode<Elem>(textOnly))).toBe(hex(protoEncode(textOnly as any, ElemSchema)));
const faceOnly: Elem = { face: { index: 42, buf: new Uint8Array([1, 2, 3]) } };
expect(hex(protobuf_encode<Elem>(faceOnly))).toBe(hex(protoEncode(faceOnly as any, ElemSchema)));
const generalFlags: Elem = { generalFlags: { uin: 10001n, longTextFlag: 1, longTextResId: 'rs' } };
expect(hex(protobuf_encode<Elem>(generalFlags))).toBe(hex(protoEncode(generalFlags as any, ElemSchema)));
});
it('encodes MsgInfo with repeated_message + deeply nested ExtBizInfo identically', () => {
const data: MsgInfo = {
msgInfoBody: [
{
index: {
info: { fileSize: 1024, fileHash: 'sha-1', fileSha1: 'sha-2', fileName: 'a.png', type: { type: 1, picFormat: 2, videoFormat: 3, voiceFormat: 4 }, width: 100, height: 200, time: 99, original: 1 },
fileUuid: 'uuid-1', storeId: 5, uploadTime: 1000, ttl: 86400, subType: 1,
},
picture: {
urlPath: '/p/1',
ext: { originalParameter: 'op', bigParameter: 'bp', thumbParameter: 'tp' },
domain: 'q.qq.com',
},
fileExist: true,
},
],
extBizInfo: {
pic: {
bizType: 5, textSummary: '[pic]',
extData: { subType: 2, textSummary: 'sum' },
fromScene: 1, toScene: 2, oldFileId: 999,
},
busiType: 3,
},
};
const legacy = protoEncode(data as any, MsgInfoSchema);
const proton = protobuf_encode<MsgInfo>(data);
expect(hex(proton)).toBe(hex(legacy));
});
// ── message.ts coverage ─────────────────────────────────────────────
it('encodes ResponseHead (nested forward + grp) identically', () => {
const data: ResponseHead = {
fromUin: 10001, fromUid: 'u_a', type: 1, sigMap: 2, toUin: 20002, toUid: 'u_b',
forward: { friendName: 'Alice' },
grp: { groupUin: 555, memberName: 'Bob', groupName: 'TestGroup' },
};
const legacy = protoEncode(data as any, ResponseHeadSchema);
const proton = protobuf_encode<ResponseHead>(data);
expect(hex(proton)).toBe(hex(legacy));
});
it('encodes PushMsgBody (with RichText holding Elem[]) identically', () => {
const data: PushMsgBody = {
responseHead: { fromUin: 1, toUin: 2, type: 1, sigMap: 3, fromUid: 'a', toUid: 'b' },
contentHead: { msgType: 1, subType: 1, divSeq: 1, msgId: 99, sequence: 100, timestamp: 1234567890 },
body: {
richText: {
elems: [
{ text: { str: 'hi ' } },
{ text: { str: 'world', link: 'lnk' } },
],
},
},
};
const legacy = protoEncode(data as any, PushMsgBodySchema);
const proton = protobuf_encode<PushMsgBody>(data);
expect(hex(proton)).toBe(hex(legacy));
});
it('encodes PushMsg (top-level) identically', () => {
const data: PushMsg = {
message: {
responseHead: { fromUin: 1, toUin: 2, type: 1, sigMap: 1, fromUid: 'a', toUid: 'b' },
contentHead: { msgType: 1, subType: 1, divSeq: 1, msgId: 1, sequence: 1, timestamp: 1 },
body: { richText: { elems: [{ text: { str: 'x' } }] } },
},
status: 1,
};
const legacy = protoEncode(data as any, PushMsgSchema);
const proton = protobuf_encode<PushMsg>(data);
expect(hex(proton)).toBe(hex(legacy));
});
// ── longmsg.ts: full migration (Content / Action / Result) ─────────
it('encodes LongMsgResult (repeated Action → Content → PushMsgBody[]) identically', () => {
const inner: PushMsgBody = {
responseHead: { fromUin: 1, toUin: 2, type: 1, sigMap: 1, fromUid: 'a', toUid: 'b' },
contentHead: { msgType: 1, subType: 1, divSeq: 1, msgId: 1, sequence: 1, timestamp: 1 },
body: { richText: { elems: [{ text: { str: 'forwarded' } }] } },
};
const data: LongMsgResult = {
action: [
{
actionCommand: 'MultiMsg',
actionData: { msgBody: [inner, inner] },
},
],
};
const legacy = protoEncode(data as any, LongMsgResultSchema);
const proton = protobuf_encode<LongMsgResult>(data);
expect(hex(proton)).toBe(hex(legacy));
});
// ── notify.ts coverage ──────────────────────────────────────────────
it('encodes GroupChange identically', () => {
const data: GroupChange = {
groupUin: 555,
flag: 1,
memberUid: 'u_x',
decreaseType: 130,
operatorBytes: new Uint8Array([1, 2, 3]),
increaseType: 1,
};
const legacy = protoEncode(data as any, GroupChangeSchema);
const proton = protobuf_encode<GroupChange>(data);
expect(hex(proton)).toBe(hex(legacy));
});
it('encodes GroupAdmin (extraEnable variant) identically', () => {
const data: GroupAdmin = {
groupUin: 777, flag: 1, isPromote: true,
body: { extraEnable: { adminUid: 'u_admin', isPromote: true } },
};
const legacy = protoEncode(data as any, GroupAdminSchema);
const proton = protobuf_encode<GroupAdmin>(data);
expect(hex(proton)).toBe(hex(legacy));
});
it('encodes NotifyMessageBody (recall variant with repeated RecallMessage) identically', () => {
const data: NotifyMessageBody = {
type: 17,
groupUin: 555,
recall: {
operatorUid: 'u_op',
recallMessages: [
{ sequence: 1, time: 100, random: 42, type: 1, flag: 1, authorUid: 'u_a' },
{ sequence: 2, time: 200, random: 43, type: 1, flag: 1, authorUid: 'u_a' },
],
groupType: 1, opType: 2,
tipInfo: { tip: 'recalled' },
},
msgSequence: 99,
};
const legacy = protoEncode(data as any, NotifyMessageBodySchema);
const proton = protobuf_encode<NotifyMessageBody>(data);
expect(hex(proton)).toBe(hex(legacy));
});
it('encodes GroupReactNotify (deeply nested) identically', () => {
const data: GroupReactNotify = {
groupUin: 555n,
field13: 35,
groupReactionData: {
data: {
data: {
groupReactionTarget: { seq: 12345n },
groupReactionDataContent: { code: '128516', count: 1, operatorUid: 'u_op', type: 1 },
},
},
},
};
const legacy = protoEncode(data as any, GroupReactNotifySchema);
const proton = protobuf_encode<GroupReactNotify>(data);
expect(hex(proton)).toBe(hex(legacy));
});
it('encodes FriendRequest identically', () => {
const data: FriendRequestNotify = {
info: { targetUid: 'u_me', sourceUid: 'u_them', newSource: 'qrcode', message: 'hello!', source: 'web' },
};
const legacy = protoEncode(data as any, FriendRequestSchema);
const proton = protobuf_encode<FriendRequestNotify>(data);
expect(hex(proton)).toBe(hex(legacy));
});
it('encodes GroupJoin identically', () => {
const data: GroupJoin = {
groupUin: 555, field2: 1, targetUid: 'u_them', field4: 1,
field6: 1, field7: 'reason', field8: 1, field9: new Uint8Array([0xaa]),
};
const legacy = protoEncode(data as any, GroupJoinSchema);
const proton = protobuf_encode<GroupJoin>(data);
expect(hex(proton)).toBe(hex(legacy));
});
// ── action.ts coverage ─────────────────────────────────────────────
it('encodes RoutingHead (c2c variant) identically', () => {
const data: RoutingHead = { c2c: { uin: 10001, uid: 'u_a' } };
const legacy = protoEncode(data as any, RoutingHeadSchema);
const proton = protobuf_encode<RoutingHead>(data);
expect(hex(proton)).toBe(hex(legacy));
});
it('encodes RoutingHead (group variant) identically', () => {
const data: RoutingHead = { grp: { groupCode: 555n } };
const legacy = protoEncode(data as any, RoutingHeadSchema);
const proton = protobuf_encode<RoutingHead>(data);
expect(hex(proton)).toBe(hex(legacy));
});
it('encodes SendMessageRequest (group with two text elements) identically', () => {
const data: SendMessageRequest = {
routingHead: { grp: { groupCode: 555n } },
contentHead: { type: 1, subType: 1, c2cCmd: 11 },
messageBody: {
richText: {
elems: [
{ text: { str: 'hi ' } },
{ text: { str: 'world', link: 'lnk' } },
],
},
},
clientSequence: 1,
random: 12345,
syncCookie: new Uint8Array([0xaa, 0xbb]),
via: 1,
dataStatist: 1,
multiSendSeq: 1,
};
const legacy = protoEncode(data as any, SendMessageRequestSchema);
const proton = protobuf_encode<SendMessageRequest>(data);
expect(hex(proton)).toBe(hex(legacy));
});
it('encodes SendMessageResponse identically', () => {
const data: SendMessageResponse = {
result: 1, errMsg: 'ok', timestamp1: 1234567890,
field10: 1, groupSequence: 100, timestamp2: 1234567891, privateSequence: 200,
};
const legacy = protoEncode(data as any, SendMessageResponseSchema);
const proton = protobuf_encode<SendMessageResponse>(data);
expect(hex(proton)).toBe(hex(legacy));
});
it('encodes MentionExtraSend identically', () => {
const data: MentionExtraSend = { type: 2, uin: 10001, field5: 1, uid: 'u_a' };
const legacy = protoEncode(data as any, MentionExtraSendSchema);
const proton = protobuf_encode<MentionExtraSend>(data);
expect(hex(proton)).toBe(hex(legacy));
});
it('encodes MarkdownData identically', () => {
const data: MarkdownData = { content: '**bold** _italic_' };
const legacy = protoEncode(data as any, MarkdownDataSchema);
const proton = protobuf_encode<MarkdownData>(data);
expect(hex(proton)).toBe(hex(legacy));
});
// ── highway.ts coverage ────────────────────────────────────────────
it('encodes HttpConn0x6FF501Request (high-numbered field tag 0x501) identically', () => {
const data: HttpConn0x6FF501Request = {
httpConn: {
field1: 1, field2: 2, field3: 16, field4: 1, field6: 3,
serviceTypes: [1, 5, 10, 21],
field9: 2, field10: 9, field11: 8, ver: '1.0.1',
},
};
const legacy = protoEncode(data as any, HttpConn0x6FF501RequestSchema);
const proton = protobuf_encode<HttpConn0x6FF501Request>(data);
expect(hex(proton)).toBe(hex(legacy));
});
it('encodes HttpConn0x6FF501Response (with repeated server infos) identically', () => {
const data: HttpConn0x6FF501Response = {
httpConn: {
sigSession: new Uint8Array([1, 2, 3]),
sessionKey: new Uint8Array([4, 5, 6]),
serverInfos: [
{ serviceType: 1, serverAddrs: [{ type: 1, ip: 0x01020304, port: 8080, area: 1 }] },
{ serviceType: 2, serverAddrs: [{ type: 1, ip: 0x05060708, port: 8081, area: 2 }] },
],
},
};
const legacy = protoEncode(data as any, HttpConn0x6FF501ResponseSchema);
const proton = protobuf_encode<HttpConn0x6FF501Response>(data);
expect(hex(proton)).toBe(hex(legacy));
});
it('encodes ReqDataHighwayHead (multiple nested messages) identically', () => {
const data: ReqDataHighwayHead = {
msgBaseHead: {
version: 1, uin: '10001', command: 'PicUp.DataUp', seq: 1, retryTimes: 1,
appId: 1600001604, dataFlag: 16, commandId: 1003,
},
msgSegHead: {
serviceId: 1, filesize: 100n, dataOffset: 50n, dataLength: 100,
retCode: 1, serviceTicket: new Uint8Array([1, 2, 3]), flag: 1,
md5: new Uint8Array([4, 5, 6]), fileMd5: new Uint8Array([7, 8, 9]),
cacheAddr: 1, cachePort: 80,
},
bytesReqExtendInfo: new Uint8Array([0xab, 0xcd]),
timestamp: 1234567890n,
msgLoginSigHead: { loginSigType: 8, appId: 1600001604 },
};
const legacy = protoEncode(data as any, ReqDataHighwayHeadSchema);
const proton = protobuf_encode<ReqDataHighwayHead>(data);
expect(hex(proton)).toBe(hex(legacy));
});
it('encodes NTV2RichMediaHighwayExt (repeated_bytes hash) identically', () => {
const data: NTV2RichMediaHighwayExt = {
fileUuid: 'uuid-1',
uKey: 'key-1',
network: { ipv4s: [{ domain: { isEnable: true, ip: '127.0.0.1' }, port: 80 }] },
blockSize: 1048576,
hash: { fileSha1: [new Uint8Array([1, 2]), new Uint8Array([3, 4])] },
};
const legacy = protoEncode(data as any, NTV2RichMediaHighwayExtSchema);
const proton = protobuf_encode<NTV2RichMediaHighwayExt>(data);
expect(hex(proton)).toBe(hex(legacy));
});
it('encodes FileUploadExt (high-numbered tags 100/200/400/600/700) identically', () => {
const data: FileUploadExt = {
unknown1: 100,
unknown2: 1,
unknown3: 1,
entry: {
busiBuff: {
busId: 102,
senderUin: 10001n,
receiverUin: 555n,
groupCode: 555n,
},
fileEntry: {
fileSize: 12345n,
md5: new Uint8Array([0x11, 0x22]),
checkKey: new Uint8Array([0x33, 0x44]),
md5S2: new Uint8Array([0x55]),
fileId: 'file-1',
uploadKey: new Uint8Array([0x66]),
},
clientInfo: {
clientType: 3, appId: '100', terminalType: 3, clientVer: '1.1.1', unknown: 4,
},
fileNameInfo: { fileName: 'a.bin' },
host: {
hosts: [
{ url: { unknown: 1, host: 'upload.qq.com' }, port: 80 },
],
},
},
unknown200: 1,
};
const legacy = protoEncode(data as any, FileUploadExtSchema);
const proton = protobuf_encode<FileUploadExt>(data);
expect(hex(proton)).toBe(hex(legacy));
});
// ── oidb.ts coverage (OidbBase<T> generic envelope) ────────────────
it('encodes OidbBase<OidbSvcTrpcTcp0xFE5_2Response> identically to makeOidbBaseSchema', () => {
// This is the exact pattern runOidb uses for the OIDB envelope. Proton's
// OidbBase<T> generic interface should monomorphize to a codec that is
// byte-equivalent to the legacy makeOidbBaseSchema(InnerSchema) factory.
// The inner Body type used here is a real schema (group-list response).
const body: OidbSvcTrpcTcp0xFE5_2Response = {
groups: [
{
groupUin: 555,
info: {
groupOwner: { uid: 'u_owner' },
createdTime: 1234567890, memberMax: 100, memberCount: 50,
groupName: 'TestGroup', description: 'desc', question: 'q?',
announcement: 'announcement',
},
customInfo: { remark: 'remark' },
},
],
};
const envelope = {
command: 0xFE5,
subCommand: 2,
errorCode: 1, // non-zero so it isn't proto3-omitted
body,
errorMsg: 'ok',
reserved: 1,
};
const legacy = protoEncode(envelope as any, makeOidbBaseSchema(OidbSvcTrpcTcp0xFE5_2ResponseSchema));
const proton = protobuf_encode<OidbBase<OidbSvcTrpcTcp0xFE5_2Response>>(envelope);
expect(hex(proton)).toBe(hex(legacy));
});
it('encodeOidbEnv<T> pass-through wrapper byte-equivalent to direct codec', () => {
// The bridge-oidb.ts module exposes encodeOidbEnv<T> / decodeOidbEnv<T>
// as pure pass-through wrappers around protobuf_encode/decode<OidbBase<T>>.
// Proton wrapper-binds them and substitutes each call site with the
// monomorphized codec, so byte-output must match a direct call.
const body: OidbSvcTrpcTcp0xFE5_2Response = {
groups: [{ groupUin: 100, info: { groupName: 'G' } }],
};
const env = makeOidbEnvelope<OidbSvcTrpcTcp0xFE5_2Response>(0xFE5, 2, body, false);
const viaWrapper = encodeOidbEnv<OidbSvcTrpcTcp0xFE5_2Response>(env);
const viaDirect = protobuf_encode<OidbBase<OidbSvcTrpcTcp0xFE5_2Response>>(env);
expect(hex(viaWrapper)).toBe(hex(viaDirect));
const back = decodeOidbEnv<OidbSvcTrpcTcp0xFE5_2Response>(viaWrapper);
expect(back.body?.groups?.[0]?.groupUin).toBe(100);
expect(back.body?.groups?.[0]?.info?.groupName).toBe('G');
});
it('round-trips OidbBase<T> with non-trivial nested body', () => {
const body: OidbSvcTrpcTcp0xFE5_2Response = {
groups: [{ groupUin: 100, info: { groupName: 'G' } }],
};
const envelope: OidbBase<OidbSvcTrpcTcp0xFE5_2Response> = {
command: 0xFE5, subCommand: 2, errorCode: 1, body, errorMsg: 'ok', reserved: 1,
};
const encoded = protobuf_encode<OidbBase<OidbSvcTrpcTcp0xFE5_2Response>>(envelope);
const decoded = protobuf_decode<OidbBase<OidbSvcTrpcTcp0xFE5_2Response>>(encoded);
expect(decoded.command).toBe(0xFE5);
expect(decoded.errorCode).toBe(1);
expect(decoded.body?.groups?.[0]?.groupUin).toBe(100);
expect(decoded.body?.groups?.[0]?.info?.groupName).toBe('G');
});
// ── Documented divergence: proto3 default-value omission ────────────
it('proton omits default-valued numeric fields (legacy emits them)', () => {
// proto3 wire format says fields equal to their default value MUST NOT be
// emitted. Proton follows that; the legacy runtime encoder always emits.
// Either form is round-trippable through a conforming proto3 reader — the
// missing field decodes as its default. This test pins that behaviour.
const data: LongMsgSettings = { field1: 0, field2: 0, field3: 0, field4: 0 };
const legacy = protoEncode(data as any, LongMsgSettingsSchema);
const proton = protobuf_encode<LongMsgSettings>(data);
expect(hex(proton)).toBe(''); // nothing on the wire
expect(legacy.length).toBeGreaterThan(0); // legacy emits all zeros
// Legacy emits explicit zero values; a proto3-conforming reader sees them
// back when decoding. (Decoding the empty wire returns null because the
// legacy decoder treats an empty buffer as "no message at all" — that's
// also semantically equivalent to "all-default values" in proto3.)
expect(protoDecode(legacy, LongMsgSettingsSchema)).toMatchObject({
field1: 0, field2: 0, field3: 0, field4: 0,
});
});
// ── round-trip via decode ───────────────────────────────────────────
it('round-trips SendLongMsgResp through proton encode → legacy decode', () => {
const data: SendLongMsgResp = { result: { resId: 'rt-1' } };
const encoded = protobuf_encode<SendLongMsgResp>(data);
const decoded = protoDecode(encoded, SendLongMsgRespSchema);
expect(decoded?.result?.resId).toBe('rt-1');
});
it('round-trips SendLongMsgResp through legacy encode → proton decode', () => {
const data: SendLongMsgResp = { result: { resId: 'rt-2' } };
const encoded = protoEncode(data as any, SendLongMsgRespSchema);
const decoded = protobuf_decode<SendLongMsgResp>(encoded);
expect(decoded.result?.resId).toBe('rt-2');
});
// ── Group album TRPC envelopes (PR #31) ─────────────────────────────
//
// Raw TRPC packets — not OIDB-wrapped — that the group-album actions
// ship to `QunAlbum.trpc.qzone.webapp_qun_*`. Field names are mostly
// positional (`field1`/`field2`/...) because the upstream protocol
// doesn't expose semantic names; the byte-for-byte parity below is
// what guarantees the migration preserved every numbered field.
// NOTE: every numeric/bytes field below is non-zero / non-empty —
// proton follows proto3 semantics and skips default-valued fields on
// the wire, while the legacy runtime encoder writes them all. Byte
// parity therefore only holds when no field equals its default. The
// actual production callers in `actions/group-album.ts` *do* pass
// some zero-valued fields (e.g. `field1: 0`), which means the
// post-migration packet drops a few leading zero tags — semantically
// equivalent to a proto3-conforming reader, see the explicit
// divergence test earlier in this file.
it('encodes GetMediaListRequest (nested ReqInfo + extMap) identically', () => {
const data: GetMediaListRequest = {
field1: 1, // proto3 non-default
field2: new Uint8Array([0xab]),
field3: new Uint8Array([0xcd]),
reqInfo: { groupId: '555', albumId: 'alb-1', field3: 7, attachInfo: 'cursor', field5: 'tag' },
traceId: '_1700000000_12345',
extMap: [{ key: 'fc-appid', value: '100' }],
};
const legacy = protoEncode(data as any, GetMediaListRequestSchema);
const proton = protobuf_encode<GetMediaListRequest>(data);
expect(hex(proton)).toBe(hex(legacy));
});
it('encodes DoQunCommentRequest (deeply nested anonymous-in-legacy schemas) identically', () => {
const data: DoQunCommentRequest = {
field1: 8527,
field2: new Uint8Array([0x01]),
field3: new Uint8Array([0x02]),
body: {
groupId: '555',
field3: 2,
reqBody: {
field1: { field3: 3, field4: 'h' },
field2: { field1: { uin: '10001' } },
field5: {
field1: {
field2: {
field1: 1, field2: 'a', lloc: 'lloc-x',
field4: 'b', field6: 'c', field7: 1, field8: 1, field9: 1,
field14: 1, field15: 1, field17: 1,
},
},
albumId: 'alb-1',
field5: 1,
},
},
field5: {
field2: { uin: '10001' },
field3: { field1: 1, field2: 'hello', field3: 'd', field4: 'e', field5: 1, field6: 'f' },
clientKey: 'ck-1',
},
},
traceId: '_1700000000_12345',
extMap: [{ key: 'fc-appid', value: '100' }],
};
const legacy = protoEncode(data as any, DoQunCommentRequestSchema);
const proton = protobuf_encode<DoQunCommentRequest>(data);
expect(hex(proton)).toBe(hex(legacy));
});
it('encodes DoQunLikeRequest (with bigint time/batchId) identically', () => {
const data: DoQunLikeRequest = {
field1: 5495,
field2: 'h5_test',
field3: 'h5_test',
body: {
type: 2,
like: { id: '421_1_0_555|alb|42', status: 1 }, // non-default
publish: {
cellCommon: { time: 1700000000000n, feedId: '422_0_42' },
cellUserInfo: { user: { uin: '10001' } },
cellMedia: { albumId: 'alb', batchId: 42n },
cellQunInfo: { qunId: '555' },
},
clientKey: 'ck',
},
extMap: [{ key: 'fc-appid', value: '100' }],
};
const legacy = protoEncode(data as any, DoQunLikeRequestSchema);
const proton = protobuf_encode<DoQunLikeRequest>(data);
expect(hex(proton)).toBe(hex(legacy));
});
it('encodes DeleteMediasRequest + decodes DeleteMediasResponse identically', () => {
const req: DeleteMediasRequest = {
field1: 8694, field2: 'h5_test', field3: 'h5_test',
body: { groupId: '555', albumId: 'alb', lloc: 'lloc-x' },
traceId: 'tr-1',
extMap: [{ key: 'fc-appid', value: '100' }],
};
expect(hex(protobuf_encode<DeleteMediasRequest>(req)))
.toBe(hex(protoEncode(req as any, DeleteMediasRequestSchema)));
// Response: encode with legacy, decode with proton, fields stay aligned.
const respBytes = protoEncode({ field1: 8694, field2: 10023, field3: 'no right delete' } as any, DeleteMediasResponseSchema);
const decoded = protobuf_decode<DeleteMediasResponse>(respBytes);
expect(decoded.field1).toBe(8694);
expect(decoded.field2).toBe(10023);
expect(decoded.field3).toBe('no right delete');
});
});
+95 -33
View File
@@ -1,10 +1,26 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '../../src/bridge/proto/proton/oidb';
import type {
OidbClientKeyResp,
OidbGetPskeyResp,
} from '../../src/bridge/proto/proton/oidb-action';
// Mock the OIDB shim so we can control what `forceFetchClientKey` and
// `getPSkey` see without standing up a Bridge.
vi.mock('../../src/bridge/bridge-oidb', () => ({
runOidb: vi.fn(async () => ({})),
}));
// `encodeOidbEnv` / `decodeOidbEnv` are proton-bound pass-through wrappers
// — the plugin substitutes them at the call site with the inlined codec,
// so mocking them on the module object is a no-op. We mock `runOidb`
// (non-generic, untouched by proton) to return real proton-encoded bytes
// that the production-side codec then decodes.
vi.mock('../../src/bridge/bridge-oidb', async () => {
const actual = await vi.importActual<typeof import('../../src/bridge/bridge-oidb')>(
'../../src/bridge/bridge-oidb',
);
return {
...actual,
runOidb: vi.fn(async () => new Uint8Array()),
makeOidbEnvelope: vi.fn((_oidbCmd, _subCmd, body) => ({ body })),
};
});
// Mock the actual HTTP cookie fetch.
vi.mock('../../src/bridge/web/request-util', () => ({
@@ -28,35 +44,54 @@ import {
const bridge = { identity: { uin: '10001' } } as any;
function resetOidbMocks() {
vi.mocked(oidb.runOidb).mockReset();
vi.mocked(oidb.runOidb).mockResolvedValue(new Uint8Array());
vi.mocked(oidb.makeOidbEnvelope).mockClear();
}
// Bake the encoded OidbBase<X> bytes a test wants `runOidb` to return.
// Keeping these inline as `protobuf_encode<OidbBase<...>>({body: ...})`
// — proton substitutes them with the inlined codec at this file's
// transform time, just like for production code.
describe('cookies — forceFetchClientKey', () => {
beforeEach(() => { vi.mocked(oidb.runOidb).mockReset(); });
beforeEach(() => { resetOidbMocks(); });
it('returns clientKey + keyIndex + expireTime from the OIDB response', async () => {
vi.mocked(oidb.runOidb).mockResolvedValueOnce({
clientKey: 'ck-xyz', keyIndex: 42, expireTime: 3600,
});
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
protobuf_encode<OidbBase<OidbClientKeyResp>>({
body: { clientKey: 'ck-xyz', keyIndex: 42, expireTime: 3600 } as any,
}),
);
const out = await forceFetchClientKey(bridge);
expect(out).toEqual({ clientKey: 'ck-xyz', keyIndex: '42', expireTime: '3600' });
});
it('falls back to default keyIndex/expireTime when the response omits them', async () => {
vi.mocked(oidb.runOidb).mockResolvedValueOnce({ clientKey: 'ck' });
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
protobuf_encode<OidbBase<OidbClientKeyResp>>({ body: { clientKey: 'ck' } as any }),
);
const out = await forceFetchClientKey(bridge);
expect(out).toEqual({ clientKey: 'ck', keyIndex: '19', expireTime: '1800' });
});
});
describe('cookies — getPSkey', () => {
beforeEach(() => { vi.mocked(oidb.runOidb).mockReset(); });
beforeEach(() => { resetOidbMocks(); });
it('folds pskeyItems into a domain → pskey Map', async () => {
vi.mocked(oidb.runOidb).mockResolvedValueOnce({
pskeyItems: [
{ domain: 'qun.qq.com', pskey: 'psk-a' },
{ domain: 'qzone.qq.com', pskey: 'psk-b' },
{ domain: 'corrupt', pskey: '' },
],
});
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
protobuf_encode<OidbBase<OidbGetPskeyResp>>({
body: {
pskeyItems: [
{ domain: 'qun.qq.com', pskey: 'psk-a' },
{ domain: 'qzone.qq.com', pskey: 'psk-b' },
{ domain: 'corrupt', pskey: '' },
],
} as any,
}),
);
const { domainPskeyMap } = await getPSkey(bridge, ['qun.qq.com', 'qzone.qq.com']);
expect(domainPskeyMap.get('qun.qq.com')).toBe('psk-a');
expect(domainPskeyMap.get('qzone.qq.com')).toBe('psk-b');
@@ -66,12 +101,16 @@ describe('cookies — getPSkey', () => {
describe('cookies — getCookies', () => {
beforeEach(() => {
vi.mocked(oidb.runOidb).mockReset();
resetOidbMocks();
vi.mocked(RequestUtil.HttpsGetCookies).mockReset();
});
it('builds the ptlogin2 jump URL with the right query params', async () => {
vi.mocked(oidb.runOidb).mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 });
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
protobuf_encode<OidbBase<OidbClientKeyResp>>({
body: { clientKey: 'ck', keyIndex: 19 } as any,
}),
);
vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({
p_skey: 'psk',
skey: 'sk',
@@ -89,10 +128,14 @@ describe('cookies — getCookies', () => {
it('falls back to getPSkey when p_skey is missing in the cookie response', async () => {
vi.mocked(oidb.runOidb)
.mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 }) // forceFetchClientKey
.mockResolvedValueOnce({ // getPSkey
pskeyItems: [{ domain: 'qun.qq.com', pskey: 'psk-from-oidb' }],
});
.mockResolvedValueOnce(
protobuf_encode<OidbBase<OidbClientKeyResp>>({ body: { clientKey: 'ck', keyIndex: 19 } as any }),
)
.mockResolvedValueOnce(
protobuf_encode<OidbBase<OidbGetPskeyResp>>({
body: { pskeyItems: [{ domain: 'qun.qq.com', pskey: 'psk-from-oidb' }] } as any,
}),
);
vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({});
const out = await getCookies(bridge, 'qun.qq.com');
@@ -101,7 +144,9 @@ describe('cookies — getCookies', () => {
it('returns whatever cookies it got if getPSkey fallback throws', async () => {
vi.mocked(oidb.runOidb)
.mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 })
.mockResolvedValueOnce(
protobuf_encode<OidbBase<OidbClientKeyResp>>({ body: { clientKey: 'ck', keyIndex: 19 } as any }),
)
.mockRejectedValueOnce(new Error('pskey unavailable'));
vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({ skey: 'sk' });
@@ -112,29 +157,38 @@ describe('cookies — getCookies', () => {
describe('cookies — getSKey', () => {
beforeEach(() => {
vi.mocked(oidb.runOidb).mockReset();
resetOidbMocks();
vi.mocked(RequestUtil.HttpsGetCookies).mockReset();
});
it('returns skey from the qzone-targeted ptlogin2 jump', async () => {
vi.mocked(oidb.runOidb).mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 });
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
protobuf_encode<OidbBase<OidbClientKeyResp>>({ body: { clientKey: 'ck', keyIndex: 19 } as any }),
);
vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({ skey: 'the-skey' });
expect(await getSKey(bridge)).toBe('the-skey');
});
it('throws when clientKey comes back empty', async () => {
vi.mocked(oidb.runOidb).mockResolvedValueOnce({ clientKey: '' });
// Empty clientKey is the proto3 default; omit so it decodes back to ''.
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
protobuf_encode<OidbBase<OidbClientKeyResp>>({ body: {} }),
);
await expect(getSKey(bridge)).rejects.toThrow(/clientKey is empty/);
});
it('throws when the jump response omits skey', async () => {
vi.mocked(oidb.runOidb).mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 });
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
protobuf_encode<OidbBase<OidbClientKeyResp>>({ body: { clientKey: 'ck', keyIndex: 19 } as any }),
);
vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({});
await expect(getSKey(bridge)).rejects.toThrow(/SKey is Empty/);
});
});
describe('cookies — pure helpers', () => {
beforeEach(() => { resetOidbMocks(); });
it('getBknFromSKey: deterministic djb2 truncated to 31 bits', () => {
// Two calls on the same input → same number; different input → different.
const a = getBknFromSKey('hello');
@@ -147,21 +201,27 @@ describe('cookies — pure helpers', () => {
});
it('getCookiesStr: joins cookies with "; "', async () => {
vi.mocked(oidb.runOidb).mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 });
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
protobuf_encode<OidbBase<OidbClientKeyResp>>({ body: { clientKey: 'ck', keyIndex: 19 } as any }),
);
vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({ p_skey: 'p', skey: 's' });
const out = await getCookiesStr(bridge, 'qun.qq.com');
expect(out).toBe('p_skey=p; skey=s');
});
it('getCsrfToken: combines getSKey + getBknFromSKey', async () => {
vi.mocked(oidb.runOidb).mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 });
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
protobuf_encode<OidbBase<OidbClientKeyResp>>({ body: { clientKey: 'ck', keyIndex: 19 } as any }),
);
vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({ skey: 'abc' });
const csrf = await getCsrfToken(bridge);
expect(csrf).toBe(getBknFromSKey('abc'));
});
it('getCredentials: returns { cookies, token, csrf_token } with bkn(p_skey)', async () => {
vi.mocked(oidb.runOidb).mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 });
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
protobuf_encode<OidbBase<OidbClientKeyResp>>({ body: { clientKey: 'ck', keyIndex: 19 } as any }),
);
vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({ p_skey: 'p', skey: 's' });
const out = await getCredentials(bridge, 'qun.qq.com');
@@ -172,7 +232,9 @@ describe('cookies — pure helpers', () => {
it('getCredentials: token is 0 when no skey/p_skey available', async () => {
vi.mocked(oidb.runOidb)
.mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 })
.mockResolvedValueOnce(
protobuf_encode<OidbBase<OidbClientKeyResp>>({ body: { clientKey: 'ck', keyIndex: 19 } as any }),
)
.mockRejectedValueOnce(new Error('no pskey'));
vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({});
+9
View File
@@ -4,6 +4,7 @@ import fs from 'fs';
import path from 'path';
import { builtinModules } from 'module';
import cp from 'vite-plugin-cp';
import protobufVitePlugin from '@snowluma/proton/vite';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const repoRoot = path.resolve(__dirname, '..', '..');
@@ -76,6 +77,14 @@ if (missingNatives.length > 0) {
}
const BaseConfigPlugin: PluginOption[] = [
// Proton substitutes every `protobuf_encode<T>` / `protobuf_decode<T>`
// call site with a monomorphized codec at build time. WITHOUT this
// plugin in the plugins array the runtime fallback in
// `@snowluma/proton/runtime.ts` throws on the first call (and the
// packaged Win/Linux release does exactly that). It MUST appear
// before `cp` so the transform runs on every source file Vite asks
// for, regardless of where `cp` later copies emitted assets.
protobufVitePlugin(),
cp({
targets: [
...runtimeDistFiles.map((file) => ({
+2
View File
@@ -1,10 +1,12 @@
import { defineConfig } from 'vitest/config';
import path from 'path';
import { fileURLToPath } from 'url';
import protobufVitePlugin from '@snowluma/proton/vite';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
export default defineConfig({
plugins: [protobufVitePlugin()],
resolve: {
alias: {
'@': path.resolve(__dirname, 'src')
+273
View File
@@ -0,0 +1,273 @@
# @snowluma/proton
Compile-time protobuf encoder/decoder generator for SnowLuma. TypeScript
interfaces in, fully-inlined zero-runtime codec functions out.
> Vendored from [SnowLuma/protobuf-dsl](https://github.com/SnowLuma/protobuf-dsl)
> with edge-case fixes applied. The unmodified upstream is kept under
> `dev/protobuf-dsl/` as a reference copy.
## What it does
You declare your wire schema as plain TypeScript interfaces marked up with
`pb<N, T>`. At build time a Vite plugin walks the call sites of
`protobuf_encode<T>` / `protobuf_decode<T>` and replaces them with
type-specific, fully-inlined codec functions. No runtime schema lookup,
no reflection, no `.proto` files, no `protoc`.
```ts
import type { pb, pb_repeated, uint_32, bool } from '@snowluma/proton';
import { protobuf_encode, protobuf_decode } from '@snowluma/proton';
interface UserProfile {
id?: pb<1, uint_32>;
username?: pb<2, string>;
active?: pb<3, bool>;
tags?: pb_repeated<4, string>;
}
const bytes = protobuf_encode<UserProfile>({
id: 42, username: 'alice', active: true, tags: ['admin'],
});
const user = protobuf_decode<UserProfile>(bytes);
```
After the plugin transform, this becomes:
```js
// pre-computed tag literals, inlined varint loops, no function-call overhead
const bytes = protobuf_encode_UserProfile({ id: 42, ... });
const user = protobuf_decode_UserProfile(bytes);
```
If the plugin **isn't** installed, calling `protobuf_encode` / `protobuf_decode`
throws a loud error rather than silently producing wrong bytes.
## Setup in SnowLuma
The package is already wired into `@snowluma/core`'s `vitest.config.ts`. To use
it elsewhere in the monorepo:
```ts
// vite.config.ts (or vitest.config.ts)
import { defineConfig } from 'vite';
import protobufVitePlugin from '@snowluma/proton/vite';
export default defineConfig({
plugins: [protobufVitePlugin()],
});
```
Add the workspace dep:
```json
{
"dependencies": { "@snowluma/proton": "workspace:*" }
}
```
## Primitive types
The marker is `pb<FieldNumber, Type>` (or `pb_repeated<FieldNumber, Type>` for
arrays). Available primitives:
| Marker | TS type | Wire |
| ----------- | ------------ | ---------------- |
| `bool` | `boolean` | varint |
| `uint_32` | `number` | varint |
| `int_32` | `number` | varint |
| `sint_32` | `number` | varint (zigzag) |
| `uint_64` | `bigint` | varint |
| `int_64` | `bigint` | varint |
| `sint_64` | `bigint` | varint (zigzag) |
| `fixed_32` | `number` | 32-bit |
| `fixed_64` | `bigint` | 64-bit |
| `sfixed_32` | `number` | 32-bit |
| `sfixed_64` | `bigint` | 64-bit |
| `float` | `number` | 32-bit |
| `double` | `number` | 64-bit |
| `string` | `string` | length-delimited |
| `bytes` | `Uint8Array` | length-delimited |
Plus message types (any other interface marked with `pb<>` fields) used as
the second type-arg to `pb<>` / `pb_repeated<>`.
## Generic templates
You can declare reusable wrappers as generic interfaces:
```ts
interface Wrapper<T> {
value?: pb<1, T>;
}
const bytes = protobuf_encode<Wrapper<uint_32>>({ value: 42 });
// ^ instantiated at the call site
```
Nested instantiations work too — `Wrapper<Wrapper<string>>` mono-morphizes to
`Wrapper__string` + `Wrapper__Wrapper__string` and both end up in the registry
at build time.
Compose them in concrete interfaces:
```ts
interface Container {
wrapped?: pb<5, Wrapper<uint_32>>;
}
```
…or in other generic templates:
```ts
interface Outer<U> {
wrapped?: pb<5, Wrapper<U>>;
}
const bytes = protobuf_encode<Outer<uint_32>>({ wrapped: { value: 42 } });
```
Both forms are covered by regression tests.
## Cross-file & wrapper-binding
Schemas can live in one file and call sites in another:
```ts
// schema/user.ts
export interface UserProfile { id?: pb<1, uint_32>; }
// usage.ts
import type { UserProfile } from './schema/user';
import { protobuf_encode } from '@snowluma/proton';
const bytes = protobuf_encode<UserProfile>({ id: 42 });
```
You can also build thin generic wrappers around `protobuf_encode` / `_decode`
and the plugin will trace through them, including across file boundaries:
```ts
// schema/wrap.ts
export function encodeWrapped<T>(v: Wrapper<T>): Uint8Array {
return protobuf_encode<Wrapper<T>>(v);
}
// usage.ts
import { encodeWrapped } from './schema/wrap';
const bytes = encodeWrapped<string>({ value: 'hi' });
// ^ plugin rewrites to protobuf_encode_Wrapper__string(...)
```
Chained forwarders also work (`A` forwards to `B` which is imported from
another module, etc.).
## proto3 default-value semantics
**Important behavioural detail.** Proton follows the proto3 wire format spec:
fields whose value equals the type's default (`0` / `false` / `""` /
empty bytes) are **not emitted** on the wire. This is byte-different from
SnowLuma's legacy `protoEncode` runtime, which always emits every field.
Both forms are wire-compatible with any conforming proto3 reader (missing
fields decode as the default value). When migrating legacy schemas to proton,
do **not** treat byte-level inequality on default values as a regression — see
[`packages/core/tests/proton-parity.test.ts`](../../packages/core/tests/proton-parity.test.ts)
for the test that pins this divergence.
If you have a wire consumer that depends on byte-level identity (e.g. for
hashing or signing), prefer to set non-default values explicitly rather than
relying on the encoder.
## Diagnostics
Anything that doesn't resolve to a primitive or a registered message **throws
at build time** rather than silently leaking a wrong wire type:
```
Cannot resolve protobuf field type "Partial__UserProfile" on message "Foo"
(field "bar", field number 3). The analyzer did not produce a primitive or
registered message for this type. Common causes: union / intersection /
mapped / conditional types, TypeScript utility types (Partial<T>, Pick<T>, …),
qualified names (ns.Type), or a missing import.
```
This is the safety net for TypeScript constructs the analyzer doesn't model.
Currently unsupported:
- Union / intersection types (`A | B`, `A & B`)
- Conditional / mapped types (`T extends X ? A : B`, `{ [K in keyof T]: ... }`)
- TS utility types (`Partial<T>`, `Pick<T>`, `Readonly<T>`, …)
- Qualified type names (`ns.Type`)
- Wrapper functions reached via namespace import (`import * as ns from`)
…all of these will throw with a clear message instead of producing bad bytes.
## Optional: runtime-map fallback
If a call site can't be statically resolved (e.g. dynamic loading after build),
the plugin can emit a JSON map that the runtime can consume to generate codecs
on the fly. Off by default.
```ts
import protobufVitePlugin from '@snowluma/proton/vite';
export default defineConfig({
plugins: [protobufVitePlugin({
runtimeMap: { enabled: true, fileName: 'snowluma-proton.runtime-map.json' },
})],
});
```
```ts
import runtimeMap from './snowluma-proton.runtime-map.json';
import { protobuf_enableRuntimeMapFallback } from '@snowluma/proton';
protobuf_enableRuntimeMapFallback(runtimeMap);
```
## Edge cases fixed on top of upstream
Each has a regression test in `test/__tests__/analyzer.test.ts`:
| # | What used to break |
| - | --------------------- |
| 1 | `import { pb as P }` — aliased markers were ignored; fields dropped silently |
| 2 | `interface Foo { x: pb<1, Wrapper<uint_32>> }` — typeName stuck at `"Wrapper"`, no mono of the inner instantiation |
| 3 | `interface Outer<U> { x: pb<1, Wrapper<U>> }` — outer mono didn't re-instantiate the inner generic |
| 4 | Wrapper-binding synthetic SourceFile had empty text → `getText()` returned garbage |
| 5 | Cross-file forwarded wrappers (chain → imported base) not detected |
| 6 | `matchForwardedKnownWrapper` didn't propagate `typePattern` — chain treated `<X>` as the encoded type instead of `Wrapper<X>` |
| 7 | Synthetic-SF WeakMap was private to analyzer.ts → replacer used the wrong SF |
Plus the build-time guard (above) that turns future analyzer gaps into hard
errors instead of silent miscodes.
## Scripts
```
pnpm --filter @snowluma/proton build # bundle src/index.ts → dist/index.js
pnpm --filter @snowluma/proton test # vitest run (95 tests)
pnpm --filter @snowluma/proton typecheck # tsc --noEmit
```
## Layout
```
src/
ast/ analyzer + type-tracking pipeline
analyzer.ts single-walk message + call-site collection
collector.ts interface → ProtobufField/GenericFieldTemplate
monomorphizer.ts generic instantiation → concrete ProtobufMessage
import-resolver.ts cross-file definition + wrapper resolution
callsite.ts matches protobuf_encode/decode invocations
utils.ts name resolution + synthetic-SF tracking
dependency-graph.ts topo sort + reachability
types.ts shared schema types
codegen/ inlined wire-format emitters
transform/ Vite plugin string edits
index.ts plugin entry (./vite)
runtime.ts runtime stubs + map fallback (.)
runtime-map.ts serialized map format
protobuf.d.ts public types (pb<>, pb_repeated<>, primitive aliases)
test/ vitest suite (analyzer + cross-file + plugin)
```
+43
View File
@@ -0,0 +1,43 @@
{
"name": "@snowluma/proton",
"version": "1.9.0",
"private": true,
"type": "module",
"description": "Compile-time protobuf encoder/decoder generator for SnowLuma. TypeScript interfaces → fully-inlined, zero-runtime protobuf codec functions. Vendored from SnowLuma/protobuf-dsl (reference copy under dev/protobuf-dsl/) with edge-case fixes applied.",
"main": "./src/runtime.ts",
"types": "./protobuf.d.ts",
"exports": {
".": {
"types": "./protobuf.d.ts",
"default": "./src/runtime.ts"
},
"./vite": {
"types": "./src/index.ts",
"default": "./dist/index.js"
}
},
"scripts": {
"build": "tsup src/index.ts --format esm --out-dir dist --target node20 --external typescript --external vite",
"test": "vitest run",
"test:watch": "vitest",
"typecheck": "tsc --noEmit",
"prepare": "test -f dist/index.js || pnpm build"
},
"dependencies": {
"typescript": "catalog:"
},
"peerDependencies": {
"vite": "catalog:"
},
"peerDependenciesMeta": {
"vite": {
"optional": true
}
},
"devDependencies": {
"@types/node": "^24.12.2",
"tsup": "^8.5.0",
"vite": "catalog:",
"vitest": "^4.1.4"
}
}
+61
View File
@@ -0,0 +1,61 @@
// ── Protobuf field markers ────────────────────────────────────────────
/** Marks a singular protobuf field: `name: pb<fieldNumber, Type>` */
export type pb<_ProtoNumber extends number, Type> = Type;
/** Marks a repeated protobuf field: `ids: pb_repeated<fieldNumber, Type>` → Type[] */
export type pb_repeated<_ProtoNumber extends number, Type> = Type[];
// ── Protobuf primitive types ──────────────────────────────────────────
export type uint_32 = number;
export type int_32 = number;
export type uint_64 = bigint;
export type int_64 = bigint;
export type sint_32 = number;
export type sint_64 = bigint;
export type bool = boolean;
export type float = number;
export type double = number;
export type fixed_32 = number;
export type fixed_64 = bigint;
export type sfixed_32 = number;
export type sfixed_64 = bigint;
export type bytes = Uint8Array;
// ── Encode / decode (replaced at compile-time by the vite plugin) ────
export function protobuf_encode<T>(params: T): Uint8Array;
export function protobuf_decode<T>(data: Uint8Array): T;
// ── Optional runtime map fallback (disabled by default) ───────────────
export interface ProtobufRuntimeField {
name: string;
fieldNumber: number;
typeName: string;
wireType: 0 | 1 | 2 | 5;
isMessage: boolean;
isOptional: boolean;
isRepeated: boolean;
}
export interface ProtobufRuntimeMessage {
name: string;
fields: ProtobufRuntimeField[];
}
export interface ProtobufRuntimeCallSite {
file: string;
line: number;
column: number;
fnName: 'protobuf_encode' | 'protobuf_decode';
typeName: string;
}
export interface ProtobufRuntimeMap {
version: 1;
messages: ProtobufRuntimeMessage[];
callSites: ProtobufRuntimeCallSite[];
}
/** Enables map-based runtime dynamic code generation fallback. */
export function protobuf_enableRuntimeMapFallback(map: ProtobufRuntimeMap): void;
/** Disables map-based runtime fallback and clears generated function cache. */
export function protobuf_disableRuntimeMapFallback(): void;
+317
View File
@@ -0,0 +1,317 @@
import ts from 'typescript';
import { WireType, PRIMITIVE_TYPE_MAP, type ProtobufMessage, type MessageRegistry, type GenericProtobufTemplate } from './types.js';
import { collectInterface, collectGenericInterface, collectConcreteFieldGenericTypeArgs } from './collector.js';
import { monomorphizeTypeNode } from './monomorphizer.js';
import {
createImportedTypeNameResolver,
typeNodeToMangledName,
registerSyntheticTypeSourceFile,
resolveSourceFileForTypeNode,
} from './utils.js';
import type { ImportedDefinitions, WrapperBinding } from './import-resolver.js';
import {
collectProtobufImportBindings,
matchProtobufCallSite,
type CanonicalProtobufFn,
} from './callsite.js';
import { buildDependencyRegistry } from './dependency-graph.js';
export { typeNodeToMangledName } from './utils.js';
function getCallableName(expr: ts.Expression): string | null {
if (ts.isIdentifier(expr)) return expr.text;
if (ts.isPropertyAccessExpression(expr)) return expr.name.text;
return null;
}
function instantiateWrapperTypePattern(
binding: WrapperBinding,
callerTypeArgs: ts.NodeArray<ts.TypeNode>,
sf: ts.SourceFile,
): ts.TypeNode | null {
if (!binding.typePattern || !binding.typeParamNames?.length) return callerTypeArgs[binding.typeArgIndex] ?? null;
let text = binding.typePattern;
for (let i = 0; i < binding.typeParamNames.length; i++) {
const arg = callerTypeArgs[i];
if (!arg) return null;
text = text.replace(new RegExp(`\\b${binding.typeParamNames[i]}\\b`, 'g'), arg.getText(sf));
}
// Parse the substituted type pattern into a fresh source file whose
// `fileName` is the binding's origin (so subsequent import resolution can
// find the right module) AND whose `text` contains the substituted source
// (so `getText()` on the resulting TypeNode returns the actual type, not
// garbage from an empty-text companion file).
const parsed = ts.createSourceFile(
binding.sourceFilePath ?? sf.fileName,
`type __T = ${text};`,
ts.ScriptTarget.Latest,
true,
);
const stmt = parsed.statements[0];
if (!ts.isTypeAliasDeclaration(stmt)) return null;
registerSyntheticTypeSourceFile(stmt.type, parsed);
return stmt.type;
}
/** A recorded call-site for later replacement. */
export interface CallSiteRecord {
fnName: CanonicalProtobufFn;
exprStart: number; // position of identifier start
typeArgsEnd: number; // position after closing '>'
firstTypeArg: ts.TypeNode; // the type argument node
line: number; // 1-based line for runtime map lookup
column: number; // 1-based column for runtime map lookup
}
export interface ResolvedCallSiteRecord extends CallSiteRecord {
typeName: string;
}
export interface AnalysisResult {
registry: MessageRegistry;
callSites: CallSiteRecord[];
sourceFile: ts.SourceFile;
}
export interface UsedRegistryResult {
registry: MessageRegistry;
roots: Set<string>;
callSites: ResolvedCallSiteRecord[];
}
/**
* Analyze TypeScript source in a **single parse + single walk**.
*
* One walk handles both:
* - Collecting concrete + generic interfaces
* - Recording protobuf_encode/decode call-sites
*
* Then post-processes: monomorphize → resolve wire types → topo sort.
*/
export function analyze(code: string, filePath: string, imported?: ImportedDefinitions): AnalysisResult {
const sf = ts.createSourceFile(filePath, code, ts.ScriptTarget.Latest, true);
const concrete: ProtobufMessage[] = [];
const templates = new Map<string, GenericProtobufTemplate>();
const mono = new Map<string, ProtobufMessage>();
const callSites: CallSiteRecord[] = [];
const deferredTypeArgs: ts.TypeNode[] = [];
const importBindings = collectProtobufImportBindings(sf);
const resolveImportedTypeName = createImportedTypeNameResolver(sf);
const wrapperBindings = imported?.wrapperBindings ?? new Map<string, WrapperBinding>();
// Seed with imported definitions
if (imported) {
concrete.push(...imported.concrete);
for (const [k, v] of imported.templates) templates.set(k, v);
}
// Stack of generic-function type-param scopes. When visiting a
// `protobuf_encode/decode<X>` call whose type arg references one of
// these (e.g. `protobuf_encode<OidbBase<T>>(env)` inside
// `function encodeOidbEnv<T>(...)`), we MUST skip monomorphization —
// the type arg only resolves once the wrapper itself is instantiated
// at a downstream call site, and that case is handled separately by
// the wrapper-binding path in `matchForwardedProtobufFn`. Without
// this skip, the analyzer would happily mint a literal `OidbBase__T`
// registry entry with a `body.typeName = 'T'` field, which the
// wire-type guard then trips on.
const enclosingTypeParamStack: Set<string>[] = [];
function typeArgReferencesEnclosingParam(typeArg: ts.TypeNode): boolean {
if (enclosingTypeParamStack.length === 0) return false;
let found = false;
function check(n: ts.Node): void {
if (found) return;
if (ts.isTypeReferenceNode(n) && ts.isIdentifier(n.typeName)) {
const name = n.typeName.text;
for (const scope of enclosingTypeParamStack) {
if (scope.has(name)) { found = true; return; }
}
}
ts.forEachChild(n, check);
}
check(typeArg);
return found;
}
function nodeIntroducesTypeParams(n: ts.Node): readonly ts.TypeParameterDeclaration[] | undefined {
if (ts.isFunctionDeclaration(n)) return n.typeParameters;
if (ts.isFunctionExpression(n)) return n.typeParameters;
if (ts.isArrowFunction(n)) return n.typeParameters;
if (ts.isMethodDeclaration(n)) return n.typeParameters;
return undefined;
}
// ── single walk ─────────────────────────────────────────────────────
ts.forEachChild(sf, function visit(node) {
const introduced = nodeIntroducesTypeParams(node);
const pushedScope = !!(introduced && introduced.length);
if (pushedScope) {
enclosingTypeParamStack.push(new Set(introduced!.map(p => p.name.text)));
}
try {
if (ts.isInterfaceDeclaration(node)) {
if (node.typeParameters?.length) {
const tpl = collectGenericInterface(node, sf, resolveImportedTypeName);
if (tpl) templates.set(tpl.name, tpl);
} else {
const msg = collectInterface(node, sf, resolveImportedTypeName);
if (msg) concrete.push(msg);
// Queue any generic-instantiated type-args appearing as field types
// (e.g. `wrapped: pb<5, Wrapper<uint_32>>`) for monomorphization.
// The call-site queue only sees the outer concrete type, so without
// this the nested instantiation would never reach the registry.
for (const ta of collectConcreteFieldGenericTypeArgs(node, resolveImportedTypeName)) {
deferredTypeArgs.push(ta);
}
}
}
if (ts.isCallExpression(node)) {
const cs = matchProtobufCallSite(node, sf, importBindings, {
allowLegacyUnboundCanonical: true,
});
if (cs) {
if (!typeArgReferencesEnclosingParam(cs.firstTypeArg)) {
deferredTypeArgs.push(cs.firstTypeArg);
callSites.push(cs);
}
// else: this call sits inside a generic wrapper definition; the
// wrapper-binding path will materialise concrete codecs at each
// downstream call site instead.
} else if (
node.typeArguments?.length &&
getCallableName(node.expression) &&
wrapperBindings.has(getCallableName(node.expression)!)
) {
const binding = wrapperBindings.get(getCallableName(node.expression)!)!;
const firstTypeArg = instantiateWrapperTypePattern(binding, node.typeArguments, sf);
if (!firstTypeArg) {
ts.forEachChild(node, visit);
return;
}
const exprStart = node.expression.getStart(sf);
const lc = sf.getLineAndCharacterOfPosition(exprStart);
deferredTypeArgs.push(firstTypeArg);
callSites.push({
fnName: binding.fnName,
exprStart,
typeArgsEnd: node.typeArguments.end + 1,
firstTypeArg,
line: lc.line + 1,
column: lc.character + 1,
});
}
}
ts.forEachChild(node, visit);
} finally {
if (pushedScope) enclosingTypeParamStack.pop();
}
});
// ── post-walk: monomorphize deferred type args ──────────────────────
for (const typeArg of deferredTypeArgs) {
const typeSf = resolveSourceFileForTypeNode(typeArg, sf);
const typeResolver = createImportedTypeNameResolver(typeSf);
monomorphizeTypeNode(typeArg, typeSf, templates, mono, typeResolver);
}
for (const m of mono.values()) concrete.push(m);
// ── resolve wire types ──────────────────────────────────────────────
// Anything that doesn't resolve to a primitive or a registered message is
// a type-tracking miss — historically these leaked the placeholder
// `WireType.Varint` into codegen and corrupted the wire format silently.
// Throw loudly instead so future analyzer gaps surface immediately.
const names = new Set(concrete.map(m => m.name));
for (const msg of concrete) {
for (const f of msg.fields) {
const prim = PRIMITIVE_TYPE_MAP[f.typeName];
if (prim) {
f.wireType = prim.wireType;
f.isMessage = false;
} else if (names.has(f.typeName)) {
f.wireType = WireType.LengthDelim;
f.isMessage = true;
} else {
throw new Error(
`Cannot resolve protobuf field type "${f.typeName}" on message "${msg.name}" ` +
`(field "${f.name}", field number ${f.fieldNumber}). The analyzer did not produce ` +
`a primitive or registered message for this type. Common causes: union / intersection / ` +
`mapped / conditional types, TypeScript utility types (Partial<T>, Pick<T>, …), ` +
`qualified names (ns.Type), or a missing import.`,
);
}
}
}
return { registry: topoSort(concrete), callSites, sourceFile: sf };
}
/**
* Backward-compatible wrapper: returns only the MessageRegistry.
* Uses the same single-walk analysis internally.
*/
export function analyzeSource(code: string, filePath: string, imported?: ImportedDefinitions): MessageRegistry {
return analyze(code, filePath, imported).registry;
}
/**
* Build a minimal message registry by collecting only call-site root types and
* their transitive message dependencies.
*/
export function selectUsedRegistry(
registry: MessageRegistry,
callSites: CallSiteRecord[],
sourceFile: ts.SourceFile,
): UsedRegistryResult {
const roots = new Set<string>();
const resolved: ResolvedCallSiteRecord[] = [];
const resolveImportedTypeName = createImportedTypeNameResolver(sourceFile);
for (const cs of callSites) {
const typeSf = resolveSourceFileForTypeNode(cs.firstTypeArg, sourceFile);
const typeName = typeNodeToMangledName(cs.firstTypeArg, typeSf, createImportedTypeNameResolver(typeSf));
if (!registry.has(typeName)) continue;
roots.add(typeName);
resolved.push({ ...cs, typeName });
}
if (roots.size === 0) {
return { registry: new Map(), roots, callSites: resolved };
}
return {
registry: buildDependencyRegistry(registry, roots),
roots,
callSites: resolved,
};
}
// ── topological sort ──────────────────────────────────────────────────
function topoSort(messages: ProtobufMessage[]): MessageRegistry {
const map = new Map(messages.map(m => [m.name, m]));
const deps = new Map(messages.map(m => [
m.name,
new Set(m.fields.filter(f => map.has(f.typeName)).map(f => f.typeName)),
]));
const sorted: ProtobufMessage[] = [];
const visited = new Set<string>();
const visiting = new Set<string>();
function dfs(name: string): void {
if (visited.has(name)) return;
if (visiting.has(name)) throw new Error(`Circular dependency: ${name}`);
visiting.add(name);
for (const d of deps.get(name) || []) dfs(d);
visiting.delete(name);
visited.add(name);
sorted.push(map.get(name)!);
}
for (const m of messages) dfs(m.name);
return new Map(sorted.map(m => [m.name, m]));
}
+119
View File
@@ -0,0 +1,119 @@
import ts from 'typescript';
export type CanonicalProtobufFn = 'protobuf_encode' | 'protobuf_decode';
const CANONICAL = new Set<CanonicalProtobufFn>(['protobuf_encode', 'protobuf_decode']);
const PROTOBUF_RUNTIME_MODULES = new Set([
'@snowluma/proton',
]);
export interface ProtobufImportBindings {
identifierToCanonical: Map<string, CanonicalProtobufFn>;
namespaceAliases: Set<string>;
blockedLegacyCanonical: Set<CanonicalProtobufFn>;
hasRuntimeImport: boolean;
}
export interface ProtobufCallSite {
fnName: CanonicalProtobufFn;
exprStart: number;
typeArgsEnd: number;
firstTypeArg: ts.TypeNode;
line: number;
column: number;
}
export function collectProtobufImportBindings(sf: ts.SourceFile): ProtobufImportBindings {
const identifierToCanonical = new Map<string, CanonicalProtobufFn>();
const namespaceAliases = new Set<string>();
const blockedLegacyCanonical = new Set<CanonicalProtobufFn>();
let hasRuntimeImport = false;
for (const stmt of sf.statements) {
if (!ts.isImportDeclaration(stmt) || !stmt.importClause) continue;
if (!ts.isStringLiteral(stmt.moduleSpecifier)) continue;
const fromRuntime = PROTOBUF_RUNTIME_MODULES.has(stmt.moduleSpecifier.text);
if (fromRuntime) hasRuntimeImport = true;
const bindings = stmt.importClause.namedBindings;
const defaultImport = stmt.importClause.name?.text;
if (defaultImport && CANONICAL.has(defaultImport as CanonicalProtobufFn) && !fromRuntime) {
blockedLegacyCanonical.add(defaultImport as CanonicalProtobufFn);
}
if (!bindings) continue;
if (ts.isNamedImports(bindings)) {
for (const el of bindings.elements) {
const imported = (el.propertyName ?? el.name).text;
if (fromRuntime && CANONICAL.has(imported as CanonicalProtobufFn)) {
identifierToCanonical.set(el.name.text, imported as CanonicalProtobufFn);
continue;
}
if (CANONICAL.has(el.name.text as CanonicalProtobufFn)) {
blockedLegacyCanonical.add(el.name.text as CanonicalProtobufFn);
}
}
continue;
}
if (fromRuntime && ts.isNamespaceImport(bindings)) {
namespaceAliases.add(bindings.name.text);
} else if (CANONICAL.has(bindings.name.text as CanonicalProtobufFn)) {
blockedLegacyCanonical.add(bindings.name.text as CanonicalProtobufFn);
}
}
return { identifierToCanonical, namespaceAliases, blockedLegacyCanonical, hasRuntimeImport };
}
interface MatchOptions {
allowLegacyUnboundCanonical?: boolean;
}
export function matchProtobufCallSite(
node: ts.CallExpression,
sf: ts.SourceFile,
bindings: ProtobufImportBindings,
options?: MatchOptions,
): ProtobufCallSite | null {
const ta = node.typeArguments;
if (!ta?.length) return null;
const expr = node.expression;
const allowLegacy = options?.allowLegacyUnboundCanonical === true;
let fnName: CanonicalProtobufFn | null = null;
let exprStart = expr.getStart(sf);
if (ts.isIdentifier(expr)) {
fnName = bindings.identifierToCanonical.get(expr.text) ?? null;
if (
!fnName &&
allowLegacy &&
!bindings.hasRuntimeImport &&
CANONICAL.has(expr.text as CanonicalProtobufFn) &&
!bindings.blockedLegacyCanonical.has(expr.text as CanonicalProtobufFn)
) {
fnName = expr.text as CanonicalProtobufFn;
}
} else if (ts.isPropertyAccessExpression(expr) && ts.isIdentifier(expr.expression)) {
if (bindings.namespaceAliases.has(expr.expression.text) && CANONICAL.has(expr.name.text as CanonicalProtobufFn)) {
fnName = expr.name.text as CanonicalProtobufFn;
exprStart = expr.getStart(sf);
}
}
if (!fnName) return null;
const lc = sf.getLineAndCharacterOfPosition(exprStart);
return {
fnName,
exprStart,
typeArgsEnd: ta.end + 1,
firstTypeArg: ta[0],
line: lc.line + 1,
column: lc.character + 1,
};
}
+165
View File
@@ -0,0 +1,165 @@
import ts from 'typescript';
import {
WireType,
PB_MARKER, PB_REPEATED_MARKER,
type ProtobufField, type ProtobufMessage,
type GenericProtobufTemplate, type GenericFieldTemplate,
} from './types.js';
import { isKeywordTypeNode, typeNodeToMangledName, type ImportedTypeNameResolver } from './utils.js';
function identityImportedTypeName(name: string): string {
return name;
}
/**
* Yield generic-instantiated type-arg nodes appearing as field types on a
* **concrete** (non-generic) interface — e.g. `wrapped: pb<5, Wrapper<uint_32>>`
* yields the `Wrapper<uint_32>` node so the analyzer can enqueue it for
* monomorphization. (The call-site-driven queue only sees the outer concrete
* type; nested generic instantiations on its fields would otherwise be missed.)
*/
export function* collectConcreteFieldGenericTypeArgs(
node: ts.InterfaceDeclaration,
resolveImportedTypeName: ImportedTypeNameResolver = identityImportedTypeName,
): IterableIterator<ts.TypeNode> {
if (node.typeParameters?.length) return;
for (const m of node.members) {
if (!ts.isPropertySignature(m) || !m.type) continue;
const parsed = parsePbTypeRef(m, resolveImportedTypeName);
if (!parsed) continue;
const ta = parsed.typeArgNode;
if (ts.isTypeReferenceNode(ta) && ta.typeArguments && ta.typeArguments.length > 0) {
yield ta;
}
}
}
/** Collect a concrete (non-generic) interface with pb<>/pb_repeated<> fields. */
export function collectInterface(
node: ts.InterfaceDeclaration,
sf: ts.SourceFile,
resolveImportedTypeName: ImportedTypeNameResolver = identityImportedTypeName,
): ProtobufMessage | null {
const fields: ProtobufField[] = [];
for (const m of node.members) {
if (!ts.isPropertySignature(m) || !m.type) continue;
const f = extractField(m, sf, resolveImportedTypeName);
if (f) fields.push(f);
}
// Register interfaces that are EXPLICITLY empty (`interface X {}`) as
// zero-field proto messages — proto3 wire format allows them and
// downstream code routinely uses them for "this OIDB call has no
// meaningful response body" placeholders. Interfaces that have
// members but no pb-marked fields are NOT proto messages — they
// belong to regular TS types and must stay unregistered to avoid
// polluting the registry.
if (fields.length === 0 && node.members.length > 0) return null;
return { name: node.name.text, fields };
}
/** Collect a generic interface template. */
export function collectGenericInterface(
node: ts.InterfaceDeclaration,
sf: ts.SourceFile,
resolveImportedTypeName: ImportedTypeNameResolver = identityImportedTypeName,
): GenericProtobufTemplate | null {
const typeParams = node.typeParameters!.map(p => p.name.text);
const tpSet = new Set(typeParams);
const fields: GenericFieldTemplate[] = [];
for (const m of node.members) {
if (!ts.isPropertySignature(m) || !m.type) continue;
const f = extractGenericField(m, sf, tpSet, resolveImportedTypeName);
if (f) fields.push(f);
}
return fields.length ? { name: node.name.text, typeParams, fields } : null;
}
// ── helpers ───────────────────────────────────────────────────────────
function parsePbTypeRef(
member: ts.PropertySignature,
resolveImportedTypeName: ImportedTypeNameResolver = identityImportedTypeName,
): { marker: string; fieldNumber: number; typeArgNode: ts.TypeNode } | null {
const t = member.type!;
if (!ts.isTypeReferenceNode(t) || !ts.isIdentifier(t.typeName)) return null;
// Resolve the marker name through aliased imports so `import { pb as P }`
// / `import { pb_repeated as PR }` still match the marker constants.
const marker = resolveImportedTypeName(t.typeName.text);
if (marker !== PB_MARKER && marker !== PB_REPEATED_MARKER) return null;
const ta = t.typeArguments;
if (!ta || ta.length !== 2) return null;
const fnNode = ta[0];
if (!ts.isLiteralTypeNode(fnNode) || !ts.isNumericLiteral(fnNode.literal)) return null;
return { marker, fieldNumber: Number(fnNode.literal.text), typeArgNode: ta[1] };
}
function resolveTypeName(
node: ts.TypeNode,
sf: ts.SourceFile,
resolveImportedTypeName: ImportedTypeNameResolver,
): string | null {
if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName)) {
// Generic instantiations (e.g. `Wrapper<uint_32>`) must resolve to the
// mangled name produced by monomorphization so wire-type resolution can
// find the message in the registry. Without this the field would carry
// the bare identifier `"Wrapper"` and never link to `Wrapper__uint_32`.
if (node.typeArguments && node.typeArguments.length > 0) {
return typeNodeToMangledName(node, sf, resolveImportedTypeName);
}
return resolveImportedTypeName(node.typeName.text);
}
if (isKeywordTypeNode(node)) return node.getText(sf);
return null;
}
function extractField(
member: ts.PropertySignature,
sf: ts.SourceFile,
resolveImportedTypeName: ImportedTypeNameResolver,
): ProtobufField | null {
const parsed = parsePbTypeRef(member, resolveImportedTypeName);
if (!parsed) return null;
const typeName = resolveTypeName(parsed.typeArgNode, sf, resolveImportedTypeName);
if (!typeName || !ts.isIdentifier(member.name)) return null;
return {
name: (member.name as ts.Identifier).text,
fieldNumber: parsed.fieldNumber,
typeName,
wireType: WireType.Varint, // placeholder
isMessage: false, // placeholder
isOptional: member.questionToken != null,
isRepeated: parsed.marker === PB_REPEATED_MARKER,
};
}
function extractGenericField(
member: ts.PropertySignature,
sf: ts.SourceFile,
tpSet: Set<string>,
resolveImportedTypeName: ImportedTypeNameResolver,
): GenericFieldTemplate | null {
const parsed = parsePbTypeRef(member, resolveImportedTypeName);
if (!parsed) return null;
const raw = resolveTypeName(parsed.typeArgNode, sf, resolveImportedTypeName);
if (!raw || !ts.isIdentifier(member.name)) return null;
const result: GenericFieldTemplate = {
name: (member.name as ts.Identifier).text,
fieldNumber: parsed.fieldNumber,
rawTypeName: tpSet.has(raw) ? raw : resolveImportedTypeName(raw),
isTypeParam: tpSet.has(raw),
isOptional: member.questionToken != null,
isRepeated: parsed.marker === PB_REPEATED_MARKER,
};
// If the field's type-arg is itself a generic instantiation (`Wrapper<U>`,
// where U is a type param of the enclosing template), capture the original
// source text so monomorphization can substitute U and re-instantiate the
// inner generic. Without this the field's `rawTypeName` would stay at the
// unsubstituted `'Wrapper__U'` form and the substituted instantiation
// would never reach the registry.
const ta = parsed.typeArgNode;
if (ts.isTypeReferenceNode(ta) && ta.typeArguments && ta.typeArguments.length > 0) {
result.genericTypeArgText = ta.getText(sf);
result.genericTypeArgSourceFilePath = sf.fileName;
}
return result;
}
@@ -0,0 +1,32 @@
import type { MessageRegistry } from './types.js';
export function collectDependencyClosure(registry: MessageRegistry, roots: Iterable<string>): Set<string> {
const selected = new Set<string>();
function visit(name: string): void {
if (selected.has(name)) return;
const msg = registry.get(name);
if (!msg) return;
selected.add(name);
for (const field of msg.fields) {
if (registry.has(field.typeName)) visit(field.typeName);
}
}
for (const root of roots) visit(root);
return selected;
}
export function pickRegistrySubset(registry: MessageRegistry, selectedNames: Set<string>): MessageRegistry {
const subset: MessageRegistry = new Map();
for (const [name, msg] of registry) {
if (selectedNames.has(name)) subset.set(name, msg);
}
return subset;
}
export function buildDependencyRegistry(registry: MessageRegistry, roots: Iterable<string>): MessageRegistry {
const selected = collectDependencyClosure(registry, roots);
return pickRegistrySubset(registry, selected);
}
Loaded 100 of 168 files, more files were not shown because too many files have changed in this diff. Show more