Migrate project to pnpm monorepo

Restructure the repository into a pnpm workspace under packages/ (core, webui, runtime). Move source files for core and webui into packages/*, add package manifests for @snowluma/core and @snowluma/runtime, and remove the old launcher package.json. Update root package.json to be a monorepo controller (scripts delegate to pnpm filters, set packageManager and Node engine). Configure build outputs to emit into the repo-root dist/ (vite config changes) so the existing release pipeline continues to work. Add .npmrc with mirrors, expand .gitignore for monorepo layout, add tsconfig base and package-level tsconfigs, and add vitest config for the core package. Adjust injector native search paths and update tests import paths to the new package layout. Small CI/workflow comment added to clarify build behavior and README updated with monorepo structure and common commands.
This commit is contained in:
手瓜一十雪 committed 2026-05-03 14:02:29 +08:00
1 parent 6bba36bba6
commit 39f1672b29
122 files changed
+279 -85

No files matched your search

+32
View File
@@ -0,0 +1,32 @@
{
"name": "@snowluma/core",
"version": "0.1.0",
"description": "SnowLuma core - NTQQ packet sniffer with Node.js native addon",
"private": true,
"type": "module",
"main": "../../dist/index.mjs",
"scripts": {
"build": "vite build",
"build:all": "cross-env BUILD_WEBUI=true vite build",
"dev": "tsx src/index.ts",
"test": "vitest run",
"test:watch": "vitest",
"typecheck": "tsc --noEmit"
},
"dependencies": {
"ws": "^8.20.0"
},
"devDependencies": {
"@hono/node-server": "^1.19.14",
"@rollup/plugin-node-resolve": "^16.0.3",
"@types/node": "^24.12.2",
"@types/ws": "^8.18.1",
"cross-env": "^10.1.0",
"hono": "^4.12.14",
"tsx": "^4.21.0",
"typescript": "catalog:",
"vite": "catalog:",
"vite-plugin-cp": "^6.0.3",
"vitest": "^4.1.4"
}
}
File diff suppressed because it is too large. Load diff
+335
View File
@@ -0,0 +1,335 @@
// Contact / info-fetching operations extracted from Bridge.
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 { sendOidbAndDecode } 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';
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
export function buildFriendProperties(raw: any): Map<number, string> {
const props = new Map<number, string>();
for (const additional of raw.additional ?? []) {
if ((additional.type ?? 0) !== 1 || !additional.layer1) continue;
for (const property of additional.layer1.properties ?? []) {
props.set(property.code ?? 0, property.value ?? '');
}
}
return props;
}
export function permissionToRole(permission: number): string {
switch (permission) {
case 1: return 'owner';
case 2: return 'admin';
default: return 'member';
}
}
// ---------------------------------------------------------------------------
// Friend list
// ---------------------------------------------------------------------------
export async function fetchFriendList(bridge: Bridge): Promise<FriendInfo[]> {
const friends: FriendInfo[] = [];
let nextUin: number | null = null;
do {
const body: any = {
friendCount: 300,
field4: 0,
field6: 1,
field7: 0x7FFFFFFF,
body: [
{ type: 1, number: { numbers: [103, 102, 20002, 27394] } },
{ type: 4, number: { numbers: [100, 101, 102] } },
],
field10002: [13578, 13579, 13573, 13572, 13568],
field10003: 4051,
};
if (nextUin !== null) {
body.nextUin = { uin: nextUin };
}
const resp = await sendOidbAndDecode<any>(
bridge, 'OidbSvcTrpcTcp.0xfd4_1', 0xFD4, 1, body,
OidbFriendListRequestSchema, OidbSvcTrpcTcp0xFD4_1ResponseSchema);
if (resp?.friends) {
for (const raw of resp.friends) {
const props = buildFriendProperties(raw);
friends.push({
uin: raw.uin ?? 0,
uid: raw.uid ?? '',
nickname: props.get(20002) ?? String(raw.uin ?? 0),
remark: props.get(103) ?? '',
});
}
}
nextUin = resp?.next?.uin ?? null;
if (nextUin === 0) nextUin = null;
} while (nextUin !== null);
bridge.qqInfo.setFriends(friends);
return friends;
}
// ---------------------------------------------------------------------------
// Group list
// ---------------------------------------------------------------------------
export async function fetchGroupList(bridge: Bridge): Promise<QQGroupInfo[]> {
const allTrue = true;
const body = {
config: {
config1: {
groupOwner: allTrue, field2: allTrue, memberMax: allTrue, memberCount: allTrue,
groupName: allTrue, field8: allTrue, field9: allTrue, field10: allTrue,
field11: allTrue, field12: allTrue, field13: allTrue, field14: allTrue,
field15: allTrue, field16: allTrue, field17: allTrue, field18: allTrue,
question: allTrue, field20: allTrue, field22: allTrue, field23: allTrue,
field24: allTrue, field25: allTrue, field26: allTrue, field27: allTrue,
field28: allTrue, field29: allTrue, field30: allTrue, field31: allTrue,
field32: allTrue, field5001: allTrue, field5002: allTrue, field5003: allTrue,
},
config2: {
field1: allTrue, field2: allTrue, field3: allTrue, field4: allTrue,
field5: allTrue, field6: allTrue, field7: allTrue, field8: allTrue,
},
config3: { field5: allTrue, field6: allTrue },
},
};
const resp = await sendOidbAndDecode<any>(
bridge, 'OidbSvcTrpcTcp.0xfe5_2', 0xFE5, 2, body,
OidbGroupListRequestSchema, OidbSvcTrpcTcp0xFE5_2ResponseSchema, true);
const groups: QQGroupInfo[] = [];
if (resp?.groups) {
for (const raw of resp.groups) {
groups.push({
groupId: raw.groupUin ?? 0,
groupName: raw.info?.groupName ?? '',
remark: raw.customInfo?.remark ?? '',
memberCount: raw.info?.memberCount ?? 0,
memberMax: raw.info?.memberMax ?? 0,
members: new Map(),
});
}
}
bridge.qqInfo.setGroups(groups);
return groups;
}
// ---------------------------------------------------------------------------
// Group member list
// ---------------------------------------------------------------------------
export async function fetchGroupMemberList(bridge: Bridge, groupId: number): Promise<GroupMemberInfo[]> {
const members: GroupMemberInfo[] = [];
let token = '';
do {
const body: any = {
groupUin: groupId,
field2: 5,
field3: 2,
body: {
memberName: true, memberCard: true, level: true, field13: true,
field16: true, specialTitle: true, field18: true, field20: true,
field21: true, joinTimestamp: true, lastMsgTimestamp: true,
shutUpTimestamp: true, field103: true, field104: true, field105: true,
field106: true, permission: true, field200: true, field201: true,
},
};
if (token) body.token = token;
const resp = await sendOidbAndDecode<any>(
bridge, 'OidbSvcTrpcTcp.0xfe7_3', 0xFE7, 3, body,
OidbGroupMemberListRequestSchema, OidbSvcTrpcTcp0xFE7_3ResponseSchema);
if (resp?.members) {
for (const raw of resp.members) {
members.push({
uin: raw.uin?.uin ?? 0,
uid: raw.uin?.uid ?? '',
nickname: raw.memberName ?? '',
card: raw.memberCard?.memberCard ?? '',
role: permissionToRole(raw.permission ?? 0),
level: raw.level?.level ?? 0,
title: raw.specialTitle ?? '',
joinTime: raw.joinTimestamp ?? 0,
lastSentTime: raw.lastMsgTimestamp ?? 0,
shutUpTime: raw.shutUpTimestamp ?? 0,
});
}
}
token = resp?.token ?? '';
} while (token);
bridge.qqInfo.setGroupMembers(groupId, members);
return members;
}
// ---------------------------------------------------------------------------
// User profile
// ---------------------------------------------------------------------------
export async function fetchUserProfile(bridge: Bridge, uin: number): Promise<UserProfileInfo> {
const keys = [20002, 27394, 20009, 20031, 101, 103, 102, 20020, 20003, 20026, 105, 27372, 27406, 20037];
const body = {
uin,
field2: 0,
keys: keys.map(k => ({ key: k })),
};
const resp = await sendOidbAndDecode<any>(
bridge, 'OidbSvcTrpcTcp.0xfe1_2', 0xFE1, 2, body,
OidbUserInfoRequestSchema, OidbUserInfoResponseSchema);
if (!resp?.body) throw new Error('user info response body missing');
const info: UserProfileInfo = {
uin: resp.body.uin ?? uin,
uid: resp.body.uid ?? '',
nickname: '', remark: '', qid: '', sex: 'unknown', age: 0, sign: '', avatar: '',
};
if (resp.body.properties) {
const bytesMap = new Map<number, Uint8Array>();
const numMap = new Map<number, number>();
for (const bp of resp.body.properties.bytesProperties ?? []) {
bytesMap.set(bp.code ?? 0, bp.value ?? new Uint8Array(0));
}
for (const np of resp.body.properties.numberProperties ?? []) {
numMap.set(np.number1 ?? 0, np.number2 ?? 0);
}
const getString = (code: number) => {
const b = bytesMap.get(code);
return b ? Buffer.from(b).toString('utf8') : '';
};
info.nickname = getString(20002);
info.remark = getString(103);
info.qid = getString(27394);
info.sign = getString(102);
const avatarBytes = bytesMap.get(101);
if (avatarBytes) {
const av = protoDecode(avatarBytes, AvatarInfoSchema);
if (av?.url) info.avatar = av.url + '640';
}
const sexNum = numMap.get(20009) ?? 0;
info.sex = sexNum === 1 ? 'male' : sexNum === 2 ? 'female' : 'unknown';
info.age = numMap.get(20037) ?? 0;
}
bridge.qqInfo.setUserProfile(info);
const selfUin = parseInt(bridge.qqInfo.uin, 10) || 0;
if (info.uin === selfUin) bridge.qqInfo.setSelfProfile(info);
return info;
}
// ---------------------------------------------------------------------------
// Group requests
// ---------------------------------------------------------------------------
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 sendOidbAndDecode<any>(
bridge, cmd, 0x10C0, subCmd, { count: 20, field2: 0 },
OidbGroupRequestListSchema, OidbSvcTrpcTcp0x10C0ResponseSchema);
const requests: GroupRequestInfo[] = [];
for (const raw of resp?.requests ?? []) {
requests.push({
groupId: raw.group?.groupUin ?? 0,
groupName: raw.group?.groupName ?? '',
targetUid: raw.target?.uid ?? '',
targetUin: 0,
targetName: raw.target?.name ?? '',
invitorUid: raw.invitor?.uid ?? '',
invitorUin: 0,
invitorName: raw.invitor?.name ?? '',
operatorUid: raw.operatorUser?.uid ?? '',
operatorUin: 0,
operatorName: raw.operatorUser?.name ?? '',
sequence: Number(raw.sequence ?? 0),
state: raw.state ?? 0,
eventType: raw.eventType ?? 0,
comment: raw.comment ?? '',
filtered,
});
}
return requests;
}
// ---------------------------------------------------------------------------
// Download RKeys
// ---------------------------------------------------------------------------
export async function fetchDownloadRKeys(bridge: Bridge): Promise<DownloadRKeyInfo[]> {
const PRIVATE_IMAGE = 10;
const GROUP_IMAGE = 20;
const FALLBACK_IMAGE = 2;
const body = {
reqHead: {
common: { requestId: 1, command: 202 },
scene: { requestType: 2, businessType: 1, sceneType: 0 },
client: { agentType: 2 },
},
downloadRkey: {
types: [PRIVATE_IMAGE, GROUP_IMAGE, FALLBACK_IMAGE],
},
};
const resp = await sendOidbAndDecode<any>(
bridge, 'OidbSvcTrpcTcp.0x9067_202', 0x9067, 202, body,
NTV2RichMediaReqSchema, NTV2RichMediaRespSchema, true);
if (resp?.respHead?.retCode && resp.respHead.retCode !== 0) {
throw new Error(resp.respHead.message ?? 'fetch download rkey failed');
}
const result: DownloadRKeyInfo[] = [];
for (const entry of resp?.downloadRkey?.rkeys ?? []) {
const rkey = entry.rkey ?? '';
const type = entry.type ?? 0;
if (rkey && type) {
result.push({
rkey,
ttlSeconds: Number(entry.rkeyTtlSec ?? 0),
storeId: entry.storeId ?? 0,
createTime: entry.rkeyCreateTime ?? 0,
type,
});
}
}
return result;
}
+91
View File
@@ -0,0 +1,91 @@
// OIDB protocol helpers -- encode requests, send+check, send+decode, UID resolution.
import type { Bridge } from './bridge';
import type { ProtoSchema } from '../protobuf/decode';
import { protoEncode, protoDecode } from '../protobuf/decode';
import { makeOidbBaseSchema } from './proto/oidb';
/**
* Build a raw OIDB request buffer (base envelope wrapping a typed body).
*/
export function makeOidbRequest(
command: number, subCommand: number,
body: any, bodySchema: ProtoSchema, isUid = false,
): Uint8Array {
const baseSchema = makeOidbBaseSchema(bodySchema);
return protoEncode({
command,
subCommand,
errorCode: 0,
body,
errorMsg: '',
reserved: isUid ? 1 : 0,
}, baseSchema);
}
/**
* Send an OIDB packet and verify it succeeded (no decode of body).
*/
export async function sendOidbAndCheck(
bridge: Bridge,
serviceCmd: string, command: number, subCommand: number,
body: any, bodySchema: ProtoSchema, isUid = false,
): Promise<void> {
const request = makeOidbRequest(command, subCommand, body, bodySchema, isUid);
const result = await bridge.sendRawPacket(serviceCmd, request);
if (!result.success) throw new Error(result.errorMessage || 'packet send failed');
if (!result.gotResponse) throw new Error(result.errorMessage || 'no response');
// Check OIDB error code if response present
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 && (resp as any).errorCode && (resp as any).errorCode !== 0) {
throw new Error(`OIDB error ${(resp as any).errorCode}: ${(resp as any).errorMsg ?? ''}`);
}
}
}
/**
* Send an OIDB packet and decode the response body with the given schema.
*/
export async function sendOidbAndDecode<T>(
bridge: Bridge,
serviceCmd: string, command: number, subCommand: number,
body: any, bodySchema: ProtoSchema, responseSchema: ProtoSchema, isUid = false,
): Promise<T> {
const request = makeOidbRequest(command, subCommand, body, bodySchema, isUid);
const result = await bridge.sendRawPacket(serviceCmd, request);
if (!result.success) throw new Error(result.errorMessage || 'packet send failed');
if (!result.gotResponse || !result.responseData) throw new Error(result.errorMessage || 'no response');
const baseSchema = makeOidbBaseSchema(responseSchema);
const resp = protoDecode(result.responseData, baseSchema);
if (!resp) throw new Error('failed to decode OIDB response');
if ((resp as any).errorCode && (resp as any).errorCode !== 0) {
throw new Error(`OIDB error ${(resp as any).errorCode}: ${(resp as any).errorMsg ?? ''}`);
}
return (resp as any).body as T;
}
/**
* Resolve a UIN to a UID string, using cache or fetching as needed.
* Mirrors C++ resolve_user_uid_for_action.
*/
export async function resolveUserUid(bridge: Bridge, uin: number, groupId?: number): Promise<string> {
// Try group member first
if (groupId !== undefined) {
const uid = bridge.qqInfo.findUidByUinInGroup(groupId, uin);
if (uid) return uid;
// Try fetching member list
try { await bridge.fetchGroupMemberList(groupId); } catch { /* ignore */ }
const uid2 = bridge.qqInfo.findUidByUinInGroup(groupId, uin);
if (uid2) return uid2;
}
// Try cached
const uid = bridge.qqInfo.findUidByUin(uin);
if (uid) return uid;
// Fetch profile
const profile = await bridge.fetchUserProfile(uin);
if (profile.uid) return profile.uid;
throw new Error(`failed to resolve UID for UIN ${uin}`);
}
+495
View File
@@ -0,0 +1,495 @@
// Bridge — per-UIN session: handler registration, packet dispatch, event routing.
// Supports packet sending via native addon.
// Heavy OIDB / contact / action logic is split into bridge-oidb, bridge-contacts, bridge-actions.
import type { PacketInfo } from '../protocol/types';
import type { ForwardNodePayload, QQEventVariant, MessageElement } from './events';
import type { FriendInfo, QQGroupInfo, GroupMemberInfo, UserProfileInfo, GroupRequestInfo } from './qq-info';
import { QQInfo } from './qq-info';
import { MSG_PUSH_CMD, parseMsgPush } from './handlers/msg-push-handler';
import type { PacketSender, SendPacketResult } from '../protocol/packet-sender';
import { protoEncode, protoDecode } from '../protobuf/decode';
import { buildSendElems } from './builders/element-builder';
import { createLogger } from '../utils/logger';
import {
SendMessageRequestSchema,
SendMessageResponseSchema,
} from './proto/action';
// Delegated modules
import { resolveUserUid as resolveUserUid_ } from './bridge-oidb';
import {
fetchFriendList as fetchFriendList_,
fetchGroupList as fetchGroupList_,
fetchGroupMemberList as fetchGroupMemberList_,
fetchUserProfile as fetchUserProfile_,
fetchGroupRequests as fetchGroupRequests_,
fetchDownloadRKeys as fetchDownloadRKeys_,
} from './bridge-contacts';
import {
muteGroupMember as muteGroupMember_,
muteGroupAll as muteGroupAll_,
kickGroupMember as kickGroupMember_,
leaveGroup as leaveGroup_,
setGroupAdmin as setGroupAdmin_,
setGroupCard as setGroupCard_,
setGroupName as setGroupName_,
setGroupSpecialTitle as setGroupSpecialTitle_,
setFriendAddRequest as setFriendAddRequest_,
deleteFriend as deleteFriend_,
uploadGroupFile as uploadGroupFile_,
uploadPrivateFile as uploadPrivateFile_,
fetchGroupFiles as fetchGroupFiles_,
fetchGroupFileUrl as fetchGroupFileUrl_,
fetchPrivateFileUrl as fetchPrivateFileUrl_,
fetchGroupPttUrlByNode as fetchGroupPttUrlByNode_,
fetchPrivatePttUrlByNode as fetchPrivatePttUrlByNode_,
fetchGroupVideoUrlByNode as fetchGroupVideoUrlByNode_,
fetchPrivateVideoUrlByNode as fetchPrivateVideoUrlByNode_,
uploadForwardNodes as uploadForwardNodes_,
fetchForwardNodes as fetchForwardNodes_,
deleteGroupFile as deleteGroupFile_,
moveGroupFile as moveGroupFile_,
createGroupFileFolder as createGroupFileFolder_,
deleteGroupFileFolder as deleteGroupFileFolder_,
renameGroupFileFolder as renameGroupFileFolder_,
setGroupAddRequest as setGroupAddRequest_,
sendPoke as sendPoke_,
sendLike as sendLike_,
setGroupEssence as setGroupEssence_,
setGroupReaction as setGroupReaction_,
recallGroupMessage as recallGroupMessage_,
recallPrivateMessage as recallPrivateMessage_,
setFriendRemark as setFriendRemark_,
fetchGroupFileCount as fetchGroupFileCount_,
} from './bridge-actions';
import type { GroupFilesResult } from './bridge-actions';
import type { MediaIndexNode } from './bridge-actions';
export type BridgeEventCallback = (event: QQEventVariant) => void;
type CmdParser = (pkt: PacketInfo, qqInfo: QQInfo) => QQEventVariant[];
export interface SendMessageReceipt {
messageId: number;
sequence: number;
clientSequence: number;
random: number;
timestamp: number;
}
export interface DownloadRKeyInfo {
rkey: string;
ttlSeconds: number;
storeId: number;
createTime: number;
type: number;
}
const log = createLogger('Bridge');
const eventLog = createLogger('Event');
export class Bridge {
private static readonly SEND_MSG_CMD = 'MessageSvc.PbSendMsg';
private qqInfo_: QQInfo;
private pids_ = new Set<number>();
private eventCallback_: BridgeEventCallback | null = null;
private cmdHandlers_ = new Map<string, CmdParser[]>();
private packetClient_: PacketSender | null = null;
private memberRefreshTasks_ = new Map<number, Promise<void>>();
// Sequence and random generators for outgoing messages
private clientSeq_ = 100000000 + (Date.now() % 1000000000);
private msgRandom_ = (Date.now() & 0xFFFFFFFF) >>> 0;
constructor(qqInfo: QQInfo) {
this.qqInfo_ = qqInfo;
this.registerDefaultHandlers();
}
get qqInfo(): QQInfo { return this.qqInfo_; }
setPacketClient(client: PacketSender): void {
this.packetClient_ = client;
}
private registerDefaultHandlers(): void {
this.registerCmd(MSG_PUSH_CMD, parseMsgPush);
}
registerCmd(cmd: string, parser: CmdParser): void {
const arr = this.cmdHandlers_.get(cmd) ?? [];
arr.push(parser);
this.cmdHandlers_.set(cmd, arr);
}
setEventCallback(cb: BridgeEventCallback): void {
this.eventCallback_ = cb;
}
handlesCmd(cmd: string): boolean {
return this.cmdHandlers_.has(cmd);
}
// --- PID management ---
attachPid(pid: number): void {
this.pids_.add(pid);
}
detachPid(pid: number): void {
this.pids_.delete(pid);
}
hasPid(pid: number): boolean { return this.pids_.has(pid); }
get empty(): boolean { return this.pids_.size === 0; }
get activePid(): number | null {
for (const pid of this.pids_) return pid;
return null;
}
// --- Packet dispatch ---
onPacket(pkt: PacketInfo): void {
const handlers = this.cmdHandlers_.get(pkt.serviceCmd);
if (!handlers) return;
for (const handler of handlers) {
try {
const events = handler(pkt, this.qqInfo_);
for (const event of events) {
this.triggerMemberCacheRefresh(event);
printEvent(event);
this.emitEvent(event);
}
} catch (e) {
log.error('handler error for %s: %s', pkt.serviceCmd, e instanceof Error ? (e.stack ?? e.message) : String(e));
}
}
}
private emitEvent(event: QQEventVariant): void {
if (this.eventCallback_) {
try { this.eventCallback_(event); } catch (e) {
log.error('event callback error: %s', e instanceof Error ? (e.stack ?? e.message) : String(e));
}
}
}
private triggerMemberCacheRefresh(event: QQEventVariant): void {
let groupId = 0;
let reason = '';
switch (event.kind) {
case 'group_member_join':
groupId = event.groupId;
reason = 'group_member_join';
break;
case 'group_member_leave':
groupId = event.groupId;
reason = 'group_member_leave';
break;
case 'group_admin':
groupId = event.groupId;
reason = 'group_admin';
break;
default:
return;
}
if (groupId <= 0) return;
if (this.memberRefreshTasks_.has(groupId)) return;
const task = (async () => {
try {
if (!this.qqInfo_.findGroup(groupId)) {
try { await this.fetchGroupList(); } catch { /* ignore */ }
}
await this.fetchGroupMemberList(groupId);
log.debug('member cache refreshed: group=%d reason=%s', groupId, reason);
} catch (e) {
log.warn('failed to refresh member cache: group=%d reason=%s err=%s',
groupId, reason, e instanceof Error ? e.message : String(e));
} finally {
this.memberRefreshTasks_.delete(groupId);
}
})();
this.memberRefreshTasks_.set(groupId, task);
}
// --- Sequence / random generators ---
private nextClientSequence(): number {
return ++this.clientSeq_;
}
private nextMessageRandom(): number {
this.msgRandom_ = (this.msgRandom_ + 0x9E3779B9) >>> 0;
return this.msgRandom_ & 0x7FFFFFFF;
}
// --- Send packet (raw) ---
async sendRawPacket(serviceCmd: string, body: Uint8Array, timeoutMs = 15000): Promise<SendPacketResult> {
if (!this.packetClient_) {
return {
success: false, gotResponse: false, errorCode: -1,
errorMessage: 'no packet sender attached', responseData: null,
};
}
return this.packetClient_.sendPacket(serviceCmd, Buffer.from(body), timeoutMs);
}
// --- Send message (high-level) ---
async sendGroupMessage(groupId: number, elements: MessageElement[]): Promise<SendMessageReceipt> {
if (elements.length === 0) throw new Error('message is empty');
const protoElems = await buildSendElems(elements, { bridge: this, groupId });
const random = this.nextMessageRandom();
const request = protoEncode({
routingHead: {
grp: { groupCode: BigInt(groupId) },
} as any,
contentHead: {
type: 1,
} as any,
messageBody: {
richText: {
elems: protoElems,
},
} as any,
clientSequence: 0,
random,
syncCookie: new Uint8Array(0),
via: 0,
dataStatist: 0,
multiSendSeq: 0,
}, SendMessageRequestSchema);
const result = await this.sendRawPacket(Bridge.SEND_MSG_CMD, request);
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(`send group message failed: ${result.errorMessage || 'no response'}`);
}
const response = protoDecode(result.responseData, SendMessageResponseSchema);
if (!response) {
throw new Error('failed to decode SendMessageResponse');
}
if (response.result !== undefined && response.result !== 0) {
throw new Error(`send group message rejected: result=${response.result} err=${response.errMsg ?? ''}`);
}
const seq = response.groupSequence ?? 0;
const messageId = (random & 0x7FFFFFFF) || seq;
const timestamp = response.timestamp1 ?? Math.floor(Date.now() / 1000);
return {
messageId,
sequence: seq,
clientSequence: 0,
random,
timestamp,
};
}
async sendPrivateMessage(userUin: number, elements: MessageElement[]): Promise<SendMessageReceipt> {
if (elements.length === 0) throw new Error('message is empty');
// Resolve UID for image upload (C++ resolves UID before building elems)
let userUid = '';
const hasMedia = elements.some(e => e.type === 'image' || e.type === 'record' || e.type === 'video');
if (hasMedia) {
userUid = await this.resolveUserUid(userUin);
}
const protoElems = await buildSendElems(elements, { bridge: this, userUid });
const random = this.nextMessageRandom();
const clientSeq = this.nextClientSequence();
const request = protoEncode({
routingHead: {
c2c: {
uin: userUin,
},
} as any,
contentHead: {
type: 1,
subType: 0,
c2cCmd: 11,
} as any,
messageBody: {
richText: {
elems: protoElems,
},
} as any,
clientSequence: clientSeq,
random,
syncCookie: new Uint8Array(0),
via: 0,
dataStatist: 0,
ctrl: {
msgFlag: Math.floor(Date.now() / 1000),
} as any,
multiSendSeq: 0,
}, SendMessageRequestSchema);
const result = await this.sendRawPacket(Bridge.SEND_MSG_CMD, request);
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(`send private message failed: ${result.errorMessage || 'no response'}`);
}
const response = protoDecode(result.responseData, SendMessageResponseSchema);
if (!response) {
throw new Error('failed to decode SendMessageResponse');
}
if (response.result !== undefined && response.result !== 0) {
throw new Error(`send private 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> {
return resolveUserUid_(this, uin, groupId);
}
// --- Delegated: Contact / info queries ---
async fetchFriendList(): Promise<FriendInfo[]> { return fetchFriendList_(this); }
async fetchGroupList(): Promise<QQGroupInfo[]> { return fetchGroupList_(this); }
async fetchGroupMemberList(groupId: number): Promise<GroupMemberInfo[]> { return fetchGroupMemberList_(this, groupId); }
async fetchUserProfile(uin: number): Promise<UserProfileInfo> { return fetchUserProfile_(this, uin); }
async fetchGroupRequests(filtered = false): Promise<GroupRequestInfo[]> { return fetchGroupRequests_(this, filtered); }
async fetchDownloadRKeys(): Promise<DownloadRKeyInfo[]> { return fetchDownloadRKeys_(this); }
// --- Delegated: Admin / action methods ---
async muteGroupMember(groupId: number, userId: number, duration: number): Promise<void> { return muteGroupMember_(this, groupId, userId, duration); }
async muteGroupAll(groupId: number, enable: boolean): Promise<void> { return muteGroupAll_(this, groupId, enable); }
async kickGroupMember(groupId: number, userId: number, reject: boolean, reason = ''): Promise<void> { return kickGroupMember_(this, groupId, userId, reject, reason); }
async leaveGroup(groupId: number): Promise<void> { return leaveGroup_(this, groupId); }
async setGroupAdmin(groupId: number, userId: number, enable: boolean): Promise<void> { return setGroupAdmin_(this, groupId, userId, enable); }
async setGroupCard(groupId: number, userId: number, card: string): Promise<void> { return setGroupCard_(this, groupId, userId, card); }
async setGroupName(groupId: number, name: string): Promise<void> { return setGroupName_(this, groupId, name); }
async setGroupSpecialTitle(groupId: number, userId: number, title: string): Promise<void> { return setGroupSpecialTitle_(this, groupId, userId, title); }
async setFriendAddRequest(uidOrFlag: string, approve: boolean): Promise<void> { return setFriendAddRequest_(this, uidOrFlag, approve); }
async deleteFriend(userId: number, block = false): Promise<void> { return deleteFriend_(this, userId, block); }
async uploadGroupFile(groupId: number, file: string, name = '', folderId = '/', uploadFile = true): Promise<{ fileId: string | null }> {
return uploadGroupFile_(this, groupId, file, name, folderId, uploadFile);
}
async uploadPrivateFile(userId: number, file: string, name = '', uploadFile = true): Promise<{ fileId: string | null }> {
return uploadPrivateFile_(this, userId, file, name, uploadFile);
}
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); }
async fetchGroupPttUrlByNode(groupId: number, node: MediaIndexNode): Promise<string> { return fetchGroupPttUrlByNode_(this, groupId, node); }
async fetchPrivatePttUrlByNode(node: MediaIndexNode): Promise<string> { return fetchPrivatePttUrlByNode_(this, node); }
async fetchGroupVideoUrlByNode(groupId: number, node: MediaIndexNode): Promise<string> { return fetchGroupVideoUrlByNode_(this, groupId, node); }
async fetchPrivateVideoUrlByNode(node: MediaIndexNode): Promise<string> { return fetchPrivateVideoUrlByNode_(this, node); }
async uploadForwardNodes(nodes: ForwardNodePayload[], groupId?: number): Promise<string> { return uploadForwardNodes_(this, nodes, groupId); }
async fetchForwardNodes(resId: string): Promise<ForwardNodePayload[]> { return fetchForwardNodes_(this, resId); }
async deleteGroupFile(groupId: number, fileId: string): Promise<void> { return deleteGroupFile_(this, groupId, fileId); }
async moveGroupFile(groupId: number, fileId: string, parentDirectory: string, targetDirectory: string): Promise<void> { return moveGroupFile_(this, groupId, fileId, parentDirectory, targetDirectory); }
async createGroupFileFolder(groupId: number, name: string, parentId = '/'): Promise<void> { return createGroupFileFolder_(this, groupId, name, parentId); }
async deleteGroupFileFolder(groupId: number, folderId: string): Promise<void> { return deleteGroupFileFolder_(this, groupId, folderId); }
async renameGroupFileFolder(groupId: number, folderId: string, newFolderName: string): Promise<void> { return renameGroupFileFolder_(this, groupId, folderId, newFolderName); }
async setGroupAddRequest(groupId: number, sequence: number, eventType: number, approve: boolean, reason = '', filtered = false): Promise<void> { return setGroupAddRequest_(this, groupId, sequence, eventType, approve, reason, filtered); }
async sendPoke(isGroup: boolean, peerUin: number, targetUin?: number): Promise<void> { return sendPoke_(this, isGroup, peerUin, targetUin); }
async sendLike(userId: number, count: number): Promise<void> { return sendLike_(this, userId, count); }
async setGroupEssence(groupId: number, sequence: number, random: number, enable: boolean): Promise<void> { return setGroupEssence_(this, groupId, sequence, random, enable); }
async setGroupReaction(groupId: number, sequence: number, code: string, isSet: boolean): Promise<void> { return setGroupReaction_(this, groupId, sequence, code, isSet); }
async recallGroupMessage(groupId: number, sequence: number): Promise<void> { return recallGroupMessage_(this, groupId, sequence); }
async recallPrivateMessage(userUin: number, clientSeq: number, msgSeq: number, random: number, timestamp: number): Promise<void> { return recallPrivateMessage_(this, userUin, clientSeq, msgSeq, random, timestamp); }
async setFriendRemark(userId: number, remark: string): Promise<void> { return setFriendRemark_(this, userId, remark); }
async fetchGroupFileCount(groupId: number): Promise<{ fileCount: number; maxCount: number }> { return fetchGroupFileCount_(this, groupId); }
}
// --- Module-level helper functions ---
function elementsToText(elements: MessageElement[]): string {
return elements.map(e => {
switch (e.type) {
case 'text': return e.text ?? '';
case 'at': return `@${e.targetUin ?? 'all'}`;
case 'face': return `[表情:${e.faceId}]`;
case 'mface': return `[${e.summary ?? '表情'}]`;
case 'image': return '[图片]';
case 'video': return '[视频]';
case 'record': return '[语音]';
case 'file': return `[文件:${e.fileName ?? ''}]`;
case 'json': return '[JSON卡片]';
case 'xml': return '[XML卡片]';
case 'reply': return `[回复:${e.replySeq}]`;
case 'poke': return '[戳一戳]';
case 'forward': return '[合并转发]';
case 'markdown': return '[Markdown]';
default: return `[${e.type}]`;
}
}).join('');
}
function printEvent(event: QQEventVariant): void {
switch (event.kind) {
case 'group_message': {
const c = elementsToText(event.elements);
const s = event.senderCard || event.senderNick || String(event.senderUin);
eventLog.success('群 %d | %s(%d): %s', event.groupId, s, event.senderUin, c);
break;
}
case 'friend_message':
eventLog.info('私聊 %s(%d): %s', event.senderNick || String(event.senderUin), event.senderUin, elementsToText(event.elements));
break;
case 'temp_message':
eventLog.info('临时 %d(群%d): %s', event.senderUin, event.groupId, elementsToText(event.elements));
break;
case 'group_recall':
eventLog.warn('群撤回 %d | %d 被 %d 撤回', event.groupId, event.authorUin, event.operatorUin);
break;
case 'friend_recall':
eventLog.warn('私聊撤回 %d 撤回了消息', event.userUin);
break;
case 'group_member_join':
eventLog.info('入群 %d 加入 %d', event.userUin, event.groupId);
break;
case 'group_member_leave':
eventLog.warn('退群 %d %s %d', event.userUin, event.isKick ? '被踢出' : '退出', event.groupId);
break;
case 'group_mute':
eventLog.warn('禁言 %d | %d %d秒', event.groupId, event.userUin, event.duration);
break;
case 'group_admin':
eventLog.info('管理 %d | %d %s管理员', event.groupId, event.userUin, event.set ? '+' : '-');
break;
case 'friend_poke':
eventLog.info('戳一戳 %d -> %d', event.userUin, event.targetUin);
break;
case 'group_poke':
eventLog.info('群戳 %d | %d -> %d', event.groupId, event.userUin, event.targetUin);
break;
case 'friend_request':
eventLog.warn('好友请求 %d: %s', event.fromUin, event.message);
break;
case 'group_invite':
eventLog.warn('群邀请 %d -> 群%d', event.fromUin, event.groupId);
break;
case 'group_essence':
eventLog.info('精华 %d | %s精华', event.groupId, event.set ? '+' : '-');
break;
}
}
@@ -0,0 +1,206 @@
// Element Builder — converts internal MessageElement[] into proto Elem objects
// for encoding with protoEncode(SendMessageRequestSchema).
// Port of src/bridge/src/bridge_messages.cpp build_send_elems()
import type { Bridge } from '../bridge';
import type { MessageElement } from '../events';
import type { ProtoDecoded } from '../../protobuf/decode';
import { protoEncode } from '../../protobuf/decode';
import {
ElemSchema,
} from '../proto/element';
import {
MentionExtraSendSchema,
MarkdownDataSchema,
} from '../proto/action';
import { uploadImageMsgInfo } from '../highway/image-upload';
type ProtoElem = Partial<ProtoDecoded<typeof ElemSchema>>;
export interface SendContext {
bridge: Bridge;
groupId?: number;
userUid?: string;
}
function makeTextElem(text: string): ProtoElem {
return {
text: { str: text } as any,
};
}
function makeFaceElem(faceId: number): ProtoElem {
return {
face: { index: faceId } as any,
};
}
function makeMentionElem(element: MessageElement): ProtoElem {
const mentionAll = element.uid === 'all' || element.targetUin === 0;
const extra = protoEncode({
type: mentionAll ? 1 : 2,
uin: mentionAll ? 0 : (element.targetUin ?? 0),
field5: 0,
uid: mentionAll ? 'all' : (element.uid ?? ''),
}, MentionExtraSendSchema);
return {
text: {
str: element.text || (mentionAll ? '@全体成员 ' : `@${element.targetUin} `),
pbReserve: extra,
} as any,
};
}
function makeReplyElem(element: MessageElement): ProtoElem {
return {
srcMsg: {
origSeqs: [element.replySeq! & 0xFFFFFFFF],
} as any,
};
}
function makeJsonElem(element: MessageElement): ProtoElem {
const content = element.text ?? '';
const payload = new Uint8Array(content.length + 1);
payload[0] = 0x00;
const encoded = new TextEncoder().encode(content);
payload.set(encoded, 1);
return {
richMsg: {
serviceId: 1,
template1: payload,
} as any,
};
}
function makeXmlElem(element: MessageElement): ProtoElem {
const content = element.text ?? '';
const payload = new Uint8Array(content.length + 1);
payload[0] = 0x00;
const encoded = new TextEncoder().encode(content);
payload.set(encoded, 1);
return {
richMsg: {
serviceId: element.subType === 0 ? 35 : (element.subType ?? 35),
template1: payload,
} as any,
};
}
function makeMarkdownElem(element: MessageElement): ProtoElem {
const data = protoEncode({ content: element.text ?? '' }, MarkdownDataSchema);
return {
commonElem: {
serviceType: 45,
pbElem: data,
businessType: 1,
} as any,
};
}
function makeForwardElem(element: MessageElement): ProtoElem {
const resId = (element.resId ?? '').trim();
if (!resId) {
throw new Error('forward resId is required');
}
const xml = `<?xml version="1.0" encoding="utf-8"?><msg templateID="1" action="viewMultiMsg" serviceID="35" brief="[聊天记录]" m_resid="${resId}" m_fileName="${resId}" actionData="${resId}" tSum="2" sourceMsgId="0" flag="3" adverSign="0" multiMsgFlag="0"><item layout="1"><title size="34" color="#000000">聊天记录</title><title size="26" color="#777777">查看转发消息</title><summary size="26" color="#808080">查看转发消息</summary></item><source name="" icon="" action="" appid="-1"/></msg>`;
const encodedXml = new TextEncoder().encode(xml);
const payload = new Uint8Array(encodedXml.length + 1);
payload[0] = 0x00;
payload.set(encodedXml, 1);
return {
richMsg: {
serviceId: 35,
template1: payload,
} as any,
};
}
async function makeImageElem(ctx: SendContext, element: MessageElement): Promise<ProtoElem> {
const isGroup = ctx.groupId !== undefined;
const targetIdOrUid = isGroup ? ctx.groupId! : (ctx.userUid ?? '');
if (!isGroup && !targetIdOrUid) {
throw new Error('private image target uid is missing');
}
const msgInfo = await uploadImageMsgInfo(ctx.bridge, isGroup, targetIdOrUid, element);
return {
commonElem: {
serviceType: 48,
pbElem: msgInfo,
businessType: isGroup ? 20 : 10,
} as any,
};
}
/**
* Build proto Elem objects from an array of MessageElements.
* Supports: text, face, at, reply, json, xml, markdown, image.
* Image elements trigger highway upload via the SendContext.
*/
export async function buildSendElems(elements: MessageElement[], ctx?: SendContext): Promise<ProtoElem[]> {
const result: ProtoElem[] = [];
for (const elem of elements) {
switch (elem.type) {
case 'text':
if (elem.text) result.push(makeTextElem(elem.text));
break;
case 'face':
if (elem.faceId !== undefined) result.push(makeFaceElem(elem.faceId));
break;
case 'at':
result.push(makeMentionElem(elem));
break;
case 'reply':
if (elem.replySeq) result.push(makeReplyElem(elem));
break;
case 'json':
if (elem.text) result.push(makeJsonElem(elem));
break;
case 'xml':
if (elem.text) result.push(makeXmlElem(elem));
break;
case 'markdown':
if (elem.text) result.push(makeMarkdownElem(elem));
break;
case 'image':
if (ctx) {
result.push(await makeImageElem(ctx, elem));
} else {
console.warn('[ElemBuilder] image send requires SendContext');
}
break;
case 'forward':
if (elem.resId) result.push(makeForwardElem(elem));
break;
case 'record':
case 'video':
console.warn(`[ElemBuilder] ${elem.type} send not yet implemented`);
break;
default:
console.warn(`[ElemBuilder] unsupported element type for send: ${elem.type}`);
break;
}
}
return result;
}
+211
View File
@@ -0,0 +1,211 @@
// Bridge event types and MessageElement.
// Port of src/bridge/include/bridge/events.h
export interface MessageElement {
type: string; // 'text'|'at'|'face'|'mface'|'image'|'video'|'record'|'file'|'json'|'xml'|'reply'|'poke'|'forward'
text?: string;
faceId?: number;
targetUin?: number;
uid?: string;
imageUrl?: string;
fileId?: string;
thumbFileId?: string;
fileName?: string;
fileSize?: number;
replySeq?: number;
url?: string;
subType?: number;
duration?: number;
width?: number;
height?: number;
summary?: string;
flash?: boolean;
resId?: string;
fileHash?: string;
mediaNode?: {
fileUuid?: string;
storeId?: number;
uploadTime?: number;
ttl?: number;
subType?: number;
info?: {
fileSize?: number;
fileHash?: string;
fileSha1?: string;
fileName?: string;
width?: number;
height?: number;
time?: number;
original?: number;
type?: {
type?: number;
picFormat?: number;
videoFormat?: number;
voiceFormat?: number;
};
};
};
}
export interface ForwardNodePayload {
userUin: number;
nickname: string;
elements: MessageElement[];
}
export interface QQEvent {
time: number;
selfUin: number;
}
export interface FriendMessage extends QQEvent {
kind: 'friend_message';
senderUin: number;
senderNick: string;
msgSeq: number;
msgId: number;
elements: MessageElement[];
}
export interface GroupMessage extends QQEvent {
kind: 'group_message';
groupId: number;
senderUin: number;
senderNick: string;
senderCard: string;
senderRole: string;
msgSeq: number;
msgId: number;
elements: MessageElement[];
}
export interface TempMessage extends QQEvent {
kind: 'temp_message';
senderUin: number;
groupId: number;
senderNick: string;
msgSeq: number;
elements: MessageElement[];
}
export interface GroupMemberJoin extends QQEvent {
kind: 'group_member_join';
groupId: number;
userUin: number;
operatorUin: number;
}
export interface GroupMemberLeave extends QQEvent {
kind: 'group_member_leave';
groupId: number;
userUin: number;
operatorUin: number;
isKick: boolean;
}
export interface GroupMuteEvent extends QQEvent {
kind: 'group_mute';
groupId: number;
userUin: number;
operatorUin: number;
duration: number;
}
export interface GroupAdminEvent extends QQEvent {
kind: 'group_admin';
groupId: number;
userUin: number;
set: boolean;
}
export interface FriendRecall extends QQEvent {
kind: 'friend_recall';
userUin: number;
msgSeq: number;
}
export interface GroupRecallEvent extends QQEvent {
kind: 'group_recall';
groupId: number;
operatorUin: number;
authorUin: number;
msgSeq: number;
}
export interface FriendRequestEvent extends QQEvent {
kind: 'friend_request';
fromUin: number;
message: string;
flag: string;
}
export interface GroupInviteEvent extends QQEvent {
kind: 'group_invite';
groupId: number;
fromUin: number;
subType: string;
message: string;
flag: string;
}
export interface FriendPokeEvent extends QQEvent {
kind: 'friend_poke';
userUin: number;
targetUin: number;
action: string;
suffix: string;
actionImgUrl: string;
}
export interface GroupPokeEvent extends QQEvent {
kind: 'group_poke';
groupId: number;
userUin: number;
targetUin: number;
action: string;
suffix: string;
actionImgUrl: string;
}
export interface GroupEssenceEvent extends QQEvent {
kind: 'group_essence';
groupId: number;
senderUin: number;
operatorUin: number;
msgSeq: number;
random: number;
set: boolean;
}
export interface GroupFileUploadEvent extends QQEvent {
kind: 'group_file_upload';
groupId: number;
userUin: number;
fileId: string;
fileName: string;
fileSize: number;
busId: number;
}
export interface FriendAddEvent extends QQEvent {
kind: 'friend_add';
userUin: number;
}
export type QQEventVariant =
| FriendMessage
| GroupMessage
| TempMessage
| GroupMemberJoin
| GroupMemberLeave
| GroupMuteEvent
| GroupAdminEvent
| FriendRecall
| GroupRecallEvent
| FriendRequestEvent
| GroupInviteEvent
| FriendPokeEvent
| GroupPokeEvent
| GroupEssenceEvent
| GroupFileUploadEvent
| FriendAddEvent;
@@ -0,0 +1,857 @@
// MsgPush packet handler — parses trpc.msg.olpush.OlPushService.MsgPush
// into bridge events. Port of src/bridge/src/handlers/msg_push_handler.h/.cpp
import { inflateSync } from 'zlib';
import { protoDecode } from '../../protobuf/decode';
import { WireMessage } from '../../protobuf/wire';
import { PushMsgSchema } from '../proto/message';
import {
MentionExtraSchema, QFaceExtraSchema, QSmallFaceExtraSchema,
MsgInfoSchema, GroupFileExtraSchema, NotOnlineImageSchema,
} from '../proto/element';
import { FileExtraSchema } from '../proto/message';
import {
GroupChangeSchema, GroupAdminSchema, GroupJoinSchema,
GroupInvitationSchema, GroupInviteSchema,
FriendRequestSchema, FriendRecallSchema,
GroupMuteSchema, NotifyMessageBodySchema,
GeneralGrayTipInfoSchema, OperatorInfoSchema,
} from '../proto/notify';
import type { QQInfo } from '../qq-info';
import type { PacketInfo } from '../../protocol/types';
import type {
QQEventVariant, MessageElement,
FriendMessage, GroupMessage, TempMessage,
GroupMemberJoin, GroupMemberLeave, GroupMuteEvent, GroupAdminEvent,
FriendRecall, GroupRecallEvent, FriendRequestEvent, GroupInviteEvent,
FriendPokeEvent, GroupPokeEvent, GroupEssenceEvent,
} from '../events';
import type { ProtoDecoded, ProtoSchema } from '../../protobuf/decode';
// --- PkgType enum ---
const enum PkgType {
ForwardFakePrivateMessage = 9,
PrivateMessage = 166,
GroupMessage = 82,
TempMessage = 141,
Event0x210 = 528,
Event0x2DC = 732,
PrivateRecordMessage = 208,
PrivateFileMessage = 529,
GroupRequestInvitationNotice = 525,
GroupRequestJoinNotice = 84,
GroupInviteNotice = 87,
GroupAdminChangedNotice = 44,
GroupMemberIncreaseNotice = 33,
GroupMemberDecreaseNotice = 34,
}
const enum Event0x2DCSubType {
GroupMuteNotice = 12,
GroupRecallNotice = 17,
GroupGreyTipNotice = 20,
GroupEssenceNotice = 21,
}
const enum Event0x210SubType {
FriendRequestNotice = 35,
FriendRecallNotice = 138,
FriendPokeNotice = 290,
}
// --- Helpers ---
function makeImageUrl(origUrl: string): string {
if (!origUrl) return '';
if (origUrl.includes('rkey')) return 'https://multimedia.nt.qq.com.cn' + origUrl;
return 'http://gchat.qpic.cn' + origUrl;
}
const HEX_CHARS = '0123456789ABCDEF';
function bytesToHex(data: Uint8Array): string {
let r = '';
for (const b of data) { r += HEX_CHARS[b >> 4]; r += HEX_CHARS[b & 0x0f]; }
return r;
}
function decompressData(data: Uint8Array): string {
if (!data || data.length === 0) return '';
if (data[0] === 0x01 && data.length > 1) {
try {
const inflated = inflateSync(Buffer.from(data.subarray(1)));
return inflated.toString('utf8');
} catch { return ''; }
}
if (data[0] === 0x00 && data.length > 1) {
return Buffer.from(data.subarray(1)).toString('utf8');
}
return Buffer.from(data).toString('utf8');
}
function isNumericUin(value: string): boolean {
return value.length > 0 && /^\d+$/.test(value);
}
function parseU64OrZero(value: string): number {
if (!value) return 0;
const n = parseInt(value, 10);
return isNaN(n) ? 0 : n;
}
function resolveUidToUin(qqInfo: QQInfo, groupId: number, uid: string, fallback = 0): number {
if (!uid) return fallback;
if (isNumericUin(uid)) {
const n = parseInt(uid, 10);
if (!isNaN(n)) return n;
}
if (groupId) {
const uin = qqInfo.resolveGroupMemberUid(groupId, uid);
if (uin !== null) return uin;
}
const uin = qqInfo.resolveUid(uid);
if (uin !== null) return uin;
return fallback;
}
function decodeOperatorUid(bytes: Uint8Array): string {
if (!bytes || bytes.length === 0) return '';
const info = protoDecode(bytes, OperatorInfoSchema);
if (info?.operatorField?.uid) return info.operatorField.uid;
return Buffer.from(bytes).toString('utf8');
}
function buildTemplateMap(params: Array<{name?: string; value?: string}>): Map<string, string> {
const map = new Map<string, string>();
for (const p of params) {
if (p.name !== undefined) map.set(p.name, p.value ?? '');
}
return map;
}
function findTemplateValue(map: Map<string, string>, ...keys: string[]): string {
for (const k of keys) {
const v = map.get(k);
if (v) return v;
}
return '';
}
function unwrapGroupNotifyPayload(content: Uint8Array): Uint8Array | null {
if (content.length <= 7) return null;
const lenBe = (content[5] << 8) | content[6];
const lenLe = content[5] | (content[6] << 8);
if (7 + lenBe <= content.length) return content.subarray(7, 7 + lenBe);
if (7 + lenLe <= content.length) return content.subarray(7, 7 + lenLe);
return content.subarray(7);
}
// --- Element conversion ---
type ElemDecoded = ProtoDecoded<typeof import('../proto/element').ElemSchema>;
function convertElements(elems: ElemDecoded[]): MessageElement[] {
const result: MessageElement[] = [];
let skipNext = false;
for (const elem of elems) {
if (skipNext) { skipNext = false; continue; }
// Reply / quote
if (elem.srcMsg?.origSeqs && elem.srcMsg.origSeqs.length > 0) {
result.push({ type: 'reply', replySeq: elem.srcMsg.origSeqs[0] });
}
// Text (with possible @ detection)
if (elem.text) {
const t = elem.text;
let mention: ProtoDecoded<typeof MentionExtraSchema> | null = null;
if (t.pbReserve && t.pbReserve.length > 0) {
mention = protoDecode(t.pbReserve, MentionExtraSchema);
}
const hasAttr6 = t.attr6Buf && t.attr6Buf.length > 11;
const hasMention = mention && (mention.type === 1 || mention.type === 2);
if (hasAttr6 || hasMention) {
const me: MessageElement = { type: 'at', text: t.str ?? '' };
if (hasAttr6) {
const buf = t.attr6Buf!;
me.targetUin = ((buf[7] << 24) | (buf[8] << 16) | (buf[9] << 8) | buf[10]) >>> 0;
}
if (hasMention && mention) {
me.uid = mention.uid ?? '';
if (!me.targetUin) me.targetUin = mention.uin ?? 0;
}
result.push(me);
} else {
const text = t.str ?? '';
if (text) result.push({ type: 'text', text });
}
}
// Face
if (elem.face) {
result.push({ type: 'face', faceId: elem.face.index ?? 0 });
}
// MarketFace
if (elem.marketFace) {
result.push({
type: 'mface',
text: elem.marketFace.faceName ?? '',
faceId: elem.marketFace.tabId ?? 0,
subType: elem.marketFace.subType ?? 0,
});
}
// NotOnlineImage (C2C image)
if (elem.notOnlineImage) {
const img = elem.notOnlineImage;
if (img.picMd5 && img.picMd5.length > 0) {
const urlPath = img.origUrl || img.bigUrl || '';
result.push({
type: 'image',
imageUrl: makeImageUrl(urlPath),
fileId: img.filePath ?? '',
fileSize: img.fileLen ?? 0,
width: img.picWidth ?? 0,
height: img.picHeight ?? 0,
subType: img.pbRes?.subType ?? 0,
summary: img.pbRes?.summary ?? '[image]',
});
}
}
// CustomFace (group image)
if (elem.customFace) {
const img = elem.customFace;
if (img.md5 && img.md5.length > 0) {
result.push({
type: 'image',
imageUrl: makeImageUrl(img.origUrl ?? ''),
fileId: img.filePath ?? '',
fileSize: img.size ?? 0,
width: img.width ?? 0,
height: img.height ?? 0,
subType: img.pbRes?.subType ?? 0,
summary: img.pbRes?.summary ?? '[image]',
});
}
}
// VideoFile
if (elem.videoFile) {
const v = elem.videoFile;
result.push({
type: 'video',
fileId: v.fileUuid ?? '',
fileName: v.fileName ?? '',
fileSize: v.fileSize ?? 0,
duration: v.fileTime ?? 0,
fileHash: v.fileMd5 && v.fileMd5.length > 0 ? bytesToHex(v.fileMd5) : '',
mediaNode: {
fileUuid: v.fileUuid ?? '',
info: {
fileSize: v.fileSize ?? 0,
fileHash: v.fileMd5 && v.fileMd5.length > 0 ? bytesToHex(v.fileMd5) : '',
fileName: v.fileName ?? '',
width: v.fileWidth ?? 0,
height: v.fileHeight ?? 0,
time: v.fileTime ?? 0,
type: {
type: 2,
videoFormat: v.fileFormat ?? 0,
},
},
},
});
}
// GroupFile
if (elem.groupFile) {
const f = elem.groupFile;
result.push({
type: 'file',
fileId: f.fileId ?? '',
fileName: f.filename ?? '',
fileSize: f.fileSize !== undefined ? Number(f.fileSize) : 0,
});
}
// TransElem type=24 (group file via transport)
if (elem.transElem) {
const te = elem.transElem;
if ((te.elemType ?? 0) === 24 && te.elemValue && te.elemValue.length > 3) {
const val = te.elemValue;
const len = (val[1] << 8) | val[2];
if (val.length >= 3 + len) {
const extra = protoDecode(val.subarray(3, 3 + len), GroupFileExtraSchema);
if (extra?.inner?.info) {
const info = extra.inner.info;
result.push({
type: 'file',
fileName: info.fileName ?? '',
fileSize: info.fileSize !== undefined ? Number(info.fileSize) : 0,
fileId: info.fileId ?? '',
});
}
}
}
}
// RichMsg
if (elem.richMsg) {
const rm = elem.richMsg;
if (rm.template1 && rm.template1.length > 0) {
const content = decompressData(rm.template1);
if (content) {
const svcId = rm.serviceId ?? 0;
if (svcId === 35) {
const pos = content.indexOf('m_resid="');
if (pos !== -1) {
const start = pos + 9;
const end = content.indexOf('"', start);
if (end !== -1) {
result.push({ type: 'forward', resId: content.substring(start, end) });
continue;
}
}
result.push({ type: 'xml', text: content, subType: svcId });
} else if (svcId === 1) {
result.push({ type: 'json', text: content });
} else {
result.push({ type: 'xml', text: content, subType: svcId });
}
}
}
}
// LightApp
if (elem.lightApp) {
const la = elem.lightApp;
if (la.data && la.data.length > 0) {
const content = decompressData(la.data);
if (content) result.push({ type: 'json', text: content });
}
}
// CommonElem
if (elem.commonElem) {
const ce = elem.commonElem;
const svcType = ce.serviceType ?? 0;
const bizType = ce.businessType ?? 0;
if (svcType === 2) {
// Poke
result.push({ type: 'poke', subType: bizType });
} else if (svcType === 3 && ce.pbElem && ce.pbElem.length > 1) {
// Flash image
const pb = ce.pbElem;
let pos = 1;
let length = 0, shift = 0;
while (pos < pb.length) {
const b = pb[pos++];
length |= (b & 0x7f) << shift;
shift += 7;
if ((b & 0x80) === 0) break;
}
if (pos + length <= pb.length) {
const img = protoDecode(pb.subarray(pos, pos + length), NotOnlineImageSchema);
if (img) {
const me: MessageElement = {
type: 'image', fileId: img.filePath ?? '',
fileSize: img.fileLen ?? 0, width: img.picWidth ?? 0,
height: img.picHeight ?? 0, flash: true, summary: '[flash image]',
};
if (img.pbRes) me.subType = img.pbRes.subType ?? 0;
if (img.picMd5 && img.picMd5.length > 0) {
me.imageUrl = 'http://gchat.qpic.cn/gchatpic_new/0/0-0-' + bytesToHex(img.picMd5) + '/0';
}
result.push(me);
}
}
skipNext = true;
} else if (ce.pbElem && (svcType === 48 || bizType === 10 || bizType === 20 || bizType === 11 || bizType === 21 || bizType === 12 || bizType === 22)) {
// NTQQ new protocol image/record/video
const info = protoDecode(ce.pbElem, MsgInfoSchema);
if (info?.msgInfoBody && info.msgInfoBody.length > 0) {
const body = info.msgInfoBody[0];
if (body.index?.info) {
const idx = body.index;
const fi = idx.info!;
if (bizType === 10 || bizType === 20) {
// Image
let url = '';
if (body.picture) {
const domain = body.picture.domain ?? 'multimedia.nt.qq.com.cn';
const path = body.picture.urlPath ?? '';
if (path) {
url = 'https://' + domain + path;
if (body.picture.ext?.originalParameter) {
url += body.picture.ext.originalParameter;
}
}
}
const me: MessageElement = {
type: 'image', fileId: fi.fileName ?? '',
fileSize: fi.fileSize ?? 0, width: fi.width ?? 0,
height: fi.height ?? 0, imageUrl: url,
};
if (info.extBizInfo?.pic) {
me.subType = info.extBizInfo.pic.bizType ?? 0;
me.summary = info.extBizInfo.pic.textSummary || '[image]';
}
result.push(me);
} else if (bizType === 12 || bizType === 22) {
// Record
result.push({
type: 'record', fileName: fi.fileName ?? '',
fileId: idx.fileUuid ?? '', duration: fi.time ?? 0,
fileHash: fi.fileHash ?? '',
mediaNode: {
fileUuid: idx.fileUuid,
storeId: idx.storeId,
uploadTime: idx.uploadTime,
ttl: idx.ttl,
subType: idx.subType,
info: {
fileSize: fi.fileSize,
fileHash: fi.fileHash,
fileSha1: fi.fileSha1,
fileName: fi.fileName,
width: fi.width,
height: fi.height,
time: fi.time,
original: fi.original,
type: {
type: fi.type?.type,
picFormat: fi.type?.picFormat,
videoFormat: fi.type?.videoFormat,
voiceFormat: fi.type?.voiceFormat,
},
},
},
});
} else if (bizType === 11 || bizType === 21) {
// Video
result.push({
type: 'video', fileName: fi.fileName ?? '',
fileId: idx.fileUuid ?? '', fileSize: fi.fileSize ?? 0,
duration: fi.time ?? 0,
fileHash: fi.fileHash ?? '',
mediaNode: {
fileUuid: idx.fileUuid,
storeId: idx.storeId,
uploadTime: idx.uploadTime,
ttl: idx.ttl,
subType: idx.subType,
info: {
fileSize: fi.fileSize,
fileHash: fi.fileHash,
fileSha1: fi.fileSha1,
fileName: fi.fileName,
width: fi.width,
height: fi.height,
time: fi.time,
original: fi.original,
type: {
type: fi.type?.type,
picFormat: fi.type?.picFormat,
videoFormat: fi.type?.videoFormat,
voiceFormat: fi.type?.voiceFormat,
},
},
},
});
}
}
}
} else if (svcType === 33 && ce.pbElem) {
// Small face
const extra = protoDecode(ce.pbElem, QSmallFaceExtraSchema);
if (extra) result.push({ type: 'face', faceId: extra.faceId ?? 0 });
} else if (svcType === 37 && ce.pbElem) {
// Big face
const extra = protoDecode(ce.pbElem, QFaceExtraSchema);
if (extra?.qsid !== undefined) result.push({ type: 'face', faceId: extra.qsid });
skipNext = true;
}
}
}
return result;
}
function extractRichtextExtras(
rt: ProtoDecoded<typeof import('../proto/message').RichTextSchema>,
elements: MessageElement[],
isGroup = false
): void {
// Ptt (voice)
if (rt.ptt) {
const p = rt.ptt;
const me: MessageElement = {
type: 'record', fileName: p.fileName ?? '',
fileSize: p.fileSize ?? 0, duration: p.time ?? 0,
fileHash: p.fileMd5 && p.fileMd5.length > 0 ? bytesToHex(p.fileMd5) : '',
};
if (isGroup && (p.fileId ?? 0n) !== 0n) {
me.fileId = p.groupFileKey ?? '';
} else {
if (p.fileUuid && p.fileUuid.length > 0) {
me.fileId = Buffer.from(p.fileUuid).toString('utf8');
}
}
me.mediaNode = {
fileUuid: me.fileId ?? '',
info: {
fileSize: p.fileSize ?? 0,
fileHash: p.fileMd5 && p.fileMd5.length > 0 ? bytesToHex(p.fileMd5) : '',
fileName: p.fileName ?? '',
time: p.time ?? 0,
type: {
type: 3,
voiceFormat: p.format ?? 0,
},
},
};
elements.push(me);
}
// NotOnlineFile (C2C file)
if (rt.notOnlineFile) {
const f = rt.notOnlineFile;
elements.push({
type: 'file', fileId: f.fileUuid ?? '',
fileName: f.fileName ?? '',
fileSize: f.fileSize !== undefined ? Number(f.fileSize) : 0,
fileHash: f.fileHash ?? '',
});
}
}
function extractMsgContent(msgContent: Uint8Array, elements: MessageElement[]): void {
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,
});
}
}
// --- Main handler ---
export const MSG_PUSH_CMD = 'trpc.msg.olpush.OlPushService.MsgPush';
export function parseMsgPush(pkt: PacketInfo, qqInfo: QQInfo): QQEventVariant[] {
if (pkt.body.length === 0) return [];
const push = protoDecode(Buffer.from(pkt.body), PushMsgSchema);
if (!push?.message) return [];
const msg = push.message;
if (!msg.contentHead) return [];
const head = msg.contentHead;
const msgType = head.msgType ?? 0;
const subType = head.subType ?? 0;
const sequence = head.sequence ?? 0;
const timestamp = head.timestamp ?? 0;
const msgId = head.msgId ?? 0;
let fromUin = 0;
let fromUid = '';
if (msg.responseHead) {
fromUin = msg.responseHead.fromUin ?? 0;
fromUid = msg.responseHead.fromUid ?? '';
}
let selfUin = 0;
if (pkt.uin) {
const n = parseInt(pkt.uin, 10);
if (!isNaN(n)) selfUin = n;
}
const content = (msg.body?.msgContent) ? msg.body.msgContent : new Uint8Array(0);
const buildElements = (isGroup: boolean): MessageElement[] => {
const elements: MessageElement[] = [];
if (msg.body?.richText) {
const rt = msg.body.richText;
if (rt.elems) elements.push(...convertElements(rt.elems as ElemDecoded[]));
extractRichtextExtras(rt, elements, isGroup);
}
if (msg.body?.msgContent && msg.body.msgContent.length > 0) {
extractMsgContent(msg.body.msgContent, elements);
}
return elements;
};
// --- Switch on msgType ---
switch (msgType as PkgType) {
case PkgType.GroupMemberIncreaseNotice: {
const change = protoDecode(content, GroupChangeSchema);
if (!change) return [];
const ev: GroupMemberJoin = {
kind: 'group_member_join', time: timestamp, selfUin,
groupId: change.groupUin ?? 0,
userUin: resolveUidToUin(qqInfo, change.groupUin ?? 0, change.memberUid ?? '', fromUin),
operatorUin: resolveUidToUin(qqInfo, change.groupUin ?? 0,
decodeOperatorUid(change.operatorBytes ?? new Uint8Array(0)), fromUin),
};
return [ev];
}
case PkgType.GroupMemberDecreaseNotice: {
const change = protoDecode(content, GroupChangeSchema);
if (!change) return [];
const dt = change.decreaseType ?? 0;
const ev: GroupMemberLeave = {
kind: 'group_member_leave', time: timestamp, selfUin,
groupId: change.groupUin ?? 0,
userUin: resolveUidToUin(qqInfo, change.groupUin ?? 0, change.memberUid ?? '', fromUin),
operatorUin: resolveUidToUin(qqInfo, change.groupUin ?? 0,
decodeOperatorUid(change.operatorBytes ?? new Uint8Array(0)), fromUin),
isKick: dt !== 0 && dt !== 130,
};
return [ev];
}
case PkgType.GroupAdminChangedNotice: {
const admin = protoDecode(content, GroupAdminSchema);
if (!admin?.body) return [];
const extra = admin.body.extraEnable ?? admin.body.extraDisable;
if (!extra) return [];
const ev: GroupAdminEvent = {
kind: 'group_admin', time: timestamp, selfUin,
groupId: admin.groupUin ?? 0,
userUin: resolveUidToUin(qqInfo, admin.groupUin ?? 0, extra.adminUid ?? '', fromUin),
set: admin.body.extraEnable !== undefined,
};
return [ev];
}
case PkgType.GroupRequestJoinNotice: {
const join = protoDecode(content, GroupJoinSchema);
if (!join) return [];
const ev: GroupInviteEvent = {
kind: 'group_invite', time: timestamp, selfUin,
groupId: join.groupUin ?? 0,
fromUin: resolveUidToUin(qqInfo, join.groupUin ?? 0, join.targetUid ?? '', fromUin),
subType: 'add', message: '',
flag: 'add:' + (join.groupUin ?? 0) + ':' + (join.targetUid ?? ''),
};
return [ev];
}
case PkgType.GroupRequestInvitationNotice: {
const invitation = protoDecode(content, GroupInvitationSchema);
if (!invitation?.info?.inner) return [];
const inner = invitation.info.inner;
const ev: GroupInviteEvent = {
kind: 'group_invite', time: timestamp, selfUin,
groupId: inner.groupUin ?? 0,
fromUin: resolveUidToUin(qqInfo, inner.groupUin ?? 0, inner.invitorUid ?? '', fromUin),
subType: 'invite', message: '',
flag: 'invite:' + (inner.groupUin ?? 0) + ':' + (inner.invitorUid ?? ''),
};
return [ev];
}
case PkgType.GroupInviteNotice: {
const invite = protoDecode(content, GroupInviteSchema);
if (!invite) return [];
const ev: GroupInviteEvent = {
kind: 'group_invite', time: timestamp, selfUin,
groupId: invite.groupUin ?? 0,
fromUin: resolveUidToUin(qqInfo, invite.groupUin ?? 0, invite.invitorUid ?? '', fromUin),
subType: 'invite', message: '',
flag: 'invite:' + (invite.groupUin ?? 0) + ':' + (invite.invitorUid ?? ''),
};
return [ev];
}
case PkgType.Event0x210: {
switch (subType as Event0x210SubType) {
case Event0x210SubType.FriendRequestNotice: {
const request = protoDecode(content, FriendRequestSchema);
if (!request?.info) return [];
const sourceUid = request.info.newSource || request.info.sourceUid || '';
const ev: FriendRequestEvent = {
kind: 'friend_request', time: timestamp, selfUin,
fromUin: resolveUidToUin(qqInfo, 0, sourceUid, fromUin),
message: request.info.message ?? '', flag: sourceUid,
};
return [ev];
}
case Event0x210SubType.FriendRecallNotice: {
const recall = protoDecode(content, FriendRecallSchema);
if (!recall?.info) return [];
const ev: FriendRecall = {
kind: 'friend_recall', time: recall.info.time ?? timestamp, selfUin,
userUin: resolveUidToUin(qqInfo, 0, recall.info.fromUid ?? '', fromUin),
msgSeq: recall.info.clientSequence ?? 0,
};
return [ev];
}
case Event0x210SubType.FriendPokeNotice: {
const grayTip = protoDecode(content, GeneralGrayTipInfoSchema);
if (!grayTip || (grayTip.busiType ?? 0n) !== 12n) return [];
const templates = buildTemplateMap(grayTip.msgTemplParam ?? []);
const actor = findTemplateValue(templates, 'uin_str1');
const target = findTemplateValue(templates, 'uin_str2');
const ev: FriendPokeEvent = {
kind: 'friend_poke', time: timestamp, selfUin,
userUin: resolveUidToUin(qqInfo, 0, actor, parseU64OrZero(actor)),
targetUin: resolveUidToUin(qqInfo, 0, target, parseU64OrZero(target)),
action: findTemplateValue(templates, 'action_str', 'alt_str1'),
suffix: findTemplateValue(templates, 'suffix_str'),
actionImgUrl: findTemplateValue(templates, 'action_img_url'),
};
return [ev];
}
}
break;
}
case PkgType.Event0x2DC: {
switch (subType as Event0x2DCSubType) {
case Event0x2DCSubType.GroupMuteNotice: {
const mute = protoDecode(content, GroupMuteSchema);
if (!mute?.data?.state) return [];
const duration = mute.data.state.duration ?? 0;
const ev: GroupMuteEvent = {
kind: 'group_mute', time: mute.data.timestamp ?? timestamp, selfUin,
groupId: mute.groupUin ?? 0,
operatorUin: resolveUidToUin(qqInfo, mute.groupUin ?? 0, mute.operatorUid ?? '', fromUin),
userUin: resolveUidToUin(qqInfo, mute.groupUin ?? 0, mute.data.state.targetUid ?? '', 0),
duration: duration === 0xFFFFFFFF ? 0x7FFFFFFF : duration,
};
return [ev];
}
case Event0x2DCSubType.GroupRecallNotice: {
const payload = unwrapGroupNotifyPayload(content);
if (!payload) return [];
const notify = protoDecode(payload, NotifyMessageBodySchema);
if (!notify?.recall?.recallMessages || notify.recall.recallMessages.length === 0) return [];
const recalled = notify.recall.recallMessages[0];
const ev: GroupRecallEvent = {
kind: 'group_recall', time: recalled.time ?? timestamp, selfUin,
groupId: notify.groupUin ?? 0,
operatorUin: resolveUidToUin(qqInfo, notify.groupUin ?? 0,
notify.recall.operatorUid || notify.operatorUid || '', fromUin),
authorUin: resolveUidToUin(qqInfo, notify.groupUin ?? 0, recalled.authorUid ?? '', fromUin),
msgSeq: recalled.sequence ?? 0,
};
return [ev];
}
case Event0x2DCSubType.GroupGreyTipNotice: {
const payload = unwrapGroupNotifyPayload(content);
if (!payload) return [];
const notify = protoDecode(payload, NotifyMessageBodySchema);
if (!notify?.generalGrayTip || (notify.generalGrayTip.busiType ?? 0n) !== 12n) return [];
const templates = buildTemplateMap(notify.generalGrayTip.msgTemplParam ?? []);
const actor = findTemplateValue(templates, 'uin_str1');
const target = findTemplateValue(templates, 'uin_str2');
const ev: GroupPokeEvent = {
kind: 'group_poke', time: timestamp, selfUin,
groupId: notify.groupUin ?? 0,
userUin: resolveUidToUin(qqInfo, notify.groupUin ?? 0, actor, parseU64OrZero(actor)),
targetUin: resolveUidToUin(qqInfo, notify.groupUin ?? 0, target, parseU64OrZero(target)),
action: findTemplateValue(templates, 'action_str', 'alt_str1'),
suffix: findTemplateValue(templates, 'suffix_str'),
actionImgUrl: findTemplateValue(templates, 'action_img_url'),
};
return [ev];
}
case Event0x2DCSubType.GroupEssenceNotice: {
const payload = unwrapGroupNotifyPayload(content);
if (!payload) return [];
const notify = protoDecode(payload, NotifyMessageBodySchema);
if (!notify?.essenceMessage) return [];
const essence = notify.essenceMessage;
const setFlag = essence.setFlag ?? essence.setFlag2 ?? 0;
const ev: GroupEssenceEvent = {
kind: 'group_essence', time: essence.timestamp ?? timestamp, selfUin,
groupId: essence.groupUin ?? notify.groupUin ?? 0,
senderUin: essence.memberUin ?? 0,
operatorUin: essence.operatorUin ?? fromUin,
msgSeq: essence.msgSequence ?? essence.msgSequence2 ?? notify.msgSequence ?? 0,
random: essence.random ?? 0,
set: setFlag === 1,
};
return [ev];
}
}
break;
}
}
// --- Message types ---
if (msgType === PkgType.GroupMessage) {
const ev: GroupMessage = {
kind: 'group_message', time: timestamp, selfUin,
senderUin: fromUin, msgSeq: sequence,
msgId: msgId & 0x7FFFFFFF,
elements: buildElements(true),
groupId: 0, senderNick: '', senderCard: '', senderRole: '',
};
if (msg.responseHead?.grp) {
ev.groupId = msg.responseHead.grp.groupUin ?? 0;
ev.senderNick = msg.responseHead.grp.memberName ?? '';
}
const member = qqInfo.findGroupMember(ev.groupId, fromUin);
if (member) {
if (!ev.senderNick) ev.senderNick = member.nickname;
ev.senderCard = member.card;
ev.senderRole = member.role;
}
return [ev];
}
if (msgType === PkgType.TempMessage) {
const ev: TempMessage = {
kind: 'temp_message', time: timestamp, selfUin,
senderUin: fromUin, msgSeq: sequence,
elements: buildElements(false),
groupId: 0, senderNick: '',
};
if (msg.responseHead?.grp) {
ev.groupId = msg.responseHead.grp.groupUin ?? 0;
ev.senderNick = msg.responseHead.grp.memberName ?? '';
}
if (!ev.senderNick) {
const friend = qqInfo.findFriend(fromUin);
if (friend) ev.senderNick = friend.nickname;
}
return [ev];
}
if (msgType === PkgType.PrivateMessage ||
msgType === PkgType.ForwardFakePrivateMessage ||
msgType === PkgType.PrivateRecordMessage ||
msgType === PkgType.PrivateFileMessage) {
const ev: FriendMessage = {
kind: 'friend_message', time: timestamp, selfUin,
senderUin: fromUin, msgSeq: sequence,
msgId: msgId & 0x7FFFFFFF,
elements: buildElements(false),
senderNick: '',
};
if (msg.responseHead?.forward?.friendName) {
ev.senderNick = msg.responseHead.forward.friendName;
}
const friend = qqInfo.findFriend(fromUin);
if (friend && !ev.senderNick) ev.senderNick = friend.nickname;
return [ev];
}
// const preview = bytesToHex(content.subarray(0, Math.min(content.length, 48)));
return [];
}
@@ -0,0 +1,216 @@
// Highway HTTP client: session fetch and chunked binary upload.
// Port of src/bridge/src/highway_client.cpp
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 { packHighwayFrame, unpackHighwayFrame, computeMd5 } from './utils';
const HIGHWAY_APP_ID = 1600001604;
const HIGHWAY_BLOCK_SIZE = 1024 * 1024;
export const PRIVATE_IMAGE_CMD_ID = 1003;
export const GROUP_IMAGE_CMD_ID = 1004;
export interface HighwaySession {
sigSession: Uint8Array;
sessionKey: Uint8Array;
host: string;
port: number;
}
function ipv4ToString(value: number): string {
return `${value & 0xFF}.${(value >> 8) & 0xFF}.${(value >> 16) & 0xFF}.${(value >> 24) & 0xFF}`;
}
export async function fetchHighwaySession(bridge: Bridge): Promise<HighwaySession> {
const request = protoEncode({
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);
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');
}
const session: HighwaySession = {
sigSession: resp.httpConn.sigSession as Uint8Array,
sessionKey: (resp.httpConn.sessionKey as Uint8Array) ?? new Uint8Array(0),
host: 'htdata3.qq.com',
port: 80,
};
for (const si of resp.httpConn.serverInfos ?? []) {
if ((si.serviceType ?? 0) !== 1 || !si.serverAddrs?.length) continue;
for (const addr of si.serverAddrs) {
const ip = addr.ip ?? 0;
const port = addr.port ?? 0;
if (ip && port) {
session.host = ipv4ToString(ip);
session.port = port;
}
}
}
console.log(`[Highway] session: ${session.host}:${session.port} sig=${(session.sigSession as Uint8Array).length}B`);
return session;
}
function makeHighwayHead(
uin: string, commandId: number, fileSize: number, offset: number, length: number,
chunkMd5: Uint8Array, fileMd5: Uint8Array, sigSession: Uint8Array, extend: Uint8Array,
): Uint8Array {
return protoEncode({
msgBaseHead: {
version: 1, uin, command: 'PicUp.DataUp', seq: 0, retryTimes: 0,
appId: HIGHWAY_APP_ID, dataFlag: 16, commandId,
},
msgSegHead: {
serviceId: 0, filesize: BigInt(fileSize), dataOffset: BigInt(offset), dataLength: length,
retCode: 0, serviceTicket: sigSession, flag: 0, md5: chunkMd5, fileMd5, cacheAddr: 0, cachePort: 0,
},
bytesReqExtendInfo: extend,
timestamp: 0n,
msgLoginSigHead: { loginSigType: 8, appId: HIGHWAY_APP_ID },
}, ReqDataHighwayHeadSchema);
}
export function buildHighwayExtend(
uKey: string, msgInfo: any, ipv4s: any[], sha1: Uint8Array,
): Uint8Array {
const msgInfoBody = msgInfo?.msgInfoBody ?? [];
if (msgInfoBody.length === 0) throw new Error('upload response missing msg_info body');
const first = msgInfoBody[0];
const networkIpv4s: any[] = [];
for (const ipv4 of ipv4s ?? []) {
const ip = ipv4.outIp ?? 0;
const port = ipv4.outPort ?? 0;
if (ip && port) {
networkIpv4s.push({ domain: { isEnable: true, ip: ipv4ToString(ip) }, port });
}
}
return protoEncode({
fileUuid: first?.index?.fileUuid ?? '',
uKey,
network: { ipv4s: networkIpv4s },
msgInfoBody: msgInfoBody.map((b: any) => ({
index: b.index, picture: b.picture, fileExist: b.fileExist, hashSum: b.hashSum,
})),
blockSize: HIGHWAY_BLOCK_SIZE,
hash: { fileSha1: [sha1] },
}, NTV2RichMediaHighwayExtSchema);
}
// --- TCP-based HTTP highway upload ---
function tcpConnect(host: string, port: number, timeoutMs = 10000): Promise<net.Socket> {
return new Promise((resolve, reject) => {
const socket = net.createConnection({ host, port }, () => resolve(socket));
socket.setTimeout(timeoutMs);
socket.on('timeout', () => { socket.destroy(); reject(new Error('TCP connect timeout')); });
socket.on('error', reject);
});
}
function socketWrite(socket: net.Socket, data: Uint8Array): Promise<void> {
return new Promise((resolve, reject) => {
socket.write(data, (err) => err ? reject(err) : resolve());
});
}
function readHttpResponseBody(socket: net.Socket): Promise<Uint8Array> {
return new Promise((resolve, reject) => {
const chunks: Buffer[] = [];
let headerEnd = -1;
let contentLength = 0;
let totalNeeded = 0;
const checkComplete = () => {
const buf = Buffer.concat(chunks);
if (headerEnd < 0) {
const idx = buf.indexOf('\r\n\r\n');
if (idx >= 0) {
headerEnd = idx + 4;
const headerStr = buf.subarray(0, headerEnd).toString('ascii').toLowerCase();
const clMatch = headerStr.match(/content-length:\s*(\d+)/);
contentLength = clMatch ? parseInt(clMatch[1], 10) : 0;
totalNeeded = headerEnd + contentLength;
}
}
if (headerEnd >= 0 && buf.length >= totalNeeded) {
socket.removeAllListeners('data');
socket.removeAllListeners('error');
resolve(new Uint8Array(buf.subarray(headerEnd, totalNeeded)));
}
};
socket.on('data', (chunk) => { chunks.push(chunk); checkComplete(); });
socket.on('error', reject);
socket.on('close', () => {
const buf = Buffer.concat(chunks);
if (headerEnd >= 0) resolve(new Uint8Array(buf.subarray(headerEnd)));
else reject(new Error('connection closed before response'));
});
});
}
async function httpPostFrame(
socket: net.Socket, host: string, path: string, body: Uint8Array,
): Promise<Uint8Array> {
const header = `POST ${path} HTTP/1.1\r\nHost: ${host}\r\nConnection: keep-alive\r\nAccept-Encoding: identity\r\nUser-Agent: Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2)\r\nContent-Length: ${body.length}\r\n\r\n`;
await socketWrite(socket, Buffer.from(header, 'ascii'));
if (body.length > 0) await socketWrite(socket, body);
return readHttpResponseBody(socket);
}
export async function uploadHighwayHttp(
bridge: Bridge, session: HighwaySession, commandId: number,
bytes: Uint8Array, fileMd5: Uint8Array, extend: Uint8Array,
): Promise<void> {
const pathStr = `/cgi-bin/httpconn?htcmd=0x6FF0087&uin=${bridge.qqInfo.uin}`;
const socket = await tcpConnect(session.host, session.port);
try {
let offset = 0;
while (offset < bytes.length) {
const chunkSize = Math.min(HIGHWAY_BLOCK_SIZE, bytes.length - offset);
const chunk = bytes.subarray(offset, offset + chunkSize);
const chunkMd5 = computeMd5(chunk);
const head = makeHighwayHead(
bridge.qqInfo.uin, commandId, bytes.length, offset, chunkSize,
chunkMd5, fileMd5, session.sigSession, extend,
);
const frame = packHighwayFrame(head, chunk);
const responseBody = await httpPostFrame(socket, session.host, pathStr, frame);
const { head: respHead } = unpackHighwayFrame(responseBody);
const resp = protoDecode(respHead, RespDataHighwayHeadSchema);
if (resp?.errorCode && resp.errorCode !== 0) {
throw new Error(`highway upload error_code=${resp.errorCode}`);
}
offset += chunkSize;
console.log(`[Highway] uploaded ${offset}/${bytes.length} bytes`);
}
} finally {
socket.destroy();
}
}
@@ -0,0 +1,195 @@
// Image upload pipeline: load image, OIDB upload request, highway upload, build message element.
// Port of src/bridge/src/highway_upload_req.cpp + highway_client.cpp (image parts)
import type { Bridge } from '../bridge';
import type { MessageElement } from '../events';
import { protoEncode, protoDecode } from '../../protobuf/decode';
import { makeOidbBaseSchema } from '../proto/oidb';
import {
NTV2UploadRichMediaReqSchema,
NTV2UploadRichMediaRespSchema,
EncodableMediaMsgInfoSchema,
} from '../proto/highway';
import {
loadBinarySource, computeHashes, detectImageFormat,
} from './utils';
import {
fetchHighwaySession, uploadHighwayHttp, buildHighwayExtend,
PRIVATE_IMAGE_CMD_ID, GROUP_IMAGE_CMD_ID,
} from './highway-client';
interface ImageData {
bytes: Uint8Array;
md5: Uint8Array;
sha1: Uint8Array;
md5Hex: string;
sha1Hex: string;
fileName: string;
summary: string;
subType: number;
width: number;
height: number;
picFormat: number;
}
function loadImage(element: MessageElement): Promise<ImageData> {
return loadImageFromSource(
element.url || element.fileId || '',
element.fileName ?? '',
element.subType ?? 0,
element.summary ?? '',
);
}
async function loadImageFromSource(source: string, fileName: string, subType: number, summary: string): Promise<ImageData> {
const loaded = await loadBinarySource(source, 'image');
const hashes = computeHashes(loaded.bytes);
const fmt = detectImageFormat(loaded.bytes);
const extMap: Record<number, string> = { 1000: '.jpg', 1001: '.png', 1002: '.webp', 1005: '.bmp', 2000: '.gif' };
const ext = extMap[fmt.format] ?? '.jpg';
let finalName = fileName || loaded.fileName;
if (!finalName) finalName = hashes.md5Hex + ext;
return {
bytes: loaded.bytes,
md5: hashes.md5,
sha1: hashes.sha1,
md5Hex: hashes.md5Hex,
sha1Hex: hashes.sha1Hex,
fileName: finalName,
summary: summary || (subType === 0 ? '[image]' : '[sticker]'),
subType,
width: fmt.width,
height: fmt.height,
picFormat: fmt.format,
};
}
async function startImageUpload(bridge: Bridge, isGroup: boolean, targetIdOrUid: string | number, image: ImageData): Promise<any> {
const body: any = {
reqHead: {
common: { requestId: 1, command: 100 },
scene: {
requestType: 2,
businessType: 1,
sceneType: isGroup ? 2 : 1,
...(isGroup
? { group: { groupUin: Number(targetIdOrUid) } }
: { c2c: { accountType: 2, targetUid: String(targetIdOrUid) } }),
},
client: { agentType: 2 },
},
upload: {
uploadInfo: [{
fileInfo: {
fileSize: image.bytes.length,
fileHash: image.md5Hex,
fileSha1: image.sha1Hex,
fileName: image.fileName,
type: { type: 1, picFormat: image.picFormat, videoFormat: 0, voiceFormat: 0 },
width: image.width,
height: image.height,
time: 0,
original: 1,
},
subFileType: 0,
}],
tryFastUploadCompleted: true,
srvSendMsg: false,
clientRandomId: BigInt(Math.floor(Math.random() * 0x7FFFFFFFFFFFFFFF)),
compatQmsgSceneType: isGroup ? 2 : 1,
extBizInfo: {
pic: {
bizType: image.subType,
textSummary: image.summary,
...(isGroup
? { reserveTroop: { subType: image.subType } }
: { reserveC2c: { subType: image.subType } }),
},
video: { bytesPbReserve: new Uint8Array(0) },
ptt: {
bytesReserve: new Uint8Array(0),
bytesPbReserve: new Uint8Array(0),
bytesGeneralFlags: new Uint8Array(0),
},
},
clientSeq: 0,
noNeedCompatMsg: false,
},
};
const oidbCmd = isGroup ? 0x11C4 : 0x11C5;
const serviceCmd = isGroup ? 'OidbSvcTrpcTcp.0x11c4_100' : 'OidbSvcTrpcTcp.0x11c5_100';
const baseSchema = makeOidbBaseSchema(NTV2UploadRichMediaReqSchema);
const request = protoEncode({
command: oidbCmd, subCommand: 100, errorCode: 0, body, errorMsg: '', reserved: 1,
}, baseSchema);
const result = await bridge.sendRawPacket(serviceCmd, request);
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(result.errorMessage || 'image upload request failed');
}
const respBaseSchema = makeOidbBaseSchema(NTV2UploadRichMediaRespSchema);
const resp: any = protoDecode(result.responseData, respBaseSchema);
if (!resp) throw new Error('failed to decode upload response');
if (resp.errorCode && resp.errorCode !== 0) {
throw new Error(`OIDB error ${resp.errorCode}: ${resp.errorMsg ?? ''}`);
}
const uploadBody = resp.body;
if (!uploadBody) throw new Error('upload response body missing');
if (uploadBody.respHead?.retCode && uploadBody.respHead.retCode !== 0) {
throw new Error(uploadBody.respHead.message ?? 'image upload failed');
}
return uploadBody.upload;
}
function finalizeImageMsgInfo(upload: any, image: ImageData): Uint8Array {
if (!upload?.msgInfo) throw new Error('upload response missing msgInfo');
const msgInfoBody = (upload.msgInfo.msgInfoBody ?? []).map((b: any) => ({
index: b.index, picture: b.picture, fileExist: b.fileExist, hashSum: b.hashSum,
}));
const extBizInfo: any = {};
if (upload.msgInfo.extBizInfo?.pic) {
extBizInfo.pic = { ...upload.msgInfo.extBizInfo.pic };
extBizInfo.pic.bizType = extBizInfo.pic.bizType ?? image.subType;
extBizInfo.pic.textSummary = extBizInfo.pic.textSummary ?? image.summary;
} else {
extBizInfo.pic = { bizType: image.subType, textSummary: image.summary };
}
if (upload.msgInfo.extBizInfo?.video) extBizInfo.video = upload.msgInfo.extBizInfo.video;
if (upload.msgInfo.extBizInfo?.ptt) extBizInfo.ptt = upload.msgInfo.extBizInfo.ptt;
if (upload.msgInfo.extBizInfo?.busiType !== undefined) extBizInfo.busiType = upload.msgInfo.extBizInfo.busiType;
return protoEncode({ msgInfoBody, extBizInfo }, EncodableMediaMsgInfoSchema);
}
/**
* Upload an image and return the encoded MsgInfo bytes to embed in a CommonElem.
*/
export async function uploadImageMsgInfo(
bridge: Bridge,
isGroup: boolean,
targetIdOrUid: string | number,
element: MessageElement,
): Promise<Uint8Array> {
const image = await loadImage(element);
const upload = await startImageUpload(bridge, isGroup, targetIdOrUid, image);
// Upload binary if uKey is present (not fast-uploaded)
const uKey = upload?.uKey ?? '';
if (uKey && upload?.msgInfo) {
const session = await fetchHighwaySession(bridge);
const extend = buildHighwayExtend(uKey, upload.msgInfo, upload.ipv4s ?? [], image.sha1);
const commandId = isGroup ? GROUP_IMAGE_CMD_ID : PRIVATE_IMAGE_CMD_ID;
await uploadHighwayHttp(bridge, session, commandId, image.bytes, image.md5, extend);
}
return finalizeImageMsgInfo(upload, image);
}
+198
View File
@@ -0,0 +1,198 @@
// Highway utilities: binary source loading, hashing, image format detection, frame packing.
// Port of src/bridge/src/highway_utils.h/.cpp
import { createHash } from 'crypto';
import fs from 'fs';
import path from 'path';
export interface LoadedBinary {
bytes: Uint8Array;
fileName: string;
}
export interface ImageHashes {
md5: Uint8Array;
sha1: Uint8Array;
md5Hex: string;
sha1Hex: string;
}
export interface ImageFormat {
format: number; // 1000=jpg, 1001=png, 1002=webp, 1005=bmp, 2000=gif
width: number;
height: number;
}
// --- Binary source loading ---
export async function loadBinarySource(source: string, resourceName: string): Promise<LoadedBinary> {
if (!source) throw new Error(`${resourceName} source is empty`);
if (source.startsWith('base64://')) {
return { bytes: Buffer.from(source.slice(9), 'base64'), fileName: '' };
}
if (source.startsWith('http://') || source.startsWith('https://')) {
const resp = await fetch(source);
if (!resp.ok) throw new Error(`HTTP download failed: ${resp.status}`);
const bytes = new Uint8Array(await resp.arrayBuffer());
const fileName = guessFileNameFromUrl(source);
return { bytes, fileName };
}
// File path (strip file:// prefix)
let filePath = source;
if (filePath.startsWith('file://')) filePath = filePath.slice(7);
// Windows: strip leading / before drive letter
if (/^\/[a-zA-Z]:/.test(filePath)) filePath = filePath.slice(1);
const bytes = fs.readFileSync(filePath);
const fileName = path.basename(filePath);
return { bytes, fileName };
}
function guessFileNameFromUrl(url: string): string {
const queryPos = url.search(/[?#]/);
const pathPart = queryPos >= 0 ? url.slice(0, queryPos) : url;
const lastSlash = pathPart.lastIndexOf('/');
return lastSlash >= 0 ? pathPart.slice(lastSlash + 1) : '';
}
// --- Hashing ---
export function computeHashes(data: Uint8Array): ImageHashes {
const md5 = createHash('md5').update(data).digest();
const sha1 = createHash('sha1').update(data).digest();
return {
md5: new Uint8Array(md5),
sha1: new Uint8Array(sha1),
md5Hex: md5.toString('hex'),
sha1Hex: sha1.toString('hex'),
};
}
export function computeMd5(data: Uint8Array): Uint8Array {
return new Uint8Array(createHash('md5').update(data).digest());
}
// --- Image format detection (port of C++ detect_image_format) ---
function readBE16(data: Uint8Array, offset: number): number {
return (data[offset] << 8) | data[offset + 1];
}
function readBE32(data: Uint8Array, offset: number): number {
return ((data[offset] << 24) | (data[offset + 1] << 16) | (data[offset + 2] << 8) | data[offset + 3]) >>> 0;
}
function readLE16(data: Uint8Array, offset: number): number {
return data[offset] | (data[offset + 1] << 8);
}
function readLE32(data: Uint8Array, offset: number): number {
return (data[offset] | (data[offset + 1] << 8) | (data[offset + 2] << 16) | (data[offset + 3] << 24)) >>> 0;
}
function readBE24(data: Uint8Array, offset: number): number {
return (data[offset] << 16) | (data[offset + 1] << 8) | data[offset + 2];
}
export function detectImageFormat(bytes: Uint8Array): ImageFormat {
let width = 0;
let height = 0;
// PNG
if (bytes.length >= 24 &&
bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4E && bytes[3] === 0x47) {
width = readBE32(bytes, 16);
height = readBE32(bytes, 20);
return { format: 1001, width, height };
}
// GIF
if (bytes.length >= 10 &&
bytes[0] === 0x47 && bytes[1] === 0x49 && bytes[2] === 0x46 && bytes[3] === 0x38 &&
(bytes[4] === 0x37 || bytes[4] === 0x39) && bytes[5] === 0x61) {
width = readLE16(bytes, 6);
height = readLE16(bytes, 8);
return { format: 2000, width, height };
}
// BMP
if (bytes.length >= 26 && bytes[0] === 0x42 && bytes[1] === 0x4D) {
width = readLE32(bytes, 18);
height = readLE32(bytes, 22);
return { format: 1005, width, height };
}
// WebP
if (bytes.length >= 30 &&
bytes[0] === 0x52 && bytes[1] === 0x49 && bytes[2] === 0x46 && bytes[3] === 0x46 &&
bytes[8] === 0x57 && bytes[9] === 0x45 && bytes[10] === 0x42 && bytes[11] === 0x50) {
if (bytes[12] === 0x56 && bytes[13] === 0x50 && bytes[14] === 0x38 && bytes[15] === 0x20) {
width = readLE16(bytes, 26);
height = readLE16(bytes, 28);
return { format: 1002, width, height };
}
if (bytes[12] === 0x56 && bytes[13] === 0x50 && bytes[14] === 0x38 && bytes[15] === 0x4C) {
const bits = readLE32(bytes, 21);
width = (bits & 0x3FFF) + 1;
height = ((bits >> 14) & 0x3FFF) + 1;
return { format: 1002, width, height };
}
if (bytes[12] === 0x56 && bytes[13] === 0x50 && bytes[14] === 0x38 && bytes[15] === 0x58) {
width = readBE24(bytes, 24) + 1;
height = readBE24(bytes, 27) + 1;
return { format: 1002, width, height };
}
}
// JPEG
if (bytes.length >= 4 && bytes[0] === 0xFF && bytes[1] === 0xD8) {
let offset = 2;
while (offset + 9 <= bytes.length) {
if (bytes[offset] !== 0xFF) { offset++; continue; }
const marker = bytes[offset + 1];
if (marker === 0xD8 || marker === 0xD9) { offset += 2; continue; }
if (offset + 4 > bytes.length) break;
const segLen = readBE16(bytes, offset + 2);
if (segLen < 2 || offset + 2 + segLen > bytes.length) break;
if ((marker & 0xFC) === 0xC0 && offset + 9 <= bytes.length) {
height = readBE16(bytes, offset + 5);
width = readBE16(bytes, offset + 7);
return { format: 1000, width, height };
}
offset += 2 + segLen;
}
return { format: 1000, width: 0, height: 0 };
}
return { format: 1000, width: 0, height: 0 };
}
// --- Highway frame packing/unpacking ---
export function packHighwayFrame(head: Uint8Array, body: Uint8Array): Uint8Array {
const frame = new Uint8Array(9 + head.length + body.length + 1);
frame[0] = 0x28;
const dv = new DataView(frame.buffer, frame.byteOffset);
dv.setUint32(1, head.length, false);
dv.setUint32(5, body.length, false);
frame.set(head, 9);
frame.set(body, 9 + head.length);
frame[frame.length - 1] = 0x29;
return frame;
}
export function unpackHighwayFrame(frame: Uint8Array): { head: Uint8Array; body: Uint8Array } {
if (frame.length < 10 || frame[0] !== 0x28 || frame[frame.length - 1] !== 0x29) {
throw new Error('invalid highway response frame');
}
const dv = new DataView(frame.buffer, frame.byteOffset);
const headLen = dv.getUint32(1, false);
const bodyLen = dv.getUint32(5, false);
return {
head: frame.subarray(9, 9 + headLen),
body: frame.subarray(9 + headLen, 9 + headLen + bodyLen),
};
}
+133
View File
@@ -0,0 +1,133 @@
// BridgeManager — manages per-UIN Bridge sessions.
// Wires NtqqHandler packets to appropriate Bridge instances.
// Port of src/bridge/include/bridge/manager.h + src/bridge/src/manager.cpp
import type { NtqqHandler } from '../protocol/ntqq-handler';
import type { PacketInfo } from '../protocol/types';
import type { QQEventVariant } from './events';
import { Bridge } from './bridge';
import { QQInfo } from './qq-info';
import type { PacketSender } from '../protocol/packet-sender';
import { createLogger } from '../utils/logger';
export type SessionStartedCallback = (uin: string, qqInfo: QQInfo, bridge: Bridge) => void;
export type SessionClosedCallback = (uin: string) => void;
export type BridgeEventCallback = (uin: string, event: QQEventVariant) => void;
interface QQSession {
qqInfo: QQInfo;
bridge: Bridge;
}
const log = createLogger('Bridge');
export class BridgeManager {
private sessions_ = new Map<string, QQSession>();
private pidToUin_ = new Map<number, string>();
private pidPacketClients_ = new Map<number, PacketSender>();
private onSessionStarted_: SessionStartedCallback | null = null;
private onSessionClosed_: SessionClosedCallback | null = null;
private onBridgeEvent_: BridgeEventCallback | null = null;
setSessionStartedCallback(cb: SessionStartedCallback): void { this.onSessionStarted_ = cb; }
setSessionClosedCallback(cb: SessionClosedCallback): void { this.onSessionClosed_ = cb; }
setEventCallback(cb: BridgeEventCallback): void { this.onBridgeEvent_ = cb; }
bind(ntqq: NtqqHandler): void {
ntqq.registerCmdAll((pkt: PacketInfo) => this.onPacket(pkt));
}
onPidDisconnected(pid: number): void {
this.pidPacketClients_.delete(pid);
const uin = this.pidToUin_.get(pid);
if (!uin) return;
this.pidToUin_.delete(pid);
const session = this.sessions_.get(uin);
if (!session) return;
session.bridge.detachPid(pid);
if (session.bridge.empty) {
this.sessions_.delete(uin);
log.debug('session closed: UIN=%s', uin);
if (this.onSessionClosed_) this.onSessionClosed_(uin);
}
}
private static isRealUin(uin: string): boolean {
if (!uin || uin === '0') return false;
return /^\d+$/.test(uin) && uin.length >= 5;
}
onHookLogin(pid: number, uin: string, packetClient: PacketSender): void {
if (!BridgeManager.isRealUin(uin)) return;
this.pidPacketClients_.set(pid, packetClient);
const { session, created } = this.ensureSession(uin);
session.bridge.attachPid(pid);
session.bridge.setPacketClient(packetClient);
this.pidToUin_.set(pid, uin);
if (created) {
log.debug('session started: UIN=%s', uin);
if (this.onSessionStarted_) {
this.onSessionStarted_(uin, session.qqInfo, session.bridge);
}
}
}
private onPacket(pkt: PacketInfo): void {
if (!pkt.uin || !BridgeManager.isRealUin(pkt.uin)) return;
const uin = pkt.uin;
// Ensure session exists
const { session, created } = this.ensureSession(uin);
// Attach PID if known
if (pkt.pid && this.pidPacketClients_.has(pkt.pid)) {
session.bridge.attachPid(pkt.pid);
this.pidToUin_.set(pkt.pid, uin);
const client = this.pidPacketClients_.get(pkt.pid);
if (client) session.bridge.setPacketClient(client);
}
// Notify session started on first real packet
if (created) {
log.debug('session started: UIN=%s', uin);
if (this.onSessionStarted_) {
this.onSessionStarted_(uin, session.qqInfo, session.bridge);
}
}
// Dispatch packet to bridge
session.bridge.onPacket(pkt);
}
private ensureSession(uin: string): { session: QQSession; created: boolean } {
let session = this.sessions_.get(uin);
if (session) return { session, created: false };
const qqInfo = new QQInfo(uin);
const bridge = new Bridge(qqInfo);
session = { qqInfo, bridge };
this.sessions_.set(uin, session);
// Wire event callback
bridge.setEventCallback((event) => {
if (this.onBridgeEvent_) this.onBridgeEvent_(uin, event);
});
return { session, created: true };
}
getSession(uin: string): QQSession | null {
return this.sessions_.get(uin) ?? null;
}
get sessions(): Map<string, { qqInfo: QQInfo; bridge: Bridge }> {
return this.sessions_;
}
}
+89
View File
@@ -0,0 +1,89 @@
// Proto schemas for outgoing message actions.
// Port of src/bridge/include/bridge/proto/action.h
import type { ProtoSchema } from '../../protobuf/decode';
import { ElemSchema } from './element';
// --- Routing ---
export const RoutingC2CSchema = {
uin: { field: 1, type: 'uint32' as const },
uid: { field: 2, type: 'string' as const },
} satisfies ProtoSchema;
export const RoutingGroupSchema = {
groupCode: { field: 1, type: 'uint64' 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 },
} satisfies ProtoSchema;
// --- Content Head (for send) ---
export const SendContentHeadSchema = {
type: { field: 1, type: 'uint32' as const },
subType: { field: 2, type: 'uint32' as const },
c2cCmd: { field: 3, type: 'uint32' as const },
} satisfies ProtoSchema;
// --- Message Control ---
export const MessageControlSchema = {
msgFlag: { field: 1, type: 'int32' as const },
} satisfies ProtoSchema;
// --- RichText (for send — only elems) ---
export const SendRichTextSchema = {
elems: { field: 2, type: 'repeated_message' as const, schema: ElemSchema },
} satisfies ProtoSchema;
// --- MessageBody (for send) ---
export const SendMessageBodySchema = {
richText: { field: 1, type: 'message' as const, schema: SendRichTextSchema },
} satisfies ProtoSchema;
// --- SendMessageRequest ---
export const SendMessageRequestSchema = {
routingHead: { field: 1, type: 'message' as const, schema: RoutingHeadSchema },
contentHead: { field: 2, type: 'message' as const, schema: SendContentHeadSchema },
messageBody: { field: 3, type: 'message' as const, schema: SendMessageBodySchema },
clientSequence: { field: 4, type: 'uint32' as const },
random: { field: 5, type: 'uint32' as const },
syncCookie: { field: 6, type: 'bytes' as const },
via: { field: 8, type: 'uint32' as const },
dataStatist: { field: 9, type: 'uint32' as const },
ctrl: { field: 12, type: 'message' as const, schema: MessageControlSchema },
multiSendSeq: { field: 14, type: 'uint32' as const },
} satisfies ProtoSchema;
// --- SendMessageResponse ---
export const SendMessageResponseSchema = {
result: { field: 1, type: 'int32' as const },
errMsg: { field: 2, type: 'string' as const },
timestamp1: { field: 3, type: 'uint32' as const },
field10: { field: 10, type: 'uint32' as const },
groupSequence: { field: 11, type: 'uint32' as const },
timestamp2: { field: 12, type: 'uint32' as const },
privateSequence: { field: 14, type: 'uint32' as const },
} satisfies ProtoSchema;
// --- MentionExtra (for building @mention text element) ---
export const MentionExtraSendSchema = {
type: { field: 3, type: 'int32' as const },
uin: { field: 4, type: 'uint32' as const },
field5: { field: 5, type: 'int32' as const },
uid: { field: 9, type: 'string' as const },
} satisfies ProtoSchema;
// --- MarkdownData ---
export const MarkdownDataSchema = {
content: { field: 1, type: 'string' as const },
} satisfies ProtoSchema;
+418
View File
@@ -0,0 +1,418 @@
// Proto schemas for QQ message elements.
// Port of src/bridge/include/bridge/proto/element.h
import type { ProtoSchema } from '../../protobuf/decode';
// --- Nested / helper schemas ---
export const CustomFacePbReserveSchema = {
subType: { field: 1, type: 'int32' as const },
summary: { field: 9, type: 'string' as const },
} satisfies ProtoSchema;
export const NotOnlineImagePbReserve2Schema = {
field1: { field: 1, type: 'int32' as const },
field2: { field: 2, type: 'string' as const },
field3: { field: 3, type: 'int32' as const },
field4: { field: 4, type: 'int32' as const },
field5: { field: 5, type: 'int32' as const },
field7: { field: 7, type: 'string' as const },
} satisfies ProtoSchema;
export const NotOnlineImagePbReserveSchema = {
subType: { field: 1, type: 'int32' as const },
field3: { field: 3, type: 'int32' as const },
field4: { field: 4, type: 'int32' as const },
summary: { field: 8, type: 'string' as const },
field10: { field: 10, type: 'int32' as const },
field20: { field: 20, type: 'message' as const, schema: NotOnlineImagePbReserve2Schema },
url: { field: 30, type: 'string' as const },
md5Str: { field: 31, type: 'string' as const },
} satisfies ProtoSchema;
// --- Core element schemas ---
export const TextElemSchema = {
str: { field: 1, type: 'string' as const },
link: { field: 2, type: 'string' as const },
attr6Buf: { field: 3, type: 'bytes' as const },
attr7Buf: { field: 4, type: 'bytes' as const },
buf: { field: 11, type: 'bytes' as const },
pbReserve: { field: 12, type: 'bytes' as const },
} satisfies ProtoSchema;
export const FaceElemSchema = {
index: { field: 1, type: 'int32' as const },
oldData: { field: 2, type: 'bytes' as const },
buf: { field: 11, type: 'bytes' as const },
} satisfies ProtoSchema;
export const OnlineImageSchema = {
guid: { field: 1, type: 'bytes' as const },
filePath: { field: 2, type: 'bytes' as const },
oldVerSendFile: { field: 3, type: 'bytes' as const },
} satisfies ProtoSchema;
export const NotOnlineImageSchema = {
filePath: { field: 1, type: 'string' as const },
fileLen: { field: 2, type: 'uint32' as const },
downloadPath: { field: 3, type: 'string' as const },
oldVerSendFile: { field: 4, type: 'bytes' as const },
imgType: { field: 5, type: 'int32' as const },
previewsImage: { field: 6, type: 'bytes' as const },
picMd5: { field: 7, type: 'bytes' as const },
picHeight: { field: 8, type: 'uint32' as const },
picWidth: { field: 9, type: 'uint32' as const },
resId: { field: 10, type: 'string' as const },
flag: { field: 11, type: 'bytes' as const },
thumbUrl: { field: 12, type: 'string' as const },
original: { field: 13, type: 'int32' as const },
bigUrl: { field: 14, type: 'string' as const },
origUrl: { field: 15, type: 'string' as const },
bizType: { field: 16, type: 'int32' as const },
result: { field: 17, type: 'int32' as const },
index: { field: 18, type: 'int32' as const },
opFaceBuf: { field: 19, type: 'bytes' as const },
oldPicMd5: { field: 20, type: 'bool' as const },
thumbWidth: { field: 21, type: 'int32' as const },
thumbHeight: { field: 22, type: 'int32' as const },
fileId: { field: 23, type: 'int32' as const },
showLen: { field: 24, type: 'uint32' as const },
downloadLen: { field: 25, type: 'uint32' as const },
x400Url: { field: 26, type: 'string' as const },
x400Width: { field: 27, type: 'int32' as const },
x400Height: { field: 28, type: 'int32' as const },
pbRes: { field: 29, type: 'message' as const, schema: NotOnlineImagePbReserveSchema },
} satisfies ProtoSchema;
export const TransElemSchema = {
elemType: { field: 1, type: 'int32' as const },
elemValue: { field: 2, type: 'bytes' as const },
} satisfies ProtoSchema;
export const MarketFaceSchema = {
faceName: { field: 1, type: 'string' as const },
itemType: { field: 2, type: 'uint32' as const },
faceInfo: { field: 3, type: 'uint32' as const },
faceId: { field: 4, type: 'bytes' as const },
tabId: { field: 5, type: 'uint32' as const },
subType: { field: 6, type: 'uint32' as const },
key: { field: 7, type: 'bytes' as const },
param: { field: 8, type: 'bytes' as const },
mediaType: { field: 9, type: 'uint32' as const },
imageWidth: { field: 10, type: 'uint32' as const },
imageHeight: { field: 11, type: 'uint32' as const },
mobileParam: { field: 12, type: 'bytes' as const },
pbReserve: { field: 13, type: 'bytes' as const },
} satisfies ProtoSchema;
export const CustomFaceSchema = {
guid: { field: 1, type: 'bytes' as const },
filePath: { field: 2, type: 'string' as const },
shortcut: { field: 3, type: 'string' as const },
buffer: { field: 4, type: 'bytes' as const },
flag: { field: 5, type: 'bytes' as const },
oldData: { field: 6, type: 'bytes' as const },
fileId: { field: 7, type: 'uint32' as const },
serverIp: { field: 8, type: 'int32' as const },
serverPort: { field: 9, type: 'int32' as const },
fileType: { field: 10, type: 'int32' as const },
signature: { field: 11, type: 'bytes' as const },
useful: { field: 12, type: 'int32' as const },
md5: { field: 13, type: 'bytes' as const },
thumbUrl: { field: 14, type: 'string' as const },
bigUrl: { field: 15, type: 'string' as const },
origUrl: { field: 16, type: 'string' as const },
bizType: { field: 17, type: 'int32' as const },
repeatIndex: { field: 18, type: 'int32' as const },
repeatImage: { field: 19, type: 'int32' as const },
imageType: { field: 20, type: 'int32' as const },
index: { field: 21, type: 'int32' as const },
width: { field: 22, type: 'int32' as const },
height: { field: 23, type: 'int32' as const },
source: { field: 24, type: 'int32' as const },
size: { field: 25, type: 'uint32' as const },
origin: { field: 26, type: 'int32' as const },
thumbWidth: { field: 27, type: 'int32' as const },
thumbHeight: { field: 28, type: 'int32' as const },
showLen: { field: 29, type: 'int32' as const },
downloadLen: { field: 30, type: 'int32' as const },
x400Url: { field: 31, type: 'string' as const },
x400Width: { field: 32, type: 'int32' as const },
x400Height: { field: 33, type: 'int32' as const },
pbRes: { field: 34, type: 'message' as const, schema: CustomFacePbReserveSchema },
} satisfies ProtoSchema;
export const RichMsgSchema = {
template1: { field: 1, type: 'bytes' as const },
serviceId: { field: 2, type: 'int32' as const },
msgResId: { field: 3, type: 'bytes' as const },
rand: { field: 4, type: 'int32' as const },
seq: { field: 5, type: 'uint32' as const },
} satisfies ProtoSchema;
export const GroupFileElemSchema = {
filename: { field: 1, type: 'string' as const },
fileSize: { field: 2, type: 'uint64' as const },
fileId: { field: 3, type: 'string' as const },
batchId: { field: 4, type: 'string' as const },
fileKey: { field: 5, type: 'string' as const },
mark: { field: 6, type: 'bytes' as const },
sequence: { field: 7, type: 'uint64' as const },
batchItemId: { field: 8, type: 'bytes' as const },
feedMsgTime: { field: 9, type: 'int32' as const },
pbReserve: { field: 10, type: 'bytes' as const },
} satisfies ProtoSchema;
export const ExtraInfoSchema = {
nick: { field: 1, type: 'bytes' as const },
groupCard: { field: 2, type: 'bytes' as const },
level: { field: 3, type: 'int32' as const },
flags: { field: 4, type: 'int32' as const },
groupMask: { field: 5, type: 'int32' as const },
msgTailId: { field: 6, type: 'int32' as const },
senderTitle: { field: 7, type: 'bytes' as const },
apnsTips: { field: 8, type: 'bytes' as const },
uin: { field: 9, type: 'uint64' as const },
msgStateFlag: { field: 10, type: 'int32' as const },
apnsSoundType: { field: 11, type: 'int32' as const },
newGroupFlag: { field: 12, type: 'int32' as const },
} satisfies ProtoSchema;
export const VideoFileSchema = {
fileUuid: { field: 1, type: 'string' as const },
fileMd5: { field: 2, type: 'bytes' as const },
fileName: { field: 3, type: 'string' as const },
fileFormat: { field: 4, type: 'int32' as const },
fileTime: { field: 5, type: 'int32' as const },
fileSize: { field: 6, type: 'int32' as const },
thumbWidth: { field: 7, type: 'int32' as const },
thumbHeight: { field: 8, type: 'int32' as const },
thumbFileMd5: { field: 9, type: 'bytes' as const },
source: { field: 10, type: 'bytes' as const },
thumbFileSize:{ field: 11, type: 'int32' as const },
busiType: { field: 12, type: 'int32' as const },
fromChatType: { field: 13, type: 'int32' as const },
toChatType: { field: 14, type: 'int32' as const },
supportProgressive: { field: 15, type: 'bool' as const },
fileWidth: { field: 16, type: 'int32' as const },
fileHeight: { field: 17, type: 'int32' as const },
subBusiType: { field: 18, type: 'int32' as const },
videoAttr: { field: 19, type: 'int32' as const },
pbReserve: { field: 24, type: 'bytes' as const },
} satisfies ProtoSchema;
export const SrcMsgSchema = {
origSeqs: { field: 1, type: 'repeated_uint32' as const },
senderUin: { field: 2, type: 'uint64' as const },
time: { field: 3, type: 'int32' as const },
flag: { field: 4, type: 'int32' as const },
elemsRaw: { field: 5, type: 'repeated_bytes' as const },
type: { field: 6, type: 'int32' as const },
richMsg: { field: 7, type: 'bytes' as const },
pbReserve: { field: 8, type: 'bytes' as const },
sourceMsg: { field: 9, type: 'bytes' as const },
toUin: { field: 10, type: 'uint64' as const },
troopName: { field: 11, type: 'bytes' as const },
} satisfies ProtoSchema;
export const LightAppElemSchema = {
data: { field: 1, type: 'bytes' as const },
msgResid: { field: 2, type: 'bytes' as const },
} satisfies ProtoSchema;
export const CommonElemSchema = {
serviceType: { field: 1, type: 'int32' as const },
pbElem: { field: 2, type: 'bytes' as const },
businessType: { field: 3, type: 'uint32' as const },
} satisfies ProtoSchema;
export const GeneralFlagsSchema = {
bubbleDiyTextId: { field: 1, type: 'int32' as const },
groupFlagNew: { field: 2, type: 'int32' as const },
uin: { field: 3, type: 'uint64' as const },
longTextFlag: { field: 6, type: 'int32' as const },
longTextResId: { field: 7, type: 'string' as const },
} satisfies ProtoSchema;
// --- Elem (union of all element types) ---
export const ElemSchema = {
text: { field: 1, type: 'message' as const, schema: TextElemSchema },
face: { field: 2, type: 'message' as const, schema: FaceElemSchema },
onlineImage: { field: 3, type: 'message' as const, schema: OnlineImageSchema },
notOnlineImage: { field: 4, type: 'message' as const, schema: NotOnlineImageSchema },
transElem: { field: 5, type: 'message' as const, schema: TransElemSchema },
marketFace: { field: 6, type: 'message' as const, schema: MarketFaceSchema },
customFace: { field: 8, type: 'message' as const, schema: CustomFaceSchema },
richMsg: { field: 12, type: 'message' as const, schema: RichMsgSchema },
groupFile: { field: 13, type: 'message' as const, schema: GroupFileElemSchema },
extraInfo: { field: 16, type: 'message' as const, schema: ExtraInfoSchema },
videoFile: { field: 19, type: 'message' as const, schema: VideoFileSchema },
generalFlags: { field: 37, type: 'message' as const, schema: GeneralFlagsSchema },
srcMsg: { field: 45, type: 'message' as const, schema: SrcMsgSchema },
lightApp: { field: 51, type: 'message' as const, schema: LightAppElemSchema },
commonElem: { field: 53, type: 'message' as const, schema: CommonElemSchema },
} satisfies ProtoSchema;
// --- Extra decode types (for CommonElem.pbElem sub-messages) ---
export const MentionExtraSchema = {
type: { field: 3, type: 'int32' as const },
uin: { field: 4, type: 'uint32' as const },
field5: { field: 5, type: 'int32' as const },
uid: { field: 9, type: 'string' as const },
} satisfies ProtoSchema;
export const QFaceExtraSchema = {
packId: { field: 1, type: 'string' as const },
stickerId: { field: 2, type: 'string' as const },
qsid: { field: 3, type: 'int32' as const },
sourceType: { field: 4, type: 'int32' as const },
stickerType: { field: 5, type: 'int32' as const },
resultId: { field: 6, type: 'string' as const },
text: { field: 7, type: 'string' as const },
randomType: { field: 9, type: 'int32' as const },
} satisfies ProtoSchema;
export const QSmallFaceExtraSchema = {
faceId: { field: 1, type: 'uint32' as const },
preview: { field: 2, type: 'string' as const },
preview2: { field: 3, type: 'string' as const },
} satisfies ProtoSchema;
// --- NTQQ MsgInfo types (CommonElem service_type 48) ---
export const FileTypeSchema = {
type: { field: 1, type: 'uint32' as const },
picFormat: { field: 2, type: 'uint32' as const },
videoFormat: { field: 3, type: 'uint32' as const },
voiceFormat: { field: 4, type: 'uint32' as const },
} satisfies ProtoSchema;
export const FileInfoSchema = {
fileSize: { field: 1, type: 'uint32' as const },
fileHash: { field: 2, type: 'string' as const },
fileSha1: { field: 3, type: 'string' as const },
fileName: { field: 4, type: 'string' as const },
type: { field: 5, type: 'message' as const, schema: FileTypeSchema },
width: { field: 6, type: 'uint32' as const },
height: { field: 7, type: 'uint32' as const },
time: { field: 8, type: 'uint32' as const },
original: { field: 9, type: 'uint32' as const },
} satisfies ProtoSchema;
export const IndexNodeSchema = {
info: { field: 1, type: 'message' as const, schema: FileInfoSchema },
fileUuid: { field: 2, type: 'string' as const },
storeId: { field: 3, type: 'uint32' as const },
uploadTime: { field: 4, type: 'uint32' as const },
ttl: { field: 5, type: 'uint32' as const },
subType: { field: 6, type: 'uint32' as const },
} satisfies ProtoSchema;
export const PicUrlExtInfoSchema = {
originalParameter: { field: 1, type: 'string' as const },
bigParameter: { field: 2, type: 'string' as const },
thumbParameter: { field: 3, type: 'string' as const },
} satisfies ProtoSchema;
export const PictureInfoSchema = {
urlPath: { field: 1, type: 'string' as const },
ext: { field: 2, type: 'message' as const, schema: PicUrlExtInfoSchema },
domain: { field: 3, type: 'string' as const },
} satisfies ProtoSchema;
export const PicExtDataSchema = {
subType: { field: 1, type: 'uint32' as const },
textSummary: { field: 9, type: 'string' as const },
} satisfies ProtoSchema;
export const PicExtBizInfoSchema = {
bizType: { field: 1, type: 'uint32' as const },
textSummary: { field: 2, type: 'string' as const },
bytesPbReserveC2c: { field: 11, type: 'bytes' as const },
extData: { field: 12, type: 'message' as const, schema: PicExtDataSchema },
fromScene: { field: 1001, type: 'uint32' as const },
toScene: { field: 1002, type: 'uint32' as const },
oldFileId: { field: 1003, type: 'uint32' as const },
} satisfies ProtoSchema;
export const VideoExtBizInfoSchema = {
fromScene: { field: 1, type: 'uint32' as const },
toScene: { field: 2, type: 'uint32' as const },
bytesPbReserve: { field: 3, type: 'bytes' as const },
} satisfies ProtoSchema;
export const PttExtBizInfoSchema = {
srcUin: { field: 1, type: 'uint64' as const },
pttScene: { field: 2, type: 'uint32' as const },
pttType: { field: 3, type: 'uint32' as const },
changeVoice: { field: 4, type: 'uint32' as const },
waveform: { field: 5, type: 'bytes' as const },
autoConvertText: { field: 6, type: 'uint32' as const },
bytesReserve: { field: 11, type: 'bytes' as const },
bytesPbReserve: { field: 12, type: 'bytes' as const },
bytesGeneralFlags: { field: 13, type: 'bytes' as const },
} satisfies ProtoSchema;
export const ExtBizInfoSchema = {
pic: { field: 1, type: 'message' as const, schema: PicExtBizInfoSchema },
video: { field: 2, type: 'message' as const, schema: VideoExtBizInfoSchema },
ptt: { field: 3, type: 'message' as const, schema: PttExtBizInfoSchema },
busiType: { field: 10, type: 'uint32' as const },
} satisfies ProtoSchema;
export const C2cSourceSchema = {
friendUid: { field: 2, type: 'string' as const },
} satisfies ProtoSchema;
export const TroopSourceSchema = {
groupUin: { field: 1, type: 'uint32' as const },
} satisfies ProtoSchema;
export const HashSumSchema = {
bytesPbReserveC2c: { field: 201, type: 'message' as const, schema: C2cSourceSchema },
troopSource: { field: 202, type: 'message' as const, schema: TroopSourceSchema },
} satisfies ProtoSchema;
export const MsgInfoBodySchema = {
index: { field: 1, type: 'message' as const, schema: IndexNodeSchema },
picture: { field: 2, type: 'message' as const, schema: PictureInfoSchema },
fileExist: { field: 5, type: 'bool' as const },
hashSum: { field: 6, type: 'message' as const, schema: HashSumSchema },
} satisfies ProtoSchema;
export const MsgInfoSchema = {
msgInfoBody: { field: 1, type: 'repeated_message' as const, schema: MsgInfoBodySchema },
extBizInfo: { field: 2, type: 'message' as const, schema: ExtBizInfoSchema },
} satisfies ProtoSchema;
// --- GroupFileExtra (TransElem type=24) ---
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 },
} satisfies ProtoSchema;
export const GroupFileExtraInnerSchema = {
info: { field: 2, type: 'message' as const, schema: GroupFileInfoSchema },
} satisfies ProtoSchema;
export const GroupFileExtraSchema = {
inner: { field: 7, type: 'message' as const, schema: GroupFileExtraInnerSchema },
} satisfies ProtoSchema;
// --- Preserve (for message receipt info) ---
export const PreserveSchema = {
messageId: { field: 3, type: 'uint64' as const },
senderUid: { field: 6, type: 'string' as const },
receiverUid: { field: 7, type: 'string' as const },
clientSequence: { field: 8, type: 'uint32' as const },
} satisfies ProtoSchema;
+354
View File
@@ -0,0 +1,354 @@
// Proto schemas for highway upload protocol.
// Port of src/bridge/include/bridge/proto/highway.h + action.h (HttpConn)
import type { ProtoSchema } from '../../protobuf/decode';
import {
IndexNodeSchema,
PictureInfoSchema,
HashSumSchema,
PicExtBizInfoSchema,
VideoExtBizInfoSchema,
PttExtBizInfoSchema,
} from '../proto/element';
// --- DataHighwayHead ---
export const DataHighwayHeadSchema = {
version: { field: 1, type: 'uint32' as const },
uin: { field: 2, type: 'string' as const },
command: { field: 3, type: 'string' as const },
seq: { field: 4, type: 'uint32' as const },
retryTimes:{ field: 5, type: 'uint32' as const },
appId: { field: 6, type: 'uint32' as const },
dataFlag: { field: 7, type: 'uint32' as const },
commandId: { field: 8, type: 'uint32' as const },
} satisfies ProtoSchema;
export const SegHeadSchema = {
serviceId: { field: 1, type: 'uint32' as const },
filesize: { field: 2, type: 'uint64' as const },
dataOffset: { field: 3, type: 'uint64' as const },
dataLength: { field: 4, type: 'uint32' as const },
retCode: { field: 5, type: 'uint32' as const },
serviceTicket: { field: 6, type: 'bytes' as const },
flag: { field: 7, type: 'uint32' as const },
md5: { field: 8, type: 'bytes' as const },
fileMd5: { field: 9, type: 'bytes' as const },
cacheAddr: { field: 10, type: 'uint32' as const },
cachePort: { field: 13, type: 'uint32' as const },
} satisfies ProtoSchema;
export const LoginSigHeadSchema = {
loginSigType: { field: 1, type: 'uint32' as const },
appId: { field: 3, type: 'uint32' as const },
} satisfies ProtoSchema;
export const ReqDataHighwayHeadSchema = {
msgBaseHead: { field: 1, type: 'message' as const, schema: DataHighwayHeadSchema },
msgSegHead: { field: 2, type: 'message' as const, schema: SegHeadSchema },
bytesReqExtendInfo: { field: 3, type: 'bytes' as const },
timestamp: { field: 4, type: 'uint64' as const },
msgLoginSigHead: { field: 5, type: 'message' as const, schema: LoginSigHeadSchema },
} satisfies ProtoSchema;
export const RespDataHighwayHeadSchema = {
msgBaseHead: { field: 1, type: 'message' as const, schema: DataHighwayHeadSchema },
msgSegHead: { field: 2, type: 'message' as const, schema: SegHeadSchema },
errorCode: { field: 3, type: 'uint32' as const },
} satisfies ProtoSchema;
// --- Highway extend (NTV2RichMediaHighwayExt) ---
export const HighwayDomainSchema = {
isEnable: { field: 1, type: 'bool' as const },
ip: { field: 2, type: 'string' as const },
} satisfies ProtoSchema;
export const HighwayIPv4Schema = {
domain: { field: 1, type: 'message' as const, schema: HighwayDomainSchema },
port: { field: 2, type: 'uint32' as const },
} satisfies ProtoSchema;
export const HighwayNetworkSchema = {
ipv4s: { field: 1, type: 'repeated_message' as const, schema: HighwayIPv4Schema },
} satisfies ProtoSchema;
export const HighwayHashSchema = {
fileSha1: { field: 1, type: 'repeated_bytes' as const },
} satisfies ProtoSchema;
export const HighwayMsgInfoBodySchema = {
index: { field: 1, type: 'message' as const, schema: IndexNodeSchema },
picture: { field: 2, type: 'message' as const, schema: PictureInfoSchema },
fileExist: { field: 5, type: 'bool' as const },
hashSum: { field: 6, type: 'message' as const, schema: HashSumSchema },
} satisfies ProtoSchema;
export const NTV2RichMediaHighwayExtSchema = {
fileUuid: { field: 1, type: 'string' as const },
uKey: { field: 2, type: 'string' as const },
network: { field: 5, type: 'message' as const, schema: HighwayNetworkSchema },
msgInfoBody: { field: 6, type: 'repeated_message' as const, schema: HighwayMsgInfoBodySchema },
blockSize: { field: 10, type: 'uint32' as const },
hash: { field: 11, type: 'message' as const, schema: HighwayHashSchema },
} satisfies ProtoSchema;
// --- File upload extend (group/private file highway) ---
export const FileUploadUrlSchema = {
unknown: { field: 1, type: 'int32' as const },
host: { field: 2, type: 'string' as const },
} satisfies ProtoSchema;
export const FileUploadHostSchema = {
url: { field: 1, type: 'message' as const, schema: FileUploadUrlSchema },
port: { field: 2, type: 'uint32' as const },
} satisfies ProtoSchema;
export const FileUploadHostConfigSchema = {
hosts: { field: 200, type: 'repeated_message' as const, schema: FileUploadHostSchema },
} satisfies ProtoSchema;
export const FileUploadNameInfoSchema = {
fileName: { field: 100, type: 'string' as const },
} satisfies ProtoSchema;
export const FileUploadClientInfoSchema = {
clientType: { field: 100, type: 'int32' as const },
appId: { field: 200, type: 'string' as const },
terminalType: { field: 300, type: 'int32' as const },
clientVer: { field: 400, type: 'string' as const },
unknown: { field: 600, type: 'int32' as const },
} satisfies ProtoSchema;
export const FileUploadFileEntrySchema = {
fileSize: { field: 100, type: 'uint64' as const },
md5: { field: 200, type: 'bytes' as const },
checkKey: { field: 300, type: 'bytes' as const },
md5S2: { field: 400, type: 'bytes' as const },
fileId: { field: 600, type: 'string' as const },
uploadKey: { field: 700, type: 'bytes' as const },
} satisfies ProtoSchema;
export const FileUploadBusiInfoSchema = {
busId: { field: 1, type: 'int32' as const },
senderUin: { field: 100, type: 'uint64' as const },
receiverUin: { field: 200, type: 'uint64' as const },
groupCode: { field: 400, type: 'uint64' as const },
} satisfies ProtoSchema;
export const FileUploadEntrySchema = {
busiBuff: { field: 100, type: 'message' as const, schema: FileUploadBusiInfoSchema },
fileEntry: { field: 200, type: 'message' as const, schema: FileUploadFileEntrySchema },
clientInfo: { field: 300, type: 'message' as const, schema: FileUploadClientInfoSchema },
fileNameInfo: { field: 400, type: 'message' as const, schema: FileUploadNameInfoSchema },
host: { field: 500, type: 'message' as const, schema: FileUploadHostConfigSchema },
} satisfies ProtoSchema;
export const FileUploadExtSchema = {
unknown1: { field: 1, type: 'int32' as const },
unknown2: { field: 2, type: 'int32' as const },
unknown3: { field: 3, type: 'int32' as const },
entry: { field: 100, type: 'message' as const, schema: FileUploadEntrySchema },
unknown200: { field: 200, type: 'int32' as const },
} satisfies ProtoSchema;
// --- Encodable MsgInfo (for embedding in message element) ---
export const EncodableMediaExtBizInfoSchema = {
pic: { field: 1, type: 'message' as const, schema: PicExtBizInfoSchema },
video: { field: 2, type: 'message' as const, schema: VideoExtBizInfoSchema },
ptt: { field: 3, type: 'message' as const, schema: PttExtBizInfoSchema },
busiType: { field: 10, type: 'uint32' as const },
} satisfies ProtoSchema;
export const EncodableMediaMsgInfoSchema = {
msgInfoBody: { field: 1, type: 'repeated_message' as const, schema: HighwayMsgInfoBodySchema },
extBizInfo: { field: 2, type: 'message' as const, schema: EncodableMediaExtBizInfoSchema },
} satisfies ProtoSchema;
// --- HttpConn.0x6ff_501 (highway session) ---
export const HttpConnSchema = {
field1: { field: 1, type: 'int32' as const },
field2: { field: 2, type: 'int32' as const },
field3: { field: 3, type: 'int32' as const },
field4: { field: 4, type: 'int32' as const },
field6: { field: 6, type: 'int32' as const },
serviceTypes: { field: 7, type: 'repeated_uint32' as const },
field9: { field: 9, type: 'int32' as const },
field10: { field: 10, type: 'int32' as const },
field11: { field: 11, type: 'int32' as const },
ver: { field: 15, type: 'string' as const },
} satisfies ProtoSchema;
export const HttpConn0x6FF501RequestSchema = {
httpConn: { field: 0x501, type: 'message' as const, schema: HttpConnSchema },
} satisfies ProtoSchema;
export const ServerAddrSchema = {
type: { field: 1, type: 'uint32' as const },
ip: { field: 2, type: 'uint32' as const }, // fixed32 as uint32
port: { field: 3, type: 'uint32' as const },
area: { field: 4, type: 'uint32' as const },
} satisfies ProtoSchema;
export const ServerInfoSchema = {
serviceType: { field: 1, type: 'uint32' as const },
serverAddrs: { field: 2, type: 'repeated_message' as const, schema: ServerAddrSchema },
} satisfies ProtoSchema;
export const HttpConnResponseSchema = {
sigSession: { field: 1, type: 'bytes' as const },
sessionKey: { field: 2, type: 'bytes' as const },
serverInfos: { field: 3, type: 'repeated_message' as const, schema: ServerInfoSchema },
} satisfies ProtoSchema;
export const HttpConn0x6FF501ResponseSchema = {
httpConn: { field: 0x501, type: 'message' as const, schema: HttpConnResponseSchema },
} satisfies ProtoSchema;
// --- NTV2 Upload Request (for OIDB 0x11C4/0x11C5) ---
export const NTV2FileTypeSchema = {
type: { field: 1, type: 'uint32' as const },
picFormat: { field: 2, type: 'uint32' as const },
videoFormat: { field: 3, type: 'uint32' as const },
voiceFormat: { field: 4, type: 'uint32' as const },
} satisfies ProtoSchema;
export const NTV2FileInfoSchema = {
fileSize: { field: 1, type: 'uint32' as const },
fileHash: { field: 2, type: 'string' as const },
fileSha1: { field: 3, type: 'string' as const },
fileName: { field: 4, type: 'string' as const },
type: { field: 5, type: 'message' as const, schema: NTV2FileTypeSchema },
width: { field: 6, type: 'uint32' as const },
height: { field: 7, type: 'uint32' as const },
time: { field: 8, type: 'uint32' as const },
original: { field: 9, type: 'uint32' as const },
} satisfies ProtoSchema;
export const NTV2UploadInfoSchema = {
fileInfo: { field: 1, type: 'message' as const, schema: NTV2FileInfoSchema },
subFileType: { field: 2, type: 'uint32' as const },
} satisfies ProtoSchema;
export const NTV2PicReserveC2CSchema = {
subType: { field: 1, type: 'uint32' as const },
} satisfies ProtoSchema;
export const NTV2PicReserveTroopSchema = {
subType: { field: 1, type: 'uint32' as const },
} satisfies ProtoSchema;
export const NTV2PicExtBizInfoSchema = {
bizType: { field: 1, type: 'uint32' as const },
textSummary: { field: 2, type: 'string' as const },
reserveC2c: { field: 11, type: 'message' as const, schema: NTV2PicReserveC2CSchema },
reserveTroop: { field: 12, type: 'message' as const, schema: NTV2PicReserveTroopSchema },
} satisfies ProtoSchema;
export const NTV2VideoExtBizInfoSchema = {
bytesPbReserve: { field: 3, type: 'bytes' as const },
} satisfies ProtoSchema;
export const NTV2PttExtBizInfoSchema = {
bytesReserve: { field: 11, type: 'bytes' as const },
bytesPbReserve: { field: 12, type: 'bytes' as const },
bytesGeneralFlags: { field: 13, type: 'bytes' as const },
} satisfies ProtoSchema;
export const NTV2ExtBizInfoSchema = {
pic: { field: 1, type: 'message' as const, schema: NTV2PicExtBizInfoSchema },
video: { field: 2, type: 'message' as const, schema: NTV2VideoExtBizInfoSchema },
ptt: { field: 3, type: 'message' as const, schema: NTV2PttExtBizInfoSchema },
busiType: { field: 10, type: 'uint32' as const },
} satisfies ProtoSchema;
export const NTV2UploadReqSchema = {
uploadInfo: { field: 1, type: 'repeated_message' as const, schema: NTV2UploadInfoSchema },
tryFastUploadCompleted: { field: 2, type: 'bool' as const },
srvSendMsg: { field: 3, type: 'bool' as const },
clientRandomId: { field: 4, type: 'uint64' as const },
compatQmsgSceneType: { field: 5, type: 'uint32' as const },
extBizInfo: { field: 6, type: 'message' as const, schema: NTV2ExtBizInfoSchema },
clientSeq: { field: 7, type: 'uint32' as const },
noNeedCompatMsg: { field: 8, type: 'bool' as const },
} satisfies ProtoSchema;
export const NTV2C2CUserInfoSchema = {
accountType: { field: 1, type: 'uint32' as const },
targetUid: { field: 2, type: 'string' as const },
} satisfies ProtoSchema;
export const NTV2GroupInfoSchema = {
groupUin: { field: 1, type: 'uint32' as const },
} satisfies ProtoSchema;
export const NTV2UploadSceneInfoSchema = {
requestType: { field: 101, type: 'uint32' as const },
businessType: { field: 102, type: 'uint32' as const },
sceneType: { field: 200, type: 'uint32' as const },
c2c: { field: 201, type: 'message' as const, schema: NTV2C2CUserInfoSchema },
group: { field: 202, type: 'message' as const, schema: NTV2GroupInfoSchema },
} satisfies ProtoSchema;
export const NTV2CommonHeadSchema = {
requestId: { field: 1, type: 'uint32' as const },
command: { field: 2, type: 'uint32' as const },
} satisfies ProtoSchema;
export const NTV2ClientMetaSchema = {
agentType: { field: 1, type: 'uint32' as const },
} satisfies ProtoSchema;
export const NTV2UploadReqHeadSchema = {
common: { field: 1, type: 'message' as const, schema: NTV2CommonHeadSchema },
scene: { field: 2, type: 'message' as const, schema: NTV2UploadSceneInfoSchema },
client: { field: 3, type: 'message' as const, schema: NTV2ClientMetaSchema },
} satisfies ProtoSchema;
export const NTV2UploadRichMediaReqSchema = {
reqHead: { field: 1, type: 'message' as const, schema: NTV2UploadReqHeadSchema },
upload: { field: 2, type: 'message' as const, schema: NTV2UploadReqSchema },
} satisfies ProtoSchema;
// --- NTV2 Upload Response ---
export const NTV2IPv4Schema = {
outIp: { field: 1, type: 'uint32' as const },
outPort: { field: 2, type: 'uint32' as const },
} satisfies ProtoSchema;
export const NTV2SubFileInfoRespSchema = {
subType: { field: 1, type: 'uint32' as const },
uKey: { field: 2, type: 'string' as const },
uKeyTtl: { field: 3, type: 'uint32' as const },
ipv4s: { field: 4, type: 'repeated_message' as const, schema: NTV2IPv4Schema },
} satisfies ProtoSchema;
export const NTV2UploadRespMsgInfoSchema = {
msgInfoBody: { field: 1, type: 'repeated_message' as const, schema: HighwayMsgInfoBodySchema },
extBizInfo: { field: 2, type: 'message' as const, schema: NTV2ExtBizInfoSchema },
} satisfies ProtoSchema;
export const NTV2UploadRespBodySchema = {
uKey: { field: 1, type: 'string' as const },
uKeyTtl: { field: 2, type: 'uint32' as const },
ipv4s: { field: 3, type: 'repeated_message' as const, schema: NTV2IPv4Schema },
msgSeq: { field: 5, type: 'uint64' as const },
msgInfo: { field: 6, type: 'message' as const, schema: NTV2UploadRespMsgInfoSchema },
subFileInfos: { field: 10, type: 'repeated_message' as const, schema: NTV2SubFileInfoRespSchema },
} satisfies ProtoSchema;
export const NTV2UploadRespHeadSchema = {
common: { field: 1, type: 'message' as const, schema: NTV2CommonHeadSchema },
retCode: { field: 2, type: 'uint32' as const },
message: { field: 3, type: 'string' as const },
} satisfies ProtoSchema;
export const NTV2UploadRichMediaRespSchema = {
respHead: { field: 1, type: 'message' as const, schema: NTV2UploadRespHeadSchema },
upload: { field: 2, type: 'message' as const, schema: NTV2UploadRespBodySchema },
} satisfies ProtoSchema;
+68
View File
@@ -0,0 +1,68 @@
import type { ProtoSchema } from '../../protobuf/decode';
import { PushMsgBodySchema } from './message';
export const LongMsgUidSchema = {
uid: { field: 2, type: 'string' as const },
} satisfies ProtoSchema;
export const LongMsgSettingsSchema = {
field1: { field: 1, type: 'uint32' as const },
field2: { field: 2, type: 'uint32' as const },
field3: { field: 3, type: 'uint32' as const },
field4: { field: 4, type: 'uint32' as const },
} satisfies ProtoSchema;
export const SendLongMsgInfoSchema = {
type: { field: 1, type: 'uint32' as const },
uid: { field: 2, type: 'message' as const, schema: LongMsgUidSchema },
groupUin: { field: 3, type: 'uint32' as const },
payload: { field: 4, type: 'bytes' as const },
} satisfies ProtoSchema;
export const SendLongMsgReqSchema = {
info: { field: 2, type: 'message' as const, schema: SendLongMsgInfoSchema },
settings: { field: 15, type: 'message' as const, schema: LongMsgSettingsSchema },
} satisfies ProtoSchema;
export const SendLongMsgRespResultSchema = {
resId: { field: 3, type: 'string' as const },
} satisfies ProtoSchema;
export const SendLongMsgRespSchema = {
result: { field: 2, type: 'message' as const, schema: SendLongMsgRespResultSchema },
settings: { field: 15, type: 'message' as const, schema: LongMsgSettingsSchema },
} satisfies ProtoSchema;
export const RecvLongMsgInfoSchema = {
uid: { field: 1, type: 'message' as const, schema: LongMsgUidSchema },
resId: { field: 2, type: 'string' as const },
acquire: { field: 3, type: 'bool' as const },
} satisfies ProtoSchema;
export const RecvLongMsgReqSchema = {
info: { field: 1, type: 'message' as const, schema: RecvLongMsgInfoSchema },
settings: { field: 15, type: 'message' as const, schema: LongMsgSettingsSchema },
} satisfies ProtoSchema;
export const RecvLongMsgRespResultSchema = {
resId: { field: 3, type: 'string' as const },
payload: { field: 4, type: 'bytes' as const },
} satisfies ProtoSchema;
export const RecvLongMsgRespSchema = {
result: { field: 1, type: 'message' as const, schema: RecvLongMsgRespResultSchema },
settings: { field: 15, type: 'message' as const, schema: LongMsgSettingsSchema },
} satisfies ProtoSchema;
export const LongMsgContentSchema = {
msgBody: { field: 1, type: 'repeated_message' as const, schema: PushMsgBodySchema },
} satisfies ProtoSchema;
export const LongMsgActionSchema = {
actionCommand: { field: 1, type: 'string' as const },
actionData: { field: 2, type: 'message' as const, schema: LongMsgContentSchema },
} satisfies ProtoSchema;
export const LongMsgResultSchema = {
action: { field: 2, type: 'repeated_message' as const, schema: LongMsgActionSchema },
} satisfies ProtoSchema;
+113
View File
@@ -0,0 +1,113 @@
// Proto schemas for message envelopes (PushMsg).
// Port of src/bridge/include/bridge/proto/message.h
import type { ProtoSchema } from '../../protobuf/decode';
import { ElemSchema } from './element';
// --- ResponseHead.Grp ---
export const ResponseGrpSchema = {
groupUin: { field: 1, type: 'uint32' as const },
memberName: { field: 2, type: 'string' as const },
groupName: { field: 4, type: 'string' as const },
} satisfies ProtoSchema;
export const ResponseForwardSchema = {
friendName: { field: 6, type: 'string' as const },
} satisfies ProtoSchema;
// --- ResponseHead ---
export const ResponseHeadSchema = {
fromUin: { field: 1, type: 'uint32' as const },
fromUid: { field: 2, type: 'string' as const },
type: { field: 3, type: 'uint32' as const },
sigMap: { field: 4, type: 'uint32' as const },
toUin: { field: 5, type: 'uint32' as const },
toUid: { field: 6, type: 'string' as const },
forward: { field: 7, type: 'message' as const, schema: ResponseForwardSchema },
grp: { field: 8, type: 'message' as const, schema: ResponseGrpSchema },
} satisfies ProtoSchema;
// --- ContentHead ---
export const ContentHeadSchema = {
msgType: { field: 1, type: 'uint32' as const },
subType: { field: 2, type: 'uint32' as const },
divSeq: { field: 3, type: 'uint32' as const },
msgId: { field: 4, type: 'uint32' as const },
sequence: { field: 5, type: 'uint32' as const },
timestamp: { field: 6, type: 'uint32' as const },
field7: { field: 7, type: 'uint64' as const },
newId: { field: 12, type: 'uint64' as const },
} satisfies ProtoSchema;
// --- Ptt (voice) ---
export const PttSchema = {
fileType: { field: 1, type: 'uint32' as const },
fileId: { field: 2, type: 'uint64' as const },
fileUuid: { field: 3, type: 'bytes' as const },
fileMd5: { field: 4, type: 'bytes' as const },
fileName: { field: 5, type: 'string' as const },
fileSize: { field: 6, type: 'uint32' as const },
groupFileKey: { field: 10, type: 'string' as const },
fileKey: { field: 14, type: 'bytes' as const },
time: { field: 19, type: 'uint32' as const },
format: { field: 29, type: 'uint32' as const },
} satisfies ProtoSchema;
// --- NotOnlineFile (C2C file) ---
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 },
} satisfies ProtoSchema;
// --- RichText ---
export const RichTextSchema = {
elems: { field: 2, type: 'repeated_message' as const, schema: ElemSchema },
notOnlineFile: { field: 3, type: 'message' as const, schema: NotOnlineFileSchema },
ptt: { field: 4, type: 'message' as const, schema: PttSchema },
} satisfies ProtoSchema;
// --- MessageBody ---
export const MessageBodySchema = {
richText: { field: 1, type: 'message' as const, schema: RichTextSchema },
msgContent: { field: 2, type: 'bytes' as const },
} 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;
export const FileExtraSchema = {
file: { field: 1, type: 'message' as const, schema: FileExtraInfoSchema },
} satisfies ProtoSchema;
// --- PushMsgBody ---
export const PushMsgBodySchema = {
responseHead: { field: 1, type: 'message' as const, schema: ResponseHeadSchema },
contentHead: { field: 2, type: 'message' as const, schema: ContentHeadSchema },
body: { field: 3, type: 'message' as const, schema: MessageBodySchema },
} satisfies ProtoSchema;
// --- PushMsg (top-level) ---
export const PushMsgSchema = {
message: { field: 1, type: 'message' as const, schema: PushMsgBodySchema },
status: { field: 3, type: 'int32' as const },
} satisfies ProtoSchema;
+207
View File
@@ -0,0 +1,207 @@
// Proto schemas for notification types.
// Port of src/bridge/include/bridge/proto/notify.h
import type { ProtoSchema } from '../../protobuf/decode';
export const OperatorField1Schema = {
uid: { field: 1, type: 'string' as const },
field2: { field: 2, type: 'uint32' as const },
field3: { field: 3, type: 'bytes' as const },
field4: { field: 4, type: 'uint32' as const },
field5: { field: 5, type: 'bytes' as const },
} satisfies ProtoSchema;
export const OperatorInfoSchema = {
operatorField: { field: 1, type: 'message' as const, schema: OperatorField1Schema },
} satisfies ProtoSchema;
export const GroupChangeSchema = {
groupUin: { field: 1, type: 'uint32' as const },
flag: { field: 2, type: 'uint32' as const },
memberUid: { field: 3, type: 'string' as const },
decreaseType: { field: 4, type: 'uint32' as const },
operatorBytes: { field: 5, type: 'bytes' as const },
increaseType: { field: 6, type: 'uint32' as const },
field7: { field: 7, type: 'bytes' as const },
} satisfies ProtoSchema;
export const GroupAdminExtraSchema = {
adminUid: { field: 1, type: 'string' as const },
isPromote: { field: 2, type: 'bool' as const },
} satisfies ProtoSchema;
export const GroupAdminBodySchema = {
extraDisable: { field: 1, type: 'message' as const, schema: GroupAdminExtraSchema },
extraEnable: { field: 2, type: 'message' as const, schema: GroupAdminExtraSchema },
} satisfies ProtoSchema;
export const GroupAdminSchema = {
groupUin: { field: 1, type: 'uint32' as const },
flag: { field: 2, type: 'uint32' as const },
isPromote: { field: 3, type: 'bool' as const },
body: { field: 4, type: 'message' as const, schema: GroupAdminBodySchema },
} satisfies ProtoSchema;
export const InvitationInnerSchema = {
groupUin: { field: 1, type: 'uint32' as const },
field2: { field: 2, type: 'uint32' as const },
field3: { field: 3, type: 'uint32' as const },
field4: { field: 4, type: 'uint32' as const },
targetUid: { field: 5, type: 'string' as const },
invitorUid: { field: 6, type: 'string' as const },
field7: { field: 7, type: 'uint32' as const },
field9: { field: 9, type: 'uint32' as const },
field10: { field: 10, type: 'bytes' as const },
field11: { field: 11, type: 'uint32' as const },
field12: { field: 12, type: 'string' as const },
} satisfies ProtoSchema;
export const InvitationInfoSchema = {
inner: { field: 1, type: 'message' as const, schema: InvitationInnerSchema },
} satisfies ProtoSchema;
export const GroupInvitationSchema = {
cmd: { field: 1, type: 'int32' as const },
info: { field: 2, type: 'message' as const, schema: InvitationInfoSchema },
} satisfies ProtoSchema;
export const GroupInviteSchema = {
groupUin: { field: 1, type: 'uint32' as const },
field2: { field: 2, type: 'uint32' as const },
field3: { field: 3, type: 'uint32' as const },
field4: { field: 4, type: 'uint32' as const },
invitorUid: { field: 5, type: 'string' as const },
hashes: { field: 6, type: 'bytes' as const },
} satisfies ProtoSchema;
export const GroupJoinSchema = {
groupUin: { field: 1, type: 'uint32' as const },
field2: { field: 2, type: 'uint32' as const },
targetUid: { field: 3, type: 'string' as const },
field4: { field: 4, type: 'uint32' as const },
field6: { field: 6, type: 'uint32' as const },
field7: { field: 7, type: 'string' as const },
field8: { field: 8, type: 'uint32' as const },
field9: { field: 9, type: 'bytes' as const },
} satisfies ProtoSchema;
export const FriendRequestInfoSchema = {
targetUid: { field: 1, type: 'string' as const },
sourceUid: { field: 2, type: 'string' as const },
newSource: { field: 5, type: 'string' as const },
message: { field: 10, type: 'string' as const },
source: { field: 11, type: 'string' as const },
} satisfies ProtoSchema;
export const FriendRequestSchema = {
info: { field: 1, type: 'message' as const, schema: FriendRequestInfoSchema },
} satisfies ProtoSchema;
export const FriendRecallTipInfoSchema = {
tip: { field: 2, type: 'string' as const },
} satisfies ProtoSchema;
export const FriendRecallInfoSchema = {
fromUid: { field: 1, type: 'string' as const },
toUid: { field: 2, type: 'string' as const },
clientSequence: { field: 3, type: 'uint32' as const },
newId: { field: 4, type: 'uint64' as const },
time: { field: 5, type: 'uint32' as const },
random: { field: 6, type: 'uint32' as const },
pkgNum: { field: 7, type: 'uint32' as const },
pkgIndex: { field: 8, type: 'uint32' as const },
divSeq: { field: 9, type: 'uint32' as const },
tipInfo: { field: 13, type: 'message' as const, schema: FriendRecallTipInfoSchema },
} satisfies ProtoSchema;
export const FriendRecallSchema = {
info: { field: 1, type: 'message' as const, schema: FriendRecallInfoSchema },
instId: { field: 2, type: 'uint32' as const },
appId: { field: 3, type: 'uint32' as const },
longMessageFlag: { field: 4, type: 'uint32' as const },
reserved: { field: 5, type: 'bytes' as const },
} satisfies ProtoSchema;
export const GroupMuteStateSchema = {
targetUid: { field: 1, type: 'string' as const },
duration: { field: 2, type: 'uint32' as const },
} satisfies ProtoSchema;
export const GroupMuteDataSchema = {
timestamp: { field: 1, type: 'uint32' as const },
type: { field: 2, type: 'uint32' as const },
state: { field: 3, type: 'message' as const, schema: GroupMuteStateSchema },
} satisfies ProtoSchema;
export const GroupMuteSchema = {
groupUin: { field: 1, type: 'uint32' as const },
subType: { field: 2, type: 'uint32' as const },
field3: { field: 3, type: 'uint32' as const },
operatorUid: { field: 4, type: 'string' as const },
data: { field: 5, type: 'message' as const, schema: GroupMuteDataSchema },
} satisfies ProtoSchema;
export const RecallMessageSchema = {
sequence: { field: 1, type: 'uint32' as const },
time: { field: 2, type: 'uint32' as const },
random: { field: 3, type: 'uint32' as const },
type: { field: 4, type: 'uint32' as const },
flag: { field: 5, type: 'uint32' as const },
authorUid: { field: 6, type: 'string' as const },
} satisfies ProtoSchema;
export const GroupRecallTipInfoSchema = {
tip: { field: 2, type: 'string' as const },
} satisfies ProtoSchema;
export const GroupRecallSchema = {
operatorUid: { field: 1, type: 'string' as const },
recallMessages: { field: 3, type: 'repeated_message' as const, schema: RecallMessageSchema },
userDef: { field: 5, type: 'bytes' as const },
groupType: { field: 6, type: 'int32' as const },
opType: { field: 7, type: 'int32' as const },
tipInfo: { field: 9, type: 'message' as const, schema: GroupRecallTipInfoSchema },
} satisfies ProtoSchema;
export const TemplParamSchema = {
name: { field: 1, type: 'string' as const },
value: { field: 2, type: 'string' as const },
} satisfies ProtoSchema;
export const GeneralGrayTipInfoSchema = {
busiType: { field: 1, type: 'uint64' as const },
busiId: { field: 2, type: 'uint64' as const },
ctrlFlag: { field: 3, type: 'uint32' as const },
c2cType: { field: 4, type: 'uint32' as const },
serviceType: { field: 5, type: 'uint32' as const },
templId: { field: 6, type: 'uint64' as const },
msgTemplParam: { field: 7, type: 'repeated_message' as const, schema: TemplParamSchema },
content: { field: 8, type: 'string' as const },
} satisfies ProtoSchema;
export const EssenceMessageSchema = {
groupUin: { field: 1, type: 'uint32' as const },
msgSequence: { field: 2, type: 'uint32' as const },
random: { field: 3, type: 'uint32' as const },
setFlag: { field: 4, type: 'uint32' as const },
memberUin: { field: 5, type: 'uint32' as const },
operatorUin: { field: 6, type: 'uint32' as const },
timestamp: { field: 7, type: 'uint32' as const },
msgSequence2: { field: 8, type: 'uint32' as const },
operatorNickname: { field: 9, type: 'string' as const },
memberNickname: { field: 10, type: 'string' as const },
setFlag2: { field: 11, type: 'uint32' as const },
} satisfies ProtoSchema;
export const NotifyMessageBodySchema = {
type: { field: 1, type: 'uint32' as const },
groupUin: { field: 4, type: 'uint32' as const },
eventParam: { field: 5, type: 'bytes' as const },
recall: { field: 11, type: 'message' as const, schema: GroupRecallSchema },
field13: { field: 13, type: 'uint32' as const },
operatorUid: { field: 21, type: 'string' as const },
generalGrayTip: { field: 26, type: 'message' as const, schema: GeneralGrayTipInfoSchema },
essenceMessage: { field: 33, type: 'message' as const, schema: EssenceMessageSchema },
msgSequence: { field: 37, type: 'uint32' as const },
field39: { field: 39, type: 'uint32' as const },
} satisfies ProtoSchema;
@@ -0,0 +1,788 @@
// Proto schemas for OIDB action requests.
// Port of src/bridge/include/bridge/proto/oidb.h (action-related structs)
// and src/bridge/src/bridge.cpp (recall message structs)
import type { ProtoSchema } from '../../protobuf/decode';
// --- 0x1253_1: Mute group member ---
export const OidbMuteMemberBodySchema = {
targetUid: { field: 1, type: 'string' as const },
duration: { field: 2, type: 'uint32' as const },
} satisfies ProtoSchema;
export const OidbMuteMemberSchema = {
groupUin: { field: 1, type: 'uint32' as const },
type: { field: 2, type: 'uint32' as const },
body: { field: 3, type: 'message' as const, schema: OidbMuteMemberBodySchema },
} satisfies ProtoSchema;
// --- 0x89A_0: Mute group all ---
export const OidbMuteAllStateSchema = {
state: { field: 17, type: 'uint32' as const },
} satisfies ProtoSchema;
export const OidbMuteAllSchema = {
groupUin: { field: 1, type: 'uint32' as const },
muteState: { field: 2, type: 'message' as const, schema: OidbMuteAllStateSchema },
} satisfies ProtoSchema;
// --- 0x8A0_1: Kick group member ---
export const OidbKickMemberSchema = {
groupUin: { field: 1, type: 'uint32' as const },
targetUid: { field: 3, type: 'string' as const },
rejectAddRequest:{ field: 4, type: 'bool' as const },
reason: { field: 5, type: 'string' as const },
} satisfies ProtoSchema;
// --- 0x1097_1: Leave group ---
export const OidbLeaveGroupSchema = {
groupUin: { field: 1, type: 'uint32' as const },
} satisfies ProtoSchema;
// --- 0xB5D_44: Friend add request ---
export const OidbFriendRequestActionSchema = {
accept: { field: 1, type: 'uint32' as const },
targetUid: { field: 2, type: 'string' as const },
} satisfies ProtoSchema;
// --- 0x126B_0: Delete friend ---
export const OidbDeleteFriendField2Field3Schema = {
field1: { field: 1, type: 'uint32' as const },
field2: { field: 2, type: 'uint32' as const },
field3: { field: 3, type: 'uint32' as const },
} satisfies ProtoSchema;
export const OidbDeleteFriendField2Schema = {
field1: { field: 1, type: 'uint32' as const },
field2: { field: 2, type: 'uint32' as const },
field3: { field: 3, type: 'message' as const, schema: OidbDeleteFriendField2Field3Schema },
} satisfies ProtoSchema;
export const OidbDeleteFriendField1Schema = {
targetUid: { field: 1, type: 'string' as const },
field2: { field: 2, type: 'message' as const, schema: OidbDeleteFriendField2Schema },
block: { field: 3, type: 'bool' as const },
field4: { field: 4, type: 'bool' as const },
} satisfies ProtoSchema;
export const OidbDeleteFriendSchema = {
field1: { field: 1, type: 'message' as const, schema: OidbDeleteFriendField1Schema },
} satisfies ProtoSchema;
// --- 0x10C8: Group request action ---
export const OidbGroupRequestBodySchema = {
sequence: { field: 1, type: 'uint64' as const },
eventType: { field: 2, type: 'uint32' as const },
groupUin: { field: 3, type: 'uint32' as const },
message: { field: 4, type: 'string' as const },
} satisfies ProtoSchema;
export const OidbGroupRequestActionSchema = {
accept: { field: 1, type: 'uint32' as const },
body: { field: 2, type: 'message' as const, schema: OidbGroupRequestBodySchema },
} satisfies ProtoSchema;
// --- 0xED3_1: Poke ---
export const OidbPokeSchema = {
uin: { field: 1, type: 'uint32' as const },
groupUin: { field: 2, type: 'uint32' as const },
friendUin: { field: 5, type: 'uint32' as const },
ext: { field: 6, type: 'uint32' as const },
} satisfies ProtoSchema;
// --- 0xEAC: Group essence ---
export const OidbEssenceSchema = {
groupUin: { field: 1, type: 'uint32' as const },
sequence: { field: 2, type: 'uint32' as const },
random: { field: 3, type: 'uint32' as const },
} satisfies ProtoSchema;
// --- 0x1096_1: Set group admin ---
export const OidbSetAdminSchema = {
groupUin: { field: 1, type: 'uint32' as const },
uid: { field: 2, type: 'string' as const },
isAdmin: { field: 3, type: 'bool' as const },
} satisfies ProtoSchema;
// --- 0x8FC_3: Set group card (rename member) ---
export const OidbRenameMemberBodySchema = {
targetUid: { field: 1, type: 'string' as const },
targetName: { field: 2, type: 'string' as const },
} satisfies ProtoSchema;
export const OidbRenameMemberSchema = {
groupUin: { field: 1, type: 'uint32' as const },
body: { field: 2, type: 'message' as const, schema: OidbRenameMemberBodySchema },
} satisfies ProtoSchema;
// --- 0x89A_15: Rename group ---
export const OidbRenameGroupBodySchema = {
targetName: { field: 1, type: 'string' as const },
} satisfies ProtoSchema;
export const OidbRenameGroupSchema = {
groupUin: { field: 1, type: 'uint32' as const },
body: { field: 2, type: 'message' as const, schema: OidbRenameGroupBodySchema },
} satisfies ProtoSchema;
// --- 0x8FC_2: Set group special title ---
export const OidbSpecialTitleBodySchema = {
targetUid: { field: 1, type: 'string' as const },
specialTitle:{ field: 5, type: 'string' as const },
expireTime: { field: 6, type: 'int32' as const },
} satisfies ProtoSchema;
export const OidbSpecialTitleSchema = {
groupUin: { field: 1, type: 'uint32' as const },
body: { field: 2, type: 'message' as const, schema: OidbSpecialTitleBodySchema },
} satisfies ProtoSchema;
// --- 0x7E5_104: Send like ---
export const OidbLikeSchema = {
targetUin: { field: 1, type: 'uint32' as const },
count: { field: 2, type: 'uint32' as const },
} satisfies ProtoSchema;
// --- 0x10C0_1 / 0x10C0_2: Group request list ---
export const OidbGroupRequestListSchema = {
count: { field: 1, type: 'uint32' as const },
field2: { field: 2, type: 'uint32' as const },
} satisfies ProtoSchema;
// --- 0xFE1_2: User profile info ---
export const OidbUserInfoKeySchema = {
key: { field: 1, type: 'uint32' as const },
} satisfies ProtoSchema;
export const OidbUserInfoRequestSchema = {
uin: { field: 1, type: 'uint32' as const },
field2: { field: 2, type: 'uint32' as const },
keys: { field: 3, type: 'repeated_message' as const, schema: OidbUserInfoKeySchema },
} satisfies ProtoSchema;
export const OidbTwoNumberSchema = {
number1: { field: 1, type: 'uint32' as const },
number2: { field: 2, type: 'uint32' as const },
} satisfies ProtoSchema;
export const OidbBytePropertySchema = {
code: { field: 1, type: 'uint32' as const },
value: { field: 2, type: 'bytes' as const },
} satisfies ProtoSchema;
export const OidbUserInfoPropertySchema = {
numberProperties: { field: 1, type: 'repeated_message' as const, schema: OidbTwoNumberSchema },
bytesProperties: { field: 2, type: 'repeated_message' as const, schema: OidbBytePropertySchema },
} satisfies ProtoSchema;
export const OidbUserInfoResponseBodySchema = {
uid: { field: 1, type: 'string' as const },
properties: { field: 2, type: 'message' as const, schema: OidbUserInfoPropertySchema },
uin: { field: 3, type: 'uint32' as const },
} satisfies ProtoSchema;
export const OidbUserInfoResponseSchema = {
body: { field: 1, type: 'message' as const, schema: OidbUserInfoResponseBodySchema },
} satisfies ProtoSchema;
export const AvatarInfoSchema = {
url: { field: 5, type: 'string' as const },
} satisfies ProtoSchema;
// --- FD4_1: Friend list request body fields ---
export const OidbFriendListNumberSchema = {
numbers: { field: 1, type: 'repeated_uint32' as const },
} satisfies ProtoSchema;
export const OidbFriendListBodyItemSchema = {
type: { field: 1, type: 'uint32' as const },
number: { field: 2, type: 'message' as const, schema: OidbFriendListNumberSchema },
} satisfies ProtoSchema;
export const OidbFriendListNextUinSchema = {
uin: { field: 1, type: 'uint32' as const },
} satisfies ProtoSchema;
export const OidbFriendListRequestSchema = {
friendCount: { field: 2, type: 'uint32' as const },
field4: { field: 4, type: 'uint32' as const },
nextUin: { field: 5, type: 'message' as const, schema: OidbFriendListNextUinSchema },
field6: { field: 6, type: 'uint32' as const },
field7: { field: 7, type: 'uint32' as const },
body: { field: 10001, type: 'repeated_message' as const, schema: OidbFriendListBodyItemSchema },
field10002: { field: 10002, type: 'repeated_uint32' as const },
field10003: { field: 10003, type: 'uint32' as const },
} satisfies ProtoSchema;
// --- FE5_2: Group list request body (config fields) ---
export const OidbGroupListConfig1Schema = {
groupOwner: { field: 1, type: 'bool' as const },
field2: { field: 2, type: 'bool' as const },
memberMax: { field: 3, type: 'bool' as const },
memberCount: { field: 4, type: 'bool' as const },
groupName: { field: 5, type: 'bool' as const },
field8: { field: 8, type: 'bool' as const },
field9: { field: 9, type: 'bool' as const },
field10: { field: 10, type: 'bool' as const },
field11: { field: 11, type: 'bool' as const },
field12: { field: 12, type: 'bool' as const },
field13: { field: 13, type: 'bool' as const },
field14: { field: 14, type: 'bool' as const },
field15: { field: 15, type: 'bool' as const },
field16: { field: 16, type: 'bool' as const },
field17: { field: 17, type: 'bool' as const },
field18: { field: 18, type: 'bool' as const },
question: { field: 19, type: 'bool' as const },
field20: { field: 20, type: 'bool' as const },
field22: { field: 22, type: 'bool' as const },
field23: { field: 23, type: 'bool' as const },
field24: { field: 24, type: 'bool' as const },
field25: { field: 25, type: 'bool' as const },
field26: { field: 26, type: 'bool' as const },
field27: { field: 27, type: 'bool' as const },
field28: { field: 28, type: 'bool' as const },
field29: { field: 29, type: 'bool' as const },
field30: { field: 30, type: 'bool' as const },
field31: { field: 31, type: 'bool' as const },
field32: { field: 32, type: 'bool' as const },
field5001: { field: 5001, type: 'bool' as const },
field5002: { field: 5002, type: 'bool' as const },
field5003: { field: 5003, type: 'bool' as const },
} satisfies ProtoSchema;
export const OidbGroupListConfig2Schema = {
field1: { field: 1, type: 'bool' as const },
field2: { field: 2, type: 'bool' as const },
field3: { field: 3, type: 'bool' as const },
field4: { field: 4, type: 'bool' as const },
field5: { field: 5, type: 'bool' as const },
field6: { field: 6, type: 'bool' as const },
field7: { field: 7, type: 'bool' as const },
field8: { field: 8, type: 'bool' as const },
} satisfies ProtoSchema;
export const OidbGroupListConfig3Schema = {
field5: { field: 5, type: 'bool' as const },
field6: { field: 6, type: 'bool' as const },
} satisfies ProtoSchema;
export const OidbGroupListConfigSchema = {
config1: { field: 1, type: 'message' as const, schema: OidbGroupListConfig1Schema },
config2: { field: 2, type: 'message' as const, schema: OidbGroupListConfig2Schema },
config3: { field: 3, type: 'message' as const, schema: OidbGroupListConfig3Schema },
} satisfies ProtoSchema;
export const OidbGroupListRequestSchema = {
config: { field: 1, type: 'message' as const, schema: OidbGroupListConfigSchema },
} satisfies ProtoSchema;
// --- FE7_3: Group member list request body ---
export const OidbGroupMemberListBodySchema = {
memberName: { field: 10, type: 'bool' as const },
memberCard: { field: 11, type: 'bool' as const },
level: { field: 12, type: 'bool' as const },
field13: { field: 13, type: 'bool' as const },
field16: { field: 16, type: 'bool' as const },
specialTitle: { field: 17, type: 'bool' as const },
field18: { field: 18, type: 'bool' as const },
field20: { field: 20, type: 'bool' as const },
field21: { field: 21, type: 'bool' as const },
joinTimestamp: { field: 100, type: 'bool' as const },
lastMsgTimestamp: { field: 101, type: 'bool' as const },
shutUpTimestamp: { field: 102, type: 'bool' as const },
field103: { field: 103, type: 'bool' as const },
field104: { field: 104, type: 'bool' as const },
field105: { field: 105, type: 'bool' as const },
field106: { field: 106, type: 'bool' as const },
permission: { field: 107, type: 'bool' as const },
field200: { field: 200, type: 'bool' as const },
field201: { field: 201, type: 'bool' as const },
} satisfies ProtoSchema;
export const OidbGroupMemberListRequestSchema = {
groupUin: { field: 1, type: 'uint32' as const },
field2: { field: 2, type: 'uint32' as const },
field3: { field: 3, type: 'uint32' as const },
body: { field: 4, type: 'message' as const, schema: OidbGroupMemberListBodySchema },
token: { field: 15, type: 'string' as const },
} satisfies ProtoSchema;
// --- Group recall message (trpc.msg.msg_svc.MsgService.SsoGroupRecallMsg) ---
export const GroupRecallInfoSchema = {
sequence: { field: 1, type: 'uint32' as const },
random: { field: 2, type: 'uint32' as const },
field3: { field: 3, type: 'uint32' as const },
} satisfies ProtoSchema;
export const GroupRecallSettingsSchema = {
field1: { field: 1, type: 'uint32' as const },
} satisfies ProtoSchema;
export const GroupRecallRequestSchema = {
type: { field: 1, type: 'uint32' as const },
groupUin: { field: 2, type: 'uint32' as const },
info: { field: 3, type: 'message' as const, schema: GroupRecallInfoSchema },
settings: { field: 4, type: 'message' as const, schema: GroupRecallSettingsSchema },
} satisfies ProtoSchema;
// --- C2C (private) recall message (trpc.msg.msg_svc.MsgService.SsoC2CRecallMsg) ---
export const C2CRecallInfoSchema = {
clientSequence: { field: 1, type: 'uint32' as const },
random: { field: 2, type: 'uint32' as const },
messageId: { field: 3, type: 'uint64' as const },
timestamp: { field: 4, type: 'uint32' as const },
field5: { field: 5, type: 'uint32' as const },
messageSequence: { field: 6, type: 'uint32' as const },
} satisfies ProtoSchema;
export const C2CRecallSettingsSchema = {
field1: { field: 1, type: 'bool' as const },
field2: { field: 2, type: 'bool' as const },
} satisfies ProtoSchema;
export const C2CRecallRequestSchema = {
type: { field: 1, type: 'uint32' as const },
targetUid:{ field: 3, type: 'string' as const },
info: { field: 4, type: 'message' as const, schema: C2CRecallInfoSchema },
settings: { field: 5, type: 'message' as const, schema: C2CRecallSettingsSchema },
field6: { field: 6, type: 'bool' as const },
} satisfies ProtoSchema;
// --- 0x9082_1: Set group reaction ---
export const OidbGroupReactionSchema = {
groupUin: { field: 1, type: 'uint32' as const },
sequence: { field: 2, type: 'uint32' as const },
code: { field: 3, type: 'string' as const },
} satisfies ProtoSchema;
// --- 0x6D8_1: Group file list ---
export const OidbGroupFileListReqSchema = {
groupUin: { field: 1, type: 'uint32' as const },
appId: { field: 2, type: 'uint32' as const },
targetDirectory: { field: 3, type: 'string' as const },
fileCount: { field: 5, type: 'uint32' as const },
sortBy: { field: 9, type: 'uint32' as const },
startIndex: { field: 13, type: 'uint32' as const },
field17: { field: 17, type: 'uint32' as const },
field18: { field: 18, type: 'uint32' as const },
} satisfies ProtoSchema;
export const OidbGroupFileViewReqSchema = {
list: { field: 2, type: 'message' as const, schema: OidbGroupFileListReqSchema },
} satisfies ProtoSchema;
export const OidbGroupFileListFolderRespSchema = {
folderId: { field: 1, type: 'string' as const },
parentDirectoryId: { field: 2, type: 'string' as const },
folderName: { field: 3, type: 'string' as const },
createTime: { field: 4, type: 'uint32' as const },
modifiedTime: { field: 5, type: 'uint32' as const },
creatorUin: { field: 6, type: 'uint32' as const },
creatorName: { field: 7, type: 'string' as const },
totalFileCount: { field: 8, type: 'uint32' as const },
} satisfies ProtoSchema;
export const OidbGroupFileListFileRespSchema = {
fileId: { field: 1, type: 'string' as const },
fileName: { field: 2, type: 'string' as const },
fileSize: { field: 3, type: 'uint64' as const },
busId: { field: 4, type: 'uint32' as const },
uploadedTime: { field: 6, type: 'uint32' as const },
expireTime: { field: 7, type: 'uint32' as const },
modifiedTime: { field: 8, type: 'uint32' as const },
downloadedTimes: { field: 9, type: 'uint32' as const },
uploaderName: { field: 14, type: 'string' as const },
uploaderUin: { field: 15, type: 'uint32' as const },
parentDirectory: { field: 16, type: 'string' as const },
} satisfies ProtoSchema;
export const OidbGroupFileListItemRespSchema = {
type: { field: 1, type: 'uint32' as const },
folderInfo: { field: 2, type: 'message' as const, schema: OidbGroupFileListFolderRespSchema },
fileInfo: { field: 3, type: 'message' as const, schema: OidbGroupFileListFileRespSchema },
} satisfies ProtoSchema;
export const OidbGroupFileListRespSchema = {
retCode: { field: 1, type: 'uint32' as const },
retMsg: { field: 2, type: 'string' as const },
clientWording: { field: 3, type: 'string' as const },
isEnd: { field: 4, type: 'bool' as const },
items: { field: 5, type: 'repeated_message' as const, schema: OidbGroupFileListItemRespSchema },
} satisfies ProtoSchema;
export const OidbGroupFileViewRespSchema = {
list: { field: 2, type: 'message' as const, schema: OidbGroupFileListRespSchema },
} satisfies ProtoSchema;
// --- 0x6D6_2 / 0x6D6_3: Group file url & delete ---
export const OidbGroupFileUploadReqSchema = {
groupUin: { field: 1, type: 'uint32' as const },
appId: { field: 2, type: 'uint32' as const },
busId: { field: 3, type: 'uint32' as const },
entrance: { field: 4, type: 'uint32' as const },
targetDirectory: { field: 5, type: 'string' as const },
fileName: { field: 6, type: 'string' as const },
localDirectory: { field: 7, type: 'string' as const },
fileSize: { field: 8, type: 'uint64' as const },
fileSha1: { field: 9, type: 'bytes' as const },
fileSha3: { field: 10, type: 'bytes' as const },
fileMd5: { field: 11, type: 'bytes' as const },
field15: { field: 15, type: 'bool' as const },
} satisfies ProtoSchema;
export const OidbGroupFileDownloadReqSchema = {
groupUin: { field: 1, type: 'uint32' as const },
appId: { field: 2, type: 'uint32' as const },
busId: { field: 3, type: 'uint32' as const },
fileId: { field: 4, type: 'string' as const },
} satisfies ProtoSchema;
export const OidbGroupFileDeleteReqSchema = {
groupUin: { field: 1, type: 'uint32' as const },
busId: { field: 3, type: 'uint32' as const },
fileId: { field: 5, type: 'string' as const },
} satisfies ProtoSchema;
export const OidbGroupFileMoveReqSchema = {
groupUin: { field: 1, type: 'uint32' as const },
appId: { field: 2, type: 'uint32' as const },
busId: { field: 3, type: 'uint32' as const },
fileId: { field: 4, type: 'string' as const },
parentDirectory: { field: 5, type: 'string' as const },
targetDirectory: { field: 6, type: 'string' as const },
} satisfies ProtoSchema;
export const OidbGroupFileReqSchema = {
file: { field: 1, type: 'message' as const, schema: OidbGroupFileUploadReqSchema },
download: { field: 3, type: 'message' as const, schema: OidbGroupFileDownloadReqSchema },
delete: { field: 4, type: 'message' as const, schema: OidbGroupFileDeleteReqSchema },
move: { field: 6, type: 'message' as const, schema: OidbGroupFileMoveReqSchema },
} satisfies ProtoSchema;
export const OidbGroupFileUploadRespSchema = {
retCode: { field: 1, type: 'int32' as const },
retMsg: { field: 2, type: 'string' as const },
clientWording: { field: 3, type: 'string' as const },
uploadIp: { field: 4, type: 'string' as const },
serverDns: { field: 5, type: 'string' as const },
busId: { field: 6, type: 'int32' as const },
fileId: { field: 7, type: 'string' as const },
checkKey: { field: 8, type: 'bytes' as const },
fileKey: { field: 9, type: 'bytes' as const },
boolFileExist: { field: 10, type: 'bool' as const },
uploadPort: { field: 14, type: 'uint32' as const },
} satisfies ProtoSchema;
export const OidbGroupFileDownloadRespSchema = {
retCode: { field: 1, type: 'uint32' as const },
retMsg: { field: 2, type: 'string' as const },
clientWording: { field: 3, type: 'string' as const },
downloadIp: { field: 4, type: 'string' as const },
downloadDns: { field: 5, type: 'string' as const },
downloadUrl: { field: 6, type: 'bytes' as const },
saveFileName: { field: 11, type: 'string' as const },
} satisfies ProtoSchema;
export const OidbGroupFileRetRespSchema = {
retCode: { field: 1, type: 'uint32' as const },
retMsg: { field: 2, type: 'string' as const },
clientWording: { field: 3, type: 'string' as const },
} satisfies ProtoSchema;
export const OidbGroupFileRespSchema = {
upload: { field: 1, type: 'message' as const, schema: OidbGroupFileUploadRespSchema },
download: { field: 3, type: 'message' as const, schema: OidbGroupFileDownloadRespSchema },
delete: { field: 4, type: 'message' as const, schema: OidbGroupFileRetRespSchema },
move: { field: 6, type: 'message' as const, schema: OidbGroupFileRetRespSchema },
} satisfies ProtoSchema;
// --- 0x6D7_0 / 0x6D7_1 / 0x6D7_2: Group file folder ops ---
export const OidbGroupFileCreateFolderReqSchema = {
groupUin: { field: 1, type: 'uint32' as const },
rootDirectory: { field: 3, type: 'string' as const },
folderName: { field: 4, type: 'string' as const },
} satisfies ProtoSchema;
export const OidbGroupFileDeleteFolderReqSchema = {
groupUin: { field: 1, type: 'uint32' as const },
folderId: { field: 3, type: 'string' as const },
} satisfies ProtoSchema;
export const OidbGroupFileRenameFolderReqSchema = {
groupUin: { field: 1, type: 'uint32' as const },
folderId: { field: 3, type: 'string' as const },
newFolderName: { field: 4, type: 'string' as const },
} satisfies ProtoSchema;
export const OidbGroupFileFolderReqSchema = {
create: { field: 1, type: 'message' as const, schema: OidbGroupFileCreateFolderReqSchema },
delete: { field: 2, type: 'message' as const, schema: OidbGroupFileDeleteFolderReqSchema },
rename: { field: 3, type: 'message' as const, schema: OidbGroupFileRenameFolderReqSchema },
} satisfies ProtoSchema;
export const OidbGroupFileFolderRetRespSchema = {
retcode: { field: 1, type: 'uint32' as const },
retMsg: { field: 2, type: 'string' as const },
clientWording: { field: 3, type: 'string' as const },
} satisfies ProtoSchema;
export const OidbGroupFileFolderRespSchema = {
create: { field: 1, type: 'message' as const, schema: OidbGroupFileFolderRetRespSchema },
delete: { field: 2, type: 'message' as const, schema: OidbGroupFileFolderRetRespSchema },
rename: { field: 3, type: 'message' as const, schema: OidbGroupFileFolderRetRespSchema },
} satisfies ProtoSchema;
// --- 0xE37_1200: Private file download url ---
export const OidbPrivateFileDownloadReqBodySchema = {
receiverUid: { field: 10, type: 'string' as const },
fileUuid: { field: 20, type: 'string' as const },
type: { field: 30, type: 'uint32' as const },
fileHash: { field: 60, type: 'string' as const },
t2: { field: 601, type: 'uint32' as const },
} satisfies ProtoSchema;
export const OidbPrivateFileDownloadReqSchema = {
subCommand: { field: 1, type: 'uint32' as const },
field2: { field: 2, type: 'uint32' as const },
body: { field: 14, type: 'message' as const, schema: OidbPrivateFileDownloadReqBodySchema },
field101: { field: 101, type: 'uint32' as const },
field102: { field: 102, type: 'uint32' as const },
field200: { field: 200, type: 'uint32' as const },
field99999: { field: 99999, type: 'bytes' as const },
} satisfies ProtoSchema;
export const OidbPrivateFileDownloadRespResultSchema = {
server: { field: 20, type: 'string' as const },
port: { field: 40, type: 'uint32' as const },
url: { field: 50, type: 'string' as const },
} satisfies ProtoSchema;
export const OidbPrivateFileDownloadRespBodySchema = {
state: { field: 20, type: 'string' as const },
result: { field: 30, type: 'message' as const, schema: OidbPrivateFileDownloadRespResultSchema },
} satisfies ProtoSchema;
export const OidbPrivateFileDownloadRespSchema = {
body: { field: 14, type: 'message' as const, schema: OidbPrivateFileDownloadRespBodySchema },
} satisfies ProtoSchema;
// --- 0xE37_1700: Private file upload ---
export const OidbPrivateFileUploadReqBodySchema = {
senderUid: { field: 10, type: 'string' as const },
receiverUid: { field: 20, type: 'string' as const },
fileSize: { field: 30, type: 'uint32' as const },
fileName: { field: 40, type: 'string' as const },
md510MCheckSum:{ field: 50, type: 'bytes' as const },
sha1CheckSum: { field: 60, type: 'bytes' as const },
localPath: { field: 70, type: 'string' as const },
md5CheckSum: { field: 110, type: 'bytes' as const },
sha3CheckSum: { field: 120, type: 'bytes' as const },
} satisfies ProtoSchema;
export const OidbPrivateFileUploadReqSchema = {
command: { field: 1, type: 'uint32' as const },
seq: { field: 2, type: 'int32' as const },
upload: { field: 19, type: 'message' as const, schema: OidbPrivateFileUploadReqBodySchema },
businessId: { field: 101, type: 'int32' as const },
clientType: { field: 102, type: 'int32' as const },
flagSupportMediaPlatform: { field: 200, type: 'int32' as const },
} satisfies ProtoSchema;
export const OidbPrivateFileUploadRespBodySchema = {
retCode: { field: 10, type: 'int32' as const },
retMsg: { field: 20, type: 'string' as const },
uploadIp: { field: 60, type: 'string' as const },
uploadPort: { field: 80, type: 'uint32' as const },
uuid: { field: 90, type: 'string' as const },
uploadKey: { field: 100, type: 'bytes' as const },
boolFileExist: { field: 110, type: 'bool' as const },
fileAddon: { field: 200, type: 'string' as const },
mediaPlatformUploadKey: { field: 220, type: 'bytes' as const },
} satisfies ProtoSchema;
export const OidbPrivateFileUploadRespSchema = {
upload: { field: 19, type: 'message' as const, schema: OidbPrivateFileUploadRespBodySchema },
} satisfies ProtoSchema;
// --- NTV2 Rich Media (0x9067_202): Download RKey ---
export const NTV2CommonHeadSchema = {
requestId: { field: 1, type: 'uint32' as const },
command: { field: 2, type: 'uint32' as const },
} satisfies ProtoSchema;
export const NTV2C2CUserInfoSchema = {
accountType: { field: 1, type: 'uint32' as const },
targetUid: { field: 2, type: 'string' as const },
} satisfies ProtoSchema;
export const NTV2GroupInfoSchema = {
groupUin: { field: 1, type: 'uint32' as const },
} satisfies ProtoSchema;
export const NTV2SceneInfoSchema = {
requestType: { field: 101, type: 'uint32' as const },
businessType: { field: 102, type: 'uint32' as const },
sceneType: { field: 200, type: 'uint32' as const },
c2c: { field: 201, type: 'message' as const, schema: NTV2C2CUserInfoSchema },
group: { field: 202, type: 'message' as const, schema: NTV2GroupInfoSchema },
} satisfies ProtoSchema;
export const NTV2ClientMetaSchema = {
agentType: { field: 1, type: 'uint32' as const },
} satisfies ProtoSchema;
export const NTV2ReqHeadSchema = {
common: { field: 1, type: 'message' as const, schema: NTV2CommonHeadSchema },
scene: { field: 2, type: 'message' as const, schema: NTV2SceneInfoSchema },
client: { field: 3, type: 'message' as const, schema: NTV2ClientMetaSchema },
} satisfies ProtoSchema;
export const NTV2DownloadRKeyReqSchema = {
types: { field: 1, type: 'repeated_uint32' as const },
} satisfies ProtoSchema;
export const NTV2FileTypeSchema = {
type: { field: 1, type: 'uint32' as const },
picFormat: { field: 2, type: 'uint32' as const },
videoFormat: { field: 3, type: 'uint32' as const },
voiceFormat: { field: 4, type: 'uint32' as const },
} satisfies ProtoSchema;
export const NTV2FileInfoSchema = {
fileSize: { field: 1, type: 'uint32' as const },
fileHash: { field: 2, type: 'string' as const },
fileSha1: { field: 3, type: 'string' as const },
fileName: { field: 4, type: 'string' as const },
type: { field: 5, type: 'message' as const, schema: NTV2FileTypeSchema },
width: { field: 6, type: 'uint32' as const },
height: { field: 7, type: 'uint32' as const },
time: { field: 8, type: 'uint32' as const },
original: { field: 9, type: 'uint32' as const },
} satisfies ProtoSchema;
export const NTV2IndexNodeSchema = {
info: { field: 1, type: 'message' as const, schema: NTV2FileInfoSchema },
fileUuid: { field: 2, type: 'string' as const },
storeId: { field: 3, type: 'uint32' as const },
uploadTime: { field: 4, type: 'uint32' as const },
ttl: { field: 5, type: 'uint32' as const },
subType: { field: 6, type: 'uint32' as const },
} satisfies ProtoSchema;
export const NTV2VideoDownloadExtSchema = {
busiType: { field: 1, type: 'uint32' as const },
sceneType: { field: 2, type: 'uint32' as const },
subBusiType: { field: 3, type: 'uint32' as const },
} satisfies ProtoSchema;
export const NTV2DownloadExtSchema = {
video: { field: 2, type: 'message' as const, schema: NTV2VideoDownloadExtSchema },
} satisfies ProtoSchema;
export const NTV2DownloadReqSchema = {
node: { field: 1, type: 'message' as const, schema: NTV2IndexNodeSchema },
download: { field: 2, type: 'message' as const, schema: NTV2DownloadExtSchema },
} satisfies ProtoSchema;
export const NTV2RichMediaReqSchema = {
reqHead: { field: 1, type: 'message' as const, schema: NTV2ReqHeadSchema },
download: { field: 3, type: 'message' as const, schema: NTV2DownloadReqSchema },
downloadRkey: { field: 4, type: 'message' as const, schema: NTV2DownloadRKeyReqSchema },
} satisfies ProtoSchema;
export const NTV2RespHeadSchema = {
common: { field: 1, type: 'message' as const, schema: NTV2CommonHeadSchema },
retCode: { field: 2, type: 'uint32' as const },
message: { field: 3, type: 'string' as const },
} satisfies ProtoSchema;
export const NTV2RKeyInfoSchema = {
rkey: { field: 1, type: 'string' as const },
rkeyTtlSec: { field: 2, type: 'uint64' as const },
storeId: { field: 3, type: 'uint32' as const },
rkeyCreateTime:{ field: 4, type: 'uint32' as const },
type: { field: 5, type: 'uint32' as const },
} satisfies ProtoSchema;
export const NTV2DownloadRKeyRespSchema = {
rkeys: { field: 1, type: 'repeated_message' as const, schema: NTV2RKeyInfoSchema },
} satisfies ProtoSchema;
export const NTV2MediaDownloadInfoSchema = {
domain: { field: 1, type: 'string' as const },
urlPath: { field: 2, type: 'string' as const },
httpsPort: { field: 3, type: 'uint32' as const },
} satisfies ProtoSchema;
export const NTV2MediaDownloadRespSchema = {
rKeyParam: { field: 1, type: 'string' as const },
rKeyTtlSecond: { field: 2, type: 'uint32' as const },
info: { field: 3, type: 'message' as const, schema: NTV2MediaDownloadInfoSchema },
rKeyCreateTime: { field: 4, type: 'uint32' as const },
} satisfies ProtoSchema;
export const NTV2RichMediaRespSchema = {
respHead: { field: 1, type: 'message' as const, schema: NTV2RespHeadSchema },
download: { field: 3, type: 'message' as const, schema: NTV2MediaDownloadRespSchema },
downloadRkey:{ field: 4, type: 'message' as const, schema: NTV2DownloadRKeyRespSchema },
} satisfies ProtoSchema;
// --- 0xB6E_2: Set friend remark ---
export const OidbSetFriendRemarkSchema = {
targetUid: { field: 1, type: 'string' as const },
remark: { field: 2, type: 'string' as const },
} satisfies ProtoSchema;
// --- 0x9082_2: Set group reaction (remove) — same schema as set ---
// (0x9082_1 for add, 0x9082_2 for remove — both use OidbGroupReactionSchema)
// --- Group file count (0x6D8_3) ---
export const OidbGroupFileCountReqSchema = {
groupUin: { field: 1, type: 'uint32' as const },
appId: { field: 2, type: 'uint32' as const },
busId: { field: 3, type: 'uint32' as const },
} satisfies ProtoSchema;
export const OidbGroupFileCountRespSchema = {
fileCount: { field: 1, type: 'uint32' as const },
maxCount: { field: 2, type: 'uint32' as const },
isEnd: { field: 3, type: 'bool' as const },
} satisfies ProtoSchema;
export const OidbGroupFileCountViewReqSchema = {
count: { field: 3, type: 'message' as const, schema: OidbGroupFileCountReqSchema },
} satisfies ProtoSchema;
export const OidbGroupFileCountViewRespSchema = {
count: { field: 3, type: 'message' as const, schema: OidbGroupFileCountRespSchema },
} satisfies ProtoSchema;
+161
View File
@@ -0,0 +1,161 @@
// Proto schemas for OidbSvc service types.
// Port of src/bridge/include/bridge/proto/oidb.h
import type { ProtoSchema } from '../../protobuf/decode';
// --- OidbSvcTrpcTcpBase wrapper ---
export const OidbPropertySchema = {
key: { field: 1, type: 'string' as const },
value: { field: 2, type: 'bytes' as const },
} satisfies ProtoSchema;
// Factory for OidbSvcTrpcTcpBase<T>
export function makeOidbBaseSchema(bodySchema: ProtoSchema): ProtoSchema {
return {
command: { field: 1, type: 'uint32' as const },
subCommand: { field: 2, type: 'uint32' as const },
errorCode: { field: 3, type: 'uint32' as const },
body: { field: 4, type: 'message' as const, schema: bodySchema },
errorMsg: { field: 5, type: 'string' as const },
properties: { field: 11, type: 'repeated_message' as const, schema: OidbPropertySchema },
reserved: { field: 12, type: 'int32' as const },
};
}
// --- Friend list (0xFD4_1) ---
export const OidbFriendPropertySchema = {
code: { field: 1, type: 'uint32' as const },
value: { field: 2, type: 'string' as const },
} satisfies ProtoSchema;
export const OidbFriendLayer1Schema = {
properties: { field: 2, type: 'repeated_message' as const, schema: OidbFriendPropertySchema },
} satisfies ProtoSchema;
export const OidbFriendAdditionalSchema = {
type: { field: 1, type: 'uint32' as const },
layer1: { field: 2, type: 'message' as const, schema: OidbFriendLayer1Schema },
} satisfies ProtoSchema;
export const OidbFriendSchema = {
uid: { field: 1, type: 'string' as const },
customGroup:{ field: 2, type: 'uint32' as const },
uin: { field: 3, type: 'uint32' as const },
additional: { field: 10001, type: 'repeated_message' as const, schema: OidbFriendAdditionalSchema },
} satisfies ProtoSchema;
export const OidbSvcTrpcTcp0xFD4_1ResponseUinSchema = {
uin: { field: 1, type: 'uint32' as const },
} satisfies ProtoSchema;
export const OidbSvcTrpcTcp0xFD4_1ResponseSchema = {
next: { field: 2, type: 'message' as const, schema: OidbSvcTrpcTcp0xFD4_1ResponseUinSchema },
displayFriendCount: { field: 3, type: 'uint32' as const },
timestamp: { field: 6, type: 'uint32' as const },
selfUin: { field: 7, type: 'uint32' as const },
friends: { field: 101, type: 'repeated_message' as const, schema: OidbFriendSchema },
groups: { field: 102, type: 'repeated_message' as const, schema: OidbFriendPropertySchema },
} satisfies ProtoSchema;
// --- Group list (0xFE5_2) ---
export const OidbSvcTrpcTcp0xFE5_2MemberSchema = {
uid: { field: 2, type: 'string' as const },
} satisfies ProtoSchema;
export const OidbSvcTrpcTcp0xFE5_2GroupInfoSchema = {
groupOwner: { field: 1, type: 'message' as const, schema: OidbSvcTrpcTcp0xFE5_2MemberSchema },
createdTime: { field: 2, type: 'uint32' as const },
memberMax: { field: 3, type: 'uint32' as const },
memberCount: { field: 4, type: 'uint32' as const },
groupName: { field: 5, type: 'string' as const },
description: { field: 18, type: 'string' as const },
question: { field: 19, type: 'string' as const },
announcement: { field: 30, type: 'string' as const },
} satisfies ProtoSchema;
export const OidbSvcTrpcTcp0xFE5_2CustomInfoSchema = {
remark: { field: 3, type: 'string' as const },
} satisfies ProtoSchema;
export const OidbSvcTrpcTcp0xFE5_2GroupSchema = {
groupUin: { field: 3, type: 'uint32' as const },
info: { field: 4, type: 'message' as const, schema: OidbSvcTrpcTcp0xFE5_2GroupInfoSchema },
customInfo: { field: 5, type: 'message' as const, schema: OidbSvcTrpcTcp0xFE5_2CustomInfoSchema },
} satisfies ProtoSchema;
export const OidbSvcTrpcTcp0xFE5_2ResponseSchema = {
groups: { field: 2, type: 'repeated_message' as const, schema: OidbSvcTrpcTcp0xFE5_2GroupSchema },
} satisfies ProtoSchema;
// --- Group member list (0xFE7_3) ---
export const OidbSvcTrpcTcp0xFE7_3UinSchema = {
uid: { field: 2, type: 'string' as const },
uin: { field: 4, type: 'uint32' as const },
} satisfies ProtoSchema;
export const OidbSvcTrpcTcp0xFE7_3CardSchema = {
memberCard: { field: 2, type: 'string' as const },
} satisfies ProtoSchema;
export const OidbSvcTrpcTcp0xFE7_3LevelSchema = {
infos: { field: 1, type: 'repeated_uint32' as const },
level: { field: 2, type: 'uint32' as const },
} satisfies ProtoSchema;
export const OidbSvcTrpcTcp0xFE7_3MemberSchema = {
uin: { field: 1, type: 'message' as const, schema: OidbSvcTrpcTcp0xFE7_3UinSchema },
memberName: { field: 10, type: 'string' as const },
specialTitle: { field: 17, type: 'string' as const },
memberCard: { field: 11, type: 'message' as const, schema: OidbSvcTrpcTcp0xFE7_3CardSchema },
level: { field: 12, type: 'message' as const, schema: OidbSvcTrpcTcp0xFE7_3LevelSchema },
joinTimestamp: { field: 100, type: 'uint32' as const },
lastMsgTimestamp: { field: 101, type: 'uint32' as const },
shutUpTimestamp: { field: 102, type: 'uint32' as const },
permission: { field: 107, type: 'uint32' as const },
} satisfies ProtoSchema;
export const OidbSvcTrpcTcp0xFE7_3ResponseSchema = {
groupUin: { field: 1, type: 'uint32' as const },
members: { field: 2, type: 'repeated_message' as const, schema: OidbSvcTrpcTcp0xFE7_3MemberSchema },
field3: { field: 3, type: 'uint32' as const },
memberChangeSeq: { field: 5, type: 'uint32' as const },
memberCardChangeSeq:{ field: 6, type: 'uint32' as const },
token: { field: 15, type: 'string' as const },
} satisfies ProtoSchema;
// --- Group request (0x10C0) ---
export const OidbSvcTrpcTcp0x10C0ResponseUserSchema = {
uid: { field: 1, type: 'string' as const },
name: { field: 2, type: 'string' as const },
} satisfies ProtoSchema;
export const OidbSvcTrpcTcp0x10C0ResponseGroupSchema = {
groupUin: { field: 1, type: 'uint32' as const },
groupName: { field: 2, type: 'string' as const },
} satisfies ProtoSchema;
export const OidbSvcTrpcTcp0x10C0ResponseRequestSchema = {
sequence: { field: 1, type: 'uint64' as const },
eventType: { field: 2, type: 'uint32' as const },
state: { field: 3, type: 'uint32' as const },
group: { field: 4, type: 'message' as const, schema: OidbSvcTrpcTcp0x10C0ResponseGroupSchema },
target: { field: 5, type: 'message' as const, schema: OidbSvcTrpcTcp0x10C0ResponseUserSchema },
invitor: { field: 6, type: 'message' as const, schema: OidbSvcTrpcTcp0x10C0ResponseUserSchema },
operatorUser: { field: 7, type: 'message' as const, schema: OidbSvcTrpcTcp0x10C0ResponseUserSchema },
field9: { field: 9, type: 'string' as const },
comment: { field: 10, type: 'string' as const },
} satisfies ProtoSchema;
export const OidbSvcTrpcTcp0x10C0ResponseSchema = {
requests: { field: 1, type: 'repeated_message' as const, schema: OidbSvcTrpcTcp0x10C0ResponseRequestSchema },
field2: { field: 2, type: 'uint64' as const },
newLatestSeq: { field: 3, type: 'uint64' as const },
field4: { field: 4, type: 'uint32' as const },
field5: { field: 5, type: 'uint64' as const },
field6: { field: 6, type: 'uint32' as const },
} satisfies ProtoSchema;
+205
View File
@@ -0,0 +1,205 @@
// QQ info store — per-UIN state for friends, groups, member lookup.
// Port of src/bridge/include/bridge/qq_info.h + src/bridge/src/qq_info.cpp
export interface UserProfileInfo {
uin: number;
uid: string;
nickname: string;
remark: string;
qid: string;
sex: string;
age: number;
sign: string;
avatar: string;
}
export interface FriendInfo {
uin: number;
uid: string;
nickname: string;
remark: string;
}
export interface GroupMemberInfo {
uin: number;
uid: string;
nickname: string;
card: string;
role: string; // 'owner' | 'admin' | 'member'
level: number;
title: string;
joinTime: number;
lastSentTime: number;
shutUpTime: number;
}
export interface QQGroupInfo {
groupId: number;
groupName: string;
remark: string;
memberCount: number;
memberMax: number;
members: Map<number, GroupMemberInfo>;
}
export interface GroupRequestInfo {
groupId: number;
groupName: string;
targetUid: string;
targetUin: number;
targetName: string;
invitorUid: string;
invitorUin: number;
invitorName: string;
operatorUid: string;
operatorUin: number;
operatorName: string;
sequence: number;
state: number;
eventType: number;
comment: string;
filtered: boolean;
}
export class QQInfo {
private uin_: string;
private nickname_ = '';
private selfProfile_: UserProfileInfo | null = null;
private userProfiles_ = new Map<number, UserProfileInfo>();
private friends_: FriendInfo[] = [];
private groups_ = new Map<number, QQGroupInfo>();
constructor(uin: string) {
this.uin_ = uin;
}
get uin(): string { return this.uin_; }
get nickname(): string { return this.nickname_; }
set nickname(v: string) { this.nickname_ = v; }
// --- Self profile ---
setSelfProfile(info: UserProfileInfo): void { this.selfProfile_ = info; }
get selfProfile(): UserProfileInfo | null { return this.selfProfile_; }
get selfUid(): string | null { return this.selfProfile_?.uid ?? null; }
// --- User profiles ---
setUserProfile(info: UserProfileInfo): void {
this.userProfiles_.set(info.uin, info);
}
findUserProfile(uin: number): UserProfileInfo | null {
return this.userProfiles_.get(uin) ?? null;
}
// --- Friends ---
setFriends(friends: FriendInfo[]): void { this.friends_ = friends; }
get friends(): FriendInfo[] { return this.friends_; }
findFriend(uin: number): FriendInfo | null {
return this.friends_.find(f => f.uin === uin) ?? null;
}
// --- Groups ---
setGroups(groups: QQGroupInfo[]): void {
this.groups_.clear();
for (const g of groups) {
this.groups_.set(g.groupId, g);
}
}
get groups(): QQGroupInfo[] { return [...this.groups_.values()]; }
findGroup(groupId: number): QQGroupInfo | null {
return this.groups_.get(groupId) ?? null;
}
findGroupMember(groupId: number, uin: number): GroupMemberInfo | null {
return this.groups_.get(groupId)?.members.get(uin) ?? null;
}
setGroupMembers(groupId: number, members: GroupMemberInfo[]): void {
const g = this.groups_.get(groupId);
if (!g) return;
g.members.clear();
for (const m of members) {
g.members.set(m.uin, m);
}
}
updateGroupMember(groupId: number, member: GroupMemberInfo): void {
const g = this.groups_.get(groupId);
if (!g) return;
g.members.set(member.uin, member);
}
// --- UID resolution ---
resolveUid(uid: string): number | null {
// Check self
if (this.selfProfile_?.uid === uid) {
return this.selfProfile_.uin || parseInt(this.uin_, 10) || null;
}
// Check friends
for (const f of this.friends_) {
if (f.uid === uid) return f.uin;
}
// Check user profiles
for (const [, p] of this.userProfiles_) {
if (p.uid === uid) return p.uin;
}
// Check all group members
for (const [, g] of this.groups_) {
for (const [, m] of g.members) {
if (m.uid === uid) return m.uin;
}
}
return null;
}
resolveGroupMemberUid(groupId: number, uid: string): number | null {
const g = this.groups_.get(groupId);
if (!g) return null;
for (const [, m] of g.members) {
if (m.uid === uid) return m.uin;
}
return null;
}
// --- Reverse UID lookup (UIN → UID) ---
findUidByUin(uin: number): string | null {
// Check self
if (this.selfProfile_ && this.selfProfile_.uin === uin && this.selfProfile_.uid) {
return this.selfProfile_.uid;
}
// Check friends
for (const f of this.friends_) {
if (f.uin === uin && f.uid) return f.uid;
}
// Check user profiles
for (const [, p] of this.userProfiles_) {
if (p.uin === uin && p.uid) return p.uid;
}
// Check all group members
for (const [, g] of this.groups_) {
for (const [, m] of g.members) {
if (m.uin === uin && m.uid) return m.uid;
}
}
return null;
}
findUidByUinInGroup(groupId: number, uin: number): string | null {
const g = this.groups_.get(groupId);
if (!g) return null;
for (const [, m] of g.members) {
if (m.uin === uin && m.uid) return m.uid;
}
return null;
}
}
+75
View File
@@ -0,0 +1,75 @@
import fs from 'fs';
import path from 'path';
export interface RuntimeConfig {
webuiPort?: number;
}
const CONFIG_DIR = 'config';
const RUNTIME_CONFIG_PATH = path.join(CONFIG_DIR, 'runtime.json');
const DEFAULT_RUNTIME_CONFIG: RuntimeConfig = {
webuiPort: 8080,
};
export function loadRuntimeConfig(): RuntimeConfig {
fs.mkdirSync(CONFIG_DIR, { recursive: true });
const loaded = tryLoadRuntimeConfig();
if (!loaded) {
saveRuntimeConfig(DEFAULT_RUNTIME_CONFIG);
return { ...DEFAULT_RUNTIME_CONFIG };
}
const normalized: RuntimeConfig = {
webuiPort: normalizePort(loaded.webuiPort ?? 8080, 8080),
};
if (
normalized.webuiPort !== loaded.webuiPort
) {
saveRuntimeConfig(normalized);
}
return normalized;
}
function tryLoadRuntimeConfig(): RuntimeConfig | null {
if (!fs.existsSync(RUNTIME_CONFIG_PATH)) return null;
try {
const raw = fs.readFileSync(RUNTIME_CONFIG_PATH, 'utf8');
const parsed = JSON.parse(raw) as unknown;
if (!isObject(parsed)) return null;
return {
webuiPort: normalizePort(parsed.webuiPort ?? 8080, 8080),
};
} catch {
return null;
}
}
function saveRuntimeConfig(config: RuntimeConfig): void {
fs.writeFileSync(RUNTIME_CONFIG_PATH, JSON.stringify(config, null, 2), 'utf8');
}
function normalizePort(value: unknown, fallback: number): number {
if (typeof value === 'number' && Number.isFinite(value)) {
const n = Math.trunc(value);
if (n > 0 && n <= 65535) return n;
return fallback;
}
if (typeof value === 'string' && value.trim()) {
const n = Number(value);
if (Number.isFinite(n)) {
const port = Math.trunc(n);
if (port > 0 && port <= 65535) return port;
}
}
return fallback;
}
function isObject(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
+1
View File
@@ -0,0 +1 @@
declare const __BUILD_WEBUI__: boolean;
+291
View File
@@ -0,0 +1,291 @@
import type { BridgeManager } from '../bridge/manager';
import type { NtqqHandler } from '../protocol/ntqq-handler';
import { createLogger } from '../utils/logger';
import { HookPacketClient } from './hook-packet-client';
import { injectHookProcess, listHookProcesses, unloadHookProcess, type HookInjectResult, type HookProcessBaseInfo } from './injector';
import { QqHookClient, type QqHookLoginState, type QqHookPacket } from './qq-hook-client';
const log = createLogger('Hook');
const CONNECT_RETRY_COUNT = 30;
const CONNECT_RETRY_INTERVAL_MS = 1000;
export type HookProcessStatus = 'available' | 'loading' | 'loaded' | 'online' | 'error' | 'disconnected';
export interface HookProcessInfo extends HookProcessBaseInfo {
injected: boolean;
connected: boolean;
loggedIn: boolean;
uin: string;
status: HookProcessStatus;
error: string;
method: string;
}
interface HookProcessState extends HookProcessInfo {
client: QqHookClient | null;
sender: HookPacketClient | null;
injectResult: HookInjectResult | null;
connectTask: Promise<void> | null;
bound: boolean;
}
export class HookManager {
private readonly states = new Map<number, HookProcessState>();
private readonly loadTasks = new Map<number, Promise<HookProcessInfo>>();
private readonly unloadTasks = new Map<number, Promise<HookProcessInfo>>();
constructor(
private readonly ntqq: NtqqHandler,
private readonly bridgeManager: BridgeManager,
) {}
async listProcesses(): Promise<HookProcessInfo[]> {
const processes = await listHookProcesses();
for (const proc of processes) {
const state = this.ensureState(proc.pid);
state.name = proc.name;
state.path = proc.path;
}
const seen = new Set(processes.map(proc => proc.pid));
const result: HookProcessInfo[] = [];
for (const proc of processes) {
result.push(this.toPublicInfo(this.ensureState(proc.pid)));
}
for (const state of this.states.values()) {
if (!seen.has(state.pid) && state.injected) {
result.push(this.toPublicInfo(state));
}
}
return result.sort((a, b) => a.pid - b.pid);
}
async loadProcess(pid: number): Promise<HookProcessInfo> {
if (!Number.isInteger(pid) || pid <= 0) {
throw new Error('invalid pid');
}
const runningTask = this.loadTasks.get(pid);
if (runningTask) return runningTask;
const task = this.loadProcessInternal(pid);
this.loadTasks.set(pid, task);
try {
return await task;
} finally {
this.loadTasks.delete(pid);
}
}
async unloadProcess(pid: number): Promise<HookProcessInfo> {
if (!Number.isInteger(pid) || pid <= 0) {
throw new Error('invalid pid');
}
const runningTask = this.unloadTasks.get(pid);
if (runningTask) return runningTask;
const task = this.unloadProcessInternal(pid);
this.unloadTasks.set(pid, task);
try {
return await task;
} finally {
this.unloadTasks.delete(pid);
}
}
dispose(): void {
for (const state of this.states.values()) {
state.client?.close();
state.client = null;
state.connected = false;
state.loggedIn = false;
state.status = state.injected ? 'disconnected' : 'available';
}
}
private async loadProcessInternal(pid: number): Promise<HookProcessInfo> {
const state = this.ensureState(pid);
state.status = 'loading';
state.error = '';
try {
if (!state.injected) {
state.injectResult = injectHookProcess(pid);
state.injected = true;
state.method = state.injectResult.method;
log.info('SnowLuma loaded into PID=%d via %s', pid, state.method);
}
state.status = state.connected ? (state.loggedIn ? 'online' : 'loaded') : 'loaded';
this.startClient(state);
} catch (error) {
state.status = 'error';
state.error = error instanceof Error ? error.message : String(error);
log.error('load failed: PID=%d err=%s', pid, state.error);
}
return this.toPublicInfo(state);
}
private async unloadProcessInternal(pid: number): Promise<HookProcessInfo> {
const state = this.ensureState(pid);
state.error = '';
try {
state.client?.close();
state.client = null;
state.sender = null;
state.connectTask = null;
state.bound = false;
state.connected = false;
state.loggedIn = false;
this.bridgeManager.onPidDisconnected(pid);
const handle = state.injectResult?.handle;
if (state.injected && handle) {
unloadHookProcess(pid, handle);
log.info('SnowLuma unloaded from PID=%d via unloadModuleManual', pid);
}
state.injected = false;
state.injectResult = null;
state.method = '';
state.uin = '0';
state.status = 'available';
} catch (error) {
state.status = 'error';
state.error = error instanceof Error ? error.message : String(error);
log.error('unload failed: PID=%d err=%s', pid, state.error);
}
return this.toPublicInfo(state);
}
private ensureState(pid: number): HookProcessState {
let state = this.states.get(pid);
if (!state) {
state = {
pid,
name: 'QQ.exe',
path: '',
injected: false,
connected: false,
loggedIn: false,
uin: '0',
status: 'available',
error: '',
method: '',
client: null,
sender: null,
injectResult: null,
connectTask: null,
bound: false,
};
this.states.set(pid, state);
}
return state;
}
private startClient(state: HookProcessState): void {
if (!state.client) {
state.client = new QqHookClient(state.pid);
state.sender = new HookPacketClient(state.client);
}
if (!state.bound) {
this.bindClient(state, state.client);
state.bound = true;
}
if (!state.connectTask) {
state.connectTask = this.connectClient(state).finally(() => {
state.connectTask = null;
});
void state.connectTask;
}
}
private bindClient(state: HookProcessState, client: QqHookClient): void {
client.on('packet', packet => this.handlePacket(state, packet));
client.on('loginState', loginState => this.handleLoginState(state, loginState));
client.on('error', error => {
state.error = error instanceof Error ? error.message : String(error);
if (!state.connected) state.status = 'error';
log.warn('pipe error: PID=%d err=%s', state.pid, state.error);
});
client.on('close', () => {
state.connected = false;
if (state.loggedIn) {
state.loggedIn = false;
state.status = 'disconnected';
this.bridgeManager.onPidDisconnected(state.pid);
}
});
}
private async connectClient(state: HookProcessState): Promise<void> {
const client = state.client;
if (!client) return;
for (let attempt = 1; attempt <= CONNECT_RETRY_COUNT; attempt++) {
try {
await client.connectAll({ recv: true });
state.connected = true;
state.status = client.isLoggedIn ? 'online' : 'loaded';
state.error = '';
const loginState = client.getLoginState();
if (loginState.loggedIn) {
this.handleLoginState(state, loginState);
}
log.info('pipe connected: PID=%d', state.pid);
return;
} catch (error) {
state.error = error instanceof Error ? error.message : String(error);
if (attempt >= CONNECT_RETRY_COUNT) {
state.status = 'error';
log.error('pipe connect failed: PID=%d err=%s', state.pid, state.error);
return;
}
await delay(CONNECT_RETRY_INTERVAL_MS);
}
}
}
private handleLoginState(state: HookProcessState, loginState: QqHookLoginState): void {
state.uin = loginState.uin || loginState.uinNumber.toString();
state.loggedIn = loginState.loggedIn && isRealUin(state.uin);
state.status = state.loggedIn ? 'online' : (state.connected ? 'loaded' : state.status);
if (!state.loggedIn || !state.sender) return;
this.bridgeManager.onHookLogin(state.pid, state.uin, state.sender);
log.success('login detected: PID=%d UIN=%s', state.pid, state.uin);
}
private handlePacket(state: HookProcessState, packet: QqHookPacket): void {
if (!state.loggedIn) return;
const uin = packet.uin || state.uin;
if (!isRealUin(uin)) return;
this.ntqq.onHookPacket(state.pid, { ...packet, uin });
}
private toPublicInfo(state: HookProcessState): HookProcessInfo {
return {
pid: state.pid,
name: state.name,
path: state.path,
injected: state.injected,
connected: state.connected,
loggedIn: state.loggedIn,
uin: state.uin,
status: state.status,
error: state.error,
method: state.method,
};
}
}
function isRealUin(uin: string): boolean {
if (!uin || uin === '0') return false;
return /^\d+$/.test(uin) && uin.length >= 5;
}
function delay(ms: number): Promise<void> {
return new Promise(resolve => setTimeout(resolve, ms));
}
@@ -0,0 +1,34 @@
import type { PacketSender, SendPacketResult } from '../protocol/packet-sender';
import { QqHookClient, type QqHookSendReply } from './qq-hook-client';
export class HookPacketClient implements PacketSender {
constructor(private readonly client: QqHookClient) {}
async sendPacket(serviceCmd: string, body: Buffer, timeoutMs = 15000): Promise<SendPacketResult> {
if (!this.client.isLoggedIn) {
return { success: false, gotResponse: false, errorCode: -1, errorMessage: 'qq_hook client is not logged in', responseData: null };
}
try {
const reply = await this.client.send(serviceCmd, body, {
wantReply: true,
replyTimeoutMs: timeoutMs,
}) as QqHookSendReply;
return {
success: reply.error === 0,
gotResponse: true,
errorCode: reply.error,
errorMessage: reply.message || '',
responseData: reply.body,
};
} catch (error) {
return {
success: false,
gotResponse: false,
errorCode: -1,
errorMessage: error instanceof Error ? error.message : String(error),
responseData: null,
};
}
}
}
+116
View File
@@ -0,0 +1,116 @@
import { existsSync } from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
export interface ManualMapHandle {
base: bigint;
entry: bigint;
exceptionTable: bigint;
size: number;
}
interface NativeHookAddon {
getAllMainProcess(): number[];
loadModuleManual(pid: number, dylibPath: string): ManualMapHandle;
unloadModuleManual(pid: number, handle: ManualMapHandle): void;
}
export interface HookProcessBaseInfo {
pid: number;
name: string;
path: string;
}
export interface HookInjectResult {
method: 'loadModuleManual';
handle?: ManualMapHandle;
}
let nativeAddon: NativeHookAddon | null = null;
let nativeLoadError: string | null = null;
function loadNativeAddon(addonPath: string): NativeHookAddon {
const mod = { exports: {} as Record<string, unknown> };
process.dlopen(mod, addonPath);
return mod.exports as unknown as NativeHookAddon;
}
function platformBinaryName(ext: 'node' | 'dll'): string {
if (process.platform === 'win32' && process.arch === 'x64') return `snowluma-win32-x64.${ext}`;
return `snowluma-${process.platform}-${process.arch}.${ext}`;
}
function nativeSearchDirs(): string[] {
// Several layouts must be supported:
// 1. Released zip (flattened dist/): __dirname=<extracted>/, native at <extracted>/native
// 2. Repo bundled build (dist/index.mjs): __dirname=<root>/dist, native at <root>/dist/native
// 3. Dev via tsx (packages/core/src/hook/injector.ts): __dirname=<root>/packages/core/src/hook
// → walk up to <root>/packages and append runtime/native
return [
path.resolve(__dirname, 'native'),
path.resolve(__dirname, '..', '..', '..', 'runtime', 'native'),
path.resolve(process.cwd(), 'dist', 'native'),
path.resolve(process.cwd(), 'packages', 'runtime', 'native'),
];
}
export function resolveHookNativePath(ext: 'node' | 'dll'): string | null {
const fileName = platformBinaryName(ext);
for (const dir of nativeSearchDirs()) {
const fullPath = path.join(dir, fileName);
if (existsSync(fullPath)) return fullPath;
}
return null;
}
export function getNativeHookAddon(): NativeHookAddon | null {
if (nativeAddon) return nativeAddon;
const addonPath = resolveHookNativePath('node');
if (!addonPath) {
nativeLoadError = `No hook native addon found for ${process.platform}-${process.arch}`;
return null;
}
try {
nativeAddon = loadNativeAddon(addonPath);
nativeLoadError = null;
return nativeAddon;
} catch (error) {
nativeLoadError = error instanceof Error ? error.message : String(error);
return null;
}
}
export function getNativeHookLoadError(): string | null {
return nativeLoadError;
}
export function listHookProcesses(): HookProcessBaseInfo[] {
const addon = getNativeHookAddon();
if (!addon) return [];
return [...new Set(addon.getAllMainProcess())]
.filter(pid => Number.isInteger(pid) && pid > 0)
.sort((a, b) => a - b)
.map(pid => ({ pid, name: 'QQ.exe', path: '' }));
}
export function injectHookProcess(pid: number): HookInjectResult {
const addon = getNativeHookAddon();
if (!addon) {
throw new Error(getNativeHookLoadError() ?? 'hook native addon is not available');
}
const dllPath = resolveHookNativePath('dll');
if (!dllPath) {
throw new Error(`No hook DLL found for ${process.platform}-${process.arch}`);
}
return { method: 'loadModuleManual', handle: addon.loadModuleManual(pid, dllPath) };
}
export function unloadHookProcess(pid: number, handle: ManualMapHandle): void {
const addon = getNativeHookAddon();
if (!addon) {
throw new Error(getNativeHookLoadError() ?? 'hook native addon is not available');
}
addon.unloadModuleManual(pid, handle);
}
+652
View File
@@ -0,0 +1,652 @@
import net from 'net';
import { EventEmitter } from 'events';
export const PIPE_MAGIC = 0x31504851;
export const PIPE_VERSION = 1;
export const HEADER_SIZE = 40;
export const DEFAULT_ACK_TIMEOUT_MS = 5000;
export const DEFAULT_REPLY_TIMEOUT_MS = 30000;
export enum PipeOp {
hello = 1,
sendRequest = 2,
sendAck = 3,
sendReply = 4,
error = 5,
recvPacket = 6,
loginState = 7,
}
const PipeFlagWantReply = 1 << 0;
const PipeFlagLoggedIn = 1 << 2;
export interface QqHookLoginState {
loggedIn: boolean;
uin: string;
uinNumber: bigint;
}
export interface QqHookPacket {
seq: number;
error: number;
cmd: string;
uin: string;
body: Buffer;
}
export interface QqHookHello {
pipeName: string;
pid: number;
recvPipe: boolean;
}
export interface QqHookSendReply {
requestId: number;
error: number;
message: string;
body: Buffer;
}
export interface QqHookClientOptions {
ackTimeoutMs?: number;
replyTimeoutMs?: number;
}
export interface QqHookSendOptions {
wantReply?: boolean;
ackTimeoutMs?: number;
replyTimeoutMs?: number;
}
interface PipeFrame {
op: number;
requestId: number;
status: number;
flags: number;
value0: bigint;
cmd: string;
msg: string;
body: Buffer;
}
interface Deferred<T> {
promise: Promise<T>;
resolve: (value: T | PromiseLike<T>) => void;
reject: (reason?: unknown) => void;
}
interface PendingAck {
resolve: (value: { requestId: number; wantReply: boolean }) => void;
reject: (reason?: unknown) => void;
wantReply: boolean;
}
function mojoPipeName(pid: number, suffix: string): string {
return `\\\\.\\pipe\\mojo.${pid}.${suffix}`;
}
function toBuffer(body: Buffer | Uint8Array | string | null | undefined): Buffer {
if (Buffer.isBuffer(body)) return body;
if (body instanceof Uint8Array) return Buffer.from(body);
if (typeof body === 'string') return Buffer.from(body, 'utf8');
if (body == null) return Buffer.alloc(0);
throw new TypeError('body must be Buffer, Uint8Array, string, or null');
}
function createDeferred<T>(): Deferred<T> {
let resolve!: (value: T | PromiseLike<T>) => void;
let reject!: (reason?: unknown) => void;
const promise = new Promise<T>((res, rej) => {
resolve = res;
reject = rej;
});
return { promise, resolve, reject };
}
function withTimeout<T>(promise: Promise<T>, timeoutMs: number, label: string): Promise<T> {
if (!timeoutMs || timeoutMs <= 0) return promise;
return new Promise<T>((resolve, reject) => {
const timer = setTimeout(() => {
reject(new Error(`${label} timed out after ${timeoutMs} ms`));
}, timeoutMs);
promise.then(
value => {
clearTimeout(timer);
resolve(value);
},
error => {
clearTimeout(timer);
reject(error);
});
});
}
function encodeFrame({
op,
requestId = 0,
status = 0,
flags = 0,
value0 = 0n,
cmd = '',
msg = '',
body = Buffer.alloc(0),
}: {
op: number;
requestId?: number;
status?: number;
flags?: number;
value0?: bigint | number;
cmd?: string;
msg?: string;
body?: Buffer | Uint8Array | string | null;
}): Buffer {
const cmdBuf = Buffer.from(cmd, 'utf8');
const msgBuf = Buffer.from(msg, 'utf8');
const bodyBuf = toBuffer(body);
const header = Buffer.alloc(HEADER_SIZE);
header.writeUInt32LE(PIPE_MAGIC, 0);
header.writeUInt16LE(PIPE_VERSION, 4);
header.writeUInt16LE(op, 6);
header.writeUInt32LE(requestId >>> 0, 8);
header.writeInt32LE(status | 0, 12);
header.writeUInt32LE(flags >>> 0, 16);
header.writeUInt32LE(cmdBuf.length >>> 0, 20);
header.writeUInt32LE(msgBuf.length >>> 0, 24);
header.writeUInt32LE(bodyBuf.length >>> 0, 28);
header.writeBigUInt64LE(BigInt(value0), 32);
return Buffer.concat([header, cmdBuf, msgBuf, bodyBuf]);
}
class FrameReader {
private buffer = Buffer.alloc(0);
constructor(private readonly onFrame: (frame: PipeFrame) => void) {}
push(chunk: Buffer): void {
this.buffer = Buffer.concat([this.buffer, chunk]);
while (this.buffer.length >= HEADER_SIZE) {
const magic = this.buffer.readUInt32LE(0);
const version = this.buffer.readUInt16LE(4);
if (magic !== PIPE_MAGIC || version !== PIPE_VERSION) {
throw new Error(`bad frame header magic=0x${magic.toString(16)} version=${version}`);
}
const cmdLen = this.buffer.readUInt32LE(20);
const msgLen = this.buffer.readUInt32LE(24);
const bodyLen = this.buffer.readUInt32LE(28);
const total = HEADER_SIZE + cmdLen + msgLen + bodyLen;
if (this.buffer.length < total) return;
const frame: PipeFrame = {
op: this.buffer.readUInt16LE(6),
requestId: this.buffer.readUInt32LE(8),
status: this.buffer.readInt32LE(12),
flags: this.buffer.readUInt32LE(16),
value0: this.buffer.readBigUInt64LE(32),
cmd: '',
msg: '',
body: Buffer.alloc(0),
};
let offset = HEADER_SIZE;
frame.cmd = this.buffer.subarray(offset, offset + cmdLen).toString('utf8');
offset += cmdLen;
frame.msg = this.buffer.subarray(offset, offset + msgLen).toString('utf8');
offset += msgLen;
frame.body = Buffer.from(this.buffer.subarray(offset, offset + bodyLen));
this.buffer = this.buffer.subarray(total);
this.onFrame(frame);
}
}
}
export class QqHookClient extends EventEmitter {
readonly pid: number;
readonly defaultAckTimeoutMs: number;
readonly defaultReplyTimeoutMs: number;
private controlSocket: net.Socket | null = null;
private recvSocket: net.Socket | null = null;
private controlConnectPromise: Promise<QqHookHello> | null = null;
private recvConnectPromise: Promise<QqHookHello> | null = null;
private nextRequestId = 1;
private pendingAcks = new Map<number, PendingAck>();
private pendingReplies = new Map<number, Deferred<QqHookSendReply>>();
private controlHello: QqHookHello | null = null;
private recvHello: QqHookHello | null = null;
private controlHelloResolver: Deferred<QqHookHello> | null = null;
private recvHelloResolver: Deferred<QqHookHello> | null = null;
private controlWriteChain: Promise<unknown> = Promise.resolve();
private closed = false;
private loginState: QqHookLoginState = { loggedIn: false, uin: '0', uinNumber: 0n };
private loginWaiters: Deferred<QqHookLoginState>[] = [];
constructor(pid: number, {
ackTimeoutMs = DEFAULT_ACK_TIMEOUT_MS,
replyTimeoutMs = DEFAULT_REPLY_TIMEOUT_MS,
}: QqHookClientOptions = {}) {
super();
this.pid = pid;
this.defaultAckTimeoutMs = ackTimeoutMs;
this.defaultReplyTimeoutMs = replyTimeoutMs;
}
get isLoggedIn(): boolean {
return this.loginState.loggedIn;
}
get currentUin(): string {
return this.loginState.uin;
}
get currentUinNumber(): bigint {
return this.loginState.uinNumber;
}
getLoginState(): QqHookLoginState {
return { ...this.loginState };
}
async waitForLogin({ timeoutMs = 0 } = {}): Promise<QqHookLoginState> {
await this.connect();
if (this.loginState.loggedIn) {
return this.getLoginState();
}
const deferred = createDeferred<QqHookLoginState>();
this.loginWaiters.push(deferred);
return withTimeout(deferred.promise, timeoutMs, 'waitForLogin');
}
static controlPipeName(pid: number): string {
return mojoPipeName(pid, 'control');
}
static recvPipeName(pid: number): string {
return mojoPipeName(pid, 'recv');
}
async connect(): Promise<QqHookHello> {
if (this.closed) {
throw new Error('qq_hook client is closed');
}
if (this.controlSocket && this.controlHello) {
return this.controlHello;
}
if (this.controlConnectPromise) {
return this.controlConnectPromise;
}
this.controlConnectPromise = (async () => {
this.controlSocket = await this.connectSocket(
QqHookClient.controlPipeName(this.pid),
'control',
frame => this.handleControlFrame(frame));
this.controlHello = await this.waitForHello(false);
return this.controlHello;
})();
try {
return await this.controlConnectPromise;
} finally {
this.controlConnectPromise = null;
}
}
async startRecv(onPacket?: (packet: QqHookPacket) => void): Promise<QqHookHello> {
if (this.closed) {
throw new Error('qq_hook client is closed');
}
if (typeof onPacket === 'function') {
this.on('packet', onPacket);
}
if (this.recvSocket && this.recvHello) {
return this.recvHello;
}
if (this.recvConnectPromise) {
return this.recvConnectPromise;
}
this.recvConnectPromise = (async () => {
this.recvSocket = await this.connectSocket(
QqHookClient.recvPipeName(this.pid),
'recv',
frame => this.handleRecvFrame(frame));
this.recvHello = await this.waitForHello(true);
return this.recvHello;
})();
try {
return await this.recvConnectPromise;
} finally {
this.recvConnectPromise = null;
}
}
async connectAll({ recv = true } = {}): Promise<{ control: QqHookHello; recv: QqHookHello | null }> {
const control = await this.connect();
const recvInfo = recv ? await this.startRecv() : null;
return { control, recv: recvInfo };
}
async send(cmd: string, body: Buffer | Uint8Array | string | null | undefined, {
wantReply = true,
ackTimeoutMs = this.defaultAckTimeoutMs,
replyTimeoutMs = this.defaultReplyTimeoutMs,
}: QqHookSendOptions = {}): Promise<QqHookSendReply | { requestId: number }> {
await this.connect();
const requestId = this.nextRequestId++ >>> 0;
const payload = encodeFrame({
op: PipeOp.sendRequest,
requestId,
flags: wantReply ? PipeFlagWantReply : 0,
cmd,
body,
});
const ackDeferred = createDeferred<{ requestId: number; wantReply: boolean }>();
this.pendingAcks.set(requestId, {
resolve: ackDeferred.resolve,
reject: ackDeferred.reject,
wantReply,
});
let replyDeferred: Deferred<QqHookSendReply> | null = null;
if (wantReply) {
replyDeferred = createDeferred<QqHookSendReply>();
this.pendingReplies.set(requestId, replyDeferred);
}
try {
await this.writeControl(payload);
await withTimeout(ackDeferred.promise, ackTimeoutMs, `send ack ${requestId}`);
if (!wantReply) {
return { requestId };
}
return await withTimeout(
replyDeferred!.promise,
replyTimeoutMs,
`send reply ${requestId}`);
} catch (error) {
this.pendingAcks.delete(requestId);
this.pendingReplies.delete(requestId);
throw error;
}
}
async sendNoReply(cmd: string, body: Buffer | Uint8Array | string | null | undefined, options: Omit<QqHookSendOptions, 'wantReply'> = {}): Promise<{ requestId: number }> {
return this.send(cmd, body, { ...options, wantReply: false }) as Promise<{ requestId: number }>;
}
async sendAndWait(cmd: string, body: Buffer | Uint8Array | string | null | undefined, options: Omit<QqHookSendOptions, 'wantReply'> = {}): Promise<QqHookSendReply> {
return this.send(cmd, body, { ...options, wantReply: true }) as Promise<QqHookSendReply>;
}
async sendMany(items: Array<{ cmd: string; body?: Buffer | Uint8Array | string | null; wantReply?: boolean; ackTimeoutMs?: number; replyTimeoutMs?: number }>, {
concurrency = 64,
wantReply = true,
ackTimeoutMs = this.defaultAckTimeoutMs,
replyTimeoutMs = this.defaultReplyTimeoutMs,
}: QqHookSendOptions & { concurrency?: number } = {}): Promise<Array<QqHookSendReply | { requestId: number }>> {
const results = new Array<QqHookSendReply | { requestId: number }>(items.length);
let nextIndex = 0;
const workerCount = Math.max(1, Math.min(concurrency | 0, items.length || 1));
const worker = async () => {
for (;;) {
const index = nextIndex;
nextIndex += 1;
if (index >= items.length) return;
const item = items[index];
const itemWantReply = item.wantReply ?? wantReply;
results[index] = await this.send(item.cmd, item.body, {
wantReply: itemWantReply,
ackTimeoutMs: item.ackTimeoutMs ?? ackTimeoutMs,
replyTimeoutMs: item.replyTimeoutMs ?? replyTimeoutMs,
});
}
};
await Promise.all(Array.from({ length: workerCount }, () => worker()));
return results;
}
waitForPacket(predicate: (packet: QqHookPacket) => boolean = () => true, { timeoutMs = 0 } = {}): Promise<QqHookPacket> {
return new Promise((resolve, reject) => {
let timer: NodeJS.Timeout | null = null;
const cleanup = () => {
this.off('packet', onPacket);
if (timer) {
clearTimeout(timer);
timer = null;
}
};
const onPacket = (packet: QqHookPacket) => {
try {
if (!predicate(packet)) return;
cleanup();
resolve(packet);
} catch (error) {
cleanup();
reject(error);
}
};
this.on('packet', onPacket);
if (timeoutMs > 0) {
timer = setTimeout(() => {
cleanup();
reject(new Error(`recv packet timed out after ${timeoutMs} ms`));
}, timeoutMs);
}
});
}
close(): void {
if (this.closed) return;
this.closed = true;
this.rejectControlPending(new Error('qq_hook client closed'));
this.rejectRecvPending(new Error('qq_hook client closed'));
this.rejectLoginWaiters(new Error('qq_hook client closed'));
if (this.controlSocket) {
this.controlSocket.destroy();
this.controlSocket = null;
}
if (this.recvSocket) {
this.recvSocket.destroy();
this.recvSocket = null;
}
this.controlHello = null;
this.recvHello = null;
this.controlWriteChain = Promise.resolve();
}
private rejectLoginWaiters(error: Error): void {
const waiters = this.loginWaiters;
this.loginWaiters = [];
for (const waiter of waiters) waiter.reject(error);
}
private rejectControlPending(error: Error): void {
for (const pending of this.pendingAcks.values()) {
pending.reject(error);
}
for (const pending of this.pendingReplies.values()) {
pending.reject(error);
}
this.pendingAcks.clear();
this.pendingReplies.clear();
if (this.controlHelloResolver) {
this.controlHelloResolver.reject(error);
this.controlHelloResolver = null;
}
}
private rejectRecvPending(error: Error): void {
if (this.recvHelloResolver) {
this.recvHelloResolver.reject(error);
this.recvHelloResolver = null;
}
}
private writeControl(payload: Buffer): Promise<void> {
const socket = this.controlSocket;
if (!socket || socket.destroyed) {
return Promise.reject(new Error('control pipe is not connected'));
}
const writePromise = this.controlWriteChain.then(() => new Promise<void>((resolve, reject) => {
if (!this.controlSocket || this.controlSocket.destroyed) {
reject(new Error('control pipe is not connected'));
return;
}
socket.write(payload, error => {
if (error) reject(error);
else resolve();
});
}));
this.controlWriteChain = writePromise.catch(() => {});
return writePromise;
}
private connectSocket(pipeName: string, kind: 'control' | 'recv', onFrame: (frame: PipeFrame) => void): Promise<net.Socket> {
return new Promise((resolve, reject) => {
const socket = net.createConnection(pipeName);
const reader = new FrameReader(onFrame);
const onInitialError = (error: Error) => reject(error);
socket.once('error', onInitialError);
socket.once('connect', () => {
socket.off('error', onInitialError);
socket.on('data', chunk => {
try {
reader.push(chunk);
} catch (error) {
this.emit('error', error);
socket.destroy(error instanceof Error ? error : undefined);
}
});
socket.on('error', error => {
this.emit('error', error);
});
socket.on('close', () => {
this.handleSocketClose(kind);
this.emit('close', kind);
});
resolve(socket);
});
});
}
private waitForHello(recvPipe: boolean): Promise<QqHookHello> {
const deferred = createDeferred<QqHookHello>();
if (recvPipe) {
this.recvHelloResolver = deferred;
} else {
this.controlHelloResolver = deferred;
}
return deferred.promise;
}
private resolveHello(frame: PipeFrame, recvPipe: boolean): void {
const resolver = recvPipe ? this.recvHelloResolver : this.controlHelloResolver;
if (!resolver) return;
if (recvPipe) this.recvHelloResolver = null;
else this.controlHelloResolver = null;
resolver.resolve({
pipeName: frame.msg,
pid: Number(frame.value0),
recvPipe,
});
}
private handleSocketClose(kind: 'control' | 'recv'): void {
if (kind === 'control') {
this.controlSocket = null;
this.controlHello = null;
this.rejectControlPending(new Error('control pipe closed'));
return;
}
this.recvSocket = null;
this.recvHello = null;
this.rejectRecvPending(new Error('recv pipe closed'));
}
private applyLoginStateFrame(frame: PipeFrame): void {
const flaggedLoggedIn = (frame.flags & PipeFlagLoggedIn) !== 0;
const statusLoggedIn = frame.status !== 0;
const loggedIn = flaggedLoggedIn || statusLoggedIn;
const uinNumber = BigInt(frame.value0);
const uin = frame.msg || uinNumber.toString();
const previous = this.loginState;
const next = { loggedIn, uin, uinNumber };
this.loginState = next;
if (previous.loggedIn !== next.loggedIn || previous.uin !== next.uin) {
this.emit('loginState', next);
if (next.loggedIn) {
const waiters = this.loginWaiters;
this.loginWaiters = [];
for (const waiter of waiters) waiter.resolve({ ...next });
}
}
}
private handleControlFrame(frame: PipeFrame): void {
if (frame.op === PipeOp.hello) {
this.resolveHello(frame, false);
return;
}
if (frame.op === PipeOp.loginState) {
this.applyLoginStateFrame(frame);
return;
}
if (frame.op === PipeOp.sendAck) {
const pending = this.pendingAcks.get(frame.requestId);
if (!pending) return;
this.pendingAcks.delete(frame.requestId);
pending.resolve({ requestId: frame.requestId, wantReply: pending.wantReply });
return;
}
if (frame.op === PipeOp.sendReply) {
const pending = this.pendingReplies.get(frame.requestId);
if (!pending) return;
this.pendingReplies.delete(frame.requestId);
pending.resolve({
requestId: frame.requestId,
error: frame.status,
message: frame.msg,
body: Buffer.from(frame.body),
});
return;
}
if (frame.op === PipeOp.error) {
const error = new Error(frame.msg || `pipe error ${frame.status}`);
const ack = this.pendingAcks.get(frame.requestId);
if (ack) {
this.pendingAcks.delete(frame.requestId);
ack.reject(error);
}
const reply = this.pendingReplies.get(frame.requestId);
if (reply) {
this.pendingReplies.delete(frame.requestId);
reply.reject(error);
}
}
}
private handleRecvFrame(frame: PipeFrame): void {
if (frame.op === PipeOp.hello) {
this.resolveHello(frame, true);
return;
}
if (frame.op === PipeOp.loginState) {
this.applyLoginStateFrame(frame);
return;
}
if (frame.op !== PipeOp.recvPacket) return;
this.emit('packet', {
seq: Number(frame.value0),
error: frame.status,
cmd: frame.cmd,
uin: frame.msg,
body: Buffer.from(frame.body),
} satisfies QqHookPacket);
}
}
export { mojoPipeName };
+45
View File
@@ -0,0 +1,45 @@
import { NtqqHandler } from './protocol/ntqq-handler';
import { BridgeManager } from './bridge/manager';
import { OneBotManager } from './onebot/manager';
import { loadRuntimeConfig } from './common/runtime';
import { createLogger } from './utils/logger';
import { HookManager } from './hook/hook-manager';
const runtimeConfig = loadRuntimeConfig();
const log = createLogger('App');
async function main() {
log.info('SnowLuma starting');
const ntqq = new NtqqHandler();
const bridgeManager = new BridgeManager();
const oneBotManager = new OneBotManager();
const hookManager = new HookManager(ntqq, bridgeManager);
// Bind bridge manager to NTQQ handler (receives all parsed packets)
bridgeManager.bind(ntqq);
oneBotManager.bind(bridgeManager);
if (typeof __BUILD_WEBUI__ !== 'undefined' && __BUILD_WEBUI__) {
try {
log.info('WebUI is enabled, starting...');
const { initWebUI } = await import('./webui/server');
initWebUI(runtimeConfig.webuiPort || 8080, oneBotManager, hookManager);
} catch (err) {
log.error('Failed to start WebUI: ', err);
}
}
// Graceful shutdown
process.on('SIGINT', () => {
log.warn('Shutting down...');
oneBotManager.dispose();
hookManager.dispose();
process.exit(0);
});
}
main().catch((error) => {
log.error(error instanceof Error ? (error.stack ?? error.message) : String(error));
process.exit(1);
});
@@ -0,0 +1,601 @@
import type { ApiHandler, ApiActionContext } from '../api-handler';
import { asMessage, asNumber, asString, asBoolean } from '../api-handler';
import { RETCODE, failedResponse, okResponse } from '../types';
export function register(h: ApiHandler, ctx: ApiActionContext): void {
// --- Likes & Pokes ---
h.registerAction('send_like', async (params) => {
const userId = asNumber(params.user_id);
const times = asNumber(params.times) || 1;
if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
if (!ctx.sendLike) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
await ctx.sendLike(userId, times);
return okResponse();
});
h.registerAction('friend_poke', async (params) => {
const userId = asNumber(params.user_id);
const targetId = asNumber(params.target_id) || undefined;
if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
if (!ctx.sendFriendPoke) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
await ctx.sendFriendPoke(userId, targetId);
return okResponse();
});
h.registerAction('group_poke', async (params) => {
const groupId = asNumber(params.group_id);
const userId = asNumber(params.user_id);
if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required');
if (!ctx.sendGroupPoke) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
await ctx.sendGroupPoke(groupId, userId);
return okResponse();
});
h.registerAction('send_poke', async (params) => {
const groupId = asNumber(params.group_id);
const userId = asNumber(params.user_id);
if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
if (groupId) {
if (!ctx.sendGroupPoke) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
await ctx.sendGroupPoke(groupId, userId);
} else {
if (!ctx.sendFriendPoke) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
await ctx.sendFriendPoke(userId);
}
return okResponse();
});
// --- Essence ---
h.registerAction('set_essence_msg', async (params) => {
const messageId = asNumber(params.message_id);
if (!Number.isInteger(messageId) || messageId === 0) {
return failedResponse(RETCODE.BAD_REQUEST, 'message_id is required');
}
if (!ctx.setEssenceMsg) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
await ctx.setEssenceMsg(messageId);
return okResponse();
});
h.registerAction('delete_essence_msg', async (params) => {
const messageId = asNumber(params.message_id);
if (!Number.isInteger(messageId) || messageId === 0) {
return failedResponse(RETCODE.BAD_REQUEST, 'message_id is required');
}
if (!ctx.deleteEssenceMsg) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
await ctx.deleteEssenceMsg(messageId);
return okResponse();
});
h.registerAction('get_essence_msg_list', async (params) => {
const groupId = asNumber(params.group_id);
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
// Essence list fetch requires web ticket/cookie flow not wired yet.
// Keep API-compatible output shape for callers.
return okResponse([]);
});
// --- Reactions ---
h.registerAction('set_group_reaction', async (params) => {
const groupId = asNumber(params.group_id);
const messageId = asNumber(params.message_id);
const code = asString(params.code);
const isSet = asBoolean(params.is_set, true);
if (!Number.isInteger(messageId) || messageId === 0 || !code) {
return failedResponse(RETCODE.BAD_REQUEST, 'message_id and code are required');
}
const meta = ctx.getMessageMeta(messageId);
if (!meta || !meta.isGroup) {
return failedResponse(RETCODE.ACTION_FAILED, 'message not found or not a group message');
}
if (groupId && groupId !== meta.targetId) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id does not match message session');
}
if (!ctx.setGroupReaction) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
await ctx.setGroupReaction(meta.targetId, meta.sequence, code, isSet);
return okResponse();
});
// --- History ---
h.registerAction('get_group_msg_history', async (params) => {
const groupId = asNumber(params.group_id);
const messageId = asNumber(params.message_id) || 0;
const count = asNumber(params.count) || 20;
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
if (!ctx.getGroupMsgHistory) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
const messages = await ctx.getGroupMsgHistory(groupId, messageId, count);
return okResponse({ messages });
});
h.registerAction('get_friend_msg_history', async (params) => {
const userId = asNumber(params.user_id);
const messageId = asNumber(params.message_id) || 0;
const count = asNumber(params.count) || 20;
if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
if (!ctx.getFriendMsgHistory) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
const messages = await ctx.getFriendMsgHistory(userId, messageId, count);
return okResponse({ messages });
});
h.registerAction('mark_msg_as_read', async () => {
return okResponse();
});
// --- RKey ---
h.registerAction('get_rkey', async () => {
if (ctx.getDownloadRKeys) {
return okResponse(await ctx.getDownloadRKeys());
}
return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
});
// --- OCR stubs ---
h.registerAction('ocr_image', async () => {
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
});
h.registerAction('.ocr_image', async () => {
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
});
// --- Group notice stubs ---
h.registerAction('_send_group_notice', async () => {
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
});
h.registerAction('_get_group_notice', async () => {
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
});
h.registerAction('_del_group_notice', async () => {
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
});
// --- Forward messages ---
h.registerAction('upload_forward_msg', async (params) => {
const messages = asMessage(params.messages ?? params.message);
const groupId = asNumber(params.group_id);
if (messages === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'message/messages is required');
if (!ctx.sendForwardMsg) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
const result = await ctx.sendForwardMsg(messages);
const data: Record<string, unknown> = {
res_id: result.forwardId,
forward_id: result.forwardId,
message_id: 0,
};
if (groupId > 0) data.group_id = groupId;
return okResponse(data as any);
});
h.registerAction('upload_foward_msg', async (params) => {
const messages = asMessage(params.messages ?? params.message);
if (messages === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'message/messages is required');
if (!ctx.sendForwardMsg) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
const result = await ctx.sendForwardMsg(messages);
return okResponse({ res_id: result.forwardId, forward_id: result.forwardId, message_id: 0 });
});
h.registerAction('send_forward_msg', async (params) => {
const messageType = asString(params.message_type);
const groupId = asNumber(params.group_id);
const userId = asNumber(params.user_id);
const messages = asMessage(params.messages ?? params.message);
if (messages === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'message/messages is required');
if ((messageType === 'group' || groupId > 0) && ctx.sendGroupForwardMsg) {
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
const result = await ctx.sendGroupForwardMsg(groupId, messages);
return okResponse({ message_id: result.messageId, res_id: result.forwardId, forward_id: result.forwardId });
}
if ((messageType === 'private' || userId > 0) && ctx.sendPrivateForwardMsg) {
if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
const result = await ctx.sendPrivateForwardMsg(userId, messages);
return okResponse({ message_id: result.messageId, res_id: result.forwardId, forward_id: result.forwardId });
}
if (!ctx.sendForwardMsg) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
const result = await ctx.sendForwardMsg(messages);
return okResponse({ message_id: 0, res_id: result.forwardId, forward_id: result.forwardId });
});
h.registerAction('send_group_forward_msg', async (params) => {
const groupId = asNumber(params.group_id);
const messages = asMessage(params.messages ?? params.message);
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
if (messages === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'message/messages is required');
if (!ctx.sendGroupForwardMsg) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
const result = await ctx.sendGroupForwardMsg(groupId, messages);
return okResponse({ message_id: result.messageId, res_id: result.forwardId, forward_id: result.forwardId });
});
h.registerAction('send_private_forward_msg', async (params) => {
const userId = asNumber(params.user_id);
const messages = asMessage(params.messages ?? params.message);
if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
if (messages === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'message/messages is required');
if (!ctx.sendPrivateForwardMsg) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
const result = await ctx.sendPrivateForwardMsg(userId, messages);
return okResponse({ message_id: result.messageId, res_id: result.forwardId, forward_id: result.forwardId });
});
h.registerAction('get_forward_msg', async (params) => {
let id = asString(params.id);
if (!id) {
const rawMessageId = params.message_id;
const numericMessageId = asNumber(rawMessageId);
if (numericMessageId > 0) {
const event = ctx.getMessage(numericMessageId);
const segments = Array.isArray(event?.message) ? event.message : [];
for (const seg of segments) {
if (typeof seg !== 'object' || seg === null || Array.isArray(seg)) continue;
const so = seg as Record<string, unknown>;
if (String(so.type ?? '') !== 'forward') continue;
const data = (typeof so.data === 'object' && so.data !== null && !Array.isArray(so.data))
? so.data as Record<string, unknown>
: null;
const candidate = asString(data?.id) || asString(data?.res_id) || asString(data?.forward_id);
if (candidate) {
id = candidate;
break;
}
}
}
if (!id) {
id = asString(rawMessageId);
}
}
if (!id) return failedResponse(RETCODE.BAD_REQUEST, 'id or message_id is required');
if (!ctx.getForwardMsg) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
const messages = await ctx.getForwardMsg(id);
return okResponse({ messages });
});
// --- Media ---
h.registerAction('get_image', async (params) => {
const file = asString(params.file);
if (!file) return failedResponse(RETCODE.BAD_REQUEST, 'file is required');
const imageInfo = findMediaInStore('image', file, ctx);
if (imageInfo) {
return okResponse(imageInfo as unknown as import('../types').JsonValue);
}
return failedResponse(RETCODE.ACTION_FAILED, 'image not found in cache');
});
h.registerAction('get_record', async (params) => {
const file = asString(params.file);
if (!file) return failedResponse(RETCODE.BAD_REQUEST, 'file is required');
const recordInfo = findMediaInStore('record', file, ctx);
if (recordInfo) {
return okResponse(recordInfo as unknown as import('../types').JsonValue);
}
return failedResponse(RETCODE.ACTION_FAILED, 'record not found in cache');
});
// --- Credentials ---
h.registerAction('get_cookies', async () => {
return okResponse({ cookies: '' });
});
h.registerAction('get_csrf_token', async () => {
return okResponse({ token: 0 });
});
h.registerAction('get_credentials', async () => {
return okResponse({ cookies: '', csrf_token: 0 });
});
// --- Utility ---
h.registerAction('set_restart', async () => {
return failedResponse(RETCODE.ACTION_FAILED, 'not supported');
});
h.registerAction('clean_cache', async () => {
return okResponse();
});
h.registerAction('.handle_quick_operation', async (params) => {
const context = params.context as import('../types').JsonObject | undefined;
const operation = params.operation as Record<string, unknown> | undefined;
if (!context || !operation) return failedResponse(RETCODE.BAD_REQUEST, 'context and operation are required');
const { executeQuickOperation } = await import('../http-post-transport');
await executeQuickOperation(context, operation, h);
return okResponse();
});
// --- NapCat-compatible extended APIs ---
h.registerAction('set_friend_remark', async (params) => {
const userId = asNumber(params.user_id);
const remark = asString(params.remark) ?? '';
if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
if (!ctx.setFriendRemark) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
await ctx.setFriendRemark(userId, remark);
return okResponse();
});
h.registerAction('set_msg_emoji_like', async (params) => {
const messageId = asNumber(params.message_id);
const emojiId = asString(params.emoji_id);
const set = asBoolean(params.set, true);
if (!Number.isInteger(messageId) || messageId === 0 || !emojiId) {
return failedResponse(RETCODE.BAD_REQUEST, 'message_id and emoji_id are required');
}
if (!ctx.setMsgEmojiLike) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
await ctx.setMsgEmojiLike(messageId, emojiId, set);
return okResponse();
});
h.registerAction('mark_private_msg_as_read', async () => {
return okResponse();
});
h.registerAction('mark_group_msg_as_read', async () => {
return okResponse();
});
h.registerAction('_mark_all_as_read', async () => {
return okResponse();
});
h.registerAction('get_group_file_system_info', async (params) => {
const groupId = asNumber(params.group_id);
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
if (ctx.getGroupFileCount) {
const info = await ctx.getGroupFileCount(groupId);
return okResponse({
file_count: info.fileCount,
limit_count: info.maxCount,
used_space: 0,
total_space: 10737418240,
});
}
return okResponse({
file_count: 0,
limit_count: 10000,
used_space: 0,
total_space: 10737418240,
});
});
h.registerAction('check_url_safely', async () => {
return okResponse({ level: 1 });
});
h.registerAction('download_file', async (params) => {
const url = asString(params.url);
const base64 = asString(params.base64);
const name = asString(params.name);
if (!url && !base64) return failedResponse(RETCODE.BAD_REQUEST, 'url or base64 is required');
const fs = await import('fs');
const pathMod = await import('path');
const cryptoMod = await import('crypto');
const tempDir = pathMod.join('data', 'downloads');
if (!fs.existsSync(tempDir)) fs.mkdirSync(tempDir, { recursive: true });
let filePath: string;
if (base64) {
const buf = Buffer.from(base64, 'base64');
const fileName = name || cryptoMod.createHash('md5').update(buf).digest('hex');
filePath = pathMod.join(tempDir, fileName);
fs.writeFileSync(filePath, buf);
} else {
const response = await fetch(url!, {
headers: parseDownloadHeaders(params.headers),
});
if (!response.ok) return failedResponse(RETCODE.ACTION_FAILED, `download failed: ${response.status}`);
const buf = Buffer.from(await response.arrayBuffer());
const fileName = name || cryptoMod.createHash('md5').update(buf).digest('hex');
filePath = pathMod.join(tempDir, fileName);
fs.writeFileSync(filePath, buf);
}
return okResponse({ file: pathMod.resolve(filePath) });
});
h.registerAction('set_qq_profile', async () => {
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
});
h.registerAction('set_online_status', async () => {
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
});
h.registerAction('get_group_ignored_notifies', async () => {
return okResponse([]);
});
h.registerAction('get_group_shut_list', async () => {
return okResponse([]);
});
h.registerAction('forward_friend_single_msg', async () => {
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
});
h.registerAction('forward_group_single_msg', async () => {
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
});
h.registerAction('get_recent_contact', async () => {
return okResponse([]);
});
h.registerAction('get_profile_like', async () => {
return okResponse({});
});
h.registerAction('get_friends_with_category', async () => {
if (ctx.getFriendList) {
return okResponse(await ctx.getFriendList());
}
return okResponse([]);
});
// --- Additional NapCat-compatible stubs ---
h.registerAction('get_online_clients', async () => {
return okResponse({ clients: [] });
});
h.registerAction('_get_model_show', async () => {
return okResponse({ variants: [] });
});
h.registerAction('_set_model_show', async () => {
return okResponse();
});
h.registerAction('.get_word_slices', async () => {
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
});
h.registerAction('get_group_at_all_remain', async () => {
return okResponse({ can_at_all: false, remain_at_all_count_for_group: 0, remain_at_all_count_for_uin: 0 });
});
h.registerAction('get_unidirectional_friend_list', async () => {
return okResponse([]);
});
h.registerAction('set_self_longnick', async () => {
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
});
h.registerAction('get_collection_list', async () => {
return okResponse([]);
});
h.registerAction('create_collection', async () => {
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
});
h.registerAction('set_qq_avatar', async () => {
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
});
h.registerAction('set_input_status', async () => {
return okResponse();
});
h.registerAction('translate_en2zh', async () => {
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
});
h.registerAction('get_clientkey', async () => {
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
});
h.registerAction('get_mini_app_ark', async () => {
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
});
h.registerAction('click_inline_keyboard_button', async () => {
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
});
h.registerAction('set_group_sign', async () => {
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
});
h.registerAction('send_group_sign', async () => {
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
});
h.registerAction('get_group_info_ex', async (params) => {
const groupId = asNumber(params.group_id);
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
if (ctx.getGroupInfo) {
return okResponse(await ctx.getGroupInfo(groupId));
}
return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
});
h.registerAction('get_group_detail_info', async (params) => {
const groupId = asNumber(params.group_id);
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
if (ctx.getGroupInfo) {
return okResponse(await ctx.getGroupInfo(groupId));
}
return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
});
h.registerAction('trans_group_file', async () => {
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
});
h.registerAction('rename_group_file', async () => {
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
});
h.registerAction('get_file', async (params) => {
const fileId = asString(params.file_id) || asString(params.file);
if (!fileId) return failedResponse(RETCODE.BAD_REQUEST, 'file_id is required');
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
});
h.registerAction('.send_packet', async () => {
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
});
}
/**
* Search through cached message segments to find a media element (image/record)
* that matches the given file identifier.
*/
function findMediaInStore(
mediaType: 'image' | 'record',
file: string,
ctx: ApiActionContext,
): Record<string, unknown> | null {
// The file param can match a file id, a URL, or a filename stored in segments.
// We don't have a reverse index, so this is best-effort from stored events.
// Most callers will pass the `file` field from a received message segment.
// Just return the info if we can look it up from any recent cached message.
// This is a known limitation — full implementation would require a media cache.
return null;
}
/**
* Parse download_file headers parameter into a Record.
*/
function parseDownloadHeaders(headers: unknown): Record<string, string> {
const result: Record<string, string> = {};
if (!headers) return result;
const headerList: string[] = [];
if (typeof headers === 'string') {
headerList.push(...headers.split(/\r?\n/).filter(Boolean));
} else if (Array.isArray(headers)) {
for (const h of headers) {
if (typeof h === 'string') headerList.push(h);
}
}
for (const line of headerList) {
const idx = line.indexOf('=');
if (idx > 0) {
result[line.substring(0, idx).trim()] = line.substring(idx + 1).trim();
}
}
return result;
}
@@ -0,0 +1,31 @@
import type { ApiHandler, ApiActionContext } from '../api-handler';
import { asNumber, asBoolean } from '../api-handler';
import { RETCODE, failedResponse, okResponse } from '../types';
export function register(h: ApiHandler, ctx: ApiActionContext): void {
h.registerAction('get_friend_list', async () => {
if (ctx.getFriendList) {
return okResponse(await ctx.getFriendList());
}
return okResponse([]);
});
h.registerAction('get_stranger_info', async (params) => {
const userId = asNumber(params.user_id);
if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
if (ctx.getStrangerInfo) {
const info = await ctx.getStrangerInfo(userId);
return okResponse(info ?? { user_id: userId, nickname: '', sex: 'unknown', age: 0 });
}
return okResponse({ user_id: userId, nickname: '', sex: 'unknown', age: 0 });
});
h.registerAction('delete_friend', async (params) => {
const userId = asNumber(params.user_id);
const block = asBoolean(params.block, false);
if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
if (!ctx.handleDeleteFriend) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
await ctx.handleDeleteFriend(userId, block);
return okResponse();
});
}
@@ -0,0 +1,93 @@
import type { ApiHandler, ApiActionContext } from '../api-handler';
import { asNumber, asString, asBoolean } from '../api-handler';
import { RETCODE, failedResponse, okResponse } from '../types';
export function register(h: ApiHandler, ctx: ApiActionContext): void {
h.registerAction('set_group_kick', async (params) => {
const groupId = asNumber(params.group_id);
const userId = asNumber(params.user_id);
const reject = asBoolean(params.reject_add_request, false);
if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required');
if (!ctx.setGroupKick) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
await ctx.setGroupKick(groupId, userId, reject);
return okResponse();
});
h.registerAction('set_group_ban', async (params) => {
const groupId = asNumber(params.group_id);
const userId = asNumber(params.user_id);
const duration = asNumber(params.duration) || 1800;
if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required');
if (!ctx.setGroupBan) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
await ctx.setGroupBan(groupId, userId, duration);
return okResponse();
});
h.registerAction('set_group_whole_ban', async (params) => {
const groupId = asNumber(params.group_id);
const enable = asBoolean(params.enable, true);
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
if (!ctx.setGroupWholeBan) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
await ctx.setGroupWholeBan(groupId, enable);
return okResponse();
});
h.registerAction('set_group_admin', async (params) => {
const groupId = asNumber(params.group_id);
const userId = asNumber(params.user_id);
const enable = asBoolean(params.enable, true);
if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required');
if (!ctx.setGroupAdmin) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
await ctx.setGroupAdmin(groupId, userId, enable);
return okResponse();
});
h.registerAction('set_group_card', async (params) => {
const groupId = asNumber(params.group_id);
const userId = asNumber(params.user_id);
const card = asString(params.card);
if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required');
if (!ctx.setGroupCard) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
await ctx.setGroupCard(groupId, userId, card);
return okResponse();
});
h.registerAction('set_group_name', async (params) => {
const groupId = asNumber(params.group_id);
const name = asString(params.group_name);
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
if (!ctx.setGroupName) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
await ctx.setGroupName(groupId, name);
return okResponse();
});
h.registerAction('set_group_leave', async (params) => {
const groupId = asNumber(params.group_id);
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
if (!ctx.setGroupLeave) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
await ctx.setGroupLeave(groupId);
return okResponse();
});
h.registerAction('set_group_special_title', async (params) => {
const groupId = asNumber(params.group_id);
const userId = asNumber(params.user_id);
const title = asString(params.special_title);
if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required');
if (!ctx.setGroupSpecialTitle) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
await ctx.setGroupSpecialTitle(groupId, userId, title);
return okResponse();
});
h.registerAction('set_group_anonymous', async () => {
return okResponse();
});
h.registerAction('set_group_anonymous_ban', async () => {
return okResponse();
});
h.registerAction('set_group_portrait', async () => {
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
});
}
@@ -0,0 +1,129 @@
import type { ApiHandler, ApiActionContext } from '../api-handler';
import { asBoolean, asNumber, asString } from '../api-handler';
import { RETCODE, failedResponse } from '../types';
import { okResponse } from '../types';
export function register(h: ApiHandler, ctx: ApiActionContext): void {
h.registerAction('upload_group_file', async (params) => {
const groupId = asNumber(params.group_id);
const file = asString(params.file);
const name = asString(params.name);
const folderId = asString(params.folder) || asString(params.folder_id) || '/';
const uploadFile = asBoolean(params.upload_file, true);
if (!groupId || !file) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and file are required');
if (!ctx.uploadGroupFile) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
const fileId = await ctx.uploadGroupFile(groupId, file, name, folderId, uploadFile);
return okResponse({ file_id: fileId });
});
h.registerAction('upload_private_file', async (params) => {
const userId = asNumber(params.user_id);
const file = asString(params.file);
const name = asString(params.name);
const uploadFile = asBoolean(params.upload_file, true);
if (!userId || !file) return failedResponse(RETCODE.BAD_REQUEST, 'user_id and file are required');
if (!ctx.uploadPrivateFile) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
const fileId = await ctx.uploadPrivateFile(userId, file, name, uploadFile);
return okResponse({ file_id: fileId });
});
h.registerAction('get_group_file_url', async (params) => {
const groupId = asNumber(params.group_id);
const fileId = asString(params.file_id);
const busId = asNumber(params.busid) || 102;
if (!groupId || !fileId) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id and file_id are required');
}
if (!ctx.getGroupFileUrl) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
return okResponse({ url: await ctx.getGroupFileUrl(groupId, fileId, busId) });
});
h.registerAction('get_group_root_files', async (params) => {
const groupId = asNumber(params.group_id);
if (!groupId) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
}
if (!ctx.getGroupFiles) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
return okResponse(await ctx.getGroupFiles(groupId, '/'));
});
h.registerAction('get_group_files_by_folder', async (params) => {
const groupId = asNumber(params.group_id);
const folderId = asString(params.folder_id) || asString(params.folder) || '/';
if (!groupId) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
}
if (!ctx.getGroupFiles) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
return okResponse(await ctx.getGroupFiles(groupId, folderId));
});
h.registerAction('delete_group_file', async (params) => {
const groupId = asNumber(params.group_id);
const fileId = asString(params.file_id);
if (!groupId || !fileId) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id and file_id are required');
}
if (!ctx.deleteGroupFile) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
await ctx.deleteGroupFile(groupId, fileId);
return okResponse();
});
h.registerAction('move_group_file', async (params) => {
const groupId = asNumber(params.group_id);
const fileId = asString(params.file_id);
const parentDirectory = asString(params.parent_directory);
const targetDirectory = asString(params.target_directory);
if (!groupId || !fileId || !parentDirectory || !targetDirectory) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id, file_id, parent_directory and target_directory are required');
}
if (!ctx.moveGroupFile) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
await ctx.moveGroupFile(groupId, fileId, parentDirectory, targetDirectory);
return okResponse();
});
h.registerAction('create_group_file_folder', async (params) => {
const groupId = asNumber(params.group_id);
const name = asString(params.name);
const parentId = asString(params.parent_id) || '/';
if (!groupId || !name) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id and name are required');
}
if (!ctx.createGroupFileFolder) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
await ctx.createGroupFileFolder(groupId, name, parentId);
return okResponse();
});
h.registerAction('delete_group_file_folder', async (params) => {
const groupId = asNumber(params.group_id);
const folderId = asString(params.folder_id);
if (!groupId || !folderId) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id and folder_id are required');
}
if (!ctx.deleteGroupFileFolder) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
await ctx.deleteGroupFileFolder(groupId, folderId);
return okResponse();
});
h.registerAction('rename_group_file_folder', async (params) => {
const groupId = asNumber(params.group_id);
const folderId = asString(params.folder_id);
const newName = asString(params.new_folder_name) || asString(params.name);
if (!groupId || !folderId || !newName) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id, folder_id and new_folder_name are required');
}
if (!ctx.renameGroupFileFolder) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
await ctx.renameGroupFileFolder(groupId, folderId, newName);
return okResponse();
});
h.registerAction('get_private_file_url', async (params) => {
const userId = asNumber(params.user_id);
const fileId = asString(params.file_id);
const fileHash = asString(params.file_hash);
if (!userId || !fileId || !fileHash) {
return failedResponse(RETCODE.BAD_REQUEST, 'user_id, file_id and file_hash are required');
}
if (!ctx.getPrivateFileUrl) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
return okResponse({ url: await ctx.getPrivateFileUrl(userId, fileId, fileHash) });
});
}
@@ -0,0 +1,70 @@
import type { ApiHandler, ApiActionContext } from '../api-handler';
import { asNumber, asBoolean } from '../api-handler';
import { RETCODE, failedResponse, okResponse } from '../types';
export function register(h: ApiHandler, ctx: ApiActionContext): void {
h.registerAction('get_group_list', async (params) => {
const noCache = asBoolean(params.no_cache, false);
if (ctx.getGroupList) {
return okResponse(await ctx.getGroupList(noCache));
}
return okResponse([]);
});
h.registerAction('get_group_info', async (params) => {
const groupId = asNumber(params.group_id);
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
const noCache = asBoolean(params.no_cache, false);
if (ctx.getGroupInfo) {
const info = await ctx.getGroupInfo(groupId, noCache);
return okResponse(info ?? { group_id: groupId, group_name: '', member_count: 0, max_member_count: 0 });
}
return okResponse({ group_id: groupId, group_name: '', member_count: 0, max_member_count: 0 });
});
h.registerAction('get_group_member_list', async (params) => {
const groupId = asNumber(params.group_id);
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
const noCache = asBoolean(params.no_cache, false);
if (ctx.getGroupMemberList) {
return okResponse(await ctx.getGroupMemberList(groupId, noCache));
}
return okResponse([]);
});
h.registerAction('get_group_member_info', async (params) => {
const groupId = asNumber(params.group_id);
const userId = asNumber(params.user_id);
if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required');
const noCache = asBoolean(params.no_cache, false);
if (ctx.getGroupMemberInfo) {
const info = await ctx.getGroupMemberInfo(groupId, userId, noCache);
return okResponse(info ?? {
group_id: groupId, user_id: userId, nickname: '', card: '',
sex: 'unknown', age: 0, join_time: 0, last_sent_time: 0,
level: '0', role: 'member', title: '',
});
}
return okResponse({
group_id: groupId, user_id: userId, nickname: '', card: '',
sex: 'unknown', age: 0, join_time: 0, last_sent_time: 0,
level: '0', role: 'member', title: '',
});
});
h.registerAction('get_group_honor_info', async (params) => {
const groupId = asNumber(params.group_id);
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
return okResponse({
group_id: groupId, current_talkative: null, talkative_list: [],
performer_list: [], legend_list: [], strong_newbie_list: [], emotion_list: [],
});
});
h.registerAction('get_group_system_msg', async () => {
if (ctx.handleGetGroupSystemMsg) {
return okResponse(await ctx.handleGetGroupSystemMsg());
}
return okResponse([]);
});
}
+30
View File
@@ -0,0 +1,30 @@
import type { ApiHandler, ApiActionContext } from '../api-handler';
import { okResponse } from '../types';
export function register(h: ApiHandler, ctx: ApiActionContext): void {
h.registerAction('get_login_info', async () => {
const login = ctx.getLoginInfo();
return okResponse({ user_id: login.userId, nickname: login.nickname });
});
h.registerAction('get_status', async () => {
const online = ctx.isOnline();
return okResponse({ online, good: online });
});
h.registerAction('get_version_info', async () => {
return okResponse({
app_name: 'SnowLuma',
app_version: '0.1.0-node',
protocol_version: 'v11',
});
});
h.registerAction('can_send_image', async () => {
return okResponse({ yes: ctx.canSendImage?.() ?? false });
});
h.registerAction('can_send_record', async () => {
return okResponse({ yes: ctx.canSendRecord?.() ?? false });
});
}
+112
View File
@@ -0,0 +1,112 @@
import type { JsonObject, JsonValue } from '../types';
import type { ApiHandler, ApiActionContext } from '../api-handler';
import { asNumber, asString, asBoolean, asMessage } from '../api-handler';
import { RETCODE, failedResponse, okResponse } from '../types';
export function register(h: ApiHandler, ctx: ApiActionContext): void {
h.registerAction('send_msg', async (params) => {
const messageType = asString(params.message_type);
const message = asMessage(params.message);
const autoEscape = asBoolean(params.auto_escape, false);
if (message === undefined) {
return failedResponse(RETCODE.BAD_REQUEST, 'message is required');
}
if (messageType === 'group' || params.group_id !== undefined) {
const groupId = asNumber(params.group_id);
if (!Number.isInteger(groupId) || groupId <= 0) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
}
if (!ctx.sendGroupMessage) {
return failedResponse(RETCODE.ACTION_FAILED, 'send_group_msg is not implemented');
}
const result = await ctx.sendGroupMessage(groupId, message, autoEscape);
return okResponse({ message_id: result.messageId });
}
const userId = asNumber(params.user_id);
if (!Number.isInteger(userId) || userId <= 0) {
return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
}
if (!ctx.sendPrivateMessage) {
return failedResponse(RETCODE.ACTION_FAILED, 'send_private_msg is not implemented');
}
const result = await ctx.sendPrivateMessage(userId, message, autoEscape);
return okResponse({ message_id: result.messageId });
});
h.registerAction('send_private_msg', async (params) => {
const userId = asNumber(params.user_id);
const message = asMessage(params.message);
const autoEscape = asBoolean(params.auto_escape, false);
if (!Number.isInteger(userId) || userId <= 0) {
return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
}
if (message === undefined) {
return failedResponse(RETCODE.BAD_REQUEST, 'message is required');
}
if (!ctx.sendPrivateMessage) {
return failedResponse(RETCODE.ACTION_FAILED, 'send_private_msg is not implemented');
}
const result = await ctx.sendPrivateMessage(userId, message, autoEscape);
return okResponse({ message_id: result.messageId });
});
h.registerAction('send_group_msg', async (params) => {
const groupId = asNumber(params.group_id);
const message = asMessage(params.message);
const autoEscape = asBoolean(params.auto_escape, false);
if (!Number.isInteger(groupId) || groupId <= 0) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
}
if (message === undefined) {
return failedResponse(RETCODE.BAD_REQUEST, 'message is required');
}
if (!ctx.sendGroupMessage) {
return failedResponse(RETCODE.ACTION_FAILED, 'send_group_msg is not implemented');
}
const result = await ctx.sendGroupMessage(groupId, message, autoEscape);
return okResponse({ message_id: result.messageId });
});
h.registerAction('get_msg', async (params) => {
const messageId = asNumber(params.message_id);
if (!Number.isInteger(messageId) || messageId === 0) {
return failedResponse(RETCODE.BAD_REQUEST, 'message_id is required');
}
const data = ctx.getMessage(messageId);
if (!data) {
return failedResponse(RETCODE.ACTION_FAILED, 'message not found');
}
const result: JsonObject = { ...data };
delete result.post_type;
delete result.self_id;
result.real_id = (result.message_id ?? messageId) as JsonValue;
return okResponse(result);
});
h.registerAction('delete_msg', async (params) => {
const messageId = asNumber(params.message_id);
if (!Number.isInteger(messageId) || messageId === 0) {
return failedResponse(RETCODE.BAD_REQUEST, 'message_id is required');
}
if (!ctx.deleteMessage) {
return failedResponse(RETCODE.ACTION_FAILED, 'delete_msg is not implemented');
}
const meta = ctx.getMessageMeta(messageId);
if (!meta) {
return failedResponse(RETCODE.ACTION_FAILED, 'message not found or not retractable');
}
await ctx.deleteMessage(messageId, meta);
return okResponse();
});
}
@@ -0,0 +1,25 @@
import type { ApiHandler, ApiActionContext } from '../api-handler';
import { asString, asBoolean } from '../api-handler';
import { RETCODE, failedResponse, okResponse } from '../types';
export function register(h: ApiHandler, ctx: ApiActionContext): void {
h.registerAction('set_friend_add_request', async (params) => {
const flag = asString(params.flag);
const approve = asBoolean(params.approve, true);
if (!flag) return failedResponse(RETCODE.BAD_REQUEST, 'flag is required');
if (!ctx.handleFriendRequest) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
await ctx.handleFriendRequest(flag, approve);
return okResponse();
});
h.registerAction('set_group_add_request', async (params) => {
const flag = asString(params.flag);
const subType = asString(params.sub_type, asString(params.type, 'add'));
const approve = asBoolean(params.approve, true);
const reason = asString(params.reason);
if (!flag) return failedResponse(RETCODE.BAD_REQUEST, 'flag is required');
if (!ctx.handleGroupRequest) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
await ctx.handleGroupRequest(flag, subType, approve, reason);
return okResponse();
});
}
+207
View File
@@ -0,0 +1,207 @@
import type { JsonObject, JsonValue, MessageMeta } from './types';
import { RETCODE, failedResponse } from './types';
import { register as registerInfo } from './actions/info';
import { register as registerMessage } from './actions/message';
import { register as registerFriend } from './actions/friend';
import { register as registerGroupInfo } from './actions/group-info';
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';
export interface MessageSendResult {
messageId: number;
meta?: MessageMeta;
echoEvent?: JsonObject;
}
export interface ApiActionContext {
getLoginInfo: () => { userId: number; nickname: string };
isOnline: () => boolean;
getMessage: (messageId: number) => JsonObject | null;
getMessageMeta: (messageId: number) => MessageMeta | null;
sendPrivateMessage?: (userId: number, message: JsonValue, autoEscape: boolean) => Promise<MessageSendResult>;
sendGroupMessage?: (groupId: number, message: JsonValue, autoEscape: boolean) => Promise<MessageSendResult>;
deleteMessage?: (messageId: number, meta: MessageMeta) => Promise<void>;
canSendImage?: () => boolean;
canSendRecord?: () => boolean;
// Info retrieval (async — triggers OIDB fetch)
getFriendList?: () => Promise<JsonObject[]>;
getGroupList?: (noCache?: boolean) => Promise<JsonObject[]>;
getGroupInfo?: (groupId: number, noCache?: boolean) => Promise<JsonObject | null>;
getGroupMemberList?: (groupId: number, noCache?: boolean) => Promise<JsonObject[]>;
getGroupMemberInfo?: (groupId: number, userId: number, noCache?: boolean) => Promise<JsonObject | null>;
getStrangerInfo?: (userId: number) => Promise<JsonObject | null>;
// Group admin
setGroupKick?: (groupId: number, userId: number, rejectAdd: boolean) => Promise<void>;
setGroupBan?: (groupId: number, userId: number, duration: number) => Promise<void>;
setGroupWholeBan?: (groupId: number, enable: boolean) => Promise<void>;
setGroupAdmin?: (groupId: number, userId: number, enable: boolean) => Promise<void>;
setGroupCard?: (groupId: number, userId: number, card: string) => Promise<void>;
setGroupName?: (groupId: number, name: string) => Promise<void>;
setGroupLeave?: (groupId: number) => Promise<void>;
setGroupSpecialTitle?: (groupId: number, userId: number, title: string) => Promise<void>;
// Group file
uploadGroupFile?: (groupId: number, file: string, name?: string, folderId?: string, uploadFile?: boolean) => Promise<string | null>;
uploadPrivateFile?: (userId: number, file: string, name?: string, uploadFile?: boolean) => Promise<string | null>;
getGroupFileUrl?: (groupId: number, fileId: string, busId?: number) => Promise<string>;
getGroupFiles?: (groupId: number, folderId?: string) => Promise<JsonObject>;
deleteGroupFile?: (groupId: number, fileId: string) => Promise<void>;
moveGroupFile?: (groupId: number, fileId: string, parentDirectory: string, targetDirectory: string) => Promise<void>;
createGroupFileFolder?: (groupId: number, name: string, parentId?: string) => Promise<void>;
deleteGroupFileFolder?: (groupId: number, folderId: string) => Promise<void>;
renameGroupFileFolder?: (groupId: number, folderId: string, newName: string) => Promise<void>;
getPrivateFileUrl?: (userId: number, fileId: string, fileHash: string) => Promise<string>;
// Requests
handleFriendRequest?: (flag: string, approve: boolean) => Promise<void>;
handleGroupRequest?: (flag: string, subType: string, approve: boolean, reason: string) => Promise<void>;
// Extended
sendLike?: (userId: number, times: number) => Promise<void>;
sendFriendPoke?: (userId: number, targetId?: number) => Promise<void>;
sendGroupPoke?: (groupId: number, userId: number) => Promise<void>;
setEssenceMsg?: (messageId: number) => Promise<void>;
deleteEssenceMsg?: (messageId: number) => Promise<void>;
// New context methods
setGroupReaction?: (groupId: number, sequence: number, code: string, isSet: boolean) => Promise<void>;
handleDeleteFriend?: (userId: number, block?: boolean) => Promise<void>;
getGroupMsgHistory?: (groupId: number, messageId?: number, count?: number) => Promise<JsonObject[]>;
getFriendMsgHistory?: (userId: number, messageId?: number, count?: number) => Promise<JsonObject[]>;
handleGetGroupSystemMsg?: () => Promise<JsonObject[]>;
getDownloadRKeys?: () => Promise<JsonObject[]>;
// Forward message
sendGroupForwardMsg?: (groupId: number, messages: JsonValue) => Promise<{ messageId: number; forwardId: string }>;
sendPrivateForwardMsg?: (userId: number, messages: JsonValue) => Promise<{ messageId: number; forwardId: string }>;
sendForwardMsg?: (messages: JsonValue) => Promise<{ forwardId: string }>;
getForwardMsg?: (resId: string) => Promise<JsonObject[]>;
// Extended NapCat-compatible
setFriendRemark?: (userId: number, remark: string) => Promise<void>;
getGroupFileCount?: (groupId: number) => Promise<{ fileCount: number; maxCount: number }>;
setMsgEmojiLike?: (messageId: number, emojiId: string, set: boolean) => Promise<void>;
}
type ActionHandler = (params: JsonObject) => Promise<import('./types').ApiResponse>;
export class ApiHandler {
private readonly handlers = new Map<string, ActionHandler>();
constructor(context: ApiActionContext) {
registerInfo(this, context);
registerMessage(this, context);
registerFriend(this, context);
registerGroupInfo(this, context);
registerGroupAdmin(this, context);
registerGroupFile(this, context);
registerRequest(this, context);
registerExtended(this, context);
}
registerAction(action: string, handler: ActionHandler): void {
this.handlers.set(action, handler);
}
async handle(action: string, params: JsonObject): Promise<import('./types').ApiResponse> {
const handler = this.handlers.get(action);
if (!handler) {
return failedResponse(RETCODE.UNKNOWN_ACTION, 'unknown action');
}
try {
return await handler(params);
} catch (error) {
const message = error instanceof Error ? error.message : 'internal error';
return failedResponse(RETCODE.INTERNAL_ERROR, message);
}
}
async processRequest(rawRequest: string): Promise<string> {
if (!rawRequest.trim()) {
return JSON.stringify(failedResponse(RETCODE.BAD_REQUEST, 'bad request'));
}
try {
const parsed = JSON.parse(rawRequest) as unknown;
if (!isJsonObject(parsed)) {
return JSON.stringify(failedResponse(RETCODE.BAD_REQUEST, 'bad request'));
}
const action = asString(parsed.action);
if (!action) {
return JSON.stringify(failedResponse(RETCODE.BAD_REQUEST, 'bad request'));
}
const params = isJsonObject(parsed.params) ? parsed.params : {};
const echo = parsed.echo;
const response = await this.handle(action, params);
if (echo !== undefined) {
response.echo = toJsonValue(echo);
}
return JSON.stringify(response);
} catch {
return JSON.stringify(failedResponse(RETCODE.BAD_REQUEST, 'bad request'));
}
}
}
function isJsonObject(value: unknown): value is JsonObject {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
export function asString(value: unknown, fallback = ''): string {
if (typeof value === 'string') return value;
if (typeof value === 'number' || typeof value === 'boolean') return String(value);
return fallback;
}
export function asNumber(value: unknown): number {
if (typeof value === 'number' && Number.isFinite(value)) return Math.trunc(value);
if (typeof value === 'string' && value.trim()) {
const n = Number(value);
if (Number.isFinite(n)) return Math.trunc(n);
}
return 0;
}
export function asBoolean(value: unknown, fallback: boolean): boolean {
if (typeof value === 'boolean') return value;
if (typeof value === 'number') return value !== 0;
if (typeof value === 'string') {
const text = value.trim().toLowerCase();
if (text === 'true' || text === '1' || text === 'yes' || text === 'on') return true;
if (text === 'false' || text === '0' || text === 'no' || text === 'off') return false;
}
return fallback;
}
export function toJsonValue(value: unknown): JsonValue {
if (value === null) return null;
if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') return value;
if (Array.isArray(value)) return value.map(toJsonValue);
if (isJsonObject(value)) {
const obj: JsonObject = {};
for (const [key, item] of Object.entries(value)) {
obj[key] = toJsonValue(item);
}
return obj;
}
return String(value);
}
export function asMessage(value: unknown): import('./types').JsonValue | undefined {
if (value === undefined) return undefined;
if (typeof value === 'string') {
const trimmed = value.trim();
if (trimmed.startsWith('[') && trimmed.endsWith(']')) {
try {
const parsed = JSON.parse(trimmed);
if (Array.isArray(parsed)) {
return toJsonValue(parsed);
}
} catch {
// Fallback to literal text if it just looks like an array but is invalid JSON
}
}
}
return toJsonValue(value);
}
+315
View File
@@ -0,0 +1,315 @@
import fs from 'fs';
import path from 'path';
import { randomBytes } from 'crypto';
import type {
HttpPostEndpoint,
HttpServerEndpoint,
JsonObject,
OneBotConfig,
WsClientEndpoint,
WsRole,
WsServerEndpoint,
} from './types';
const CONFIG_DIR = 'config';
const DEFAULT_CONFIG_PATH = path.join(CONFIG_DIR, 'onebot.json');
export function makeDefaultOneBotConfig(): OneBotConfig {
return {
httpServers: [{ host: '0.0.0.0', port: 3000, path: '/' }],
httpPostEndpoints: [],
wsServers: [{ host: '0.0.0.0', port: 3001 }],
wsClients: [],
musicSignUrl: '',
};
}
export function loadOneBotConfig(uin: string): OneBotConfig {
ensureConfigDir();
const merged = deepClone(toJsonObject(makeDefaultOneBotConfig()));
const globalConfig = tryLoadJson(DEFAULT_CONFIG_PATH);
if (globalConfig) {
deepMerge(merged, globalConfig);
}
const perUinPath = path.join(CONFIG_DIR, `onebot_${uin}.json`);
const perUinConfig = tryLoadJson(perUinPath);
if (perUinConfig) {
deepMerge(merged, perUinConfig);
}
const config = fromJson(merged);
let shouldSave = !perUinConfig;
// Auto-generate per-endpoint accessToken if not set.
for (const s of config.httpServers) {
if (!s.accessToken) {
s.accessToken = generateRandomKey();
shouldSave = true;
}
}
for (const s of config.wsServers) {
if (!s.accessToken) {
s.accessToken = generateRandomKey();
shouldSave = true;
}
}
for (const c of config.wsClients) {
if (!c.accessToken) {
c.accessToken = generateRandomKey();
shouldSave = true;
}
}
// Persist normalized endpoints and generated keys.
merged.httpServers = config.httpServers.map((s) => {
const out: JsonObject = {
host: s.host,
port: s.port,
path: s.path ?? '/',
accessToken: s.accessToken ?? '',
};
if (s.name) out.name = s.name;
return out;
});
merged.httpPostEndpoints = config.httpPostEndpoints.map((e) => {
const out: JsonObject = { url: e.url };
if (e.name) out.name = e.name;
if (e.accessToken) out.accessToken = e.accessToken;
if (typeof e.timeoutMs === 'number') out.timeoutMs = e.timeoutMs;
return out;
});
merged.wsServers = config.wsServers.map((s) => {
const out: JsonObject = {
host: s.host,
port: s.port,
path: s.path ?? '/',
role: s.role ?? 'universal',
accessToken: s.accessToken ?? '',
};
if (s.name) out.name = s.name;
return out;
});
merged.wsClients = config.wsClients.map((c) => {
const out: JsonObject = {
url: c.url,
role: c.role ?? 'universal',
accessToken: c.accessToken ?? '',
};
if (c.name) out.name = c.name;
if (typeof c.reconnectIntervalMs === 'number' && Number.isFinite(c.reconnectIntervalMs)) {
out.reconnectIntervalMs = Math.max(1000, Math.trunc(c.reconnectIntervalMs));
}
return out;
});
merged.musicSignUrl = config.musicSignUrl ?? '';
if (shouldSave) {
saveJson(perUinPath, merged);
}
return config;
}
export function saveOneBotConfig(uin: string, config: OneBotConfig): void {
ensureConfigDir();
const perUinPath = path.join(CONFIG_DIR, `onebot_${uin}.json`);
const jsonObj = toJsonObject(config);
saveJson(perUinPath, jsonObj);
}
function ensureConfigDir(): void {
fs.mkdirSync(CONFIG_DIR, { recursive: true });
}
function toJsonObject(config: OneBotConfig): JsonObject {
return {
httpServers: config.httpServers.map((s) => {
const out: JsonObject = { host: s.host, port: s.port, path: s.path ?? '/', accessToken: s.accessToken ?? '' };
if (s.name) out.name = s.name;
return out;
}),
httpPostEndpoints: config.httpPostEndpoints.map((e) => {
const out: JsonObject = { url: e.url };
if (e.name) out.name = e.name;
if (e.accessToken) out.accessToken = e.accessToken;
if (typeof e.timeoutMs === 'number') out.timeoutMs = e.timeoutMs;
return out;
}),
wsServers: config.wsServers.map((s) => {
const out: JsonObject = { host: s.host, port: s.port, path: s.path ?? '/', role: s.role ?? 'universal', accessToken: s.accessToken ?? '' };
if (s.name) out.name = s.name;
return out;
}),
wsClients: config.wsClients.map((c) => {
const out: JsonObject = {
url: c.url,
role: c.role ?? 'universal',
accessToken: c.accessToken ?? '',
};
if (c.name) out.name = c.name;
if (typeof c.reconnectIntervalMs === 'number' && Number.isFinite(c.reconnectIntervalMs)) {
out.reconnectIntervalMs = Math.max(1000, Math.trunc(c.reconnectIntervalMs));
}
return out;
}),
musicSignUrl: config.musicSignUrl ?? '',
};
}
function fromJson(json: JsonObject): OneBotConfig {
const httpServers = toHttpServers(json.httpServers);
const httpPostEndpoints = toHttpPostEndpoints(json.httpPostEndpoints);
const wsServers = toWsServers(json.wsServers);
const wsClients = toWsClients(json.wsClients);
return {
httpServers: httpServers.length > 0 ? httpServers : [{ host: '0.0.0.0', port: 3000, path: '/' }],
httpPostEndpoints,
wsServers: wsServers.length > 0 ? wsServers : [{ host: '0.0.0.0', port: 3001 }],
wsClients,
musicSignUrl: typeof json.musicSignUrl === 'string' ? json.musicSignUrl : '',
};
}
function toHttpServers(value: unknown): HttpServerEndpoint[] {
if (!Array.isArray(value)) return [];
const result: HttpServerEndpoint[] = [];
for (const item of value) {
if (!isObject(item)) continue;
const host = asString(item.host, '0.0.0.0');
const port = asNumber(item.port, 3000);
const pathValue = asString(item.path, '/');
const endpoint: HttpServerEndpoint = { host, port, path: pathValue };
const name = asString(item.name);
if (name) endpoint.name = name;
const token = asString(item.accessToken);
if (token) endpoint.accessToken = token;
result.push(endpoint);
}
return result;
}
function toHttpPostEndpoints(value: unknown): HttpPostEndpoint[] {
if (!Array.isArray(value)) return [];
const result: HttpPostEndpoint[] = [];
for (const item of value) {
if (!isObject(item)) continue;
const url = asString(item.url);
if (!url) continue;
const endpoint: HttpPostEndpoint = { url };
const name = asString(item.name);
if (name) endpoint.name = name;
const token = asString(item.accessToken);
if (token) endpoint.accessToken = token;
const timeout = asNumber(item.timeoutMs, 0);
if (timeout > 0) endpoint.timeoutMs = timeout;
result.push(endpoint);
}
return result;
}
function toWsServers(value: unknown): WsServerEndpoint[] {
if (!Array.isArray(value)) return [];
const result: WsServerEndpoint[] = [];
for (const item of value) {
if (!isObject(item)) continue;
const host = asString(item.host, '0.0.0.0');
const port = asNumber(item.port, 3001);
const pathValue = asString(item.path, '/');
const role = asRole(item.role, 'universal');
const endpoint: WsServerEndpoint = { host, port, path: pathValue, role };
const name = asString(item.name);
if (name) endpoint.name = name;
const token = asString(item.accessToken);
if (token) endpoint.accessToken = token;
result.push(endpoint);
}
return result;
}
function toWsClients(value: unknown): WsClientEndpoint[] {
if (!Array.isArray(value)) return [];
const result: WsClientEndpoint[] = [];
for (const item of value) {
if (!isObject(item)) continue;
const url = asString(item.url);
if (!url) continue;
const role = asRole(item.role, 'universal');
const reconnectIntervalMs = asNumber(item.reconnectIntervalMs, 5000);
const endpoint: WsClientEndpoint = { url, role, reconnectIntervalMs };
const name = asString(item.name);
if (name) endpoint.name = name;
const token = asString(item.accessToken);
if (token) endpoint.accessToken = token;
result.push(endpoint);
}
return result;
}
function asRole(value: unknown, fallback: WsRole): WsRole {
const text = asString(value, fallback);
return text === 'api' || text === 'event' || text === 'universal' ? text : fallback;
}
function asString(value: unknown, fallback = ''): string {
if (typeof value === 'string') return value;
if (typeof value === 'number' || typeof value === 'boolean') return String(value);
return fallback;
}
function asNumber(value: unknown, fallback = 0): number {
if (typeof value === 'number' && Number.isFinite(value)) return Math.max(0, Math.trunc(value));
if (typeof value === 'string' && value.trim()) {
const n = Number(value);
if (Number.isFinite(n)) return Math.max(0, Math.trunc(n));
}
return fallback;
}
function generateRandomKey(byteLength = 18): string {
return randomBytes(byteLength).toString('hex');
}
function tryLoadJson(filePath: string): JsonObject | null {
if (!fs.existsSync(filePath)) return null;
try {
const raw = fs.readFileSync(filePath, 'utf8');
const parsed = JSON.parse(raw) as unknown;
return isObject(parsed) ? parsed : null;
} catch {
return null;
}
}
function saveJson(filePath: string, json: JsonObject): void {
fs.mkdirSync(path.dirname(filePath), { recursive: true });
fs.writeFileSync(filePath, JSON.stringify(json, null, 2), 'utf8');
}
function deepClone(obj: JsonObject): JsonObject {
return JSON.parse(JSON.stringify(obj)) as JsonObject;
}
function deepMerge(base: JsonObject, override: JsonObject): void {
for (const [key, value] of Object.entries(override)) {
if (isObject(base[key]) && isObject(value)) {
deepMerge(base[key] as JsonObject, value);
} else {
base[key] = value as never;
}
}
}
function isObject(value: unknown): value is JsonObject {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
+513
View File
@@ -0,0 +1,513 @@
import type { MessageElement, QQEventVariant } from '../bridge/events';
import type { JsonArray, JsonObject } from './types';
import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT } from './message-id';
export type ImageUrlResolver = (element: MessageElement, isGroup: boolean) => string;
export type MediaUrlResolver = (element: MessageElement, isGroup: boolean, sessionId: number) => Promise<string>;
export type MessageIdResolver = (isGroup: boolean, sessionId: number, sequence: number, eventName: string) => number;
export class EventConverter {
private imageUrlResolver_: ImageUrlResolver | null = null;
private mediaUrlResolver_: MediaUrlResolver | null = null;
private messageIdResolver_: MessageIdResolver | null = null;
setImageUrlResolver(resolver: ImageUrlResolver): void {
this.imageUrlResolver_ = resolver;
}
setMediaUrlResolver(resolver: MediaUrlResolver): void {
this.mediaUrlResolver_ = resolver;
}
setMessageIdResolver(resolver: MessageIdResolver): void {
this.messageIdResolver_ = resolver;
}
async convert(instanceUin: string, event: QQEventVariant): Promise<JsonObject | null> {
const selfId = parseSelfId(instanceUin);
switch (event.kind) {
case 'friend_message':
{
const messageId = this.resolveMessageId(false, event.senderUin, event.msgSeq, PRIVATE_MESSAGE_EVENT);
const segments = await elementsToJson(event.elements, false, event.senderUin, this.imageUrlResolver_, this.mediaUrlResolver_, this.messageIdResolver_);
return {
time: event.time,
self_id: selfId,
post_type: 'message',
message_type: 'private',
sub_type: 'friend',
message_id: messageId,
message_seq: event.msgSeq,
user_id: event.senderUin,
message: segments,
raw_message: segmentsToRawMessage(segments),
font: 0,
sender: {
user_id: event.senderUin,
nickname: event.senderNick,
sex: 'unknown',
age: 0,
},
};
}
case 'group_message':
{
const messageId = this.resolveMessageId(true, event.groupId, event.msgSeq, GROUP_MESSAGE_EVENT);
const segments = await elementsToJson(event.elements, true, event.groupId, this.imageUrlResolver_, this.mediaUrlResolver_, this.messageIdResolver_);
return {
time: event.time,
self_id: selfId,
post_type: 'message',
message_type: 'group',
sub_type: 'normal',
message_id: messageId,
message_seq: event.msgSeq,
group_id: event.groupId,
user_id: event.senderUin,
message: segments,
raw_message: segmentsToRawMessage(segments),
font: 0,
sender: {
user_id: event.senderUin,
nickname: event.senderNick,
card: event.senderCard,
role: event.senderRole || 'member',
sex: 'unknown',
age: 0,
},
anonymous: null,
};
}
case 'temp_message':
{
const messageId = this.resolveMessageId(false, event.senderUin, event.msgSeq, PRIVATE_MESSAGE_EVENT);
const segments = await elementsToJson(event.elements, false, event.senderUin, this.imageUrlResolver_, this.mediaUrlResolver_, this.messageIdResolver_);
return {
time: event.time,
self_id: selfId,
post_type: 'message',
message_type: 'private',
sub_type: 'group',
message_id: messageId,
message_seq: event.msgSeq,
user_id: event.senderUin,
message: segments,
raw_message: segmentsToRawMessage(segments),
font: 0,
sender: {
user_id: event.senderUin,
nickname: event.senderNick,
sex: 'unknown',
age: 0,
},
};
}
case 'group_member_join':
return {
time: event.time,
self_id: selfId,
post_type: 'notice',
notice_type: 'group_increase',
sub_type: event.operatorUin === event.userUin ? 'approve' : 'invite',
group_id: event.groupId,
operator_id: event.operatorUin,
user_id: event.userUin,
};
case 'group_member_leave':
{
let subType: string;
if (event.isKick) {
subType = event.userUin === parseSelfId(instanceUin) ? 'kick_me' : 'kick';
} else {
subType = 'leave';
}
return {
time: event.time,
self_id: selfId,
post_type: 'notice',
notice_type: 'group_decrease',
sub_type: subType,
group_id: event.groupId,
operator_id: event.operatorUin,
user_id: event.userUin,
};
}
case 'group_mute':
return {
time: event.time,
self_id: selfId,
post_type: 'notice',
notice_type: 'group_ban',
sub_type: event.duration > 0 ? 'ban' : 'lift_ban',
group_id: event.groupId,
operator_id: event.operatorUin,
user_id: event.userUin,
duration: event.duration,
};
case 'group_admin':
return {
time: event.time,
self_id: selfId,
post_type: 'notice',
notice_type: 'group_admin',
sub_type: event.set ? 'set' : 'unset',
group_id: event.groupId,
user_id: event.userUin,
};
case 'friend_recall':
{
const messageId = this.resolveMessageId(false, event.userUin, event.msgSeq, PRIVATE_MESSAGE_EVENT);
return {
time: event.time,
self_id: selfId,
post_type: 'notice',
notice_type: 'friend_recall',
user_id: event.userUin,
message_id: messageId,
};
}
case 'group_recall':
{
const messageId = this.resolveMessageId(true, event.groupId, event.msgSeq, GROUP_MESSAGE_EVENT);
return {
time: event.time,
self_id: selfId,
post_type: 'notice',
notice_type: 'group_recall',
group_id: event.groupId,
operator_id: event.operatorUin,
user_id: event.authorUin,
message_id: messageId,
};
}
case 'friend_request':
return {
time: event.time,
self_id: selfId,
post_type: 'request',
request_type: 'friend',
user_id: event.fromUin,
comment: event.message,
flag: event.flag,
};
case 'group_invite':
return {
time: event.time,
self_id: selfId,
post_type: 'request',
request_type: 'group',
sub_type: event.subType || 'invite',
group_id: event.groupId,
user_id: event.fromUin,
comment: event.message,
flag: event.flag,
};
case 'friend_poke':
return {
time: event.time,
self_id: selfId,
post_type: 'notice',
notice_type: 'notify',
sub_type: 'poke',
user_id: event.userUin,
target_id: event.targetUin,
action: event.action,
suffix: event.suffix,
action_img_url: event.actionImgUrl,
};
case 'group_poke':
return {
time: event.time,
self_id: selfId,
post_type: 'notice',
notice_type: 'notify',
sub_type: 'poke',
group_id: event.groupId,
user_id: event.userUin,
target_id: event.targetUin,
action: event.action,
suffix: event.suffix,
action_img_url: event.actionImgUrl,
};
case 'group_essence':
{
const messageId = this.resolveMessageId(true, event.groupId, event.msgSeq, GROUP_MESSAGE_EVENT);
return {
time: event.time,
self_id: selfId,
post_type: 'notice',
notice_type: 'essence',
sub_type: event.set ? 'add' : 'delete',
group_id: event.groupId,
user_id: event.senderUin,
sender_id: event.senderUin,
operator_id: event.operatorUin,
message_id: messageId,
message_seq: event.msgSeq,
random: event.random,
};
}
case 'group_file_upload':
return {
time: event.time,
self_id: selfId,
post_type: 'notice',
notice_type: 'group_upload',
group_id: event.groupId,
user_id: event.userUin,
file: {
id: event.fileId,
name: event.fileName,
size: event.fileSize,
busid: event.busId,
},
};
case 'friend_add':
return {
time: event.time,
self_id: selfId,
post_type: 'notice',
notice_type: 'friend_add',
user_id: event.userUin,
};
default:
return null;
}
}
private resolveMessageId(isGroup: boolean, sessionId: number, sequence: number, eventName: string): number {
if (this.messageIdResolver_) {
const resolved = this.messageIdResolver_(isGroup, sessionId, sequence, eventName);
if (Number.isInteger(resolved) && resolved !== 0) return resolved;
}
const seq = Math.trunc(sequence);
return seq === 0 ? 0 : seq;
}
}
function parseSelfId(instanceUin: string): number {
const parsed = Number.parseInt(instanceUin, 10);
return Number.isNaN(parsed) ? 0 : parsed;
}
async function elementsToJson(
elements: MessageElement[],
isGroup: boolean,
sessionId: number,
resolver?: ImageUrlResolver | null,
mediaResolver?: MediaUrlResolver | null,
messageIdResolver?: MessageIdResolver | null,
): Promise<JsonArray> {
const result: JsonArray = [];
for (const element of elements) {
result.push(await elementToSegment(element, isGroup, sessionId, resolver, mediaResolver, messageIdResolver));
}
return result;
}
export async function elementsToOneBotSegments(
elements: MessageElement[],
isGroup: boolean,
sessionId: number,
resolver?: ImageUrlResolver | null,
mediaResolver?: MediaUrlResolver | null,
messageIdResolver?: MessageIdResolver | null,
): Promise<JsonArray> {
return elementsToJson(elements, isGroup, sessionId, resolver, mediaResolver, messageIdResolver);
}
async function elementToSegment(
element: MessageElement,
isGroup: boolean,
sessionId: number,
resolver?: ImageUrlResolver | null,
mediaResolver?: MediaUrlResolver | null,
messageIdResolver?: MessageIdResolver | null,
): Promise<JsonObject> {
if (element.type === 'text') {
return { type: 'text', data: { text: element.text ?? '' } };
}
if (element.type === 'face') {
return { type: 'face', data: { id: String(element.faceId ?? 0) } };
}
if (element.type === 'image') {
const url = resolver ? resolver(element, isGroup) : (element.imageUrl ?? '');
return {
type: 'image',
data: {
url,
file: element.fileId ?? '',
},
};
}
if (element.type === 'at') {
const qq = (element.uid === 'all' || element.targetUin === 0)
? 'all'
: String(element.targetUin ?? 0);
return { type: 'at', data: { qq } };
}
if (element.type === 'reply') {
const id = resolveReplyId(isGroup, sessionId, element.replySeq ?? 0, messageIdResolver);
return { type: 'reply', data: { id: String(id) } };
}
if (element.type === 'record') {
const url = mediaResolver ? await mediaResolver(element, isGroup, sessionId) : (element.url ?? '');
return {
type: 'record',
data: {
file: element.fileName ?? element.fileId ?? '',
url,
},
};
}
if (element.type === 'video') {
const url = mediaResolver ? await mediaResolver(element, isGroup, sessionId) : (element.url ?? '');
return {
type: 'video',
data: {
file: element.fileName ?? element.fileId ?? '',
url,
},
};
}
if (element.type === 'json') {
return { type: 'json', data: { data: element.text ?? '' } };
}
if (element.type === 'xml') {
return {
type: 'xml',
data: {
data: element.text ?? '',
resid: element.subType ?? 35,
},
};
}
if (element.type === 'file') {
const url = mediaResolver ? await mediaResolver(element, isGroup, sessionId) : (element.url ?? '');
return {
type: 'file',
data: {
name: element.fileName ?? '',
size: element.fileSize ?? 0,
id: element.fileId ?? '',
url,
file_hash: element.fileHash ?? '',
},
};
}
if (element.type === 'mface') {
return {
type: 'mface',
data: {
name: element.text ?? '',
tab_id: element.faceId ?? 0,
sub_type: element.subType ?? 0,
},
};
}
if (element.type === 'poke') {
return {
type: 'poke',
data: {
type: element.subType ?? 0,
},
};
}
if (!isGroup && element.type === 'at') {
return { type: 'text', data: { text: element.text ?? '' } };
}
return { type: element.type, data: {} };
}
// --- CQ code raw_message generation (from already-resolved JSON segments) ---
function cqEscape(text: string): string {
return text.replace(/&/g, '&amp;').replace(/\[/g, '&#91;').replace(/\]/g, '&#93;').replace(/,/g, '&#44;');
}
function segmentsToRawMessage(segments: JsonArray): string {
return segments.map(seg => segmentToCQ(seg as JsonObject)).join('');
}
function segmentToCQ(seg: JsonObject): string {
const type = String(seg.type ?? '');
const data = (seg.data ?? {}) as Record<string, unknown>;
switch (type) {
case 'text':
return cqEscape(String(data.text ?? ''));
case 'face':
return `[CQ:face,id=${data.id ?? 0}]`;
case 'image':
return `[CQ:image,file=${cqEscape(String(data.file ?? ''))},url=${cqEscape(String(data.url ?? ''))}]`;
case 'at':
return `[CQ:at,qq=${data.qq ?? ''}]`;
case 'reply':
return `[CQ:reply,id=${data.id ?? 0}]`;
case 'record':
return `[CQ:record,file=${cqEscape(String(data.file ?? ''))},url=${cqEscape(String(data.url ?? ''))}]`;
case 'video':
return `[CQ:video,file=${cqEscape(String(data.file ?? ''))},url=${cqEscape(String(data.url ?? ''))}]`;
case 'json':
return `[CQ:json,data=${cqEscape(String(data.data ?? ''))}]`;
case 'xml':
return `[CQ:xml,data=${cqEscape(String(data.data ?? ''))}]`;
case 'forward':
return `[CQ:forward,id=${cqEscape(String(data.id ?? ''))}]`;
case 'mface':
return `[CQ:mface,name=${cqEscape(String(data.name ?? ''))}]`;
case 'poke':
return `[CQ:poke,type=${data.type ?? 0}]`;
case 'file':
return `[CQ:file,name=${cqEscape(String(data.name ?? ''))},size=${data.size ?? 0},id=${cqEscape(String(data.id ?? ''))},url=${cqEscape(String(data.url ?? ''))}]`;
default:
return `[CQ:${type}]`;
}
}
function resolveReplyId(
isGroup: boolean,
sessionId: number,
sequence: number,
resolver?: MessageIdResolver | null,
): number {
const seq = Math.trunc(sequence);
if (seq === 0) return 0;
if (resolver) {
const eventName = isGroup ? GROUP_MESSAGE_EVENT : PRIVATE_MESSAGE_EVENT;
const resolved = resolver(isGroup, sessionId, seq, eventName);
if (Number.isInteger(resolved) && resolved !== 0) return resolved;
}
return seq;
}
@@ -0,0 +1,197 @@
import type { JsonObject, OneBotConfig, HttpPostEndpoint } from './types';
import { createLogger } from '../utils/logger';
export interface HttpPostTransportContext {
uin: string;
api: import('./api-handler').ApiHandler;
}
const log = createLogger('OneBot.POST');
const DEFAULT_TIMEOUT_MS = 5000;
export class HttpPostTransport {
private readonly context: HttpPostTransportContext;
private endpoints: HttpPostEndpoint[] = [];
private stopped = false;
constructor(config: OneBotConfig, context: HttpPostTransportContext) {
this.endpoints = [...config.httpPostEndpoints];
this.context = context;
}
start(): void {
this.stopped = false;
const count = this.endpoints.length;
if (count > 0) {
log.info('configured %d HTTP POST endpoint(s)', count);
}
}
reloadConfig(config: OneBotConfig): void {
this.endpoints = [...config.httpPostEndpoints];
log.info('reloaded %d HTTP POST endpoint(s)', this.endpoints.length);
}
stop(): void {
this.stopped = true;
}
publishEvent(event: JsonObject): void {
const endpoints = this.endpoints;
if (!endpoints || endpoints.length === 0) return;
const payload = JSON.stringify(event);
for (const endpoint of endpoints) {
void this.postEvent(endpoint, payload, event);
}
}
private async postEvent(endpoint: HttpPostEndpoint, payload: string, event: JsonObject): Promise<void> {
if (this.stopped) return;
const headers: Record<string, string> = {
'Content-Type': 'application/json',
'User-Agent': 'OneBot',
'X-Self-ID': this.context.uin,
};
if (endpoint.accessToken) {
headers['X-Signature'] = await computeHmacSha1(endpoint.accessToken, payload);
}
const timeoutMs = endpoint.timeoutMs ?? DEFAULT_TIMEOUT_MS;
try {
const response = await fetch(endpoint.url, {
method: 'POST',
headers,
body: payload,
signal: AbortSignal.timeout(timeoutMs),
});
// OneBot v11: if the response has a JSON body, it's a quick operation
if (response.ok) {
const contentType = response.headers.get('content-type') ?? '';
if (contentType.includes('application/json')) {
const body = await response.text();
if (body.trim()) {
await this.handleQuickOperation(event, body);
}
}
} else {
log.warn('POST %s returned %d', endpoint.url, response.status);
}
} catch (error) {
if (!this.stopped) {
log.warn('POST %s failed: %s', endpoint.url, error instanceof Error ? error.message : String(error));
}
}
}
private async handleQuickOperation(event: JsonObject, responseBody: string): Promise<void> {
try {
const operation = JSON.parse(responseBody) as Record<string, unknown>;
if (!operation || typeof operation !== 'object') return;
await executeQuickOperation(event, operation, this.context.api);
} catch (error) {
log.warn('quick operation failed: %s', error instanceof Error ? error.message : String(error));
}
}
}
async function computeHmacSha1(secret: string, payload: string): Promise<string> {
const { createHmac } = await import('crypto');
return 'sha1=' + createHmac('sha1', secret).update(payload).digest('hex');
}
/**
* Execute a quick operation based on the event type and the response body.
* This implements the .handle_quick_operation hidden API behavior.
* See: https://github.com/botuniverse/onebot-11/blob/master/api/hidden.md
*/
export async function executeQuickOperation(
event: JsonObject,
operation: Record<string, unknown>,
api: import('./api-handler').ApiHandler,
): Promise<void> {
const postType = event.post_type as string;
if (postType === 'message') {
// Quick reply
if (operation.reply !== undefined && operation.reply !== null && operation.reply !== '') {
const messageType = event.message_type as string;
const autoEscape = !!operation.auto_escape;
if (messageType === 'group') {
const params: JsonObject = {
group_id: event.group_id as number,
message: operation.reply as import('./types').JsonValue,
auto_escape: autoEscape,
};
// at_sender defaults to true for group messages
if (operation.at_sender !== false && event.user_id) {
// Prepend an @ segment
const atSegment = { type: 'at', data: { qq: String(event.user_id) } };
if (typeof operation.reply === 'string') {
params.message = [atSegment, { type: 'text', data: { text: operation.reply as string } }] as import('./types').JsonValue;
params.auto_escape = false;
} else if (Array.isArray(operation.reply)) {
params.message = [atSegment, ...(operation.reply as unknown[])] as import('./types').JsonValue;
}
}
await api.handle('send_group_msg', params);
} else if (messageType === 'private') {
await api.handle('send_private_msg', {
user_id: event.user_id as number,
message: operation.reply as import('./types').JsonValue,
auto_escape: autoEscape,
});
}
}
// Quick delete
if (operation.delete) {
await api.handle('delete_msg', { message_id: event.message_id as number });
}
// Quick ban (group only)
if (operation.ban && event.message_type === 'group') {
const duration = typeof operation.ban_duration === 'number' ? operation.ban_duration : 1800;
await api.handle('set_group_ban', {
group_id: event.group_id as number,
user_id: event.user_id as number,
duration: duration as import('./types').JsonValue,
});
}
// Quick kick (group only)
if (operation.kick && event.message_type === 'group') {
await api.handle('set_group_kick', {
group_id: event.group_id as number,
user_id: event.user_id as number,
reject_add_request: !!operation.reject_add_request as unknown as import('./types').JsonValue,
});
}
}
if (postType === 'request') {
if (operation.approve !== undefined) {
const requestType = event.request_type as string;
if (requestType === 'friend') {
await api.handle('set_friend_add_request', {
flag: event.flag as string,
approve: operation.approve as import('./types').JsonValue,
remark: (operation.remark ?? '') as import('./types').JsonValue,
});
} else if (requestType === 'group') {
await api.handle('set_group_add_request', {
flag: event.flag as string,
sub_type: event.sub_type as string,
approve: operation.approve as import('./types').JsonValue,
reason: (operation.reason ?? '') as import('./types').JsonValue,
});
}
}
}
}
+228
View File
@@ -0,0 +1,228 @@
import {
createServer,
type IncomingMessage,
type Server,
type ServerResponse,
} from 'http';
import type { ApiHandler } from './api-handler';
import type { HttpServerEndpoint, OneBotConfig } from './types';
import { createLogger } from '../utils/logger';
export interface HttpTransportContext {
api: ApiHandler;
}
const log = createLogger('OneBot.HTTP');
export class HttpTransport {
private readonly context: HttpTransportContext;
private readonly servers = new Map<string, Server>();
private endpoints: HttpServerEndpoint[] = [];
constructor(config: OneBotConfig, context: HttpTransportContext) {
this.endpoints = [...config.httpServers];
this.context = context;
}
start(): void {
for (const endpoint of this.endpoints) this.startEndpoint(endpoint);
}
reloadConfig(config: OneBotConfig): void {
const nextEndpoints = [...config.httpServers];
const nextKeys = new Set(nextEndpoints.map(httpServerKey));
for (const [key, server] of this.servers) {
if (!nextKeys.has(key)) {
server.close();
this.servers.delete(key);
log.info('stopped %s', key);
}
}
for (const endpoint of nextEndpoints) {
if (!this.servers.has(httpServerKey(endpoint))) {
this.startEndpoint(endpoint);
}
}
this.endpoints = nextEndpoints;
}
stop(): void {
for (const server of this.servers.values()) {
server.close();
}
this.servers.clear();
}
private startEndpoint(endpoint: HttpServerEndpoint): void {
const expectedPath = normalizePath(endpoint.path ?? '/');
const endpointToken = endpoint.accessToken ?? '';
const server = createServer((req, res) => {
void this.handleRequest(expectedPath, endpointToken, req, res);
});
server.on('listening', () => {
const label = endpoint.name ? `[${endpoint.name}] ` : '';
log.success('%slistening %s:%d%s', label, endpoint.host, endpoint.port, expectedPath);
});
server.on('error', (error) => {
log.warn('server error: %s', error instanceof Error ? error.message : String(error));
});
server.listen(endpoint.port, endpoint.host);
this.servers.set(httpServerKey(endpoint), server);
}
private async handleRequest(expectedPath: string, accessToken: string, req: IncomingMessage, res: ServerResponse): Promise<void> {
const parsedUrl = new URL(req.url ?? '/', 'http://127.0.0.1');
const incomingPath = parsedUrl.pathname;
// Determine the expected prefix (e.g., "/" or "/api/")
const ep = expectedPath.endsWith('/') ? expectedPath : expectedPath + '/';
let action = '';
if (incomingPath === expectedPath || incomingPath === expectedPath + '/') {
action = ''; // No action in URL (legacy body mode)
} else if (incomingPath.startsWith(ep)) {
action = incomingPath.substring(ep.length); // Extract action from URL
} else {
writeJson(res, 404, { status: 'failed', retcode: 1404, data: null, wording: 'not found' });
return;
}
if (!isAuthorized(req, accessToken)) {
writeJson(res, 401, { status: 'failed', retcode: 1401, data: null, wording: 'unauthorized' });
return;
}
if (req.method === 'GET' && !action) {
writeJson(res, 200, { status: 'ok', retcode: 0, data: { online: true } });
return;
}
try {
let params: Record<string, unknown> = {};
let echo: unknown;
if (req.method === 'GET') {
parsedUrl.searchParams.forEach((value, key) => {
try {
params[key] = JSON.parse(value);
} catch {
params[key] = value;
}
});
} 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)) {
// Legacy format: { action: "...", params: {...} } vs standard raw params
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 {
writeJson(res, 400, { status: 'failed', retcode: 1400, data: null, wording: 'bad request: invalid json' });
return;
}
}
} else {
writeJson(res, 405, { status: 'failed', retcode: 1400, data: null, wording: 'method not allowed' });
return;
}
if (!action) {
writeJson(res, 400, { status: 'failed', retcode: 1400, data: null, wording: 'bad request: missing action' });
return;
}
// Handle the API call
const response = await this.context.api.handle(action, params as import('./types').JsonObject);
if (echo !== undefined) {
response.echo = echo as import('./types').JsonValue;
}
writeJson(res, 200, response);
} catch (error) {
const wording = error instanceof Error ? error.message : 'internal error';
writeJson(res, 500, { status: 'failed', retcode: 1200, data: null, wording });
}
}
}
function parseRequestPath(urlValue: string): string {
try {
return new URL(urlValue, 'http://127.0.0.1').pathname;
} catch {
return '/';
}
}
function normalizePath(pathValue: string): string {
const path = pathValue.trim() || '/';
if (path === '/') return '/';
return path.endsWith('/') ? path.slice(0, -1) : path;
}
function httpServerKey(endpoint: HttpServerEndpoint): string {
return `${endpoint.host}:${endpoint.port}${normalizePath(endpoint.path ?? '/')}#${endpoint.accessToken ?? ''}`;
}
function isAuthorized(request: IncomingMessage, token: string): boolean {
if (!token) return true;
// 1. Header auth
const rawAuth = request.headers.authorization;
const auth = Array.isArray(rawAuth) ? rawAuth[0] : rawAuth ?? '';
if (auth === `Bearer ${token}`) return true;
// 2. Query string auth
try {
const url = new URL(request.url ?? '/', 'http://127.0.0.1');
if (url.searchParams.get('access_token') === token) {
return true;
}
} catch {}
return false;
}
function readRequestBody(req: IncomingMessage, maxBytes = 2 * 1024 * 1024): Promise<string> {
return new Promise((resolve, reject) => {
const chunks: Buffer[] = [];
let total = 0;
req.on('data', (chunk: Buffer) => {
total += chunk.length;
if (total > maxBytes) {
reject(new Error('request body too large'));
req.destroy();
return;
}
chunks.push(chunk);
});
req.on('end', () => {
resolve(Buffer.concat(chunks).toString('utf8'));
});
req.on('error', reject);
});
}
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));
}
@@ -0,0 +1,614 @@
import type { Bridge } from '../bridge/bridge';
import type { ForwardNodePayload } from '../bridge/events';
import type { QQInfo } from '../bridge/qq-info';
import type { ApiActionContext, MessageSendResult } from './api-handler';
import { elementsToOneBotSegments } from './event-converter';
import { MessageStore } from './message-store';
import { parseMessage } from './message-parser';
import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT, hashMessageIdInt32 } from './message-id';
import type { JsonObject, JsonValue, MessageMeta } from './types';
export interface InstanceRef {
uin: string;
qqInfo: QQInfo;
bridge: Bridge;
messageStore: MessageStore;
musicSignUrl?: string;
cacheMessageMeta(messageId: number, meta: MessageMeta): void;
}
export function buildApiContext(ref: InstanceRef): ApiActionContext {
const { bridge, qqInfo, messageStore } = ref;
return {
getLoginInfo: () => getLoginInfo(ref),
isOnline: () => true,
getMessage: (messageId) => messageStore.findEvent(messageId),
getMessageMeta: (messageId) => messageStore.findMeta(messageId),
canSendImage: () => true,
canSendRecord: () => false,
sendPrivateMessage: (userId, message, autoEscape) => handleSendPrivate(ref, userId, message, autoEscape),
sendGroupMessage: (groupId, message, autoEscape) => handleSendGroup(ref, groupId, message, autoEscape),
deleteMessage: (messageId, meta) => handleDeleteMessage(bridge, meta),
// Info retrieval (async, triggers OIDB fetch)
getFriendList: () => handleGetFriendList(bridge, qqInfo),
getGroupList: (noCache) => handleGetGroupList(bridge, qqInfo, noCache),
getGroupInfo: (groupId, noCache) => handleGetGroupInfo(bridge, qqInfo, groupId, noCache),
getGroupMemberList: (groupId, noCache) => handleGetGroupMemberList(bridge, qqInfo, groupId, noCache),
getGroupMemberInfo: (groupId, userId, noCache) => handleGetGroupMemberInfo(bridge, qqInfo, groupId, userId, noCache),
getStrangerInfo: (userId) => handleGetStrangerInfo(bridge, qqInfo, userId),
// Group admin
setGroupKick: (groupId, userId, reject) => bridge.kickGroupMember(groupId, userId, reject),
setGroupBan: (groupId, userId, duration) => bridge.muteGroupMember(groupId, userId, duration),
setGroupWholeBan: (groupId, enable) => bridge.muteGroupAll(groupId, enable),
setGroupAdmin: (groupId, userId, enable) => bridge.setGroupAdmin(groupId, userId, enable),
setGroupCard: (groupId, userId, card) => bridge.setGroupCard(groupId, userId, card),
setGroupName: (groupId, name) => bridge.setGroupName(groupId, name),
setGroupLeave: (groupId) => bridge.leaveGroup(groupId),
setGroupSpecialTitle: (groupId, userId, title) => bridge.setGroupSpecialTitle(groupId, userId, title),
// Group file
uploadGroupFile: async (groupId, file, name, folderId, uploadFile) => {
const result = await bridge.uploadGroupFile(groupId, file, name ?? '', folderId ?? '/', uploadFile ?? true);
return result.fileId;
},
uploadPrivateFile: async (userId, file, name, uploadFile) => {
const result = await bridge.uploadPrivateFile(userId, file, name ?? '', uploadFile ?? true);
return result.fileId;
},
getGroupFileUrl: (groupId, fileId, busId) => bridge.fetchGroupFileUrl(groupId, fileId, busId ?? 102),
getGroupFiles: (groupId, folderId) => handleGetGroupFiles(bridge, groupId, folderId),
deleteGroupFile: (groupId, fileId) => bridge.deleteGroupFile(groupId, fileId),
moveGroupFile: (groupId, fileId, parentDirectory, targetDirectory) => bridge.moveGroupFile(groupId, fileId, parentDirectory, targetDirectory),
createGroupFileFolder: (groupId, name, parentId) => bridge.createGroupFileFolder(groupId, name, parentId ?? '/'),
deleteGroupFileFolder: (groupId, folderId) => bridge.deleteGroupFileFolder(groupId, folderId),
renameGroupFileFolder: (groupId, folderId, newName) => bridge.renameGroupFileFolder(groupId, folderId, newName),
getPrivateFileUrl: (userId, fileId, fileHash) => bridge.fetchPrivateFileUrl(userId, fileId, fileHash),
// Requests
handleFriendRequest: (flag, approve) => bridge.setFriendAddRequest(flag, approve),
handleGroupRequest: (flag, _subType, approve, reason) => handleGroupAddRequest(bridge, flag, approve, reason),
// Extended
sendLike: (userId, times) => bridge.sendLike(userId, times),
sendFriendPoke: (userId, targetId) => bridge.sendPoke(false, userId, targetId),
sendGroupPoke: (groupId, userId) => bridge.sendPoke(true, groupId, userId),
setEssenceMsg: (messageId) => handleSetEssence(bridge, messageStore, messageId, true),
deleteEssenceMsg: (messageId) => handleSetEssence(bridge, messageStore, messageId, false),
// New extended
setGroupReaction: (groupId, sequence, code, isSet) => bridge.setGroupReaction(groupId, sequence, code, isSet),
handleDeleteFriend: (userId, block) => bridge.deleteFriend(userId, !!block),
getGroupMsgHistory: (groupId, messageId, count) => handleGetGroupMsgHistory(messageStore, groupId, messageId, count),
getFriendMsgHistory: (userId, messageId, count) => handleGetFriendMsgHistory(messageStore, userId, messageId, count),
handleGetGroupSystemMsg: async () => {
try {
const reqs = await bridge.fetchGroupRequests();
return reqs.map(r => ({
group_id: r.groupId, group_name: r.groupName,
request_id: r.sequence, requester_uin: r.targetUin,
requester_nick: r.targetName, message: r.comment,
flag: `${r.eventType}:${r.groupId}:${r.targetUid}`,
} as JsonObject));
} catch { return []; }
},
getDownloadRKeys: async () => {
try {
const rkeys = await bridge.fetchDownloadRKeys();
return rkeys.map(r => ({
rkey: r.rkey, type: r.type, ttl: r.ttlSeconds, create_time: r.createTime,
} as JsonObject));
} catch { return []; }
},
sendGroupForwardMsg: async (groupId, messages) => {
return handleSendGroupForward(ref, groupId, messages);
},
sendPrivateForwardMsg: async (userId, messages) => {
return handleSendPrivateForward(ref, userId, messages);
},
sendForwardMsg: async (messages) => {
return handleUploadForward(ref, messages);
},
getForwardMsg: async (resId) => {
return handleGetForward(ref, resId);
},
// Extended NapCat-compatible
setFriendRemark: (userId, remark) => bridge.setFriendRemark(userId, remark),
getGroupFileCount: (groupId) => bridge.fetchGroupFileCount(groupId),
setMsgEmojiLike: async (messageId, emojiId, set) => {
const meta = messageStore.findMeta(messageId);
if (!meta || !meta.isGroup) throw new Error('message not found or not a group message');
await bridge.setGroupReaction(meta.targetId, meta.sequence, emojiId, set);
},
};
}
// --- Login info ---
function getLoginInfo(ref: InstanceRef): { userId: number; nickname: string } {
const userId = parseInt(ref.uin, 10) || 0;
const nickname = ref.qqInfo.nickname || ref.uin;
return { userId, nickname };
}
async function refreshAllGroupMembersCache(bridge: Bridge, qqInfo: QQInfo): Promise<void> {
let groups = qqInfo.groups;
try {
groups = await bridge.fetchGroupList();
} catch { /* use cached groups */ }
for (const g of groups) {
try {
await bridge.fetchGroupMemberList(g.groupId);
} catch { /* best effort */ }
}
}
function normalizeHistoryCount(count?: number): number {
if (!Number.isFinite(count)) return 20;
const n = Math.trunc(count as number);
if (n <= 0) return 20;
if (n > 200) return 200;
return n;
}
function sanitizeMessageEventForApi(event: JsonObject): JsonObject {
const result: JsonObject = { ...event };
delete result.post_type;
delete result.self_id;
result.real_id = (result.message_id ?? 0) as JsonValue;
return result;
}
// --- Info retrieval ---
async function handleGetFriendList(bridge: Bridge, qqInfo: QQInfo): Promise<JsonObject[]> {
try {
const friends = await bridge.fetchFriendList();
return friends.map(f => ({
user_id: f.uin as any,
nickname: f.nickname as any,
remark: f.remark as any,
}));
} catch {
return qqInfo.friends.map(f => ({
user_id: f.uin as any,
nickname: f.nickname as any,
remark: f.remark as any,
}));
}
}
async function handleGetGroupList(bridge: Bridge, qqInfo: QQInfo, noCache?: boolean): Promise<JsonObject[]> {
try {
if (noCache) {
await refreshAllGroupMembersCache(bridge, qqInfo);
} else if (qqInfo.groups.length === 0) {
await bridge.fetchGroupList();
}
} catch { /* use cached */ }
return qqInfo.groups.map(g => ({
group_id: g.groupId as any,
group_name: g.groupName as any,
member_count: g.memberCount as any,
max_member_count: g.memberMax as any,
}));
}
async function handleGetGroupInfo(bridge: Bridge, qqInfo: QQInfo, groupId: number, noCache?: boolean): Promise<JsonObject | null> {
if (noCache) {
try { await refreshAllGroupMembersCache(bridge, qqInfo); } catch { /* use cached */ }
} else if (!qqInfo.findGroup(groupId)) {
try { await bridge.fetchGroupList(); } catch { /* use cached */ }
}
const g = qqInfo.findGroup(groupId);
if (!g) return null;
return {
group_id: g.groupId as any,
group_name: g.groupName as any,
member_count: g.memberCount as any,
max_member_count: g.memberMax as any,
};
}
async function handleGetGroupMemberList(bridge: Bridge, qqInfo: QQInfo, groupId: number, noCache?: boolean): Promise<JsonObject[]> {
if (noCache) {
try { await refreshAllGroupMembersCache(bridge, qqInfo); } catch { /* use cached */ }
const g = qqInfo.findGroup(groupId);
if (!g) return [];
const result: JsonObject[] = [];
for (const [, m] of g.members) {
result.push({
group_id: groupId as any, user_id: m.uin as any,
nickname: m.nickname as any, card: m.card as any,
sex: 'unknown' as any, age: 0 as any,
join_time: m.joinTime as any, last_sent_time: m.lastSentTime as any,
level: String(m.level) as any, role: m.role as any, title: m.title as any,
});
}
return result;
}
try {
const members = await bridge.fetchGroupMemberList(groupId);
return members.map(m => ({
group_id: groupId as any,
user_id: m.uin as any,
nickname: m.nickname as any,
card: m.card as any,
sex: 'unknown' as any,
age: 0 as any,
join_time: m.joinTime as any,
last_sent_time: m.lastSentTime as any,
level: String(m.level) as any,
role: m.role as any,
title: m.title as any,
}));
} catch {
const g = qqInfo.findGroup(groupId);
if (!g) return [];
const result: JsonObject[] = [];
for (const [, m] of g.members) {
result.push({
group_id: groupId as any, user_id: m.uin as any,
nickname: m.nickname as any, card: m.card as any,
sex: 'unknown' as any, age: 0 as any,
join_time: m.joinTime as any, last_sent_time: m.lastSentTime as any,
level: String(m.level) as any, role: m.role as any, title: m.title as any,
});
}
return result;
}
}
async function handleGetGroupMemberInfo(bridge: Bridge, qqInfo: QQInfo, groupId: number, userId: number, noCache?: boolean): Promise<JsonObject | null> {
if (noCache) {
try { await refreshAllGroupMembersCache(bridge, qqInfo); } catch { /* use cached */ }
} else if (!qqInfo.findGroupMember(groupId, userId)) {
try { await bridge.fetchGroupMemberList(groupId); } catch { /* use cached */ }
}
const m = qqInfo.findGroupMember(groupId, userId);
if (!m) return null;
return {
group_id: groupId as any, user_id: m.uin as any,
nickname: m.nickname as any, card: m.card as any,
sex: 'unknown' as any, age: 0 as any,
join_time: m.joinTime as any, last_sent_time: m.lastSentTime as any,
level: String(m.level) as any, role: m.role as any, title: m.title as any,
};
}
async function handleGetGroupFiles(bridge: Bridge, groupId: number, folderId?: string): Promise<JsonObject> {
const result = await bridge.fetchGroupFiles(groupId, folderId ?? '/');
return {
files: result.files.map((file) => ({
group_id: groupId as any,
file_id: file.fileId as any,
file_name: file.fileName as any,
busid: file.busId as any,
file_size: file.fileSize as any,
upload_time: file.uploadTime as any,
dead_time: file.deadTime as any,
modify_time: file.modifyTime as any,
download_times: file.downloadTimes as any,
uploader: file.uploader as any,
uploader_name: file.uploaderName as any,
} as JsonObject)) as any,
folders: result.folders.map((folder) => ({
group_id: groupId as any,
folder_id: folder.folderId as any,
folder_name: folder.folderName as any,
create_time: folder.createTime as any,
creator: folder.creator as any,
create_name: folder.creatorName as any,
total_file_count: folder.totalFileCount as any,
} as JsonObject)) as any,
};
}
async function handleGetStrangerInfo(bridge: Bridge, qqInfo: QQInfo, userId: number): Promise<JsonObject | null> {
try {
const p = await bridge.fetchUserProfile(userId);
return {
user_id: p.uin as any,
nickname: p.nickname as any,
sex: p.sex as any,
age: p.age as any,
};
} catch {
const p = qqInfo.findUserProfile(userId);
if (!p) return null;
return { user_id: p.uin as any, nickname: p.nickname as any, sex: p.sex as any, age: p.age as any };
}
}
// --- Message history ---
async function handleGetGroupMsgHistory(
messageStore: MessageStore,
groupId: number,
messageId?: number,
count?: number,
): Promise<JsonObject[]> {
if (!Number.isInteger(groupId) || groupId <= 0) return [];
const limit = normalizeHistoryCount(count);
let anchorSequence: number | undefined;
if (Number.isInteger(messageId) && messageId !== 0) {
const meta = messageStore.findMeta(messageId as number);
if (!meta || !meta.isGroup || meta.targetId !== groupId || meta.sequence <= 0) return [];
anchorSequence = meta.sequence;
}
const events = messageStore.listSessionEvents(true, groupId, limit, anchorSequence);
return events
.filter((event) => {
if (event.message_type !== 'group') return false;
const gid = Number(event.group_id ?? 0);
return Number.isFinite(gid) && Math.trunc(gid) === groupId;
})
.map(sanitizeMessageEventForApi);
}
async function handleGetFriendMsgHistory(
messageStore: MessageStore,
userId: number,
messageId?: number,
count?: number,
): Promise<JsonObject[]> {
if (!Number.isInteger(userId) || userId <= 0) return [];
const limit = normalizeHistoryCount(count);
let anchorSequence: number | undefined;
if (Number.isInteger(messageId) && messageId !== 0) {
const meta = messageStore.findMeta(messageId as number);
if (!meta || meta.isGroup || meta.targetId !== userId || meta.sequence <= 0) return [];
anchorSequence = meta.sequence;
}
const events = messageStore.listSessionEvents(false, userId, limit, anchorSequence);
return events
.filter((event) => {
if (event.message_type !== 'private') return false;
const uid = Number(event.user_id ?? 0);
return Number.isFinite(uid) && Math.trunc(uid) === userId;
})
.map(sanitizeMessageEventForApi);
}
// --- Delete message ---
async function handleDeleteMessage(bridge: Bridge, meta: MessageMeta): Promise<void> {
if (meta.isGroup) {
await bridge.recallGroupMessage(meta.targetId, meta.sequence);
} else {
await bridge.recallPrivateMessage(
meta.targetId, meta.clientSequence, meta.sequence, meta.random, meta.timestamp);
}
}
// --- Group request ---
async function handleGroupAddRequest(bridge: Bridge, flag: string, approve: boolean, reason: string): Promise<void> {
// 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 groupId = parseInt(parts[1], 10);
if (!groupId) throw new Error('invalid group_id in flag');
// We need sequence and eventType -- fetch from group requests
const requests = await bridge.fetchGroupRequests();
const matching = requests.find(r => r.groupId === groupId);
if (matching) {
await bridge.setGroupAddRequest(groupId, matching.sequence, matching.eventType, approve, reason, matching.filtered);
} else {
throw new Error('matching group request not found');
}
}
// --- Essence ---
async function handleSetEssence(bridge: Bridge, messageStore: MessageStore, messageId: number, enable: boolean): Promise<void> {
const meta = messageStore.findMeta(messageId);
if (!meta || !meta.isGroup) throw new Error('message not found or not a group message');
await bridge.setGroupEssence(meta.targetId, meta.sequence, meta.random, enable);
}
// --- Send message ---
async function handleSendPrivate(
ref: InstanceRef,
userId: number,
message: JsonValue,
autoEscape: boolean,
): Promise<MessageSendResult> {
const elements = await parseMessage(message, autoEscape, {
resolveReplySequence: (replyMessageId) =>
ref.messageStore.resolveReplySequence(false, userId, replyMessageId),
musicSignUrl: ref.musicSignUrl,
});
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);
// Cache the sent message meta
ref.cacheMessageMeta(messageId, {
isGroup: false,
targetId: userId,
sequence: receipt.sequence,
eventName: PRIVATE_MESSAGE_EVENT,
clientSequence: receipt.clientSequence,
random: receipt.random,
timestamp: receipt.timestamp,
});
return { messageId };
}
async function handleSendGroup(
ref: InstanceRef,
groupId: number,
message: JsonValue,
autoEscape: boolean,
): Promise<MessageSendResult> {
const elements = await parseMessage(message, autoEscape, {
resolveReplySequence: (replyMessageId) =>
ref.messageStore.resolveReplySequence(true, groupId, replyMessageId),
musicSignUrl: ref.musicSignUrl,
});
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);
// Cache the sent message meta
ref.cacheMessageMeta(messageId, {
isGroup: true,
targetId: groupId,
sequence: receipt.sequence,
eventName: GROUP_MESSAGE_EVENT,
clientSequence: receipt.clientSequence,
random: receipt.random,
timestamp: receipt.timestamp,
});
return { messageId };
}
async function handleSendGroupForward(
ref: InstanceRef,
groupId: number,
messages: JsonValue,
): Promise<{ messageId: number; forwardId: string }> {
const nodes = await parseForwardNodes(ref, messages);
const forwardId = await ref.bridge.uploadForwardNodes(nodes, groupId);
const receipt = await ref.bridge.sendGroupMessage(groupId, [{ type: 'forward', resId: forwardId }]);
const messageId = hashMessageIdInt32(receipt.sequence, groupId, GROUP_MESSAGE_EVENT);
ref.cacheMessageMeta(messageId, {
isGroup: true,
targetId: groupId,
sequence: receipt.sequence,
eventName: GROUP_MESSAGE_EVENT,
clientSequence: receipt.clientSequence,
random: receipt.random,
timestamp: receipt.timestamp,
});
return { messageId, forwardId };
}
async function handleSendPrivateForward(
ref: InstanceRef,
userId: number,
messages: JsonValue,
): Promise<{ messageId: number; forwardId: string }> {
const nodes = await parseForwardNodes(ref, messages);
const forwardId = await ref.bridge.uploadForwardNodes(nodes);
const receipt = await ref.bridge.sendPrivateMessage(userId, [{ type: 'forward', resId: forwardId }]);
const messageId = hashMessageIdInt32(receipt.sequence, userId, PRIVATE_MESSAGE_EVENT);
ref.cacheMessageMeta(messageId, {
isGroup: false,
targetId: userId,
sequence: receipt.sequence,
eventName: PRIVATE_MESSAGE_EVENT,
clientSequence: receipt.clientSequence,
random: receipt.random,
timestamp: receipt.timestamp,
});
return { messageId, forwardId };
}
async function handleUploadForward(
ref: InstanceRef,
messages: JsonValue,
): Promise<{ forwardId: string }> {
const nodes = await parseForwardNodes(ref, messages);
const forwardId = await ref.bridge.uploadForwardNodes(nodes);
return { forwardId };
}
async function handleGetForward(
ref: InstanceRef,
resId: string,
): Promise<JsonObject[]> {
const nodes = await ref.bridge.fetchForwardNodes(resId);
const results: JsonObject[] = [];
for (const node of nodes) {
results.push({
type: 'node' as any,
data: {
user_id: node.userUin as any,
nickname: node.nickname as any,
uin: String(node.userUin) as any,
name: node.nickname as any,
content: await elementsToOneBotSegments(node.elements, false, node.userUin) as any,
} as any,
} as JsonObject);
}
return results;
}
async function parseForwardNodes(ref: InstanceRef, messages: JsonValue): Promise<ForwardNodePayload[]> {
if (!Array.isArray(messages)) {
throw new Error('forward messages must be an array');
}
const nodes: ForwardNodePayload[] = [];
for (const item of messages) {
const segment = asJsonObject(item);
if (!segment) continue;
let nodeData: JsonObject | null = null;
if (String(segment.type ?? '') === 'node') {
nodeData = asJsonObject(segment.data);
} else if (segment.content !== undefined || segment.message !== undefined) {
nodeData = segment;
}
if (!nodeData) continue;
const messageId = toPositiveInt(nodeData.id ?? nodeData.message_id);
if (messageId > 0) {
const event = ref.messageStore.findEvent(messageId);
if (!event) throw new Error(`forward node message_id not found: ${messageId}`);
const eventSender = asJsonObject(event.sender) ?? {};
const nickname = String(eventSender.card ?? eventSender.nickname ?? nodeData.nickname ?? nodeData.name ?? '');
const userUin = toPositiveInt(event.user_id);
const content = (event.message ?? event.raw_message ?? '') as JsonValue;
const elements = await parseMessage(content, false);
if (userUin > 0 && elements.length > 0) {
nodes.push({ userUin, nickname: nickname || String(userUin), elements });
}
continue;
}
const userUin = toPositiveInt(nodeData.user_id ?? nodeData.uin);
if (userUin <= 0) throw new Error('forward node user_id/uin is required');
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 });
}
if (nodes.length === 0) {
throw new Error('forward node list is empty');
}
return nodes;
}
function asJsonObject(value: JsonValue | undefined): JsonObject | null {
if (typeof value !== 'object' || value === null || Array.isArray(value)) return null;
return value as JsonObject;
}
function toPositiveInt(value: JsonValue | undefined): number {
if (typeof value === 'number' && Number.isFinite(value)) return Math.max(0, Math.trunc(value));
if (typeof value === 'string' && value.trim()) {
const parsed = Number(value);
if (Number.isFinite(parsed)) return Math.max(0, Math.trunc(parsed));
}
return 0;
}
+143
View File
@@ -0,0 +1,143 @@
import type { MessageElement } from '../bridge/events';
import type { Bridge, DownloadRKeyInfo } from '../bridge/bridge';
import { createLogger } from '../utils/logger';
const log = createLogger('OneBot');
interface CachedRKey {
value: string;
type: number;
createTime: number;
ttlSeconds: number;
expiresAt: number;
}
const RKEY_REFRESH_SKEW = 60;
const RKEY_REFRESH_COOLDOWN = 30;
const PRIVATE_IMAGE_RKEY_TYPE = 10;
const GROUP_IMAGE_RKEY_TYPE = 20;
const PRIVATE_VIDEO_RKEY_TYPE = 12;
const GROUP_VIDEO_RKEY_TYPE = 22;
const PRIVATE_PTT_RKEY_TYPE = 14;
const GROUP_PTT_RKEY_TYPE = 24;
const FALLBACK_IMAGE_RKEY_TYPE = 2;
export class RKeyCache {
private cache = new Map<number, CachedRKey>();
private lastRefreshAttempt = 0;
warmUp(bridge: Bridge, uin: string): void {
bridge.fetchDownloadRKeys().then(
(rkeys) => {
this.updateCache(rkeys);
log.info('rkeys loaded: UIN=%s count=%d', uin, rkeys.length);
},
(err) => {
log.warn('failed to load rkeys for UIN %s: %s', uin, err instanceof Error ? err.message : String(err));
},
);
}
resolveImageUrl(bridge: Bridge, element: MessageElement, isGroup: boolean): string {
const url = element.imageUrl ?? '';
if (!urlNeedsRKey(url)) return url;
const rkey = this.findRKey(bridge, isGroup);
if (!rkey) return url;
const cleanRKey = stripRKeyPrefix(rkey);
const separator = url.includes('?') ? '&rkey=' : '?rkey=';
return url + separator + encodeURIComponent(cleanRKey);
}
/**
* Resolve a URL for video/record/file media elements.
* Appends the correct RKey type based on media kind and group/private context.
*/
resolveMediaUrl(bridge: Bridge, element: MessageElement, isGroup: boolean): string {
const url = element.url ?? '';
if (!url || !urlNeedsRKey(url)) return url;
const mediaType = element.type;
let primaryType: number;
if (mediaType === 'video') {
primaryType = isGroup ? GROUP_VIDEO_RKEY_TYPE : PRIVATE_VIDEO_RKEY_TYPE;
} else if (mediaType === 'record') {
primaryType = isGroup ? GROUP_PTT_RKEY_TYPE : PRIVATE_PTT_RKEY_TYPE;
} else {
// For file types, try image rkeys as a fallback (file URLs typically use image rkeys)
primaryType = isGroup ? GROUP_IMAGE_RKEY_TYPE : PRIVATE_IMAGE_RKEY_TYPE;
}
const rkey = this.findRKeyForType(bridge, primaryType);
if (!rkey) return url;
const cleanRKey = stripRKeyPrefix(rkey);
const separator = url.includes('?') ? '&rkey=' : '?rkey=';
return url + separator + encodeURIComponent(cleanRKey);
}
private updateCache(rkeys: DownloadRKeyInfo[]): void {
const now = Math.floor(Date.now() / 1000);
for (const rk of rkeys) {
if (!rk.rkey || !rk.type) continue;
const baseTime = rk.createTime || now;
const ttl = rk.ttlSeconds || 3600;
this.cache.set(rk.type, {
value: rk.rkey,
type: rk.type,
createTime: rk.createTime,
ttlSeconds: rk.ttlSeconds,
expiresAt: baseTime + ttl,
});
}
}
private findRKey(bridge: Bridge, isGroup: boolean): string | null {
const primaryType = isGroup ? GROUP_IMAGE_RKEY_TYPE : PRIVATE_IMAGE_RKEY_TYPE;
return this.findRKeyForType(bridge, primaryType);
}
private findRKeyForType(bridge: Bridge, primaryType: number): string | null {
const now = Math.floor(Date.now() / 1000);
const tryFind = (type: number): string | null => {
const cached = this.cache.get(type);
if (!cached || !cached.value) return null;
if (cached.expiresAt !== 0 && now + RKEY_REFRESH_SKEW >= cached.expiresAt) return null;
return cached.value;
};
let result = tryFind(primaryType) ?? tryFind(FALLBACK_IMAGE_RKEY_TYPE);
if (result) return result;
// Refresh check cooldown
if (now - this.lastRefreshAttempt < RKEY_REFRESH_COOLDOWN) return null;
this.lastRefreshAttempt = now;
// Schedule async refresh
bridge.fetchDownloadRKeys().then(
(rkeys) => this.updateCache(rkeys),
() => { /* ignore */ },
);
// Try again (won't be ready yet for this call, but future calls will benefit)
result = tryFind(primaryType) ?? tryFind(FALLBACK_IMAGE_RKEY_TYPE);
return result;
}
}
function urlNeedsRKey(url: string): boolean {
if (!url || url.includes('rkey=')) return false;
if (url.includes('gchat.qpic.cn')) return false;
return url.includes('multimedia.nt.qq.com.cn') ||
url.includes('.nt.qq.com.cn') ||
url.includes('/download');
}
function stripRKeyPrefix(rkey: string): string {
for (const prefix of ['&rkey=', '?rkey=']) {
if (rkey.startsWith(prefix)) return rkey.slice(prefix.length);
}
return rkey;
}
+276
View File
@@ -0,0 +1,276 @@
import path from 'path';
import type { QQEventVariant } from '../bridge/events';
import type { Bridge } from '../bridge/bridge';
import type { QQInfo } from '../bridge/qq-info';
import { ApiHandler } from './api-handler';
import { EventConverter } from './event-converter';
import { MessageStore } from './message-store';
import { RKeyCache } from './instance-rkey';
import { buildApiContext } from './instance-context';
import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT, hashMessageIdInt32 } from './message-id';
import type { JsonObject, MessageMeta, OneBotConfig } from './types';
import { HttpTransport } from './http-transport';
import { HttpPostTransport } from './http-post-transport';
import { WsTransport } from './ws-transport';
export class OneBotInstance {
readonly uin: string;
readonly qqInfo: QQInfo;
private readonly bridge: Bridge;
private readonly apiHandler: ApiHandler;
private readonly eventConverter: EventConverter;
private readonly messageStore: MessageStore;
private readonly httpTransport: HttpTransport;
private readonly httpPostTransport: HttpPostTransport;
private readonly wsTransport: WsTransport;
private readonly rkeyCache: RKeyCache;
private readonly pids = new Set<number>();
private online = true;
private heartbeatTimer: NodeJS.Timeout | null = null;
private static readonly HEARTBEAT_INTERVAL = 30000;
constructor(uin: string, qqInfo: QQInfo, bridge: Bridge, config: OneBotConfig) {
this.uin = uin;
this.qqInfo = qqInfo;
this.bridge = bridge;
this.eventConverter = new EventConverter();
this.rkeyCache = new RKeyCache();
this.eventConverter.setImageUrlResolver((element, isGroup) =>
this.rkeyCache.resolveImageUrl(this.bridge, element, isGroup));
this.eventConverter.setMediaUrlResolver(async (element, isGroup, sessionId) => {
// Fetch URL from bridge if not already present
if (!element.url) {
try {
if (element.type === 'file' && element.fileId) {
element.url = isGroup
? await this.bridge.fetchGroupFileUrl(sessionId, element.fileId)
: element.fileHash
? await this.bridge.fetchPrivateFileUrl(sessionId, element.fileId, element.fileHash)
: '';
} else if ((element.type === 'record' || element.type === 'video') && element.mediaNode) {
if (isGroup) {
element.url = element.type === 'record'
? await this.bridge.fetchGroupPttUrlByNode(sessionId, element.mediaNode)
: await this.bridge.fetchGroupVideoUrlByNode(sessionId, element.mediaNode);
} else {
element.url = element.type === 'record'
? await this.bridge.fetchPrivatePttUrlByNode(element.mediaNode)
: await this.bridge.fetchPrivateVideoUrlByNode(element.mediaNode);
}
}
} catch { /* best-effort */ }
}
// Then apply RKey if needed
return this.rkeyCache.resolveMediaUrl(this.bridge, element, isGroup);
});
this.eventConverter.setMessageIdResolver((isGroup, sessionId, sequence, eventName) =>
hashMessageIdInt32(sequence, sessionId, eventName || (isGroup ? GROUP_MESSAGE_EVENT : PRIVATE_MESSAGE_EVENT)));
this.messageStore = new MessageStore(path.join('data', this.uin, 'messages.json'));
const context = buildApiContext({
uin: this.uin,
qqInfo: this.qqInfo,
bridge: this.bridge,
messageStore: this.messageStore,
musicSignUrl: config.musicSignUrl,
cacheMessageMeta: (messageId, meta) => this.cacheMessageMeta(messageId, meta),
});
this.apiHandler = new ApiHandler(context);
this.httpTransport = new HttpTransport(config, {
api: this.apiHandler,
});
this.httpPostTransport = new HttpPostTransport(config, {
uin: this.uin,
api: this.apiHandler,
});
this.wsTransport = new WsTransport(config, {
uin: this.uin,
api: this.apiHandler,
buildLifecycleEvent: (subType) => this.makeLifecycleEvent(subType),
buildHeartbeatEvent: () => this.makeHeartbeatEvent(),
});
this.httpTransport.start();
this.httpPostTransport.start();
this.wsTransport.start();
this.startHeartbeat();
this.rkeyCache.warmUp(this.bridge, this.uin);
}
reloadConfig(config: OneBotConfig): void {
this.httpTransport.reloadConfig(config);
this.httpPostTransport.reloadConfig(config);
this.wsTransport.reloadConfig(config);
}
dispose(): void {
this.online = false;
this.stopHeartbeat();
this.httpTransport.stop();
this.httpPostTransport.stop();
this.wsTransport.stop();
this.messageStore.close();
}
onBridgeEvent(event: QQEventVariant): void {
this.cacheMessageMetaFromBridgeEvent(event);
void this.dispatchBridgeEventAsync(event);
}
private async dispatchBridgeEventAsync(event: QQEventVariant): Promise<void> {
const converted = await this.eventConverter.convert(this.uin, event);
if (!converted) return;
this.dispatchEvent(converted);
}
addPid(pid: number): void {
this.pids.add(pid);
}
removePid(pid: number): void {
this.pids.delete(pid);
}
hasPid(pid: number): boolean {
return this.pids.has(pid);
}
getPids(): number[] {
return [...this.pids];
}
get empty(): boolean {
return this.pids.size === 0;
}
private dispatchEvent(event: JsonObject): void {
this.cacheMessageEvent(event);
this.wsTransport.publishEvent(event);
this.httpPostTransport.publishEvent(event);
}
private cacheMessageEvent(event: JsonObject): void {
if (event.post_type !== 'message') return;
const messageId = toInt(event.message_id);
if (messageId === 0) return;
const isGroup = event.message_type === 'group';
const sessionId = isGroup ? toInt(event.group_id) : toInt(event.user_id);
const sequence = toInt(event.message_seq);
const eventName = isGroup ? GROUP_MESSAGE_EVENT : PRIVATE_MESSAGE_EVENT;
if (sessionId === 0) return;
this.messageStore.storeEvent(messageId, isGroup, sessionId, sequence, eventName, event);
}
private cacheMessageMetaFromBridgeEvent(event: QQEventVariant): void {
if (event.kind === 'group_message') {
const messageId = hashMessageIdInt32(event.msgSeq, event.groupId, GROUP_MESSAGE_EVENT);
this.cacheMessageMeta(messageId, {
isGroup: true,
targetId: event.groupId,
sequence: event.msgSeq,
eventName: GROUP_MESSAGE_EVENT,
clientSequence: 0,
random: event.msgId,
timestamp: event.time,
});
return;
}
if (event.kind === 'friend_message') {
const messageId = hashMessageIdInt32(event.msgSeq, event.senderUin, PRIVATE_MESSAGE_EVENT);
this.cacheMessageMeta(messageId, {
isGroup: false,
targetId: event.senderUin,
sequence: event.msgSeq,
eventName: PRIVATE_MESSAGE_EVENT,
clientSequence: 0,
random: event.msgId,
timestamp: event.time,
});
return;
}
if (event.kind === 'temp_message') {
const messageId = hashMessageIdInt32(event.msgSeq, event.senderUin, PRIVATE_MESSAGE_EVENT);
this.cacheMessageMeta(messageId, {
isGroup: false,
targetId: event.senderUin,
sequence: event.msgSeq,
eventName: PRIVATE_MESSAGE_EVENT,
clientSequence: 0,
random: 0,
timestamp: event.time,
});
}
}
private cacheMessageMeta(messageId: number, meta: MessageMeta): void {
if (!Number.isInteger(messageId) || messageId === 0) return;
this.messageStore.storeMeta(messageId, meta);
}
private makeLifecycleEvent(subType: 'connect' | 'enable' | 'disable'): JsonObject {
const selfId = parseInt(this.uin, 10) || 0;
const time = Math.floor(Date.now() / 1000);
return {
time,
self_id: selfId,
post_type: 'meta_event',
meta_event_type: 'lifecycle',
sub_type: subType,
status: {
online: this.online,
good: this.online,
},
};
}
// --- Heartbeat ---
private startHeartbeat(): void {
this.heartbeatTimer = setInterval(() => {
this.dispatchEvent(this.makeHeartbeatEvent());
}, OneBotInstance.HEARTBEAT_INTERVAL);
this.heartbeatTimer.unref?.();
}
private makeHeartbeatEvent(): JsonObject {
const selfId = parseInt(this.uin, 10) || 0;
const time = Math.floor(Date.now() / 1000);
return {
time,
self_id: selfId,
post_type: 'meta_event',
meta_event_type: 'heartbeat',
status: { online: this.online, good: this.online },
interval: OneBotInstance.HEARTBEAT_INTERVAL,
};
}
private stopHeartbeat(): void {
if (this.heartbeatTimer) {
clearInterval(this.heartbeatTimer);
this.heartbeatTimer = null;
}
}
}
function toInt(value: unknown): number {
if (typeof value === 'number' && Number.isFinite(value)) return Math.trunc(value);
if (typeof value === 'string' && value.trim()) {
const parsed = Number(value);
if (Number.isFinite(parsed)) return Math.trunc(parsed);
}
return 0;
}
+149
View File
@@ -0,0 +1,149 @@
import type { QQEventVariant } from '../bridge/events';
import type { Bridge } from '../bridge/bridge';
import type { QQInfo } from '../bridge/qq-info';
import type { BridgeManager } from '../bridge/manager';
import { loadOneBotConfig } from './config';
import { OneBotInstance } from './instance';
import { createLogger } from '../utils/logger';
const log = createLogger('OneBot');
const VERBOSE_WARMUP = process.env.SNOWLUMA_VERBOSE_WARMUP === '1';
export class OneBotManager {
private readonly instances = new Map<string, OneBotInstance>();
bind(bridgeManager: BridgeManager): void {
bridgeManager.setSessionStartedCallback((uin, qqInfo, bridge) => {
this.onSessionStarted(uin, qqInfo, bridge);
});
bridgeManager.setSessionClosedCallback((uin) => {
this.onSessionClosed(uin);
});
bridgeManager.setEventCallback((uin, event) => {
this.onBridgeEvent(uin, event);
});
}
getInstance(uin: string): OneBotInstance | null {
return this.instances.get(uin) ?? null;
}
getInstances(): OneBotInstance[] {
return [...this.instances.values()];
}
reloadConfig(uin: string): boolean {
const instance = this.instances.get(uin);
if (!instance) return false;
const config = loadOneBotConfig(uin);
instance.reloadConfig(config);
log.info('configuration reloaded: UIN=%s', uin);
return true;
}
dispose(): void {
for (const instance of this.instances.values()) {
instance.dispose();
}
this.instances.clear();
}
private onSessionStarted(uin: string, qqInfo: QQInfo, bridge: Bridge): void {
if (this.instances.has(uin)) return;
const config = loadOneBotConfig(uin);
const instance = new OneBotInstance(uin, qqInfo, bridge, config);
const activePid = bridge.activePid;
if (activePid !== null) {
instance.addPid(activePid);
}
this.instances.set(uin, instance);
log.info('session started: UIN=%s', uin);
// Warm up bridge state asynchronously (mirrors C++ warm_up_bridge_state)
warmUpBridgeState(uin, qqInfo, bridge).catch((err) => {
log.warn('warmup error for UIN %s: %s', uin, err instanceof Error ? (err.stack ?? err.message) : String(err));
});
}
private onSessionClosed(uin: string): void {
const instance = this.instances.get(uin);
if (!instance) return;
instance.dispose();
this.instances.delete(uin);
log.info('session closed: UIN=%s', uin);
}
private onBridgeEvent(uin: string, event: QQEventVariant): void {
const instance = this.instances.get(uin);
if (!instance) return;
instance.onBridgeEvent(event);
}
}
async function warmUpBridgeState(uin: string, qqInfo: QQInfo, bridge: Bridge): Promise<void> {
// Step 1: Fetch friend list + derive self profile
try {
const friends = await bridge.fetchFriendList();
log.info('friends loaded: UIN=%s count=%d', uin, friends.length);
const selfUin = parseInt(uin, 10) || 0;
for (const f of friends) {
if (f.uin === selfUin) {
qqInfo.setSelfProfile({
uin: f.uin, uid: f.uid,
nickname: f.nickname || uin,
remark: '', qid: '', sex: 'unknown', age: 0, sign: '', avatar: '',
});
qqInfo.nickname = f.nickname || uin;
log.debug('self info: UIN=%s uid=%s nickname=%s', uin, f.uid, f.nickname ?? '');
break;
}
}
} catch (e) {
log.warn('failed to load friends for UIN %s: %s', uin, e instanceof Error ? e.message : String(e));
}
// Step 2: Fetch group list
let groups: { groupId: number }[] = [];
try {
groups = await bridge.fetchGroupList();
log.info('groups loaded: UIN=%s count=%d', uin, groups.length);
} catch (e) {
log.warn('failed to load groups for UIN %s: %s', uin, e instanceof Error ? e.message : String(e));
}
// Step 3: Fetch members for each group
let loadedGroupCount = 0;
let loadedMemberCount = 0;
let failedGroupCount = 0;
for (const g of groups) {
try {
const members = await bridge.fetchGroupMemberList(g.groupId);
loadedGroupCount += 1;
loadedMemberCount += members.length;
if (VERBOSE_WARMUP) {
log.debug('members loaded: group=%d count=%d', g.groupId, members.length);
}
} catch (e) {
failedGroupCount += 1;
log.warn('failed to load members for group %d: %s', g.groupId, e instanceof Error ? e.message : String(e));
}
}
log.info(
'member warmup completed: UIN=%s groups=%d/%d members=%d failed=%d',
uin,
loadedGroupCount,
groups.length,
loadedMemberCount,
failedGroupCount,
);
}
+15
View File
@@ -0,0 +1,15 @@
import { createHash } from 'node:crypto';
export const GROUP_MESSAGE_EVENT = 'group_message';
export const PRIVATE_MESSAGE_EVENT = 'private_message';
export function hashMessageIdInt32(sequence: number, sessionId: number, eventName: string): number {
const seq = Number.isFinite(sequence) ? Math.trunc(sequence) : 0;
const session = Number.isFinite(sessionId) ? Math.trunc(sessionId) : 0;
const key = `${seq}:${session}:${eventName}`;
const digest = createHash('sha1').update(key).digest();
let id = digest.readInt32BE(0);
if (id === 0) id = 1;
return id;
}
+326
View File
@@ -0,0 +1,326 @@
// OneBot11 message segment parser.
// Converts OneBot message format (string with CQ codes or JSON segment arrays)
// into internal MessageElement arrays for sending.
import type { MessageElement } from '../bridge/events';
import type { JsonValue, JsonObject } from './types';
export interface ParseMessageOptions {
resolveReplySequence?: (replyMessageId: number) => number | null;
musicSignUrl?: string;
}
// --- CQ Code parsing ---
const CQ_REGEX = /\[CQ:([a-z]+)(?:,([^\]]*))?\]/g;
function parseCQParams(raw: string): Record<string, string> {
const params: Record<string, string> = {};
if (!raw) return params;
for (const pair of raw.split(',')) {
const eq = pair.indexOf('=');
if (eq > 0) {
params[pair.substring(0, eq)] = pair.substring(eq + 1)
.replace(/&#91;/g, '[')
.replace(/&#93;/g, ']')
.replace(/&#44;/g, ',')
.replace(/&amp;/g, '&');
}
}
return params;
}
function cqUnescape(text: string): string {
return text
.replace(/&#91;/g, '[')
.replace(/&#93;/g, ']')
.replace(/&amp;/g, '&');
}
async function parseFromCQString(message: string, options?: ParseMessageOptions): Promise<MessageElement[]> {
const elements: MessageElement[] = [];
let lastIndex = 0;
for (const match of message.matchAll(CQ_REGEX)) {
// Text before this CQ code
if (match.index! > lastIndex) {
const text = cqUnescape(message.substring(lastIndex, match.index!));
if (text) elements.push({ type: 'text', text });
}
lastIndex = match.index! + match[0].length;
const cqType = match[1];
const params = parseCQParams(match[2] || '');
const elem = await segmentToElement(cqType, params, options);
if (elem) elements.push(elem);
}
// Trailing text
if (lastIndex < message.length) {
const text = cqUnescape(message.substring(lastIndex));
if (text) elements.push({ type: 'text', text });
}
return elements;
}
// --- JSON segment parsing ---
interface MessageSegment {
type: string;
data?: Record<string, unknown>;
}
function isSegmentArray(val: unknown): val is MessageSegment[] {
return Array.isArray(val) && val.every(
(item) => typeof item === 'object' && item !== null && 'type' in item
);
}
async function segmentToElement(type: string, data: Record<string, unknown>, options?: ParseMessageOptions): Promise<MessageElement | null> {
switch (type) {
case 'text': {
const text = String(data.text ?? '');
return text ? { type: 'text', text } : null;
}
case 'face': {
const id = parseInt(String(data.id ?? '0'), 10);
return { type: 'face', faceId: id };
}
case 'at': {
const qq = String(data.qq ?? '');
if (qq === 'all') {
return { type: 'at', targetUin: 0, uid: 'all', text: '@全体成员 ' };
}
const uin = parseInt(qq, 10);
return uin > 0 ? { type: 'at', targetUin: uin, text: `@${uin} ` } : null;
}
case 'reply': {
const id = parseInt(String(data.id ?? '0'), 10);
if (!Number.isInteger(id) || id === 0) return null;
if (options?.resolveReplySequence) {
const resolved = options.resolveReplySequence(id);
if (typeof resolved === 'number' && resolved > 0) {
return { type: 'reply', replySeq: resolved };
}
}
// Backward-compatible path: allow direct seq reply IDs.
return id > 0 ? { type: 'reply', replySeq: id } : null;
}
case 'image': {
return {
type: 'image',
url: String(data.file ?? data.url ?? ''),
flash: data.type === 'flash',
subType: parseInt(String(data.subType ?? '0'), 10),
summary: data.summary ? String(data.summary) : undefined,
};
}
case 'record': {
return {
type: 'record',
url: String(data.file ?? data.url ?? ''),
};
}
case 'video': {
return {
type: 'video',
url: String(data.file ?? data.url ?? ''),
};
}
case 'json': {
return {
type: 'json',
text: String(data.data ?? ''),
};
}
case 'xml': {
return {
type: 'xml',
text: String(data.data ?? ''),
subType: parseInt(String(data.id ?? '0'), 10),
};
}
case 'poke': {
return {
type: 'poke',
faceId: parseInt(String(data.type ?? data.id ?? '0'), 10),
};
}
case 'forward': {
return {
type: 'forward',
resId: String(data.id ?? ''),
};
}
case 'node': {
// Fake forward node segment — store the raw data for later processing
// The content field may be a segment array, a single segment, or a CQ string
const uin = String(data.user_id ?? data.uin ?? '0');
const name = String(data.nickname ?? data.name ?? '');
return {
type: 'node',
targetUin: parseInt(uin, 10) || 0,
text: name,
// Raw content is stored as JSON string in resId for later processing
resId: JSON.stringify(data.content ?? ''),
};
}
case 'markdown': {
return {
type: 'markdown',
text: String(data.content ?? ''),
};
}
case 'share': {
// Link share — map to json card message
const url = String(data.url ?? '');
const title = String(data.title ?? '');
const content = String(data.content ?? '');
const image = String(data.image ?? '');
const jsonData = JSON.stringify({
app: 'com.tencent.structmsg',
view: 'news',
prompt: title,
meta: { news: { title, desc: content, jumpUrl: url, preview: image } },
});
return { type: 'json', text: jsonData };
}
case 'music': {
// Music share — uses external signing service (NapCat-compatible)
const musicType = String(data.type ?? '');
const signUrl = options?.musicSignUrl || 'https://ss.xingzhige.com/music_card/card';
try {
let postData: Record<string, unknown>;
if (musicType === 'custom') {
postData = {
type: 'custom',
id: undefined,
url: String(data.url ?? ''),
audio: String(data.audio ?? ''),
title: String(data.title ?? ''),
image: String(data.image ?? ''),
singer: String(data.content ?? ''),
};
} else {
postData = { type: musicType, id: String(data.id ?? '') };
}
const resp = await fetch(signUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(postData),
});
if (!resp.ok) throw new Error(`music sign HTTP ${resp.status}`);
const musicJson = await resp.text();
return { type: 'json', text: musicJson };
} catch (e) {
console.warn(`[MsgParser] music sign failed: ${e}, falling back to local card`);
// Fallback: build a basic card locally
const title = String(data.title ?? 'Music');
const jsonData = JSON.stringify({
app: 'com.tencent.structmsg',
view: 'music',
prompt: `[音乐]${title}`,
meta: {
music: {
title,
desc: String(data.content ?? ''),
jumpUrl: String(data.url ?? ''),
musicUrl: String(data.audio ?? ''),
preview: String(data.image ?? ''),
},
},
});
return { type: 'json', text: jsonData };
}
}
case 'location': {
// Location — map to json card
const lat = String(data.lat ?? '');
const lon = String(data.lon ?? '');
const title = String(data.title ?? '位置');
const content = String(data.content ?? `${lat},${lon}`);
const jsonData = JSON.stringify({
app: 'com.tencent.map',
view: 'LocationShare',
prompt: `[位置]${title}`,
meta: { Location: { lat, lng: lon, title, address: content } },
});
return { type: 'json', text: jsonData };
}
case 'contact': {
// Contact card — map to json card
const contactType = String(data.type ?? 'qq');
const contactId = String(data.id ?? '');
const jsonData = JSON.stringify({
app: 'com.tencent.contact.lua',
view: 'contact',
prompt: `[推荐${contactType === 'group' ? '群' : '好友'}]`,
meta: { contact: { type: contactType, id: contactId } },
});
return { type: 'json', text: jsonData };
}
case 'rps': {
// Rock-paper-scissors — map to dice-like face
return { type: 'face', faceId: 359 };
}
case 'dice': {
// Dice — map to dice face
return { type: 'face', faceId: 358 };
}
case 'shake': {
// Window shake — map to poke
return { type: 'poke', faceId: 1 };
}
case 'anonymous': {
// Anonymous flag — ignored during send, the protocol handles anonymity
return null;
}
default:
console.warn(`[MsgParser] unsupported segment type: ${type}`);
return null;
}
}
// --- Public API ---
/**
* Parse an OneBot11 message value into internal MessageElement array.
* Supports:
* - string (plain text or CQ code string)
* - array of { type, data } segments (JSON segment format)
*
* If autoEscape is true, the string is treated as plain text (no CQ parsing).
*/
export async function parseMessage(message: JsonValue, autoEscape: boolean, options?: ParseMessageOptions): Promise<MessageElement[]> {
if (typeof message === 'string') {
if (autoEscape) {
return message ? [{ type: 'text', text: message }] : [];
}
return parseFromCQString(message, options);
}
if (isSegmentArray(message)) {
const elements: MessageElement[] = [];
for (const seg of message) {
const data = (seg.data ?? {}) as Record<string, unknown>;
const elem = await segmentToElement(seg.type, data, options);
if (elem) elements.push(elem);
}
return elements;
}
// Single segment object
if (typeof message === 'object' && message !== null && !Array.isArray(message)) {
const seg = message as unknown as MessageSegment;
if (seg.type) {
const data = (seg.data ?? {}) as Record<string, unknown>;
const elem = await segmentToElement(seg.type, data, options);
return elem ? [elem] : [];
}
}
return [];
}
+218
View File
@@ -0,0 +1,218 @@
// SQLite-backed message store using node:sqlite (DatabaseSync).
// Refactored to use a single unified `messages` table for all message types.
import fs from 'fs';
import path from 'path';
import { DatabaseSync } from 'node:sqlite';
import type { JsonObject, MessageMeta } from './types';
export class MessageStore {
private readonly db: DatabaseSync;
constructor(dbPath: string) {
const dir = path.dirname(dbPath);
fs.mkdirSync(dir, { recursive: true });
// Replace .json extension with .db if present
const finalPath = dbPath.replace(/\.json$/, '.db');
this.db = new DatabaseSync(finalPath);
this.db.exec('PRAGMA journal_mode = WAL');
this.db.exec('PRAGMA synchronous = NORMAL');
this.initSchema();
}
close(): void {
this.db.close();
}
storeEvent(
messageId: number,
isGroup: boolean,
sessionId: number,
sequence: number,
eventName: string,
event: JsonObject
): void {
if (!isValidMessageId(messageId)) return;
const json = JSON.stringify(event);
const timestamp = toInt(event.time);
this.db.prepare(
`INSERT INTO messages
(message_hash, is_group, session_id, sequence, event_name, client_sequence, random, timestamp, data)
VALUES (?, ?, ?, ?, ?, 0, 0, ?, ?)
ON CONFLICT(message_hash) DO UPDATE SET
is_group = excluded.is_group,
session_id = excluded.session_id,
sequence = excluded.sequence,
event_name = excluded.event_name,
timestamp = excluded.timestamp,
data = excluded.data`
).run(messageId, isGroup ? 1 : 0, sessionId, sequence, eventName, timestamp, json);
}
storeMeta(messageId: number, meta: MessageMeta): void {
if (!isValidMessageId(messageId)) return;
this.db.prepare(
`INSERT INTO messages
(message_hash, is_group, session_id, sequence, event_name, client_sequence, random, timestamp)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(message_hash) DO UPDATE SET
is_group = excluded.is_group,
session_id = excluded.session_id,
sequence = excluded.sequence,
event_name = excluded.event_name,
client_sequence = excluded.client_sequence,
random = excluded.random,
timestamp = excluded.timestamp`
).run(
messageId,
meta.isGroup ? 1 : 0,
meta.targetId,
meta.sequence,
meta.eventName,
meta.clientSequence,
meta.random,
meta.timestamp
);
}
findEvent(messageId: number): JsonObject | null {
if (!isValidMessageId(messageId)) return null;
const row = this.db.prepare(
'SELECT data FROM messages WHERE message_hash = ? AND data IS NOT NULL',
).get(messageId) as { data: string } | undefined;
if (!row?.data) return null;
try {
return JSON.parse(row.data) as JsonObject;
} catch {
return null;
}
}
findMeta(messageId: number): MessageMeta | null {
if (!isValidMessageId(messageId)) return null;
const row = this.db.prepare(
'SELECT is_group, session_id, sequence, event_name, client_sequence, random, timestamp FROM messages WHERE message_hash = ?',
).get(messageId) as {
is_group: number;
session_id: number;
sequence: number;
event_name: string;
client_sequence: number;
random: number;
timestamp: number;
} | undefined;
if (!row) return null;
return {
isGroup: row.is_group === 1,
targetId: row.session_id,
sequence: row.sequence,
eventName: row.event_name,
clientSequence: row.client_sequence,
random: row.random,
timestamp: row.timestamp,
};
}
resolveReplySequence(isGroup: boolean, sessionId: number, messageId: number): number | null {
if (!Number.isInteger(sessionId) || sessionId <= 0 || !isValidMessageId(messageId)) return null;
const row = this.db.prepare(
`SELECT sequence
FROM messages
WHERE is_group = ? AND session_id = ? AND message_hash = ?
LIMIT 1`
).get(isGroup ? 1 : 0, sessionId, messageId) as { sequence: number } | undefined;
if (!row || !Number.isInteger(row.sequence) || row.sequence <= 0) return null;
return row.sequence;
}
listSessionEvents(
isGroup: boolean,
sessionId: number,
count = 20,
anchorSequence?: number,
): JsonObject[] {
if (!Number.isInteger(sessionId) || sessionId <= 0) return [];
const limit = normalizePositiveInt(count, 20, 200);
const hasAnchor = Number.isInteger(anchorSequence) && (anchorSequence as number) > 0;
const anchor = hasAnchor ? (anchorSequence as number) : 0;
const rows = hasAnchor
? this.db.prepare(
`SELECT data
FROM messages
WHERE is_group = ? AND session_id = ? AND data IS NOT NULL AND sequence <= ?
ORDER BY sequence DESC
LIMIT ?`
).all(isGroup ? 1 : 0, sessionId, anchor, limit)
: this.db.prepare(
`SELECT data
FROM messages
WHERE is_group = ? AND session_id = ? AND data IS NOT NULL
ORDER BY sequence DESC
LIMIT ?`
).all(isGroup ? 1 : 0, sessionId, limit);
const result: JsonObject[] = [];
for (const row of rows as Array<{ data: string }>) {
if (!row?.data) continue;
try {
const parsed = JSON.parse(row.data) as JsonObject;
result.push(parsed);
} catch {
// Ignore malformed rows to avoid breaking history APIs.
}
}
// Keep chronological order (oldest -> newest) for API consumers.
result.reverse();
return result;
}
private initSchema(): void {
this.db.exec(`
CREATE TABLE IF NOT EXISTS messages (
message_hash INTEGER PRIMARY KEY,
is_group INTEGER NOT NULL,
session_id INTEGER NOT NULL,
sequence INTEGER NOT NULL,
event_name TEXT NOT NULL,
client_sequence INTEGER NOT NULL DEFAULT 0,
random INTEGER NOT NULL DEFAULT 0,
timestamp INTEGER NOT NULL DEFAULT 0,
data TEXT
)
`);
this.db.exec('CREATE INDEX IF NOT EXISTS idx_messages_session_seq ON messages(is_group, session_id, sequence)');
}
}
function isValidMessageId(messageId: number): boolean {
return Number.isInteger(messageId) && messageId !== 0;
}
function toInt(value: unknown): number {
if (typeof value === 'number' && Number.isFinite(value)) return Math.trunc(value);
if (typeof value === 'string' && value.trim()) {
const parsed = Number(value);
if (Number.isFinite(parsed)) return Math.trunc(parsed);
}
return 0;
}
function normalizePositiveInt(value: number, fallback: number, max: number): number {
if (!Number.isFinite(value)) return fallback;
const n = Math.trunc(value);
if (n <= 0) return fallback;
if (n > max) return max;
return n;
}
+96
View File
@@ -0,0 +1,96 @@
export type JsonPrimitive = string | number | boolean | null;
export type JsonValue = JsonPrimitive | JsonObject | JsonArray;
export interface JsonObject {
[key: string]: JsonValue;
}
export type JsonArray = JsonValue[];
export interface ApiResponse {
status: 'ok' | 'failed';
retcode: number;
data: JsonValue;
echo?: JsonValue;
wording?: string;
}
export interface OneBotRequest {
action: string;
params?: JsonObject;
echo?: JsonValue;
}
export interface WsServerEndpoint {
name?: string;
host: string;
port: number;
path?: string;
role?: WsRole;
accessToken?: string;
}
export interface HttpServerEndpoint {
name?: string;
host: string;
port: number;
path?: string;
accessToken?: string;
}
export interface WsClientEndpoint {
name?: string;
url: string;
role?: WsRole;
reconnectIntervalMs?: number;
accessToken?: string;
}
export interface HttpPostEndpoint {
name?: string;
url: string;
accessToken?: string;
timeoutMs?: number;
}
export interface OneBotConfig {
httpServers: HttpServerEndpoint[];
httpPostEndpoints: HttpPostEndpoint[];
wsServers: WsServerEndpoint[];
wsClients: WsClientEndpoint[];
musicSignUrl?: string;
}
export type WsRole = 'api' | 'event' | 'universal';
export interface MessageMeta {
isGroup: boolean;
targetId: number;
sequence: number;
eventName: string;
clientSequence: number;
random: number;
timestamp: number;
}
export const RETCODE = {
ACTION_FAILED: 100,
INTERNAL_ERROR: 1200,
BAD_REQUEST: 1400,
UNKNOWN_ACTION: 1404,
} as const;
export function okResponse(data: JsonValue = null): ApiResponse {
return {
status: 'ok',
retcode: 0,
data,
};
}
export function failedResponse(retcode: number, wording: string): ApiResponse {
return {
status: 'failed',
retcode,
data: null,
wording,
};
}
+335
View File
@@ -0,0 +1,335 @@
import WebSocket, { WebSocketServer } from 'ws';
import type { IncomingHttpHeaders, IncomingMessage } from 'http';
import type { ApiHandler } from './api-handler';
import type { JsonObject, OneBotConfig, WsClientEndpoint, WsRole, WsServerEndpoint } from './types';
import { createLogger } from '../utils/logger';
interface ForwardConnection {
socket: WebSocket;
role: WsRole;
}
interface ReverseConnection {
socket: WebSocket;
role: WsRole;
endpointUrl: string;
reconnectIntervalMs: number;
key: string;
}
export interface WsTransportContext {
uin: string;
api: ApiHandler;
buildLifecycleEvent: (subType: 'connect' | 'enable' | 'disable') => JsonObject;
buildHeartbeatEvent: () => JsonObject;
}
const log = createLogger('OneBot.WS');
export class WsTransport {
private readonly context: WsTransportContext;
private readonly servers = new Map<string, WebSocketServer>();
private readonly forwardConnections = new Map<WebSocket, ForwardConnection>();
private readonly reverseConnections = new Set<ReverseConnection>();
private readonly reconnectTimers = new Set<NodeJS.Timeout>();
private serverEndpoints: WsServerEndpoint[] = [];
private clientEndpoints: WsClientEndpoint[] = [];
private stopped = false;
constructor(config: OneBotConfig, context: WsTransportContext) {
this.serverEndpoints = [...config.wsServers];
this.clientEndpoints = [...config.wsClients];
this.context = context;
}
start(): void {
this.stopped = false;
this.startServers();
this.startReverseClients();
}
reloadConfig(config: OneBotConfig): void {
const nextServers = [...config.wsServers];
const nextClients = [...config.wsClients];
const nextServerKeys = new Set(nextServers.map(wsServerKey));
const nextClientKeys = new Set(nextClients.map(wsClientKey));
for (const [key, server] of this.servers) {
if (!nextServerKeys.has(key)) {
server.close();
this.servers.delete(key);
log.info('stopped forward server %s', key);
}
}
for (const endpoint of nextServers) {
if (!this.servers.has(wsServerKey(endpoint))) {
this.startServerEndpoint(endpoint);
}
}
for (const conn of [...this.reverseConnections]) {
if (!nextClientKeys.has(conn.key)) {
safeClose(conn.socket);
this.reverseConnections.delete(conn);
log.info('stopped reverse client %s', conn.endpointUrl);
}
}
for (const endpoint of nextClients) {
const key = wsClientKey(endpoint);
if (![...this.reverseConnections].some(conn => conn.key === key)) {
this.startClientEndpoint(endpoint);
}
}
this.serverEndpoints = nextServers;
this.clientEndpoints = nextClients;
}
stop(): void {
this.stopped = true;
this.publishEvent(this.context.buildLifecycleEvent('disable'));
for (const timer of this.reconnectTimers) {
clearTimeout(timer);
}
this.reconnectTimers.clear();
for (const [socket] of this.forwardConnections) {
safeClose(socket);
}
this.forwardConnections.clear();
for (const conn of this.reverseConnections) {
safeClose(conn.socket);
}
this.reverseConnections.clear();
for (const server of this.servers.values()) {
server.close();
}
this.servers.clear();
}
publishEvent(event: JsonObject): void {
const payload = JSON.stringify(event);
for (const { socket, role } of this.forwardConnections.values()) {
if (role === 'event' || role === 'universal') {
safeSend(socket, payload);
}
}
for (const { socket, role } of this.reverseConnections.values()) {
if (role === 'event' || role === 'universal') {
safeSend(socket, payload);
}
}
}
private startServers(): void {
for (const endpoint of this.serverEndpoints) {
this.startServerEndpoint(endpoint);
}
}
private startServerEndpoint(endpoint: WsServerEndpoint): void {
const wss = new WebSocketServer({
host: endpoint.host,
port: endpoint.port,
path: endpoint.path ?? '/',
});
wss.on('listening', () => {
const label = endpoint.name ? `[${endpoint.name}] ` : '';
log.success('%slistening %s:%d%s', label, endpoint.host, endpoint.port, endpoint.path ?? '/');
});
wss.on('connection', (socket, request) => {
if (!isAuthorized(request, endpoint.accessToken ?? '')) {
safeClose(socket, 1008, 'invalid access token');
return;
}
const role = endpoint.role ?? classifyForwardRole(request);
const conn: ForwardConnection = { socket, role };
this.forwardConnections.set(socket, conn);
socket.on('message', (raw) => {
void this.handleApiMessage(socket, role, raw);
});
socket.on('close', () => {
this.forwardConnections.delete(socket);
});
socket.on('error', (error) => {
log.warn('forward socket error: %s', error instanceof Error ? error.message : String(error));
});
this.sendBootstrapMetaEvents(socket, role);
});
wss.on('error', (error) => {
log.warn('server error: %s', error instanceof Error ? error.message : String(error));
});
this.servers.set(wsServerKey(endpoint), wss);
}
private startReverseClients(): void {
for (const endpoint of this.clientEndpoints) this.startClientEndpoint(endpoint);
}
private startClientEndpoint(endpoint: WsClientEndpoint): void {
const role = endpoint.role ?? 'universal';
const reconnectIntervalMs = Math.max(1000, endpoint.reconnectIntervalMs ?? 5000);
this.connectReverseClient(endpoint.url, role, reconnectIntervalMs, endpoint.accessToken ?? '', endpoint.name);
}
private connectReverseClient(endpointUrl: string, role: WsRole, reconnectIntervalMs: number, accessToken: string, name?: string): void {
if (this.stopped) return;
const headers: Record<string, string> = {
'User-Agent': 'OneBot',
'X-Self-ID': this.context.uin,
'X-Client-Role': role,
};
if (accessToken) {
headers.Authorization = `Bearer ${accessToken}`;
}
const socket = new WebSocket(endpointUrl, { headers });
const conn: ReverseConnection = { socket, role, endpointUrl, reconnectIntervalMs, key: wsClientPartsKey(endpointUrl, role, reconnectIntervalMs, accessToken) };
this.reverseConnections.add(conn);
socket.on('open', () => {
const label = name ? `[${name}] ` : '';
log.info('%sreverse connected %s', label, endpointUrl);
this.sendBootstrapMetaEvents(socket, role);
});
socket.on('message', (raw) => {
void this.handleApiMessage(socket, role, raw);
});
socket.on('close', () => {
this.reverseConnections.delete(conn);
if (this.stopped) return;
const timer = setTimeout(() => {
this.reconnectTimers.delete(timer);
this.connectReverseClient(endpointUrl, role, reconnectIntervalMs, accessToken, name);
}, reconnectIntervalMs);
timer.unref?.();
this.reconnectTimers.add(timer);
});
socket.on('error', (error) => {
log.warn('reverse error %s: %s', endpointUrl, error instanceof Error ? error.message : String(error));
});
}
private async handleApiMessage(socket: WebSocket, role: WsRole, raw: WebSocket.RawData): Promise<void> {
if (role !== 'api' && role !== 'universal') return;
const text = rawDataToString(raw);
if (!text) return;
const response = await this.context.api.processRequest(text);
safeSend(socket, response);
}
private sendBootstrapMetaEvents(socket: WebSocket, role: WsRole): void {
if (role !== 'event' && role !== 'universal') return;
const connectEvent = this.context.buildLifecycleEvent('connect');
const enableEvent = this.context.buildLifecycleEvent('enable');
const heartbeatEvent = this.context.buildHeartbeatEvent();
safeSend(socket, JSON.stringify(connectEvent));
safeSend(socket, JSON.stringify(enableEvent));
safeSend(socket, JSON.stringify(heartbeatEvent));
}
}
function classifyForwardRole(request: IncomingMessage): WsRole {
const path = parseRequestPath(request.url ?? '/');
if (path.endsWith('/api')) return 'api';
if (path.endsWith('/event')) return 'event';
return 'universal';
}
function parseRequestPath(urlValue: string): string {
try {
return new URL(urlValue, 'ws://127.0.0.1').pathname;
} catch {
return '/';
}
}
function normalizeWsPath(pathValue: string | undefined): string {
const path = (pathValue ?? '/').trim() || '/';
if (path === '/') return '/';
return path.endsWith('/') ? path.slice(0, -1) : path;
}
function wsServerKey(endpoint: WsServerEndpoint): string {
return `${endpoint.host}:${endpoint.port}${normalizeWsPath(endpoint.path)}#${endpoint.role ?? 'auto'}#${endpoint.accessToken ?? ''}`;
}
function wsClientPartsKey(endpointUrl: string, role: WsRole, reconnectIntervalMs: number, accessToken: string): string {
return `${endpointUrl}#${role}#${reconnectIntervalMs}#${accessToken}`;
}
function wsClientKey(endpoint: WsClientEndpoint): string {
const role = endpoint.role ?? 'universal';
const reconnectIntervalMs = Math.max(1000, endpoint.reconnectIntervalMs ?? 5000);
return wsClientPartsKey(endpoint.url, role, reconnectIntervalMs, endpoint.accessToken ?? '');
}
function isAuthorized(request: IncomingMessage, token: string): boolean {
if (!token) return true;
// 1. Header auth
const rawAuth = request.headers.authorization;
const auth = Array.isArray(rawAuth) ? rawAuth[0] : rawAuth ?? '';
if (auth === `Bearer ${token}`) return true;
// 2. Query string auth
try {
const url = new URL(request.url ?? '/', 'ws://127.0.0.1');
if (url.searchParams.get('access_token') === token) {
return true;
}
} catch {}
return false;
}
function rawDataToString(raw: WebSocket.RawData): string {
if (typeof raw === 'string') return raw;
if (raw instanceof Buffer) return raw.toString('utf8');
if (Array.isArray(raw)) return Buffer.concat(raw).toString('utf8');
if (raw instanceof ArrayBuffer) return Buffer.from(new Uint8Array(raw)).toString('utf8');
if (ArrayBuffer.isView(raw)) {
return Buffer.from(raw.buffer, raw.byteOffset, raw.byteLength).toString('utf8');
}
return '';
}
function safeSend(socket: WebSocket, payload: string): void {
if (socket.readyState !== WebSocket.OPEN) return;
socket.send(payload, (error) => {
if (error) {
log.warn('send error: %s', error instanceof Error ? error.message : String(error));
}
});
}
function safeClose(socket: WebSocket, code = 1000, reason = 'normal'): void {
if (socket.readyState === WebSocket.CLOSED || socket.readyState === WebSocket.CLOSING) return;
socket.close(code, reason);
}
+241
View File
@@ -0,0 +1,241 @@
// Runtime schema-based protobuf decode/encode.
// TypeScript equivalent of the C++ proto_field<N,T> DSL using plain schema objects.
//
// Usage:
// const MyMessageSchema = {
// fromUin: { field: 1, type: 'uint32' as const },
// fromUid: { field: 2, type: 'string' as const },
// grp: { field: 8, type: 'message' as const, schema: GrpSchema },
// elements: { field: 2, type: 'repeated_message' as const, schema: ElemSchema },
// };
// type MyMessage = ProtoDecoded<typeof MyMessageSchema>;
// const msg = protoDecode(rawBytes, MyMessageSchema);
import { WireMessage, WireType, encodeVarint, encodeKey, decodeVarint } from './wire';
// --- Schema types ---
export type FieldType =
| 'bool' | 'int32' | 'uint32' | 'int64' | 'uint64'
| 'string' | 'bytes' | 'message'
| 'repeated_varint' | 'repeated_uint32' | 'repeated_string'
| 'repeated_bytes' | 'repeated_message';
export interface FieldDef {
field: number;
type: FieldType;
schema?: ProtoSchema; // required for 'message' / 'repeated_message'
}
export type ProtoSchema = { [key: string]: FieldDef };
// --- Decoded type inference ---
type FieldTypeToTS<T extends FieldType, S extends ProtoSchema | undefined> =
T extends 'bool' ? boolean :
T extends 'int32' | 'uint32' ? number :
T extends 'int64' | 'uint64' ? bigint :
T extends 'string' ? string :
T extends 'bytes' ? Uint8Array :
T extends 'message' ? (S extends ProtoSchema ? ProtoDecoded<S> : Record<string, unknown>) :
T extends 'repeated_varint' | 'repeated_uint32' ? number[] :
T extends 'repeated_string' ? string[] :
T extends 'repeated_bytes' ? Uint8Array[] :
T extends 'repeated_message' ? (S extends ProtoSchema ? ProtoDecoded<S>[] : Record<string, unknown>[]) :
never;
type IsRepeated<T extends FieldType> = T extends `repeated_${string}` ? true : false;
type FieldValue<F extends FieldDef> =
IsRepeated<F['type']> extends true
? FieldTypeToTS<F['type'], F['schema']>
: FieldTypeToTS<F['type'], F['schema']> | undefined;
export type ProtoDecoded<S extends ProtoSchema> = {
[K in keyof S]: FieldValue<S[K]>;
};
// --- Decode ---
export function protoDecode<S extends ProtoSchema>(
data: Uint8Array | WireMessage,
schema: S
): ProtoDecoded<S> | null {
const wire = data instanceof WireMessage ? data : WireMessage.decode(data);
if (!wire) return null;
const result: Record<string, unknown> = {};
for (const [key, def] of Object.entries(schema)) {
switch (def.type) {
case 'bool': {
const v = wire.getVarint(def.field);
if (v !== null) result[key] = v !== 0n;
break;
}
case 'int32': {
const v = wire.getInt32(def.field);
if (v !== null) result[key] = v;
break;
}
case 'uint32': {
const v = wire.getUint32(def.field);
if (v !== null) result[key] = v;
break;
}
case 'int64': {
const v = wire.getInt64(def.field);
if (v !== null) result[key] = v;
break;
}
case 'uint64': {
const v = wire.getUint64(def.field);
if (v !== null) result[key] = v;
break;
}
case 'string': {
const v = wire.getString(def.field);
if (v !== null) result[key] = v;
break;
}
case 'bytes': {
const v = wire.getBytes(def.field);
if (v !== null) result[key] = v;
break;
}
case 'message': {
const sub = wire.getMessage(def.field);
if (sub && def.schema) {
result[key] = protoDecode(sub, def.schema);
}
break;
}
case 'repeated_varint': {
const vals = wire.getRepeatedVarint(def.field);
result[key] = vals.map(v => Number(BigInt.asIntN(32, v)));
break;
}
case 'repeated_uint32': {
const vals = wire.getRepeatedVarint(def.field);
result[key] = vals.map(v => Number(BigInt.asUintN(32, v)));
break;
}
case 'repeated_string': {
result[key] = wire.getRepeatedString(def.field);
break;
}
case 'repeated_bytes': {
const flds = wire.fields(def.field);
result[key] = flds
.filter(f => f.wireType === WireType.LengthDelimited)
.map(f => f.bytes);
break;
}
case 'repeated_message': {
if (!def.schema) { result[key] = []; break; }
const msgs = wire.getRepeatedMessage(def.field);
result[key] = msgs
.map(m => protoDecode(m, def.schema!))
.filter((m): m is NonNullable<typeof m> => m !== null);
break;
}
}
}
return result as ProtoDecoded<S>;
}
// --- Encode ---
export function protoEncode<S extends ProtoSchema>(
obj: Partial<ProtoDecoded<S>>,
schema: S
): Uint8Array {
const out: number[] = [];
const record = obj as Record<string, any>;
for (const [key, def] of Object.entries(schema)) {
const val = record[key];
if (val === undefined || val === null) continue;
switch (def.type) {
case 'bool': {
encodeKey(def.field, WireType.Varint, out);
encodeVarint(val ? 1 : 0, out);
break;
}
case 'int32':
case 'uint32': {
encodeKey(def.field, WireType.Varint, out);
encodeVarint(val as number, out);
break;
}
case 'int64':
case 'uint64': {
encodeKey(def.field, WireType.Varint, out);
encodeVarint(val as bigint, out);
break;
}
case 'string': {
const encoded = new TextEncoder().encode(val as string);
encodeKey(def.field, WireType.LengthDelimited, out);
encodeVarint(encoded.length, out);
for (const b of encoded) out.push(b);
break;
}
case 'bytes': {
const buf = val as Uint8Array;
encodeKey(def.field, WireType.LengthDelimited, out);
encodeVarint(buf.length, out);
for (const b of buf) out.push(b);
break;
}
case 'message': {
if (!def.schema) break;
const nested = protoEncode(val as any, def.schema);
encodeKey(def.field, WireType.LengthDelimited, out);
encodeVarint(nested.length, out);
for (const b of nested) out.push(b);
break;
}
case 'repeated_varint':
case 'repeated_uint32': {
for (const v of val as number[]) {
encodeKey(def.field, WireType.Varint, out);
encodeVarint(v, out);
}
break;
}
case 'repeated_string': {
const encoder = new TextEncoder();
for (const s of val as string[]) {
const encoded = encoder.encode(s);
encodeKey(def.field, WireType.LengthDelimited, out);
encodeVarint(encoded.length, out);
for (const b of encoded) out.push(b);
}
break;
}
case 'repeated_bytes': {
for (const buf of val as Uint8Array[]) {
encodeKey(def.field, WireType.LengthDelimited, out);
encodeVarint(buf.length, out);
for (const b of buf) out.push(b);
}
break;
}
case 'repeated_message': {
if (!def.schema) break;
for (const item of val as any[]) {
const nested = protoEncode(item, def.schema);
encodeKey(def.field, WireType.LengthDelimited, out);
encodeVarint(nested.length, out);
for (const b of nested) out.push(b);
}
break;
}
}
}
return new Uint8Array(out);
}
+242
View File
@@ -0,0 +1,242 @@
// Protobuf wire-format decoder/encoder.
// Generic decoder that works without .proto schemas — decodes any protobuf
// binary into a field_number → value tree structure.
// Port of src/protobuf/wire.h + wire.cpp
export enum WireType {
Varint = 0,
Fixed64 = 1,
LengthDelimited = 2,
Fixed32 = 5,
}
export interface WireField {
fieldNumber: number;
wireType: WireType;
varint: bigint; // Varint, Fixed64, Fixed32
bytes: Uint8Array; // LengthDelimited
}
// --- Varint decode ---
export function decodeVarint(data: Uint8Array, offset: number): [bigint, number] | null {
let result = 0n;
for (let i = 0; i < 10 && offset + i < data.length; i++) {
result |= BigInt(data[offset + i] & 0x7f) << BigInt(7 * i);
if ((data[offset + i] & 0x80) === 0) {
return [result, i + 1];
}
}
return null;
}
// --- Varint encode ---
export function encodeVarint(value: bigint | number, out: number[]): void {
let v = typeof value === 'number' ? BigInt(value >>> 0) : value;
if (v < 0n) v = v + (1n << 64n); // treat as unsigned 64-bit
while (v >= 0x80n) {
out.push(Number(v & 0x7Fn) | 0x80);
v >>= 7n;
}
out.push(Number(v));
}
// --- Key encode ---
export function encodeKey(fieldNumber: number, wireType: WireType, out: number[]): void {
encodeVarint(BigInt(fieldNumber) << 3n | BigInt(wireType), out);
}
// --- Field value helpers ---
export function fieldAsInt32(f: WireField): number { return Number(BigInt.asIntN(32, f.varint)); }
export function fieldAsUint32(f: WireField): number { return Number(BigInt.asUintN(32, f.varint)); }
export function fieldAsInt64(f: WireField): bigint { return BigInt.asIntN(64, f.varint); }
export function fieldAsUint64(f: WireField): bigint { return f.varint; }
export function fieldAsBool(f: WireField): boolean { return f.varint !== 0n; }
export function fieldAsString(f: WireField): string {
return new TextDecoder().decode(f.bytes);
}
export function fieldAsBytes(f: WireField): Uint8Array {
return f.bytes;
}
export class WireMessage {
private fields_: WireField[];
private constructor(fields: WireField[]) {
this.fields_ = fields;
}
static decode(data: Uint8Array): WireMessage | null {
if (!data || data.length === 0) return null;
const fields: WireField[] = [];
let pos = 0;
while (pos < data.length) {
const tagResult = decodeVarint(data, pos);
if (!tagResult) break;
const [tag, tagLen] = tagResult;
pos += tagLen;
const fieldNum = Number(tag >> 3n);
const wireType = Number(tag & 0x07n) as WireType;
if (fieldNum === 0) break;
const field: WireField = {
fieldNumber: fieldNum,
wireType,
varint: 0n,
bytes: new Uint8Array(0),
};
switch (wireType) {
case WireType.Varint: {
const valResult = decodeVarint(data, pos);
if (!valResult) return null;
field.varint = valResult[0];
pos += valResult[1];
break;
}
case WireType.Fixed64: {
if (pos + 8 > data.length) return null;
const dv = new DataView(data.buffer, data.byteOffset + pos, 8);
field.varint = dv.getBigUint64(0, true);
pos += 8;
break;
}
case WireType.Fixed32: {
if (pos + 4 > data.length) return null;
const dv = new DataView(data.buffer, data.byteOffset + pos, 4);
field.varint = BigInt(dv.getUint32(0, true));
pos += 4;
break;
}
case WireType.LengthDelimited: {
const lenResult = decodeVarint(data, pos);
if (!lenResult) return null;
const fieldLen = Number(lenResult[0]);
pos += lenResult[1];
if (pos + fieldLen > data.length) return null;
field.bytes = data.subarray(pos, pos + fieldLen);
pos += fieldLen;
break;
}
default:
return null;
}
fields.push(field);
}
return new WireMessage(fields);
}
// --- Single field access ---
field(num: number): WireField | null {
for (const f of this.fields_) {
if (f.fieldNumber === num) return f;
}
return null;
}
has(num: number): boolean {
return this.field(num) !== null;
}
getVarint(num: number): bigint | null {
const f = this.field(num);
if (!f || f.wireType !== WireType.Varint) return null;
return f.varint;
}
getInt32(num: number): number | null {
const v = this.getVarint(num);
return v !== null ? Number(BigInt.asIntN(32, v)) : null;
}
getUint32(num: number): number | null {
const v = this.getVarint(num);
return v !== null ? Number(BigInt.asUintN(32, v)) : null;
}
getInt64(num: number): bigint | null {
const v = this.getVarint(num);
return v !== null ? BigInt.asIntN(64, v) : null;
}
getUint64(num: number): bigint | null {
return this.getVarint(num);
}
getString(num: number): string | null {
const f = this.field(num);
if (!f || f.wireType !== WireType.LengthDelimited) return null;
return fieldAsString(f);
}
getBytes(num: number): Uint8Array | null {
const f = this.field(num);
if (!f || f.wireType !== WireType.LengthDelimited) return null;
return f.bytes;
}
getMessage(num: number): WireMessage | null {
const f = this.field(num);
if (!f || f.wireType !== WireType.LengthDelimited) return null;
return WireMessage.decode(f.bytes);
}
// --- Repeated field access ---
fields(num: number): WireField[] {
return this.fields_.filter(f => f.fieldNumber === num);
}
getRepeatedVarint(num: number): bigint[] {
const result: bigint[] = [];
for (const f of this.fields_) {
if (f.fieldNumber !== num) continue;
if (f.wireType === WireType.Varint) {
result.push(f.varint);
} else if (f.wireType === WireType.LengthDelimited) {
// Packed repeated varint
let pos = 0;
while (pos < f.bytes.length) {
const r = decodeVarint(f.bytes, pos);
if (!r) break;
result.push(r[0]);
pos += r[1];
}
}
}
return result;
}
getRepeatedString(num: number): string[] {
const result: string[] = [];
const decoder = new TextDecoder();
for (const f of this.fields_) {
if (f.fieldNumber === num && f.wireType === WireType.LengthDelimited) {
result.push(decoder.decode(f.bytes));
}
}
return result;
}
getRepeatedMessage(num: number): WireMessage[] {
const result: WireMessage[] = [];
for (const f of this.fields_) {
if (f.fieldNumber === num && f.wireType === WireType.LengthDelimited) {
const sub = WireMessage.decode(f.bytes);
if (sub) result.push(sub);
}
}
return result;
}
// --- Raw iteration ---
get allFields(): WireField[] { return this.fields_; }
get empty(): boolean { return this.fields_.length === 0; }
}
@@ -0,0 +1,54 @@
import { createLogger } from '../utils/logger';
import type { PacketInfo } from './types';
const log = createLogger('NTQQ');
export type CmdCallback = (pkt: PacketInfo) => void;
export interface HookPacketInput {
seq: number;
error: number;
cmd: string;
uin: string;
body: Uint8Array;
}
export class NtqqHandler {
private cmdHandlers = new Map<string, CmdCallback[]>();
private cmdAllHandlers: CmdCallback[] = [];
registerCmd(cmd: string, cb: CmdCallback): void {
const arr = this.cmdHandlers.get(cmd) ?? [];
arr.push(cb);
this.cmdHandlers.set(cmd, arr);
}
registerCmdAll(cb: CmdCallback): void { this.cmdAllHandlers.push(cb); }
onHookPacket(pid: number, packet: HookPacketInput): void {
this.dispatchPacket({
pid,
uin: packet.uin,
serviceCmd: packet.cmd,
seqId: packet.seq,
retCode: packet.error,
fromClient: false,
body: Buffer.from(packet.body),
});
}
private dispatchPacket(pkt: PacketInfo): void {
const specific = this.cmdHandlers.get(pkt.serviceCmd);
if (specific) {
for (const cb of specific) {
try { cb(pkt); } catch (e) {
log.error('dispatch error for %s: %s', pkt.serviceCmd, e instanceof Error ? (e.stack ?? e.message) : String(e));
}
}
}
for (const cb of this.cmdAllHandlers) {
try { cb(pkt); } catch (e) {
log.error('dispatch error for %s: %s', pkt.serviceCmd, e instanceof Error ? (e.stack ?? e.message) : String(e));
}
}
}
}
@@ -0,0 +1,11 @@
export interface SendPacketResult {
success: boolean;
gotResponse: boolean;
errorCode: number;
errorMessage: string;
responseData: Buffer | null;
}
export interface PacketSender {
sendPacket(serviceCmd: string, body: Buffer, timeoutMs?: number): Promise<SendPacketResult>;
}
+10
View File
@@ -0,0 +1,10 @@
export interface PacketInfo {
pid: number;
uin: string;
packetType?: number;
serviceCmd: string;
seqId: number;
retCode: number;
fromClient: boolean;
body: Uint8Array;
}
+25
View File
@@ -0,0 +1,25 @@
const HEX_CHARS = '0123456789abcdef';
export function toHex(data: Uint8Array | Buffer): string {
let h = '';
for (const b of data) {
h += HEX_CHARS[b >> 4];
h += HEX_CHARS[b & 0xf];
}
return h;
}
export function hexPreview(data: Uint8Array | Buffer, maxBytes = 64): string {
const limit = Math.max(0, Math.min(maxBytes, data.length));
const head = toHex(data.subarray(0, limit));
return data.length > limit ? `${head}...` : head;
}
export function fromHex(hex: string): Buffer {
if (hex.length % 2 !== 0) throw new Error('Invalid hex string length');
const buf = Buffer.alloc(hex.length / 2);
for (let i = 0; i < buf.length; i++) {
buf[i] = parseInt(hex.substring(i * 2, i * 2 + 2), 16);
}
return buf;
}
+148
View File
@@ -0,0 +1,148 @@
import { format } from 'util';
type LogLevel = 'debug' | 'info' | 'success' | 'warn' | 'error';
export interface LogEntry {
id: number;
time: string;
level: LogLevel;
scope: string;
message: string;
line: string;
}
interface LogOptions {
scope: string;
}
const LEVEL_WEIGHT: Record<LogLevel, number> = {
debug: 10,
info: 20,
success: 25,
warn: 30,
error: 40,
};
const LEVEL_LABEL: Record<LogLevel, string> = {
debug: 'DEBUG',
info: 'INFO',
success: 'OK',
warn: 'WARN',
error: 'ERROR',
};
const COLOR_CODE: Record<LogLevel, number> = {
debug: 90,
info: 36,
success: 32,
warn: 33,
error: 31,
};
const COLOR_SCOPE = 35;
const COLOR_DIM = 2;
const COLOR_RESET = '\x1b[0m';
const MAX_LOG_ENTRIES = 1000;
const logEntries: LogEntry[] = [];
const logSubscribers = new Set<(entry: LogEntry) => void>();
let nextLogId = 1;
function resolveMinLevel(): LogLevel {
const raw = (process.env.SNOWLUMA_LOG_LEVEL ?? 'info').toLowerCase();
if (raw === 'debug' || raw === 'info' || raw === 'success' || raw === 'warn' || raw === 'error') {
return raw;
}
return 'info';
}
const MIN_LEVEL = resolveMinLevel();
function shouldLog(level: LogLevel): boolean {
return LEVEL_WEIGHT[level] >= LEVEL_WEIGHT[MIN_LEVEL];
}
function useColor(): boolean {
if (process.env.NO_COLOR === '1') return false;
return Boolean(process.stdout.isTTY);
}
function ansi(code: number, text: string): string {
return `\x1b[${code}m${text}${COLOR_RESET}`;
}
function currentTime(): string {
const d = new Date();
const hh = String(d.getHours()).padStart(2, '0');
const mm = String(d.getMinutes()).padStart(2, '0');
const ss = String(d.getSeconds()).padStart(2, '0');
return `${hh}:${mm}:${ss}`;
}
function render(level: LogLevel, scope: string, args: unknown[]): string {
const message = format(...args);
const ts = currentTime();
const label = LEVEL_LABEL[level].padEnd(5, ' ');
if (!useColor()) {
return `${ts} ${label} [${scope}] ${message}`;
}
const cTs = ansi(COLOR_DIM, ts);
const cLabel = ansi(COLOR_CODE[level], label);
const cScope = ansi(COLOR_SCOPE, `[${scope}]`);
return `${cTs} ${cLabel} ${cScope} ${message}`;
}
function emit(level: LogLevel, options: LogOptions, args: unknown[]): void {
if (!shouldLog(level)) return;
const message = format(...args);
const line = render(level, options.scope, args);
const entry: LogEntry = {
id: nextLogId++,
time: new Date().toISOString(),
level,
scope: options.scope,
message,
line,
};
logEntries.push(entry);
if (logEntries.length > MAX_LOG_ENTRIES) logEntries.shift();
for (const subscriber of logSubscribers) subscriber(entry);
const stream = level === 'warn' || level === 'error' ? process.stderr : process.stdout;
// Strip ASCII control characters before writing to terminal to prevent
// BEL (0x07) in user-provided strings (e.g. group member names) from
// triggering Windows system beep sounds.
// eslint-disable-next-line no-control-regex
stream.write(line.replace(/[\x00-\x1F\x7F]/g, '') + '\n');
}
export function getRecentLogs(limit = 300): LogEntry[] {
const n = Math.max(1, Math.min(Math.trunc(limit), MAX_LOG_ENTRIES));
return logEntries.slice(-n);
}
export function subscribeLogs(callback: (entry: LogEntry) => void): () => void {
logSubscribers.add(callback);
return () => {
logSubscribers.delete(callback);
};
}
export interface Logger {
debug: (...args: unknown[]) => void;
info: (...args: unknown[]) => void;
success: (...args: unknown[]) => void;
warn: (...args: unknown[]) => void;
error: (...args: unknown[]) => void;
}
export function createLogger(scope: string): Logger {
const options: LogOptions = { scope };
return {
debug: (...args: unknown[]) => emit('debug', options, args),
info: (...args: unknown[]) => emit('info', options, args),
success: (...args: unknown[]) => emit('success', options, args),
warn: (...args: unknown[]) => emit('warn', options, args),
error: (...args: unknown[]) => emit('error', options, args),
};
}
+272
View File
@@ -0,0 +1,272 @@
import { serve } from '@hono/node-server';
import { serveStatic } from '@hono/node-server/serve-static';
import { Hono } from 'hono';
import { createLogger, getRecentLogs, subscribeLogs } from '../utils/logger';
import { randomBytes } from 'crypto';
import type { OneBotManager } from '../onebot/manager';
import { loadOneBotConfig, saveOneBotConfig } from '../onebot/config';
import type { OneBotConfig } from '../onebot/types';
import type { HookManager } from '../hook/hook-manager';
import path from 'path';
import { fileURLToPath } from 'url';
const log = createLogger('WebUI');
const __dirname = path.dirname(fileURLToPath(import.meta.url));
// Session token store: token -> expiry timestamp (24h)
const sessionTokens = new Map<string, number>();
// Login attempt tracker: ip -> { count, resetAt }
const loginAttempts = new Map<string, { count: number; resetAt: number }>();
const LOGIN_MAX_ATTEMPTS = 5;
const LOGIN_LOCKOUT_MS = 15 * 60 * 1000; // 15 minutes
const TOKEN_TTL_MS = 24 * 60 * 60 * 1000; // 24 hours
const AVATAR_CACHE_TTL_MS = 30 * 24 * 60 * 60 * 1000;
const AVATAR_BROWSER_CACHE_SECONDS = 30 * 24 * 60 * 60;
const avatarCache = new Map<string, { body: Uint8Array; contentType: string; expiresAt: number }>();
function purgeExpiredTokens() {
const now = Date.now();
for (const [token, expiry] of sessionTokens) {
if (now > expiry) sessionTokens.delete(token);
}
}
function getClientIp(req: Request): string {
return req.headers.get('x-forwarded-for')?.split(',')[0].trim() ?? '127.0.0.1';
}
async function fetchQqAvatar(uin: string): Promise<{ body: Uint8Array; contentType: string }> {
const response = await fetch(`https://q1.qlogo.cn/g?b=qq&nk=${encodeURIComponent(uin)}&s=100`, {
headers: {
'User-Agent': 'SnowLuma WebUI',
'Accept': 'image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8',
},
});
if (!response.ok) {
throw new Error(`avatar upstream responded with ${response.status}`);
}
const contentType = response.headers.get('content-type') || 'image/jpeg';
const body = new Uint8Array(await response.arrayBuffer());
return { body, contentType };
}
export function initWebUI(port: number = 8080, oneBotManager: OneBotManager, hookManager?: HookManager) {
const app = new Hono();
// Generate random password (printed once at startup)
const randomPassword = randomBytes(8).toString('hex');
log.info(`=========================================`);
log.info(`WebUI 安全认证`);
log.info(`默认用户: admin`);
log.info(`临时密码: ${randomPassword}`);
log.info(`=========================================`);
// API Auth middleware
app.use('/api/*', async (c, next) => {
if (c.req.path === '/api/login') {
return next();
}
const authHeader = c.req.header('Authorization');
const bearerToken = authHeader?.startsWith('Bearer ') ? authHeader.slice(7) : '';
const queryToken = c.req.query('token') ?? '';
const token = bearerToken || queryToken;
if (!token) {
return c.json({ status: 'failed', message: 'Unauthorized' }, 401);
}
purgeExpiredTokens();
const expiry = sessionTokens.get(token);
if (!expiry || Date.now() > expiry) {
return c.json({ status: 'failed', message: 'Token expired or invalid' }, 401);
}
await next();
});
// Login Endpoint with rate limiting
app.post('/api/login', async (c) => {
const ip = getClientIp(c.req.raw);
const now = Date.now();
const attempt = loginAttempts.get(ip);
if (attempt && attempt.count >= LOGIN_MAX_ATTEMPTS && now < attempt.resetAt) {
const waitSec = Math.ceil((attempt.resetAt - now) / 1000);
return c.json({ success: false, message: `登录尝试过多,请 ${waitSec} 秒后重试` }, 429);
}
try {
const { password } = await c.req.json();
if (password === randomPassword) {
loginAttempts.delete(ip);
purgeExpiredTokens();
const token = randomBytes(32).toString('hex');
sessionTokens.set(token, now + TOKEN_TTL_MS);
return c.json({ success: true, token });
}
const current = loginAttempts.get(ip) ?? { count: 0, resetAt: now + LOGIN_LOCKOUT_MS };
current.count += 1;
if (current.count === 1) current.resetAt = now + LOGIN_LOCKOUT_MS;
loginAttempts.set(ip, current);
return c.json({ success: false, message: '密码错误' }, 401);
} catch {
return c.json({ success: false, message: '请求格式错误' }, 400);
}
});
app.get('/avatar/:uin', async (c) => {
const uin = c.req.param('uin');
if (!/^\d{5,12}$/.test(uin)) {
return c.text('invalid uin', 400);
}
const now = Date.now();
let cached = avatarCache.get(uin);
if (!cached || cached.expiresAt <= now) {
try {
const avatar = await fetchQqAvatar(uin);
cached = { ...avatar, expiresAt: now + AVATAR_CACHE_TTL_MS };
avatarCache.set(uin, cached);
} catch (err) {
log.warn('failed to proxy avatar for UIN %s: %s', uin, err instanceof Error ? err.message : String(err));
if (!cached) return c.text('avatar unavailable', 502);
}
}
return new Response(cached.body, {
headers: {
'Content-Type': cached.contentType,
'Cache-Control': `public, max-age=${AVATAR_BROWSER_CACHE_SECONDS}, immutable`,
},
});
});
// API Routes
app.get('/api/status', (c) => {
return c.json({ status: 'running' });
});
app.get('/api/qq-list', (c) => {
const instances = oneBotManager.getInstances();
const list = instances.map(inst => ({
uin: inst.uin,
nickname: inst.qqInfo.nickname
}));
return c.json({ list });
});
app.get('/api/logs', (c) => {
const limit = Number(c.req.query('limit') ?? 300);
return c.json({ list: getRecentLogs(limit) });
});
app.get('/api/logs/stream', (c) => {
const stream = new ReadableStream({
start(controller) {
const encoder = new TextEncoder();
const send = (event: unknown) => {
controller.enqueue(encoder.encode(`data: ${JSON.stringify(event)}\n\n`));
};
send({ type: 'ready' });
const unsubscribe = subscribeLogs((entry) => send(entry));
const heartbeat = setInterval(() => {
controller.enqueue(encoder.encode(': heartbeat\n\n'));
}, 15000);
c.req.raw.signal.addEventListener('abort', () => {
clearInterval(heartbeat);
unsubscribe();
try {
controller.close();
} catch {
}
});
},
});
return new Response(stream, {
headers: {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive',
},
});
});
app.get('/api/processes', async (c) => {
if (!hookManager) return c.json({ list: [] });
try {
return c.json({ list: await hookManager.listProcesses() });
} catch (err) {
return c.json({ list: [], message: err instanceof Error ? err.message : String(err) }, 500);
}
});
app.post('/api/processes/:pid/load', async (c) => {
if (!hookManager) return c.json({ success: false, message: 'hook manager is not available' }, 503);
const pid = Number(c.req.param('pid'));
if (!Number.isInteger(pid) || pid <= 0) {
return c.json({ success: false, message: 'invalid pid' }, 400);
}
try {
const processInfo = await hookManager.loadProcess(pid);
return c.json({ success: processInfo.status !== 'error', process: processInfo });
} catch (err) {
return c.json({ success: false, message: err instanceof Error ? err.message : String(err) }, 500);
}
});
app.post('/api/processes/:pid/unload', async (c) => {
if (!hookManager) return c.json({ success: false, message: 'hook manager is not available' }, 503);
const pid = Number(c.req.param('pid'));
if (!Number.isInteger(pid) || pid <= 0) {
return c.json({ success: false, message: 'invalid pid' }, 400);
}
try {
const processInfo = await hookManager.unloadProcess(pid);
return c.json({ success: processInfo.status !== 'error', process: processInfo });
} catch (err) {
return c.json({ success: false, message: err instanceof Error ? err.message : String(err) }, 500);
}
});
app.get('/api/config/:uin', (c) => {
const uin = c.req.param('uin');
const config = loadOneBotConfig(uin);
return c.json({ config });
});
app.post('/api/config/:uin', async (c) => {
try {
const uin = c.req.param('uin');
const body = await c.req.json() as OneBotConfig;
saveOneBotConfig(uin, body);
const reloaded = oneBotManager.reloadConfig(uin);
log.info('Updated OneBot config for UIN: %s%s', uin, reloaded ? ' and reloaded' : '');
return c.json({
success: true,
reloaded,
message: reloaded ? '配置保存成功,已热重载当前会话。' : '配置保存成功,当前会话未在线,将在下次连接时生效。',
});
} catch (err) {
return c.json({ success: false, message: String(err) }, 400);
}
});
// Serve static files generated by the React frontend
const staticRoot = path.join(__dirname, 'client');
app.use('/*', serveStatic({ root: staticRoot }));
serve({
fetch: app.fetch,
port
}, (info) => {
log.info(`WebUI server is listening on http://localhost:${info.port}`);
});
}
+16
View File
@@ -0,0 +1,16 @@
import { describe, it, expect } from 'vitest';
import { loadOneBotConfig, makeDefaultOneBotConfig } from '../src/onebot/config';
describe('makeDefaultOneBotConfig', () => {
it('returns default config structure', () => {
const config = makeDefaultOneBotConfig();
expect(config.httpServers).toHaveLength(1);
expect(config.httpServers[0].host).toBe('0.0.0.0');
expect(config.httpServers[0].port).toBe(3000);
expect(config.httpPostEndpoints).toEqual([]);
expect(config.wsServers).toHaveLength(1);
expect(config.wsServers[0].port).toBe(3001);
expect(config.wsClients).toEqual([]);
expect(config.musicSignUrl).toBe('');
});
});
+173
View File
@@ -0,0 +1,173 @@
import { describe, it, expect } from 'vitest';
import { protoDecode, protoEncode, type ProtoSchema } from '../src/protobuf/decode';
import { WireMessage, encodeKey, encodeVarint, WireType } from '../src/protobuf/wire';
describe('protoDecode', () => {
const SimpleSchema = {
name: { field: 1, type: 'string' as const },
age: { field: 2, type: 'uint32' as const },
active: { field: 3, type: 'bool' as const },
};
function buildProto(): Uint8Array {
const out: number[] = [];
// field 1 string "Alice"
encodeKey(1, WireType.LengthDelimited, out);
const str = new TextEncoder().encode('Alice');
encodeVarint(str.length, out);
out.push(...str);
// field 2 uint32 = 30
encodeKey(2, WireType.Varint, out);
encodeVarint(30, out);
// field 3 bool = true
encodeKey(3, WireType.Varint, out);
encodeVarint(1, out);
return new Uint8Array(out);
}
it('decodes all fields', () => {
const result = protoDecode(buildProto(), SimpleSchema);
expect(result).not.toBeNull();
expect(result!.name).toBe('Alice');
expect(result!.age).toBe(30);
expect(result!.active).toBe(true);
});
it('handles missing fields', () => {
// Only field 1
const out: number[] = [];
encodeKey(1, WireType.LengthDelimited, out);
const str = new TextEncoder().encode('Bob');
encodeVarint(str.length, out);
out.push(...str);
const result = protoDecode(new Uint8Array(out), SimpleSchema);
expect(result).not.toBeNull();
expect(result!.name).toBe('Bob');
expect(result!.age).toBeUndefined();
expect(result!.active).toBeUndefined();
});
it('returns null for empty data', () => {
expect(protoDecode(new Uint8Array(0), SimpleSchema)).toBeNull();
});
it('decodes nested messages', () => {
const InnerSchema = {
value: { field: 1, type: 'uint32' as const },
};
const OuterSchema = {
inner: { field: 1, type: 'message' as const, schema: InnerSchema },
};
// Build inner
const innerOut: number[] = [];
encodeKey(1, WireType.Varint, innerOut);
encodeVarint(99, innerOut);
// Build outer
const outerOut: number[] = [];
encodeKey(1, WireType.LengthDelimited, outerOut);
encodeVarint(innerOut.length, outerOut);
outerOut.push(...innerOut);
const result = protoDecode(new Uint8Array(outerOut), OuterSchema);
expect(result).not.toBeNull();
expect(result!.inner).not.toBeUndefined();
expect(result!.inner!.value).toBe(99);
});
it('decodes repeated messages', () => {
const ItemSchema = {
id: { field: 1, type: 'uint32' as const },
};
const ListSchema = {
items: { field: 1, type: 'repeated_message' as const, schema: ItemSchema },
};
const out: number[] = [];
for (const id of [1, 2, 3]) {
const itemOut: number[] = [];
encodeKey(1, WireType.Varint, itemOut);
encodeVarint(id, itemOut);
encodeKey(1, WireType.LengthDelimited, out);
encodeVarint(itemOut.length, out);
out.push(...itemOut);
}
const result = protoDecode(new Uint8Array(out), ListSchema);
expect(result).not.toBeNull();
expect(result!.items).toHaveLength(3);
expect(result!.items.map((i) => i.id)).toEqual([1, 2, 3]);
});
it('accepts WireMessage directly', () => {
const wire = WireMessage.decode(buildProto());
const result = protoDecode(wire!, SimpleSchema);
expect(result!.name).toBe('Alice');
});
});
describe('protoEncode', () => {
const SimpleSchema = {
name: { field: 1, type: 'string' as const },
age: { field: 2, type: 'uint32' as const },
active: { field: 3, type: 'bool' as const },
};
it('encodes and decodes roundtrip', () => {
const data = { name: 'Charlie', age: 25, active: true };
const encoded = protoEncode(data, SimpleSchema);
const decoded = protoDecode(encoded, SimpleSchema);
expect(decoded).not.toBeNull();
expect(decoded!.name).toBe('Charlie');
expect(decoded!.age).toBe(25);
expect(decoded!.active).toBe(true);
});
it('skips undefined fields', () => {
const data = { name: 'Dave', age: undefined, active: undefined };
const encoded = protoEncode(data as any, SimpleSchema);
const decoded = protoDecode(encoded, SimpleSchema);
expect(decoded!.name).toBe('Dave');
expect(decoded!.age).toBeUndefined();
expect(decoded!.active).toBeUndefined();
});
it('encodes bytes', () => {
const ByteSchema = {
payload: { field: 1, type: 'bytes' as const },
};
const data = { payload: new Uint8Array([0xDE, 0xAD]) };
const encoded = protoEncode(data, ByteSchema);
const decoded = protoDecode(encoded, ByteSchema);
expect(decoded!.payload).toEqual(new Uint8Array([0xDE, 0xAD]));
});
it('encodes nested messages', () => {
const InnerSchema = {
value: { field: 1, type: 'uint32' as const },
};
const OuterSchema = {
inner: { field: 1, type: 'message' as const, schema: InnerSchema },
};
const data = { inner: { value: 42 } };
const encoded = protoEncode(data, OuterSchema);
const decoded = protoDecode(encoded, OuterSchema);
expect(decoded!.inner!.value).toBe(42);
});
it('encodes int64/uint64', () => {
const BigSchema = {
signed: { field: 1, type: 'int64' as const },
unsigned: { field: 2, type: 'uint64' as const },
};
const data = { signed: -1n, unsigned: 0xFFFFFFFFFFFFFFFFn };
const encoded = protoEncode(data, BigSchema);
const decoded = protoDecode(encoded, BigSchema);
expect(decoded!.signed).toBe(-1n);
expect(decoded!.unsigned).toBe(0xFFFFFFFFFFFFFFFFn);
});
});
+65
View File
@@ -0,0 +1,65 @@
import { describe, it, expect } from 'vitest';
import { toHex, fromHex, hexPreview } from '../src/utils/hex';
describe('toHex', () => {
it('converts empty buffer', () => {
expect(toHex(new Uint8Array(0))).toBe('');
});
it('converts single byte', () => {
expect(toHex(new Uint8Array([0xff]))).toBe('ff');
expect(toHex(new Uint8Array([0x00]))).toBe('00');
expect(toHex(new Uint8Array([0x0a]))).toBe('0a');
});
it('converts multiple bytes', () => {
expect(toHex(new Uint8Array([0xde, 0xad, 0xbe, 0xef]))).toBe('deadbeef');
});
it('works with Buffer', () => {
expect(toHex(Buffer.from([0x01, 0x23, 0x45]))).toBe('012345');
});
});
describe('fromHex', () => {
it('converts empty string', () => {
expect(fromHex('')).toEqual(Buffer.alloc(0));
});
it('converts hex string', () => {
const buf = fromHex('deadbeef');
expect(buf).toEqual(Buffer.from([0xde, 0xad, 0xbe, 0xef]));
});
it('handles uppercase', () => {
const buf = fromHex('DEADBEEF');
expect(buf).toEqual(Buffer.from([0xde, 0xad, 0xbe, 0xef]));
});
it('throws on odd-length string', () => {
expect(() => fromHex('abc')).toThrow('Invalid hex string length');
});
it('roundtrips with toHex', () => {
const original = Buffer.from([0x00, 0x7f, 0x80, 0xff]);
expect(fromHex(toHex(original))).toEqual(original);
});
});
describe('hexPreview', () => {
it('shows full hex for small data', () => {
const data = new Uint8Array([0xab, 0xcd]);
expect(hexPreview(data)).toBe('abcd');
});
it('truncates with ellipsis', () => {
const data = new Uint8Array(128).fill(0xaa);
const preview = hexPreview(data, 4);
expect(preview).toBe('aaaaaaaa...');
});
it('no ellipsis when exactly at limit', () => {
const data = new Uint8Array(4).fill(0xbb);
expect(hexPreview(data, 4)).toBe('bbbbbbbb');
});
});
+49
View File
@@ -0,0 +1,49 @@
import { describe, it, expect } from 'vitest';
import { hashMessageIdInt32, GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT } from '../src/onebot/message-id';
describe('hashMessageIdInt32', () => {
it('returns consistent hash for same inputs', () => {
const id1 = hashMessageIdInt32(100, 12345, GROUP_MESSAGE_EVENT);
const id2 = hashMessageIdInt32(100, 12345, GROUP_MESSAGE_EVENT);
expect(id1).toBe(id2);
});
it('returns non-zero', () => {
// The function ensures id !== 0 by setting it to 1
const id = hashMessageIdInt32(0, 0, '');
expect(id).not.toBe(0);
});
it('returns different values for different sequences', () => {
const id1 = hashMessageIdInt32(1, 12345, GROUP_MESSAGE_EVENT);
const id2 = hashMessageIdInt32(2, 12345, GROUP_MESSAGE_EVENT);
expect(id1).not.toBe(id2);
});
it('returns different values for different sessions', () => {
const id1 = hashMessageIdInt32(100, 11111, GROUP_MESSAGE_EVENT);
const id2 = hashMessageIdInt32(100, 22222, GROUP_MESSAGE_EVENT);
expect(id1).not.toBe(id2);
});
it('returns different values for different event names', () => {
const id1 = hashMessageIdInt32(100, 12345, GROUP_MESSAGE_EVENT);
const id2 = hashMessageIdInt32(100, 12345, PRIVATE_MESSAGE_EVENT);
expect(id1).not.toBe(id2);
});
it('returns 32-bit integer', () => {
const id = hashMessageIdInt32(999999, 123456789, GROUP_MESSAGE_EVENT);
expect(id).toBeGreaterThanOrEqual(-2147483648);
expect(id).toBeLessThanOrEqual(2147483647);
});
it('handles non-finite inputs gracefully', () => {
const id1 = hashMessageIdInt32(NaN, 0, 'test');
const id2 = hashMessageIdInt32(Infinity, 0, 'test');
expect(typeof id1).toBe('number');
expect(typeof id2).toBe('number');
// Both should map to sequence=0
expect(id1).toBe(id2);
});
});
+248
View File
@@ -0,0 +1,248 @@
import { describe, it, expect } from 'vitest';
import { parseMessage } from '../src/onebot/message-parser';
describe('parseMessage', () => {
describe('plain text', () => {
it('parses simple text', async () => {
const result = await parseMessage('hello world', false);
expect(result).toEqual([{ type: 'text', text: 'hello world' }]);
});
it('returns empty for empty string', async () => {
const result = await parseMessage('', false);
expect(result).toEqual([]);
});
it('autoEscape treats CQ codes as text', async () => {
const result = await parseMessage('[CQ:face,id=123]', true);
expect(result).toEqual([{ type: 'text', text: '[CQ:face,id=123]' }]);
});
});
describe('CQ code parsing', () => {
it('parses face CQ code', async () => {
const result = await parseMessage('[CQ:face,id=123]', false);
expect(result).toHaveLength(1);
expect(result[0].type).toBe('face');
expect(result[0].faceId).toBe(123);
});
it('parses at CQ code', async () => {
const result = await parseMessage('[CQ:at,qq=12345]', false);
expect(result).toHaveLength(1);
expect(result[0].type).toBe('at');
expect(result[0].targetUin).toBe(12345);
});
it('parses at all', async () => {
const result = await parseMessage('[CQ:at,qq=all]', false);
expect(result).toHaveLength(1);
expect(result[0].type).toBe('at');
expect(result[0].targetUin).toBe(0);
});
it('parses mixed text and CQ codes', async () => {
const result = await parseMessage('Hello [CQ:face,id=1] World', false);
expect(result).toHaveLength(3);
expect(result[0]).toEqual({ type: 'text', text: 'Hello ' });
expect(result[1].type).toBe('face');
expect(result[2]).toEqual({ type: 'text', text: ' World' });
});
it('unescapes CQ special chars', async () => {
const result = await parseMessage('a&amp;b&#91;c&#93;d', false);
expect(result).toEqual([{ type: 'text', text: 'a&b[c]d' }]);
});
});
describe('JSON segment array', () => {
it('parses text segment', async () => {
const result = await parseMessage(
[{ type: 'text', data: { text: 'hello' } }] as any,
false,
);
expect(result).toEqual([{ type: 'text', text: 'hello' }]);
});
it('parses face segment', async () => {
const result = await parseMessage(
[{ type: 'face', data: { id: 123 } }] as any,
false,
);
expect(result).toHaveLength(1);
expect(result[0].type).toBe('face');
expect(result[0].faceId).toBe(123);
});
it('parses image segment', async () => {
const result = await parseMessage(
[{ type: 'image', data: { file: 'https://example.com/img.png' } }] as any,
false,
);
expect(result).toHaveLength(1);
expect(result[0].type).toBe('image');
expect(result[0].url).toBe('https://example.com/img.png');
});
it('parses at segment', async () => {
const result = await parseMessage(
[{ type: 'at', data: { qq: 12345 } }] as any,
false,
);
expect(result).toHaveLength(1);
expect(result[0].type).toBe('at');
expect(result[0].targetUin).toBe(12345);
});
it('parses multiple segments', async () => {
const result = await parseMessage(
[
{ type: 'text', data: { text: 'hi ' } },
{ type: 'at', data: { qq: 999 } },
{ type: 'text', data: { text: ' there' } },
] as any,
false,
);
expect(result).toHaveLength(3);
expect(result[0].type).toBe('text');
expect(result[1].type).toBe('at');
expect(result[2].type).toBe('text');
});
it('skips unknown segment types', async () => {
const result = await parseMessage(
[
{ type: 'text', data: { text: 'ok' } },
{ type: 'unknown_type_xyz', data: {} },
] as any,
false,
);
expect(result).toHaveLength(1);
expect(result[0].type).toBe('text');
});
});
describe('special segments', () => {
it('parses json segment', async () => {
const result = await parseMessage(
[{ type: 'json', data: { data: '{"app":"test"}' } }] as any,
false,
);
expect(result).toHaveLength(1);
expect(result[0].type).toBe('json');
expect(result[0].text).toBe('{"app":"test"}');
});
it('parses reply segment with resolveReplySequence', async () => {
const result = await parseMessage(
[{ type: 'reply', data: { id: 42 } }] as any,
false,
{ resolveReplySequence: (id) => id === 42 ? 100 : null },
);
expect(result).toHaveLength(1);
expect(result[0].type).toBe('reply');
expect(result[0].replySeq).toBe(100);
});
it('parses share as json card', async () => {
const result = await parseMessage(
[{ type: 'share', data: { url: 'https://example.com', title: 'Test' } }] as any,
false,
);
expect(result).toHaveLength(1);
expect(result[0].type).toBe('json');
expect(result[0].text).toBeDefined();
const parsed = JSON.parse(result[0].text!);
expect(parsed.app).toBe('com.tencent.structmsg');
expect(parsed.meta.news.title).toBe('Test');
});
it('parses rps as face', async () => {
const result = await parseMessage(
[{ type: 'rps', data: {} }] as any,
false,
);
expect(result).toHaveLength(1);
expect(result[0].type).toBe('face');
expect(result[0].faceId).toBe(359);
});
it('parses dice as face', async () => {
const result = await parseMessage(
[{ type: 'dice', data: {} }] as any,
false,
);
expect(result).toHaveLength(1);
expect(result[0].type).toBe('face');
expect(result[0].faceId).toBe(358);
});
it('parses shake as poke', async () => {
const result = await parseMessage(
[{ type: 'shake', data: {} }] as any,
false,
);
expect(result).toHaveLength(1);
expect(result[0].type).toBe('poke');
});
it('ignores anonymous segment', async () => {
const result = await parseMessage(
[
{ type: 'anonymous', data: {} },
{ type: 'text', data: { text: 'hi' } },
] as any,
false,
);
expect(result).toHaveLength(1);
expect(result[0].type).toBe('text');
});
it('parses location as json card', async () => {
const result = await parseMessage(
[{ type: 'location', data: { lat: '39.9', lon: '116.3', title: 'Beijing' } }] as any,
false,
);
expect(result).toHaveLength(1);
expect(result[0].type).toBe('json');
expect(result[0].text).toBeDefined();
const parsed = JSON.parse(result[0].text!);
expect(parsed.app).toBe('com.tencent.map');
expect(parsed.meta.Location.lat).toBe('39.9');
});
it('parses contact as json card', async () => {
const result = await parseMessage(
[{ type: 'contact', data: { type: 'group', id: '12345' } }] as any,
false,
);
expect(result).toHaveLength(1);
expect(result[0].type).toBe('json');
expect(result[0].text).toBeDefined();
const parsed = JSON.parse(result[0].text!);
expect(parsed.meta.contact.type).toBe('group');
});
});
describe('single segment object', () => {
it('parses single segment object', async () => {
const result = await parseMessage(
{ type: 'text', data: { text: 'single' } } as any,
false,
);
expect(result).toEqual([{ type: 'text', text: 'single' }]);
});
});
describe('edge cases', () => {
it('returns empty for null', async () => {
const result = await parseMessage(null as any, false);
expect(result).toEqual([]);
});
it('returns empty for number', async () => {
const result = await parseMessage(42 as any, false);
expect(result).toEqual([]);
});
});
});
+175
View File
@@ -0,0 +1,175 @@
import { describe, it, expect } from 'vitest';
import {
WireType,
WireMessage,
decodeVarint,
encodeVarint,
encodeKey,
fieldAsInt32,
fieldAsUint32,
fieldAsString,
fieldAsBool,
} from '../src/protobuf/wire';
// Helper to build bytes from number array
function bytes(...vals: number[]): Uint8Array {
return new Uint8Array(vals);
}
describe('decodeVarint', () => {
it('decodes single-byte varint', () => {
const result = decodeVarint(bytes(0x05), 0);
expect(result).toEqual([5n, 1]);
});
it('decodes zero', () => {
const result = decodeVarint(bytes(0x00), 0);
expect(result).toEqual([0n, 1]);
});
it('decodes multi-byte varint (300)', () => {
// 300 = 0b100101100 => 0xAC 0x02
const result = decodeVarint(bytes(0xac, 0x02), 0);
expect(result).toEqual([300n, 2]);
});
it('decodes with offset', () => {
const result = decodeVarint(bytes(0xff, 0x01), 1);
expect(result).toEqual([1n, 1]);
});
it('returns null on empty data', () => {
const result = decodeVarint(bytes(), 0);
expect(result).toBeNull();
});
});
describe('encodeVarint', () => {
it('encodes small number', () => {
const out: number[] = [];
encodeVarint(5, out);
expect(out).toEqual([5]);
});
it('encodes 300', () => {
const out: number[] = [];
encodeVarint(300, out);
expect(out).toEqual([0xac, 0x02]);
});
it('encodes bigint', () => {
const out: number[] = [];
encodeVarint(300n, out);
expect(out).toEqual([0xac, 0x02]);
});
it('roundtrips', () => {
for (const val of [0, 1, 127, 128, 300, 65535, 2147483647]) {
const out: number[] = [];
encodeVarint(val, out);
const [decoded] = decodeVarint(new Uint8Array(out), 0)!;
expect(Number(decoded)).toBe(val);
}
});
});
describe('encodeKey', () => {
it('encodes field 1 varint', () => {
const out: number[] = [];
encodeKey(1, WireType.Varint, out);
expect(out).toEqual([0x08]); // (1 << 3) | 0 = 8
});
it('encodes field 2 length-delimited', () => {
const out: number[] = [];
encodeKey(2, WireType.LengthDelimited, out);
expect(out).toEqual([0x12]); // (2 << 3) | 2 = 18
});
});
describe('WireMessage', () => {
// Build a simple protobuf: field 1 = varint 150, field 2 = string "testing"
function buildSimpleMessage(): Uint8Array {
const out: number[] = [];
// field 1, varint = 150
encodeKey(1, WireType.Varint, out);
encodeVarint(150, out);
// field 2, string = "testing"
encodeKey(2, WireType.LengthDelimited, out);
const str = new TextEncoder().encode('testing');
encodeVarint(str.length, out);
out.push(...str);
return new Uint8Array(out);
}
it('decodes empty data returns null', () => {
expect(WireMessage.decode(new Uint8Array(0))).toBeNull();
});
it('decodes varint field', () => {
const msg = WireMessage.decode(buildSimpleMessage());
expect(msg).not.toBeNull();
expect(msg!.getUint32(1)).toBe(150);
});
it('decodes string field', () => {
const msg = WireMessage.decode(buildSimpleMessage());
expect(msg).not.toBeNull();
expect(msg!.getString(2)).toBe('testing');
});
it('returns null for missing fields', () => {
const msg = WireMessage.decode(buildSimpleMessage());
expect(msg!.getUint32(99)).toBeNull();
expect(msg!.getString(99)).toBeNull();
});
it('has() works', () => {
const msg = WireMessage.decode(buildSimpleMessage());
expect(msg!.has(1)).toBe(true);
expect(msg!.has(2)).toBe(true);
expect(msg!.has(3)).toBe(false);
});
it('decodes nested message', () => {
const inner: number[] = [];
encodeKey(1, WireType.Varint, inner);
encodeVarint(42, inner);
const outer: number[] = [];
encodeKey(3, WireType.LengthDelimited, outer);
encodeVarint(inner.length, outer);
outer.push(...inner);
const msg = WireMessage.decode(new Uint8Array(outer));
const nested = msg!.getMessage(3);
expect(nested).not.toBeNull();
expect(nested!.getUint32(1)).toBe(42);
});
it('handles repeated fields', () => {
const out: number[] = [];
for (const v of [10, 20, 30]) {
encodeKey(1, WireType.Varint, out);
encodeVarint(v, out);
}
const msg = WireMessage.decode(new Uint8Array(out));
const vals = msg!.getRepeatedVarint(1);
expect(vals.map(Number)).toEqual([10, 20, 30]);
});
it('field helpers work correctly', () => {
const out: number[] = [];
encodeKey(1, WireType.Varint, out);
encodeVarint(1, out); // bool true
encodeKey(2, WireType.Varint, out);
encodeVarint(0xFFFFFFFF, out); // uint32 max
const msg = WireMessage.decode(new Uint8Array(out))!;
const f1 = msg.field(1)!;
const f2 = msg.field(2)!;
expect(fieldAsBool(f1)).toBe(true);
expect(fieldAsUint32(f2)).toBe(0xFFFFFFFF);
});
});
+13
View File
@@ -0,0 +1,13 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"outDir": "./dist",
// Tests live outside src/ so we don't pin rootDir; tsc --noEmit doesn't write output anyway.
"types": ["node", "vitest/globals"],
"paths": {
"@/*": ["./src/*"]
}
},
"include": ["src/**/*", "tests/**/*"],
"exclude": ["node_modules", "dist"]
}
+84
View File
@@ -0,0 +1,84 @@
import { defineConfig, PluginOption, UserConfig } from 'vite';
import { fileURLToPath } from 'url';
import path from 'path';
import { builtinModules } from 'module';
import cp from 'vite-plugin-cp';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const repoRoot = path.resolve(__dirname, '..', '..');
const distDir = path.resolve(repoRoot, 'dist');
const runtimeDir = path.resolve(repoRoot, 'packages', 'runtime');
const nativeDir = path.resolve(runtimeDir, 'native');
// vite-plugin-cp consumes globs through globby; on Windows we must use POSIX-style separators.
const toPosix = (p: string) => p.replace(/\\/g, '/');
const external = [
'ws'
];
const nodeModules = [...builtinModules, ...builtinModules.map((m) => `node:${m}`), 'node:sqlite'].flat();
const runtimeSrc = toPosix(runtimeDir);
const nativeSrc = toPosix(nativeDir);
// Only the runtime distribution assets land in dist/.
// (.gitignore and other dev artifacts must NOT be shipped.)
const runtimeDistFiles = ['launcher.bat', 'package.json'];
const BaseConfigPlugin: PluginOption[] = [
cp({
targets: [
...runtimeDistFiles.map((file) => ({
src: `${runtimeSrc}/${file}`,
dest: distDir,
flatten: true,
})),
{ src: `${nativeSrc}/*`, dest: path.join(distDir, 'native'), flatten: true },
]
})
];
const BaseConfig = (source_map: boolean = false) => defineConfig({
resolve: {
conditions: ['node', 'default'],
alias: {
'@': path.resolve(__dirname, 'src')
}
},
build: {
sourcemap: source_map,
target: 'esnext',
minify: false,
lib: {
entry: {
index: path.resolve(__dirname, 'src/index.ts')
},
formats: ['es'],
fileName: (_, entryName) => `${entryName}.mjs`
},
rollupOptions: {
external: [...nodeModules, ...external]
},
// Emit to monorepo root dist/ so the existing release pipeline keeps working.
outDir: distDir,
// Required since outDir is outside the vite project root.
emptyOutDir: true
},
define: {
__BUILD_WEBUI__: process.env.BUILD_WEBUI === 'true'
}
});
export default defineConfig(({ mode }): UserConfig => {
if (mode === 'development') {
return {
...BaseConfig(true),
plugins: [...BaseConfigPlugin]
};
}
return {
...BaseConfig(),
plugins: [...BaseConfigPlugin]
};
});
+17
View File
@@ -0,0 +1,17 @@
import { defineConfig } from 'vitest/config';
import path from 'path';
import { fileURLToPath } from 'url';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
export default defineConfig({
resolve: {
alias: {
'@': path.resolve(__dirname, 'src')
}
},
test: {
include: ['tests/**/*.test.ts'],
environment: 'node'
}
});