Refactor bridge modules: imports & cleanup

Standardize and reorganize imports, type usages and minor formatting across the bridge modules. This commit moves protobuf helpers, makeOidbEnvelope/runOidb, OidbBase and logger imports into consistent places, reorders and groups action/contacts exports in Bridge, removes or trims file-level comments, and fixes whitespace/logic ordering in several highway, element-builder and msg-push files. These are refactors and import/type adjustments across many files under packages/core/src (bridge, highway, msg-push, webui, utils, etc.) with no intended behavioral changes.
This commit is contained in:
手瓜一十雪 committed 2026-05-20 19:35:09 +08:00
1 parent c49ae1c8d9
commit b56868878c
83 files changed
+356 -919

No files matched your search

+1 -6
View File
@@ -1,11 +1,6 @@
// Tier-2 napcat-parity actions ported as pure oidb calls. Each function
// here corresponds to one napcat PacketApi.pkt.operation.* entry; the
// schemas live in proto/oidb-action.ts. Nothing in this file touches
// the NTQQ NodeIKernel — every wire trip is one runOidb round-trip.
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { Bridge } from '../bridge';
import { runOidb, makeOidbEnvelope } from '../bridge-oidb';
import { makeOidbEnvelope, runOidb } from '../bridge-oidb';
import { OidbBase } from '../proto/proton/oidb';
import type {
OidbGroupTodo,
+6 -11
View File
@@ -1,16 +1,11 @@
// Forward-message upload / download via the long-message service.
// Uses gzipped protobufs over `trpc.group.long_msg_interface`.
// An in-memory cache keeps res_ids stable across rapid re-fetches
// from the same OneBot client (avoids re-decoding the same payload).
import type { Bridge } from '../bridge';
import { gunzipSync, gzipSync } from 'zlib';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import { randomUUID } from 'crypto';
import { protobuf_encode, protobuf_decode } from '@snowluma/proton';
import { buildSendElems } from '../element-builder';
import { parseMsgPush } from '../msg-push';
import type { ForwardNodePayload, MessageElement } from '../events';
import { gunzipSync, gzipSync } from 'zlib';
import type { PacketInfo } from '../../protocol/types';
import type { Bridge } from '../bridge';
import { buildSendElems } from '../element-builder';
import type { ForwardNodePayload, MessageElement } from '../events';
import { parseMsgPush } from '../msg-push';
import type {
LongMsgResult,
RecvLongMsgReq,
+2 -6
View File
@@ -1,16 +1,12 @@
// Friend-list operations: accept/reject add request, delete, set the
// local remark label. Each one resolves a UID first because the OIDB
// protocol uses opaque UIDs rather than QQ uin numbers.
import { protobuf_encode } from '@snowluma/proton';
import type { Bridge } from '../bridge';
import { runOidb, makeOidbEnvelope } from '../bridge-oidb';
import { makeOidbEnvelope, runOidb } from '../bridge-oidb';
import { OidbBase } from '../proto/proton/oidb';
import type {
OidbDeleteFriend,
OidbFriendRequestAction,
OidbSetFriendRemark,
} from '../proto/proton/oidb-actions/base';
import { OidbBase } from '../proto/proton/oidb';
export async function setFriendAddRequest(bridge: Bridge, uidOrFlag: string, approve: boolean): Promise<void> {
let targetUid = uidOrFlag;
@@ -1,11 +1,6 @@
// Group admin actions: mute/kick/leave/role/profile + join-request approval.
// Every function ultimately routes through one OIDB schema; the function
// names match the OneBot action names (set_group_kick, set_group_ban, ...)
// so callers can grep across the two layers.
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { Bridge } from '../bridge';
import { runOidb, makeOidbEnvelope } from '../bridge-oidb';
import { makeOidbEnvelope, runOidb } from '../bridge-oidb';
import { OidbBase } from '../proto/proton/oidb';
import type {
Oidb0x89a_0AddOption,
@@ -1,22 +1,14 @@
// Group album actions via TRPC protocol.
//
// Unlike the OIDB action family, these endpoints speak raw TRPC
// (service command `QunAlbum.trpc.qzone.webapp_qun_*`) without an
// `OidbBase<T>` envelope. We hit `bridge.sendRawPacket` directly with
// proton-encoded bodies and decode the responses through proton's
// monomorphized codecs.
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { Bridge } from '../bridge';
import { protobuf_encode, protobuf_decode } from '@snowluma/proton';
import type {
GetMediaListRequest,
GetMediaListResponse,
DeleteMediasRequest,
DeleteMediasResponse,
DoQunCommentRequest,
DoQunCommentResponse,
DoQunLikeRequest,
DoQunLikeResponse,
DeleteMediasRequest,
DeleteMediasResponse,
GetMediaListRequest,
GetMediaListResponse,
} from '../proto/proton/oidb-actions/group-album';
export interface GroupAlbumMediaResult {
+8 -15
View File
@@ -1,15 +1,12 @@
// Group + private file operations: upload (with highway fast-path),
// folder management, file listing, file/media URL fetch. All upload
// paths share the same shape (resolve target → OIDB metadata exchange
// → highway HTTP PUT if the server says we must), but the OIDB schemas
// and field layouts differ enough between group and private that they
// stay as separate functions.
import type { Bridge } from '../bridge';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import { runOidb, makeOidbEnvelope } from '../bridge-oidb';
import { toHexUpper } from '../../utils/hex';
import { createLogger } from '../../utils/logger';
import type { Bridge } from '../bridge';
import { makeOidbEnvelope, runOidb } from '../bridge-oidb';
import { fetchHighwaySession, uploadHighwayHttp } from '../highway/highway-client';
import { computeHashes, computeMd5, FILE_UPLOAD_MAX_BYTES, loadBinarySource } from '../highway/utils';
import type { FileUploadExt } from '../proto/proton/highway';
import { OidbBase } from '../proto/proton/oidb';
import type {
OidbGroupFileCountViewReq,
OidbGroupFileCountViewResp,
@@ -22,18 +19,14 @@ import type {
OidbGroupSendFileReq,
} from '../proto/proton/oidb-actions/group-file';
import type {
NTV2RichMediaReq,
NTV2RichMediaResp,
OidbPrivateFileDownloadReq,
OidbPrivateFileDownloadResp,
OidbPrivateFileUploadReq,
OidbPrivateFileUploadResp,
NTV2RichMediaReq,
NTV2RichMediaResp,
} from '../proto/proton/oidb-actions/media';
import type { FileUploadExt } from '../proto/proton/highway';
import { toHexUpper } from '../../utils/hex';
import { createLogger } from '../../utils/logger';
import { ensureRetCodeZero, resolveSelfUid, toInt, type MediaIndexNode } from './shared';
import { OidbBase } from '../proto/proton/oidb';
const log = createLogger('GroupFile');
@@ -1,13 +1,8 @@
// Operations targeting an existing message: recall (group / private),
// mark-as-read (group / private), and the "essence" highlight toggle.
// All of these take a message identifier and modify server-side state
// without producing a downstream observable event.
import type { Bridge } from '../bridge';
import { runOidb, makeOidbEnvelope } from '../bridge-oidb';
import type { C2CRecallRequest, GroupRecallRequest, OidbEssence, SsoReadedReportReq } from '../proto/proton/oidb-actions/base';
import { protobuf_encode } from '@snowluma/proton';
import type { Bridge } from '../bridge';
import { makeOidbEnvelope, runOidb } from '../bridge-oidb';
import { OidbBase } from '../proto/proton/oidb';
import type { C2CRecallRequest, GroupRecallRequest, OidbEssence, SsoReadedReportReq } from '../proto/proton/oidb-actions/base';
export async function recallGroupMessage(bridge: Bridge, groupId: number, sequence: number): Promise<void> {
const request = protobuf_encode<GroupRecallRequest>({
@@ -1,10 +1,7 @@
// Lightweight social-interaction actions: poke, like, emoji reaction,
// and the related read-side "who reacted with X" query. None of these
// edit message content — they're purely social signals.
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { Bridge } from '../bridge';
import { runOidb, makeOidbEnvelope } from '../bridge-oidb';
import { makeOidbEnvelope, runOidb } from '../bridge-oidb';
import { OidbBase } from '../proto/proton/oidb';
import type {
Oidb0x9083Req,
Oidb0x9083Resp,
@@ -12,7 +9,6 @@ import type {
OidbLike,
OidbPoke,
} from '../proto/proton/oidb-actions/base';
import { OidbBase } from '../proto/proton/oidb';
export async function sendPoke(bridge: Bridge, isGroup: boolean, peerUin: number, targetUin?: number): Promise<void> {
const env = makeOidbEnvelope<OidbPoke>(0xED3, 1, {
+3 -7
View File
@@ -1,9 +1,7 @@
// Grab-bag: action verbs that don't share a theme with anything else.
// Kept together so the directory stays small; if any of these grow new
// related siblings, lift the whole group out into its own file.
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { Bridge } from '../bridge';
import { runOidb, makeOidbEnvelope } from '../bridge-oidb';
import { makeOidbEnvelope, runOidb } from '../bridge-oidb';
import { OidbBase } from '../proto/proton/oidb';
import type {
MiniAppShareReq,
MiniAppShareResp,
@@ -14,8 +12,6 @@ import type {
Oidb0xeb7Req,
Oidb0xeb7Resp,
} from '../proto/proton/oidb-actions/base';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import { OidbBase } from '../proto/proton/oidb';
export async function translateEn2Zh(
bridge: Bridge,
+3 -7
View File
@@ -1,11 +1,9 @@
// Operations that touch the bot's own profile / status, plus the
// related queries about my profile likes and unidirectional friends.
// All of these read/write fields on the self-uin via OIDB.
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { Bridge } from '../bridge';
import { runOidb, makeOidbEnvelope } from '../bridge-oidb';
import { makeOidbEnvelope, runOidb } from '../bridge-oidb';
import { fetchHighwaySession, uploadHighwayHttp } from '../highway/highway-client';
import { computeHashes, loadBinarySource } from '../highway/utils';
import { OidbBase } from '../proto/proton/oidb';
import type {
FaceroamOpReq,
FaceroamOpResp,
@@ -23,8 +21,6 @@ import type {
SetStatusResp,
} from '../proto/proton/oidb-actions/base';
import { resolveSelfUid } from './shared';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import { OidbBase } from '../proto/proton/oidb';
// ─────────────── status / profile setters ───────────────
@@ -1,7 +1,3 @@
// Shared private helpers for the action modules. None of this is part
// of the public Bridge API; keeping it here avoids re-importing the
// same five-line utility from every themed file.
import type { Bridge } from '../bridge';
/**
+8 -11
View File
@@ -1,30 +1,27 @@
// 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 { runOidb, makeOidbEnvelope } from './bridge-oidb';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { Bridge, DownloadRKeyInfo } from './bridge';
import { makeOidbEnvelope, runOidb } from './bridge-oidb';
import type {
OidbBase,
OidbSvcTrpcTcp0x10C0Response,
OidbSvcTrpcTcp0xFD4_1Response,
OidbSvcTrpcTcp0xFE5_2Response,
OidbSvcTrpcTcp0xFE7_3Response,
OidbSvcTrpcTcp0x10C0Response,
OidbBase,
} from './proto/proton/oidb';
import type {
AvatarInfo,
OidbFriendListRequest,
OidbGroupListRequest,
OidbGroupMemberListRequest,
OidbGroupRequestList,
OidbUserInfoRequest,
OidbUserInfoResponse,
OidbGroupRequestList,
AvatarInfo,
} from './proto/proton/oidb-actions/base';
import type {
NTV2RichMediaReq,
NTV2RichMediaResp,
} from './proto/proton/oidb-actions/media';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { FriendInfo, GroupMemberInfo, GroupRequestInfo, QQGroupInfo, UserProfileInfo } from './qq-info';
// ---------------------------------------------------------------------------
// Helpers
+14 -21
View File
@@ -1,30 +1,23 @@
// BridgeInterface — the surface OneBot (and any other external consumer)
// is allowed to see. The concrete Bridge class additionally exposes raw
// protocol primitives (sendRawPacket, packet dispatch, PID management)
// used by the in-tree action / contacts / highway modules; those internal
// methods deliberately do NOT appear here so that callers depending on
// the interface stay decoupled from the wire format.
//
// Every method below has a matching signature on Bridge; `Bridge
// implements BridgeInterface` is the compile-time enforcement.
import type { BridgeEventBus } from './event-bus';
import type { IdentityService } from './identity-service';
import type {
FriendInfo, QQGroupInfo, GroupMemberInfo,
UserProfileInfo, GroupRequestInfo,
} from './qq-info';
import type { MessageElement, ForwardNodePayload } from './events';
import type { SendPacketResult } from '../protocol/packet-sender';
import type { GroupFilesResult } from './actions/group-file';
import type { MediaIndexNode } from './actions/shared';
import type { WebHonorType } from './web/group-honor';
import type {
SendMessageReceipt,
DownloadRKeyInfo,
ClientKeyInfo,
DownloadRKeyInfo,
SendMessageReceipt,
UploadedFileMeta,
} from './bridge';
import type { SendPacketResult } from '../protocol/packet-sender';
import type { BridgeEventBus } from './event-bus';
import type { ForwardNodePayload, MessageElement } from './events';
import type { IdentityService } from './identity-service';
import type {
FriendInfo,
GroupMemberInfo,
GroupRequestInfo,
QQGroupInfo,
UserProfileInfo,
} from './qq-info';
import type { WebHonorType } from './web/group-honor';
export interface BridgeInterface {
// ─── Shared state ───
+5 -21
View File
@@ -1,21 +1,5 @@
// One deep entry point for a single OIDB round-trip: dispatch a
// pre-encoded envelope via Bridge.sendRawPacket, validate the envelope
// retCode, and return the raw response bytes.
//
// History note. The legacy implementation used a runtime
// `makeOidbBaseSchema(InnerSchema)` factory and ran a runtime
// schema-walking encoder. Proton is compile-time, so the envelope is
// the generic interface `OidbBase<T>` (proto/proton/oidb.ts). Proton's
// wrapper-binding requires *pass-through* wrappers (the wrapper's first
// arg must be forwarded unchanged to the inner codec — see
// proton/src/transform/replacer.ts), so this file exposes thin
// pass-through helpers (`encodeOidbEnv<T>` / `decodeOidbEnv<T>`) that
// proton monomorphizes at every call site. `runOidb` itself is
// non-generic — it just sends pre-encoded bytes and peeks at the
// envelope retCode via the non-generic `OidbBaseMeta` view.
import type { Bridge } from './bridge';
import { protobuf_decode } from '@snowluma/proton';
import type { Bridge } from './bridge';
import type { OidbBase, OidbBaseMeta } from './proto/proton/oidb';
/**
@@ -35,12 +19,12 @@ export function makeOidbEnvelope<T>(
isUid: boolean = false,
): OidbBase<T> {
return {
command: oidbCmd,
command: oidbCmd,
subCommand: subCmd,
errorCode: 0,
errorCode: 0,
body,
errorMsg: '',
reserved: isUid ? 1 : 0,
errorMsg: '',
reserved: isUid ? 1 : 0,
};
}
+115 -118
View File
@@ -1,143 +1,140 @@
// 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, MessageElement } from './events';
import type { FriendInfo, QQGroupInfo, GroupMemberInfo, UserProfileInfo, GroupRequestInfo } from './qq-info';
import { MSG_PUSH_CMD, parseMsgPush } from './msg-push';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { PacketSender, SendPacketResult } from '../protocol/packet-sender';
import { protobuf_encode, protobuf_decode } from '@snowluma/proton';
import { buildSendElems } from './element-builder';
import { IdentityService } from './identity-service';
import type { PacketInfo } from '../protocol/types';
import type { BridgeInterface } from './bridge-interface';
import { buildSendElems } from './element-builder';
import type { ForwardNodePayload, MessageElement } from './events';
import { IdentityService } from './identity-service';
import { MSG_PUSH_CMD, parseMsgPush } from './msg-push';
import { IncomingPacketPipeline, type CmdParser } from './packet-pipeline';
import type {
SendMessageRequest,
SendMessageResponse,
} from './proto/proton/action';
import type { FileExtra } from './proto/proton/message';
import type { FriendInfo, GroupMemberInfo, GroupRequestInfo, QQGroupInfo, UserProfileInfo } from './qq-info';
// Delegated modules
import {
fetchFriendList as fetchFriendList_,
fetchGroupList as fetchGroupList_,
fetchGroupMemberList as fetchGroupMemberList_,
fetchUserProfile as fetchUserProfile_,
fetchGroupRequests as fetchGroupRequests_,
fetchDownloadRKeys as fetchDownloadRKeys_,
} from './bridge-contacts';
import type { WebHonorType } from './web/group-honor';
import {
muteGroupMember as muteGroupMember_,
muteGroupAll as muteGroupAll_,
setGroupAddOption as setGroupAddOption_,
setGroupSearch as setGroupSearch_,
setGroupAddRequest as setGroupAddRequest_,
kickGroupMember as kickGroupMember_,
kickGroupMembers as kickGroupMembers_,
leaveGroup as leaveGroup_,
setGroupAdmin as setGroupAdmin_,
setGroupCard as setGroupCard_,
setGroupName as setGroupName_,
setGroupSpecialTitle as setGroupSpecialTitle_,
setGroupRemark as setGroupRemark_,
getGroupAtAllRemain as getGroupAtAllRemain_,
} from './actions/group-admin';
import {
uploadGroupFile as uploadGroupFile_,
uploadPrivateFile as uploadPrivateFile_,
sendGroupFileMessage as sendGroupFileMessage_,
fetchGroupFiles as fetchGroupFiles_,
fetchGroupFileUrl as fetchGroupFileUrl_,
fetchPrivateFileUrl as fetchPrivateFileUrl_,
fetchGroupPttUrlByNode as fetchGroupPttUrlByNode_,
fetchPrivatePttUrlByNode as fetchPrivatePttUrlByNode_,
fetchGroupVideoUrlByNode as fetchGroupVideoUrlByNode_,
fetchPrivateVideoUrlByNode as fetchPrivateVideoUrlByNode_,
deleteGroupFile as deleteGroupFile_,
moveGroupFile as moveGroupFile_,
createGroupFileFolder as createGroupFileFolder_,
deleteGroupFileFolder as deleteGroupFileFolder_,
renameGroupFileFolder as renameGroupFileFolder_,
fetchGroupFileCount as fetchGroupFileCount_,
} from './actions/group-file';
import {
recallGroupMessage as recallGroupMessage_,
recallPrivateMessage as recallPrivateMessage_,
markPrivateMessageRead as markGroupMsgAsRead_,
markGroupMessageRead as markPrivateMsgAsRead_,
setGroupEssence as setGroupEssence_,
} from './actions/group-message';
import {
sendPoke as sendPoke_,
sendLike as sendLike_,
setGroupReaction as setGroupReaction_,
getEmojiLikes as getEmojiLikes_,
} from './actions/interaction';
import {
uploadForwardNodes as uploadForwardNodes_,
fetchForwardNodes as fetchForwardNodes_,
} from './actions/forward';
import {
setFriendAddRequest as setFriendAddRequest_,
deleteFriend as deleteFriend_,
setFriendRemark as setFriendRemark_,
} from './actions/friend';
import {
setOnlineStatus as setOnlineStatus_,
setDiyOnlineStatus as setDiyOnlineStatus_,
setProfile as setProfile_,
setSelfLongNick as setSelfLongNick_,
setInputStatus as setInputStatus_,
setAvatar as setAvatar_,
setGroupAvatar as setGroupAvatar_,
fetchCustomFace as fetchCustomFace_,
getProfileLike as getProfileLike_,
getUnidirectionalFriendList as getUnidirectionalFriendList_,
} from './actions/profile';
import {
translateEn2Zh as translateEn2Zh_,
getMiniAppArk as getMiniAppArk_,
clickInlineKeyboardButton as clickInlineKeyboardButton_,
sendGroupSign as sendGroupSign_,
} from './actions/misc';
import {
setGroupTodo as setGroupTodo_,
completeGroupTodo as completeGroupTodo_,
cancelGroupTodo as cancelGroupTodo_,
getStrangerStatus as getStrangerStatus_,
fetchAiVoiceList as fetchAiVoiceList_,
fetchAiVoice as fetchAiVoice_,
AiVoiceChatType,
cancelGroupTodo as cancelGroupTodo_,
completeGroupTodo as completeGroupTodo_,
fetchAiVoice as fetchAiVoice_,
fetchAiVoiceList as fetchAiVoiceList_,
getStrangerStatus as getStrangerStatus_,
setGroupTodo as setGroupTodo_,
type AiVoiceCategory,
type AiVoiceChatType as AiVoiceChatTypeT,
type StrangerStatus,
} from './actions/extras';
export { AiVoiceChatType };
export type { AiVoiceCategory, StrangerStatus };
import {
getGroupHonorInfo as getGroupHonorInfo_,
forceFetchClientKey as forceFetchClientKey_,
getGroupEssence as getGroupEssence_,
getGroupEssenceAll as getGroupEssenceAll_,
sendGroupNotice as sendGroupNotice_,
getGroupNotice as getGroupNotice_,
deleteGroupNoticeByFid as deleteGroupNotice_,
getCookiesStr as getCookiesStr_,
getCsrfToken as getCsrfToken_,
getCredentials as getCredentials_,
getGroupAlbumListWeb as getGroupAlbumListWeb_,
uploadImageToGroupAlbumWeb as uploadImageToGroupAlbumWeb_,
} from './web-actions';
import { getGroupAlbumMediaList as getGroupAlbumMediaList_,
fetchForwardNodes as fetchForwardNodes_,
uploadForwardNodes as uploadForwardNodes_,
} from './actions/forward';
import {
deleteFriend as deleteFriend_,
setFriendAddRequest as setFriendAddRequest_,
setFriendRemark as setFriendRemark_,
} from './actions/friend';
import {
getGroupAtAllRemain as getGroupAtAllRemain_,
kickGroupMember as kickGroupMember_,
kickGroupMembers as kickGroupMembers_,
leaveGroup as leaveGroup_,
muteGroupAll as muteGroupAll_,
muteGroupMember as muteGroupMember_,
setGroupAddOption as setGroupAddOption_,
setGroupAddRequest as setGroupAddRequest_,
setGroupAdmin as setGroupAdmin_,
setGroupCard as setGroupCard_,
setGroupName as setGroupName_,
setGroupRemark as setGroupRemark_,
setGroupSearch as setGroupSearch_,
setGroupSpecialTitle as setGroupSpecialTitle_,
} from './actions/group-admin';
import {
commentGroupAlbumMedia as commentGroupAlbumMedia_,
likeGroupAlbumMedia as likeGroupAlbumMedia_,
deleteGroupAlbumMedia as deleteGroupAlbumMedia_,
getGroupAlbumMediaList as getGroupAlbumMediaList_,
likeGroupAlbumMedia as likeGroupAlbumMedia_,
} from './actions/group-album';
import type { GroupFilesResult } from './actions/group-file';
import {
createGroupFileFolder as createGroupFileFolder_,
deleteGroupFile as deleteGroupFile_,
deleteGroupFileFolder as deleteGroupFileFolder_,
fetchGroupFileCount as fetchGroupFileCount_,
fetchGroupFiles as fetchGroupFiles_,
fetchGroupFileUrl as fetchGroupFileUrl_,
fetchGroupPttUrlByNode as fetchGroupPttUrlByNode_,
fetchGroupVideoUrlByNode as fetchGroupVideoUrlByNode_,
fetchPrivateFileUrl as fetchPrivateFileUrl_,
fetchPrivatePttUrlByNode as fetchPrivatePttUrlByNode_,
fetchPrivateVideoUrlByNode as fetchPrivateVideoUrlByNode_,
moveGroupFile as moveGroupFile_,
renameGroupFileFolder as renameGroupFileFolder_,
sendGroupFileMessage as sendGroupFileMessage_,
uploadGroupFile as uploadGroupFile_,
uploadPrivateFile as uploadPrivateFile_,
} from './actions/group-file';
import {
markPrivateMessageRead as markGroupMsgAsRead_,
markGroupMessageRead as markPrivateMsgAsRead_,
recallGroupMessage as recallGroupMessage_,
recallPrivateMessage as recallPrivateMessage_,
setGroupEssence as setGroupEssence_,
} from './actions/group-message';
import {
getEmojiLikes as getEmojiLikes_,
sendLike as sendLike_,
sendPoke as sendPoke_,
setGroupReaction as setGroupReaction_,
} from './actions/interaction';
import {
clickInlineKeyboardButton as clickInlineKeyboardButton_,
getMiniAppArk as getMiniAppArk_,
sendGroupSign as sendGroupSign_,
translateEn2Zh as translateEn2Zh_,
} from './actions/misc';
import {
fetchCustomFace as fetchCustomFace_,
getProfileLike as getProfileLike_,
getUnidirectionalFriendList as getUnidirectionalFriendList_,
setAvatar as setAvatar_,
setDiyOnlineStatus as setDiyOnlineStatus_,
setGroupAvatar as setGroupAvatar_,
setInputStatus as setInputStatus_,
setOnlineStatus as setOnlineStatus_,
setProfile as setProfile_,
setSelfLongNick as setSelfLongNick_,
} from './actions/profile';
import type { MediaIndexNode } from './actions/shared';
import {
fetchDownloadRKeys as fetchDownloadRKeys_,
fetchFriendList as fetchFriendList_,
fetchGroupList as fetchGroupList_,
fetchGroupMemberList as fetchGroupMemberList_,
fetchGroupRequests as fetchGroupRequests_,
fetchUserProfile as fetchUserProfile_,
} from './bridge-contacts';
import { BridgeEventBus } from './event-bus';
import {
deleteGroupNoticeByFid as deleteGroupNotice_,
forceFetchClientKey as forceFetchClientKey_,
getCookiesStr as getCookiesStr_,
getCredentials as getCredentials_,
getCsrfToken as getCsrfToken_,
getGroupAlbumListWeb as getGroupAlbumListWeb_,
getGroupEssence as getGroupEssence_,
getGroupEssenceAll as getGroupEssenceAll_,
getGroupHonorInfo as getGroupHonorInfo_,
getGroupNotice as getGroupNotice_,
sendGroupNotice as sendGroupNotice_,
uploadImageToGroupAlbumWeb as uploadImageToGroupAlbumWeb_,
} from './web-actions';
import type { WebHonorType } from './web/group-honor';
export { AiVoiceChatType };
export type { AiVoiceCategory, StrangerStatus };
export interface SendMessageReceipt {
messageId: number;
@@ -663,7 +660,7 @@ export class Bridge implements BridgeInterface {
async getGroupHonorInfo(groupId: number, type: WebHonorType | string): Promise<any> {
return getGroupHonorInfo_(this, groupId, type);
}
async forceFetchClientKey(): Promise<ClientKeyInfo> { return forceFetchClientKey_(this)}
async forceFetchClientKey(): Promise<ClientKeyInfo> { return forceFetchClientKey_(this) }
async getGroupEssence(groupId: number, pageStart: number = 0, pageLimit: number = 50): Promise<any> {
return getGroupEssence_(this, groupId, pageStart, pageLimit);
}
+10 -14
View File
@@ -1,19 +1,15 @@
// Element Builder — converts internal MessageElement[] into proto Elem objects
// for encoding with protobuf_encode<SendMessageRequest>.
// Port of src/bridge/src/bridge_messages.cpp build_send_elems()
import { protobuf_encode } from '@snowluma/proton';
import type { Bridge } from './bridge';
import type { MessageElement } from './events';
import { protobuf_encode } from '@snowluma/proton';
import type {
MentionExtraSend,
MarkdownData,
} from './proto/proton/action';
import type { Elem, GroupFileExtra } from './proto/proton/element';
import { uploadImageMsgInfo } from './highway/image-upload';
import { hexToBytes } from './highway/pipeline';
import { uploadPttMsgInfo } from './highway/ptt-upload';
import { uploadVideoMsgInfo } from './highway/video-upload';
import { hexToBytes } from './highway/pipeline';
import type {
MarkdownData,
MentionExtraSend,
} from './proto/proton/action';
import type { Elem, GroupFileExtra } from './proto/proton/element';
type ProtoElem = Partial<Elem>;
@@ -91,11 +87,11 @@ function makeMentionElem(element: MessageElement, ctx?: SendContext): ProtoElem
function makeReplyElem(element: MessageElement): ProtoElem {
const seq = element.replySeq! & 0xFFFFFFFF;
const srcMsg: any = {
origSeqs: [seq],
};
// Add additional fields if available for better reply display
if (element.replySenderUin) {
srcMsg.senderUin = BigInt(element.replySenderUin);
@@ -103,7 +99,7 @@ function makeReplyElem(element: MessageElement): ProtoElem {
if (element.replyTime) {
srcMsg.time = element.replyTime;
}
return { srcMsg };
}
+1 -12
View File
@@ -1,16 +1,5 @@
// Typed, per-kind pub/sub for bridge-level events.
//
// Replaces the single-callback firehose where every consumer received every
// event variant and had to switch on `event.kind`. Now each downstream
// concern (OneBot dispatch, member cache refresh, etc.) registers exactly
// the kinds it cares about, much closer to NapCat's per-listener pattern.
//
// `emit` is fire-and-forget: subscribers can be sync or async; async
// rejections are surfaced via `Promise.allSettled` and reported through the
// optional `onError` hook so one buggy handler never starves the others.
import type { QQEventVariant } from './events';
import { createLogger } from '../utils/logger';
import type { QQEventVariant } from './events';
type EventKind = QQEventVariant['kind'];
type EventOf<K extends EventKind> = Extract<QQEventVariant, { kind: K }>;
-3
View File
@@ -1,6 +1,3 @@
// 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;
@@ -1,14 +1,7 @@
// FFmpeg native addon wrapper — port of NapCat's FFmpegAddonAdapter.
// No fallback: throws if the addon isn't available on this platform/arch.
//
// The addon is shipped under `native/ffmpeg/ffmpegAddon.<platform>.<arch>.node`
// to match the layout used by the upstream NapCat build so the binaries
// can be dropped in as-is.
import crypto from 'crypto';
import fs from 'fs';
import os from 'os';
import path from 'path';
import crypto from 'crypto';
import { fileURLToPath } from 'url';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
@@ -1,17 +1,14 @@
// Highway HTTP client: session fetch and chunked binary upload.
// Port of src/bridge/src/highway_client.cpp
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import net from 'net';
import type { Bridge } from '../bridge';
import { protobuf_encode, protobuf_decode } from '@snowluma/proton';
import type {
HttpConn0x6FF501Request,
HttpConn0x6FF501Response,
NTV2RichMediaHighwayExt,
ReqDataHighwayHead,
RespDataHighwayHead,
NTV2RichMediaHighwayExt,
} from '../proto/proton/highway';
import { packHighwayFrame, unpackHighwayFrame, computeMd5 } from './utils';
import { computeMd5, packHighwayFrame, unpackHighwayFrame } from './utils';
const HIGHWAY_APP_ID = 1600001604;
const HIGHWAY_BLOCK_SIZE = 1024 * 1024;
@@ -1,13 +1,6 @@
// Image upload: load the source, run NTV2 upload + (optional) Highway PUT,
// return the encoded MsgInfo for the outgoing commonElem.
//
// Shared OIDB envelope + response handling + Highway PUT live in
// pipeline.ts; this file just supplies the image-specific bits (format
// detection, picFormat, bizType, command ids).
import { createLogger } from '../../utils/logger';
import type { Bridge } from '../bridge';
import type { MessageElement } from '../events';
import { createLogger } from '../../utils/logger';
import { GROUP_IMAGE_CMD_ID, PRIVATE_IMAGE_CMD_ID } from './highway-client';
import {
finalizeMediaMsgInfo,
+4 -21
View File
@@ -1,32 +1,15 @@
// Shared NTV2 rich-media upload pipeline.
//
// Image, PTT, and video all follow the same three-step shape:
// 1. send a NTV2UploadRichMediaReq OIDB packet describing the file(s),
// 2. for any sub-file the server signals it wants (uKey present in the
// response), do a Highway HTTP PUT of the bytes,
// 3. encode the returned msgInfo into the bytes that go inside a
// commonElem on the outgoing message.
//
// The per-format files (image-upload, ptt-upload, video-upload) used to
// each implement steps 1 / 2 / 3 inline with subtle drift between them.
// This module pulls the envelope, response decoding, error handling, and
// the Highway PUT loop into one place, leaving each format file with
// only: how to load the file, how to fill the type-specific fileInfo +
// extBizInfo, and which command ids to use.
import crypto from 'crypto';
import type { Bridge } from '../bridge';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import crypto from 'crypto';
import { createLogger } from '../../utils/logger';
import type { Bridge } from '../bridge';
import { makeOidbEnvelope } from '../bridge-oidb';
import type {
EncodableMediaMsgInfo,
NTV2UploadRichMediaReq,
NTV2UploadRichMediaResp,
} from '../proto/proton/highway';
import { buildHighwayExtend, fetchHighwaySession, uploadHighwayHttp } from './highway-client';
import { createLogger } from '../../utils/logger';
import { OidbBase } from '../proto/proton/oidb';
import { buildHighwayExtend, fetchHighwaySession, uploadHighwayHttp } from './highway-client';
const moduleLog = createLogger('Highway');
+3 -11
View File
@@ -1,26 +1,18 @@
// Voice (PTT) upload: stage the audio bytes (convert to NT silk if
// necessary), run NTV2 upload + (optional) Highway PUT, return the
// encoded MsgInfo for the outgoing commonElem.
//
// Shared OIDB envelope + response handling + Highway PUT live in
// pipeline.ts; this file owns the silk transcoding, the temp-file
// cleanup hooks, and the PTT-specific OIDB fields.
import crypto from 'crypto';
import fs from 'fs';
import path from 'path';
import crypto from 'crypto';
import { createLogger } from '../../utils/logger';
import type { Bridge } from '../bridge';
import type { MessageElement } from '../events';
import { computeHashes, loadBinarySource, resolveLocalFilePath } from './utils';
import { defaultPttTempDir, encodeSilk } from './ffmpeg-addon';
import { createLogger } from '../../utils/logger';
import {
finalizeMediaMsgInfo,
hexToBytes,
runNtv2Upload,
type MediaSubFileUpload,
} from './pipeline';
import { computeHashes, loadBinarySource, resolveLocalFilePath } from './utils';
const moduleLog = createLogger('Highway.Ptt');
+6 -9
View File
@@ -1,6 +1,3 @@
// 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';
@@ -193,7 +190,7 @@ export function detectImageFormat(bytes: Uint8Array): ImageFormat {
// PNG
if (bytes.length >= 24 &&
bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4E && bytes[3] === 0x47) {
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 };
@@ -201,8 +198,8 @@ export function detectImageFormat(bytes: Uint8Array): ImageFormat {
// 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) {
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 };
@@ -217,8 +214,8 @@ export function detectImageFormat(bytes: Uint8Array): ImageFormat {
// 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) {
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);
@@ -251,7 +248,7 @@ export function detectImageFormat(bytes: Uint8Array): ImageFormat {
// (DAC). The previous `(marker & 0xFC) === 0xC0` check accepted DHT
// and friends, then misread Huffman table bytes as image dimensions.
const isSof = marker >= 0xC0 && marker <= 0xCF
&& marker !== 0xC4 && marker !== 0xC8 && marker !== 0xCC;
&& marker !== 0xC4 && marker !== 0xC8 && marker !== 0xCC;
if (isSof && segLen >= 7 && offset + 9 <= bytes.length) {
height = readBE16(bytes, offset + 5);
width = readBE16(bytes, offset + 7);
@@ -1,33 +1,23 @@
// Video upload: stage the source video and a thumbnail (extracted via
// ffmpeg if not supplied), run NTV2 upload + (optional) Highway PUTs for
// both files, return the encoded MsgInfo for the outgoing commonElem.
//
// Shared OIDB envelope + response handling + Highway PUT loop live in
// pipeline.ts; this file owns the ffmpeg thumb extraction, the 1 MB
// streaming sha1 used by main-video Highway uploads, and the
// video-specific OIDB fields (uploadInfo has TWO entries — main + thumb).
import crypto from 'crypto';
import fs from 'fs';
import os from 'os';
import path from 'path';
import crypto from 'crypto';
import { createLogger } from '../../utils/logger';
import type { Bridge } from '../bridge';
import type { MessageElement } from '../events';
import {
computeHashes,
detectImageFormat,
loadBinarySource,
resolveLocalFilePath,
} from './utils';
import { getFFmpegAddon } from './ffmpeg-addon';
import { createLogger } from '../../utils/logger';
import {
finalizeMediaMsgInfo,
hexToBytes,
runNtv2Upload,
type MediaSubFileUpload,
} from './pipeline';
import {
computeHashes,
detectImageFormat,
loadBinarySource,
resolveLocalFilePath,
} from './utils';
const moduleLog = createLogger('Highway.Video');
+2 -7
View File
@@ -1,13 +1,8 @@
// BridgeManager — manages per-UIN Bridge sessions.
// onPacket() is the single entry point for parsed hook packets;
// HookManager wires it as the default packet sink for every HookSession.
// Port of src/bridge/include/bridge/manager.h + src/bridge/src/manager.cpp
import type { PacketSender } from '../protocol/packet-sender';
import type { PacketInfo } from '../protocol/types';
import { createLogger } from '../utils/logger';
import { Bridge } from './bridge';
import { IdentityService } from './identity-service';
import type { PacketSender } from '../protocol/packet-sender';
import { createLogger } from '../utils/logger';
export type SessionStartedCallback = (uin: string, bridge: Bridge) => void;
export type SessionClosedCallback = (uin: string) => void;
+1 -5
View File
@@ -1,11 +1,7 @@
// MsgPushContext — the decoded envelope fields every decoder may need.
// One unified shape: notice decoders pick from `content`, message decoders
// pick from `body` / `responseHead`. Decoders ignore fields they don't need.
import { protobuf_decode } from '@snowluma/proton';
import type { ContentHead, MessageBody, PushMsg, ResponseHead } from '../proto/proton/message';
import type { PacketInfo } from '../../protocol/types';
import type { IdentityService } from '../identity-service';
import type { ContentHead, MessageBody, PushMsg, ResponseHead } from '../proto/proton/message';
export type PushMsgBody = MessageBody;
export type PushMsgResponseHead = ResponseHead;
@@ -1,36 +1,27 @@
// Handles Event0x210 wrapper (528). Internal switch on subType dispatches
// to FriendRequest (35) / FriendRecall (138, 139) / NewFriend
// (179, 226) / FriendPoke (290).
import { protobuf_decode } from '@snowluma/proton';
// Proto types imported unaliased — proton's import-resolver registers
// `importedTypeSources` keyed on the *imported* name. If we also did
// `import type { FriendRecall } from '../../events'` it would shadow
// the proto-side mapping (last-write-wins), point the resolver at the
// event-side file which has no `pb<>` schema, and the codec would
// never get generated — `protobuf_decode<FriendRecall>(...)` then
// falls through to the runtime fallback and throws (silently caught
// by `MsgPushRegistry.decode`). The event-side colliding names are
// re-derived from `QQEventVariant` below via `Extract` instead.
import { createLogger } from '../../../utils/logger';
import type {
FriendAddEvent,
FriendPokeEvent,
FriendRequestEvent,
QQEventVariant,
} from '../../events';
import type {
FriendRequest,
FriendRecall,
FriendRequest,
GeneralGrayTipInfo,
NewFriend,
} from '../../proto/proton/notify';
import type {
FriendRequestEvent, FriendPokeEvent,
FriendAddEvent, QQEventVariant,
} from '../../events';
type FriendRecallEvent = Extract<QQEventVariant, { kind: 'friend_recall' }>;
import type { MsgPushDecoder } from '../registry';
import type { MsgPushContext } from '../context';
import { Event0x210SubType } from '../enums';
import {
resolveUidToUin, parseU64OrZero, buildTemplateMap, findTemplateValue,
buildTemplateMap, findTemplateValue,
parseU64OrZero,
resolveUidToUin,
} from '../helpers';
import { createLogger } from '../../../utils/logger';
import type { MsgPushDecoder } from '../registry';
type FriendRecallEvent = Extract<QQEventVariant, { kind: 'friend_recall' }>;
const unknownLog = createLogger('MsgPush.Unknown');
@@ -1,24 +1,27 @@
// Handles Event0x2DC wrapper (732). Internal switch on subType dispatches
// to GroupMute (12) / GroupMsgEmojiLike (16) / GroupRecall (17) /
// GroupGreyTip (20) / GroupEssence (21).
import { protobuf_decode } from '@snowluma/proton';
import { createLogger } from '../../../utils/logger';
import type {
GroupMute, NotifyMessageBody, GroupReactNotify,
} from '../../proto/proton/notify';
import type {
GroupMuteEvent, GroupRecallEvent, GroupPokeEvent, GroupEssenceEvent,
GroupEssenceEvent,
GroupMsgEmojiLikeEvent,
GroupMuteEvent,
GroupPokeEvent,
GroupRecallEvent,
QQEventVariant,
} from '../../events';
import type { MsgPushDecoder } from '../registry';
import type {
GroupMute,
GroupReactNotify,
NotifyMessageBody,
} from '../../proto/proton/notify';
import type { MsgPushContext } from '../context';
import { Event0x2DCSubType } from '../enums';
import {
resolveUidToUin, parseU64OrZero, buildTemplateMap, findTemplateValue,
buildTemplateMap, findTemplateValue,
parseU64OrZero,
resolveUidToUin,
unwrapGroupNotifyPayload,
} from '../helpers';
import { createLogger } from '../../../utils/logger';
import type { MsgPushDecoder } from '../registry';
const unknownLog = createLogger('MsgPush.Unknown');
@@ -1,9 +1,3 @@
// Handles the four PkgTypes that produce a FriendMessage event:
// PrivateMessage (166), ForwardFakePrivateMessage (9),
// PrivateRecordMessage (208), PrivateFileMessage (529). The PkgType
// difference only affects which proto-level elements show up in the
// body — decodeRichBody handles all of them uniformly.
import type { FriendMessage } from '../../events';
import type { MsgPushDecoder } from '../registry';
import { decodeRichBody } from '../rich-body-decoder';
@@ -1,11 +1,8 @@
// Handles GroupAdminChangedNotice (44). extraEnable / extraDisable
// distinguishes set vs. unset.
import { protobuf_decode } from '@snowluma/proton';
import type { GroupAdmin } from '../../proto/proton/notify';
import type { GroupAdminEvent } from '../../events';
import type { MsgPushDecoder } from '../registry';
import type { GroupAdmin } from '../../proto/proton/notify';
import { resolveUidToUin } from '../helpers';
import type { MsgPushDecoder } from '../registry';
export const decodeGroupAdmin: MsgPushDecoder = (ctx) => {
const admin = protobuf_decode<GroupAdmin>(ctx.content);
@@ -1,14 +1,11 @@
// Handles GroupRequestJoinNotice (84) + GroupRequestInvitationNotice (525)
// + GroupInviteNotice (87). All three produce GroupInviteEvent with
// different subType ('add' / 'invite') and flag prefixes.
import { protobuf_decode } from '@snowluma/proton';
import type {
GroupJoin, GroupInvitation, GroupInvite,
} from '../../proto/proton/notify';
import type { GroupInviteEvent } from '../../events';
import type { MsgPushDecoder } from '../registry';
import type {
GroupInvitation, GroupInvite,
GroupJoin,
} from '../../proto/proton/notify';
import { resolveUidToUin } from '../helpers';
import type { MsgPushDecoder } from '../registry';
export const decodeGroupJoinRequest: MsgPushDecoder = (ctx) => {
const join = protobuf_decode<GroupJoin>(ctx.content);
@@ -1,24 +1,8 @@
// Handles GroupMemberIncreaseNotice (33) + GroupMemberDecreaseNotice (34) +
// GroupSelfJoinedNotice (85, bot-self admittance).
//
// 33/34 share GroupChangeSchema; the decreaseType field distinguishes
// kick vs voluntary leave (dt != 0 && dt != 130 means kicked).
//
// 85 carries a different wire shape (`SelfJoinInGroup`) — without it
// the bot has no signal that its own `set_group_add_request` was
// approved (33 fires only for *other* members joining). We surface
// 85 as a regular GroupMemberJoin with `userUin = selfUin` so the
// existing OneBot converter naturally produces
// `notice.group_increase` with `sub_type: 'approve' | 'invite'`
// (the converter compares operator == user to pick the sub_type;
// for self-join the operator is the admin/inviter, so 'invite' is
// emitted — matching go-cqhttp / NapCat semantics).
import { protobuf_decode } from '@snowluma/proton';
import type { GroupChange, SelfJoinInGroup } from '../../proto/proton/notify';
import type { GroupMemberJoin, GroupMemberLeave } from '../../events';
import type { MsgPushDecoder } from '../registry';
import type { GroupChange, SelfJoinInGroup } from '../../proto/proton/notify';
import { decodeOperatorUid, resolveUidToUin } from '../helpers';
import type { MsgPushDecoder } from '../registry';
export const decodeGroupMemberJoin: MsgPushDecoder = (ctx) => {
const change = protobuf_decode<GroupChange>(ctx.content);
@@ -1,6 +1,3 @@
// Handles GroupMessage (82). Resolves senderCard / senderRole from the
// group member roster when present.
import type { GroupMessage } from '../../events';
import type { MsgPushDecoder } from '../registry';
import { decodeRichBody } from '../rich-body-decoder';
@@ -1,6 +1,3 @@
// Handles TempMessage (141). Pulls senderNick from group hint first
// then falls back to friend roster.
import type { TempMessage } from '../../events';
import type { MsgPushDecoder } from '../registry';
import { decodeRichBody } from '../rich-body-decoder';
@@ -1,7 +1,3 @@
// MsgPush PkgType taxonomy. The top-level msgType field in PushMsg.contentHead
// names a QQ-protocol-defined packet shape; Event0x210 / Event0x2DC are wrapper
// PkgTypes whose payload is further dispatched by subType.
export enum PkgType {
ForwardFakePrivateMessage = 9,
PrivateMessage = 166,
+3 -6
View File
@@ -1,10 +1,7 @@
// MsgPush decode helpers — pure functions shared across PkgType decoders
// and the rich-body decoder. No state, no I/O.
import { inflateSync } from 'zlib';
import { protobuf_decode } from '@snowluma/proton';
import type { OperatorInfo } from '../proto/proton/notify';
import { inflateSync } from 'zlib';
import type { IdentityService } from '../identity-service';
import type { OperatorInfo } from '../proto/proton/notify';
export function makeImageUrl(origUrl: string): string {
if (!origUrl) return '';
@@ -57,7 +54,7 @@ export function decodeOperatorUid(bytes: Uint8Array): string {
return Buffer.from(bytes).toString('utf8');
}
export function buildTemplateMap(params: Array<{name?: string; value?: string}>): Map<string, string> {
export 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 ?? '');
+11 -14
View File
@@ -1,25 +1,22 @@
// MsgPush entry point — assembles the PkgType registry and exposes
// `parseMsgPush(pkt, identity)` as the single CmdParser registered against
// `MSG_PUSH_CMD` on the IncomingPacketPipeline.
import type { PacketInfo } from '../../protocol/types';
import type { IdentityService } from '../identity-service';
import type { QQEventVariant } from '../events';
import type { IdentityService } from '../identity-service';
import { buildContext } from './context';
import { MsgPushRegistry } from './registry';
import { PkgType } from './enums';
import { decodeEvent0x210 } from './decoders/event-0x210';
import { decodeEvent0x2DC } from './decoders/event-0x2dc';
import { decodeFriendMessage } from './decoders/friend-message';
import { decodeGroupAdmin } from './decoders/group-admin';
import {
decodeGroupInvitation, decodeGroupInvite,
decodeGroupJoinRequest,
} from './decoders/group-join-request';
import {
decodeGroupMemberJoin, decodeGroupMemberLeave, decodeGroupSelfJoined,
} from './decoders/group-member-change';
import { decodeGroupAdmin } from './decoders/group-admin';
import {
decodeGroupJoinRequest, decodeGroupInvitation, decodeGroupInvite,
} from './decoders/group-join-request';
import { decodeEvent0x210 } from './decoders/event-0x210';
import { decodeEvent0x2DC } from './decoders/event-0x2dc';
import { decodeGroupMessage } from './decoders/group-message';
import { decodeTempMessage } from './decoders/temp-message';
import { decodeFriendMessage } from './decoders/friend-message';
import { PkgType } from './enums';
import { MsgPushRegistry } from './registry';
export const MSG_PUSH_CMD = 'trpc.msg.olpush.OlPushService.MsgPush';
@@ -1,8 +1,3 @@
// MsgPushRegistry — per-PkgType dispatch table. Each PkgType maps to a single
// decoder; double-registration is a programming error (throws at register time).
// Decoder errors are caught and logged with the PkgType so a single bad decoder
// can never silently take down sibling decoders sharing the cmd.
import { createLogger } from '../../utils/logger';
import type { QQEventVariant } from '../events';
import type { MsgPushContext } from './context';
@@ -1,10 +1,6 @@
// Rich body decoder — turns the proto MessageBody (richText.elems +
// richText.ptt/notOnlineFile + msgContent) of a MsgPush message into
// the bridge-internal MessageElement[] sequence. Pure, no identity
// lookups, no I/O. The single small interface `decodeRichBody` hides
// ~400 lines of per-element-type decoding behind it.
import { protobuf_decode } from '@snowluma/proton';
import { toHexUpper } from '../../utils/hex';
import type { MessageElement } from '../events';
import type {
Elem,
GroupFileExtra,
@@ -15,8 +11,6 @@ import type {
QSmallFaceExtra,
} from '../proto/proton/element';
import type { FileExtra, MessageBody, RichText } from '../proto/proton/message';
import type { MessageElement } from '../events';
import { toHexUpper } from '../../utils/hex';
import { decompressData, makeImageUrl } from './helpers';
type ElemDecoded = Elem;
+3 -21
View File
@@ -1,27 +1,9 @@
// Incoming packet pipeline — the chain that turns a single PacketInfo
// arriving from the hook layer into a stream of QQEventVariant
// emissions on the typed event bus. Replaces the inline orchestration
// that previously lived on Bridge.onPacket / triggerMemberCacheRefresh /
// rememberEventIdentity / dispatchAfterIdentityRefresh / etc.
//
// Stage chain per parser output:
// parse → enrich identity (sync, or async refresh)
// → side-effects (remember UID/UIN + schedule roster refresh)
// → log
// → emit on bus
//
// The pipeline owns its cmd handler map and its per-group coalesce table
// for background member-list refreshes. It does NOT own protocol calls
// — `refreshMemberCache` is injected by Bridge because it ultimately
// dispatches OIDB packets through Bridge.fetchGroupList /
// Bridge.fetchGroupMemberList.
import type { PacketInfo } from '../protocol/types';
import { formatEvent } from '../utils/event-format';
import { createLogger, type Logger } from '../utils/logger';
import type { BridgeEventBus } from './event-bus';
import type { QQEventVariant } from './events';
import type { IdentityService } from './identity-service';
import type { BridgeEventBus } from './event-bus';
import { createLogger, type Logger } from '../utils/logger';
import { formatEvent } from '../utils/event-format';
const moduleLog = createLogger('Bridge');
const moduleEventLog = createLogger('Event');
-5
View File
@@ -1,8 +1,3 @@
// Domain object shapes shared by IdentityService and its callers. The
// concrete state (own UIN, friends list, group rosters, profile cache)
// lives inside IdentityService — these interfaces just describe the
// records that flow across remember*/refresh* and find* boundaries.
export interface UserProfileInfo {
uin: number;
uid: string;
@@ -1,11 +1,6 @@
// Web-cookie / credential primitives — every other web-action in this
// directory builds on these. Each Bridge-level web call ends up doing
// roughly: forceFetchClientKey -> ptlogin2 jump -> cookie dict ->
// thread the cookies into a qun.qq.com REST endpoint.
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { Bridge } from '../bridge';
import { runOidb, makeOidbEnvelope } from '../bridge-oidb';
import { makeOidbEnvelope, runOidb } from '../bridge-oidb';
import { OidbBase } from '../proto/proton/oidb';
import type {
OidbClientKeyReq,
@@ -57,8 +52,8 @@ export async function getCookies(bridge: Bridge, domain: string) {
// bot to swap its clientKey for cookie-jar entries on a given
// qq.com subdomain.
const requestUrl = 'https://ssl.ptlogin2.qq.com/jump?ptlang=1033&clientuin=' + bridge.identity.uin +
'&clientkey=' + ClientKeyData.clientKey +
'&u1=https%3A%2F%2F' + domain + '%2F' + bridge.identity.uin + '%2Finfocenter&keyindex=' + ClientKeyData.keyIndex;
'&clientkey=' + ClientKeyData.clientKey +
'&u1=https%3A%2F%2F' + domain + '%2F' + bridge.identity.uin + '%2Finfocenter&keyindex=' + ClientKeyData.keyIndex;
const data = await RequestUtil.HttpsGetCookies(requestUrl);
@@ -89,10 +84,10 @@ export async function getSKey(bridge: Bridge): Promise<string> {
const u1 = encodeURIComponent('https://h5.qzone.qq.com/qqnt/qzoneinpcqq/friend?refresh=0&clientuin=0&darkMode=0');
const requestUrl = 'https://ssl.ptlogin2.qq.com/jump?ptlang=1033' +
'&clientuin=' + bridge.identity.uin +
'&clientkey=' + ClientKeyData.clientKey +
'&u1=' + u1 +
'&keyindex=' + ClientKeyData.keyIndex;
'&clientuin=' + bridge.identity.uin +
'&clientkey=' + ClientKeyData.clientKey +
'&u1=' + u1 +
'&keyindex=' + ClientKeyData.keyIndex;
const cookies: { [key: string]: string } = await RequestUtil.HttpsGetCookies(requestUrl);
const skey = cookies['skey'];
@@ -1,5 +1,3 @@
// Group album actions via web API
import type { Bridge } from '../bridge';
import { getGroupAlbumList, uploadImageToGroupAlbum } from '../web/group-album';
import { getCookies } from './cookies';
@@ -1,7 +1,3 @@
// `get_essence_msg_list` — group essence (highlighted) messages.
// Two flavors: paginated (`getGroupEssence`) and the convenience
// fetch-everything (`getGroupEssenceAll`).
import type { Bridge } from '../bridge';
import { getGroupEssenceMsg, getGroupEssenceMsgAll } from '../web/group-essence';
import { getCookies } from './cookies';
@@ -1,8 +1,3 @@
// `get_group_honor_info` — queries the per-group honor leaderboards
// (talkative / performer / legend / emotion / strong_newbie).
// Each honor type is a separate web call; ALL fetches all four
// non-newbie lists and folds them into one response.
import type { Bridge } from '../bridge';
import { getHonorListWebAPI, WebHonorType } from '../web/group-honor';
import { getCookies } from './cookies';
@@ -1,14 +1,9 @@
// Group notice (`群公告`) web actions: send / list / delete.
// `sendGroupNotice` can attach an optional image; when present it
// stages the bytes (HTTP URL or local file) and uploads via the
// notice-image endpoint before posting the notice itself.
import type { Bridge } from '../bridge';
import {
setGroupNoticeWebAPI,
getGroupNoticeWebAPI,
uploadGroupNoticeImage,
deleteGroupNotice,
getGroupNoticeWebAPI,
setGroupNoticeWebAPI,
uploadGroupNoticeImage,
} from '../web/group-notice';
import { getCookies } from './cookies';
+5 -17
View File
@@ -1,32 +1,20 @@
// Barrel for the web-action themed split. `bridge.ts` imports
// everything from this directory as if it were a single file; the
// per-theme files keep the implementation discoverable.
export {
forceFetchClientKey,
getPSkey,
getCookies,
getSKey,
getBknFromSKey,
getCookiesStr,
getCsrfToken,
getCredentials,
forceFetchClientKey, getBknFromSKey, getCookies, getCookiesStr, getCredentials, getCsrfToken, getPSkey, getSKey
} from './cookies';
export { getGroupHonorInfo } from './group-honor';
export {
getGroupEssence,
getGroupEssenceAll,
getGroupEssenceAll
} from './group-essence';
export {
sendGroupNotice,
getGroupNotice,
deleteGroupNoticeByFid,
deleteGroupNoticeByFid, getGroupNotice, sendGroupNotice
} from './group-notice';
export {
getGroupAlbumListWeb,
uploadImageToGroupAlbumWeb,
uploadImageToGroupAlbumWeb
} from './group-album';
-6
View File
@@ -1,11 +1,5 @@
import type { HookProcessBaseInfo } from './injector';
/**
* Lifecycle status of a single per-PID HookSession.
*
* Transitions live inside HookSession; this union only enumerates the
* states visible to API callers (WebUI, manager.listProcesses()).
*/
export type HookProcessStatus =
| 'available'
| 'loading'
+2 -6
View File
@@ -1,12 +1,8 @@
import type { ApiHandler, ApiActionContext } from '../api-handler';
import { asMessage, asNumber, asString, asBoolean } from '../api-handler';
import type { ApiActionContext, ApiHandler } from '../api-handler';
import { asBoolean, asMessage, asNumber, asString } from '../api-handler';
import type { ForwardPreviewMeta } from '../modules/message-actions';
import { RETCODE, failedResponse, okResponse } from '../types';
// Bounded download for the OneBot `download_file` action. An authenticated
// client could otherwise hand us a multi-GB URL (or chunked response with
// no Content-Length) and OOM the bot — `await response.arrayBuffer()`
// happily allocates the whole payload before any size check fires.
const DOWNLOAD_FILE_MAX_BYTES = 1024 * 1024 * 1024; // 1 GiB
const DOWNLOAD_FILE_TIMEOUT_MS = 60_000;
@@ -1,12 +1,3 @@
// Bridge event -> OneBot top-level event conversion.
//
// Replaces the old `EventConverter` class. The class held four
// resolver fields (image-url / media-url / message-id / media-segment
// sink) wired in lazily via setters; the new shape passes them as a
// `ConverterContext` object so each case is a pure function and the
// per-case test setup is two lines, not a class instance plus four
// setter calls.
import type { MessageElement, QQEventVariant } from '../../bridge/events';
import type { JsonObject } from '../types';
import {
@@ -84,26 +75,26 @@ export async function convertEvent(
switch (event.kind) {
// Messages.
case 'friend_message': return convertFriendMessage(ctx, event);
case 'group_message': return convertGroupMessage(ctx, event);
case 'temp_message': return convertTempMessage(ctx, event);
case 'group_message': return convertGroupMessage(ctx, event);
case 'temp_message': return convertTempMessage(ctx, event);
// Notices.
case 'group_member_join': return convertGroupMemberJoin(ctx, event);
case 'group_member_join': return convertGroupMemberJoin(ctx, event);
case 'group_member_leave': return convertGroupMemberLeave(ctx, event);
case 'group_mute': return convertGroupMute(ctx, event);
case 'group_admin': return convertGroupAdmin(ctx, event);
case 'friend_recall': return convertFriendRecall(ctx, event);
case 'group_recall': return convertGroupRecall(ctx, event);
case 'friend_poke': return convertFriendPoke(ctx, event);
case 'group_poke': return convertGroupPoke(ctx, event);
case 'group_essence': return convertGroupEssence(ctx, event);
case 'group_file_upload': return convertGroupFileUpload(ctx, event);
case 'friend_add': return convertFriendAdd(ctx, event);
case 'group_mute': return convertGroupMute(ctx, event);
case 'group_admin': return convertGroupAdmin(ctx, event);
case 'friend_recall': return convertFriendRecall(ctx, event);
case 'group_recall': return convertGroupRecall(ctx, event);
case 'friend_poke': return convertFriendPoke(ctx, event);
case 'group_poke': return convertGroupPoke(ctx, event);
case 'group_essence': return convertGroupEssence(ctx, event);
case 'group_file_upload': return convertGroupFileUpload(ctx, event);
case 'friend_add': return convertFriendAdd(ctx, event);
case 'group_msg_emoji_like': return convertGroupMsgEmojiLike(ctx, event);
// Requests.
case 'friend_request': return convertFriendRequest(ctx, event);
case 'group_invite': return convertGroupInvite(ctx, event);
case 'friend_request': return convertFriendRequest(ctx, event);
case 'group_invite': return convertGroupInvite(ctx, event);
default:
return null;
@@ -1,11 +1,6 @@
// Message-kind handlers: friend_message, group_message, temp_message.
// Each takes a ConverterContext (which carries selfId + the four
// resolver/sink callbacks) and the typed bridge event, and returns the
// OneBot top-level event JSON.
import type { QQEventVariant } from '../../bridge/events';
import type { JsonObject } from '../types';
import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT } from '../message-id';
import type { JsonObject } from '../types';
import type { ConverterContext } from './index';
import { elementsToJson } from './to-segment';
import { applyMessageIdResolver, segmentsToRawMessage } from './utils';
@@ -1,12 +1,6 @@
// Notice-kind handlers (10 cases). These produce OneBot `notice` events
// with no message body / no element conversion — pure field projections
// from the bridge event into the OneBot wire shape. None of them call
// resolvers except the two recall handlers and group_essence, which
// need a message-id resolution.
import type { QQEventVariant } from '../../bridge/events';
import type { JsonObject } from '../types';
import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT } from '../message-id';
import type { JsonObject } from '../types';
import type { ConverterContext } from './index';
import { applyMessageIdResolver, isSameActor } from './utils';
@@ -1,8 +1,3 @@
// Request-kind handlers (2 cases). OneBot `request` events for friend
// adds and group invites/joins — both carry the bridge-supplied `flag`
// that the caller later passes back to `set_friend_add_request` /
// `set_group_add_request`.
import type { QQEventVariant } from '../../bridge/events';
import type { JsonObject } from '../types';
import type { ConverterContext } from './index';
@@ -1,8 +1,3 @@
// Per-element converter: 13 element types -> one OneBot message segment.
// Used by message-events (friend/group/temp) for inline elements AND by
// modules/message-actions.ts for forward-message rebuilding (re-exported
// from this module via the index barrel as `elementsToOneBotSegments`).
import type { MessageElement } from '../../bridge/events';
import type { JsonArray, JsonObject } from '../types';
import type {
@@ -1,11 +1,5 @@
// Pure helpers shared across the per-post_type converter modules.
//
// Nothing here touches I/O or class state; everything is a small
// function so the per-event tests can import what they need without
// dragging in resolver wiring.
import type { JsonArray, JsonObject } from '../types';
import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT } from '../message-id';
import type { JsonArray, JsonObject } from '../types';
import type { MessageIdResolver } from './index';
export function parseSelfId(instanceUin: string): number {
-7
View File
@@ -1,11 +1,4 @@
import type { JsonObject, JsonValue, MessageFormat } from './types';
/**
* Per-adapter view of how an event should be reported.
*
* Built once from each adapter's own configuration at (re)load time so the
* per-publish dispatch loop is just a couple of object lookups.
*/
export interface EventReportOptions {
/** Effective `messageFormat` for this adapter. */
messageFormat: MessageFormat;
+3 -11
View File
@@ -1,15 +1,7 @@
// Per-kind bridge → OneBot event handlers.
//
// Replaces the legacy single-firehose `OneBotInstance.onBridgeEvent` switch.
// Every bridge event kind gets a small async handler bound to a shared
// `OneBotInstanceContext`; subscribers register on `ctx.bridge.events` so
// multiple unrelated downstream concerns (meta caching, OB11 conversion,
// dispatch) compose cleanly without one giant switch statement.
import type { OneBotInstanceContext } from './instance-context';
import { convertEvent } from './event-converter';
import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT, hashMessageIdInt32 } from './message-id';
import type { QQEventVariant } from '../bridge/events';
import { convertEvent } from './event-converter';
import type { OneBotInstanceContext } from './instance-context';
import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT, hashMessageIdInt32 } from './message-id';
/**
* Subscribe every `OneBotInstanceContext`-aware handler onto the bridge
+1 -4
View File
@@ -1,8 +1,8 @@
import type { BridgeInterface } from '../bridge/bridge-interface';
import type { BridgeManager } from '../bridge/manager';
import { createLogger } from '../utils/logger';
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';
@@ -18,9 +18,6 @@ export class OneBotManager {
bridgeManager.setSessionClosedCallback((uin) => {
this.onSessionClosed(uin);
});
// Per-kind subscriptions to `bridge.events` happen inside
// `OneBotInstance` itself; no global firehose to wire here.
}
getInstance(uin: string): OneBotInstance | null {
+2 -10
View File
@@ -1,23 +1,15 @@
// Side-channel observer that watches every image / record / video
// segment emitted by the event converter and writes a row into the
// MediaStore so later `get_image` / `get_record` OneBot actions can
// resolve the original `data.file` back to a URL + metadata.
//
// Used as the `mediaSegmentSink` callback in `ConverterContext`.
//
// The fan-out is uniform (always one rememberX call per segment), but
// each mediaType maps to a slightly different MediaStore record shape;
// keeping the three field maps in one place makes the divergence
// visible at a glance.
import type { MessageElement } from '../bridge/events';
import type { JsonObject } from './types';
import type { MediaStore } from './media-store';
import type { JsonObject } from './types';
export type MediaType = 'image' | 'record' | 'video';
export class MediaIndexer {
constructor(private readonly mediaStore: MediaStore) {}
constructor(private readonly mediaStore: MediaStore) { }
remember(
mediaType: MediaType,
+1 -15
View File
@@ -3,24 +3,10 @@
// The `get_image` / `get_record` actions need to map a `data.file` (or related
// identifier) we previously emitted in a message segment back to the URL,
// size, name, and any OIDB media-node info needed to re-resolve a stale URL.
//
// Earlier this lived in an in-memory `MediaCache`, which meant the lookup
// table was lost on every restart. This implementation persists everything
// alongside the message store so OneBot consumers can always resolve the
// media that produced any segment ever stored, even after the bot restarts.
//
// Schema overview (single SQLite file per UIN, e.g. `data/<uin>/media.db`):
// media_entries(type, primary_key, data JSON, last_seen) -- one row per logical media item
// media_keys(type, key, primary_key) -- secondary index for every alias
//
// `rememberImage` / `rememberRecord` upsert exactly one entry row plus one
// alias row per identifier (file / fileName / fileId / url). The alias rows
// always point to the canonical entry so URL refreshes propagate to every
// alias automatically.
import fs from 'fs';
import path from 'path';
import { DatabaseSync, type StatementSync } from 'node:sqlite';
import path from 'path';
import type { MessageElement } from '../bridge/events';
+1 -15
View File
@@ -1,17 +1,3 @@
// Resolves the URL for an image / record / video / file element on its
// way out of the bridge into an OneBot segment.
//
// Two steps:
// 1. If the bridge event arrived without a `url` (the receive path
// sometimes does), fetch a fresh URL from the right Bridge API
// based on element.type + isGroup, mutating the element in-place
// so any downstream cache sees the URL too.
// 2. Apply the cached RKey (the per-UIN signed download key) the
// RKeyCache knows about — both to brand-new URLs from step 1 and
// to URLs that came in with the event already.
//
// Used as the `mediaUrlResolver` callback in `ConverterContext`.
import type { BridgeInterface } from '../bridge/bridge-interface';
import type { MessageElement } from '../bridge/events';
import type { RKeyCache } from './instance-rkey';
@@ -20,7 +6,7 @@ export class MediaUrlResolver {
constructor(
private readonly bridge: BridgeInterface,
private readonly rkeyCache: RKeyCache,
) {}
) { }
async resolve(element: MessageElement, isGroup: boolean, sessionId: number): Promise<string> {
if (!element.url) {
+5 -9
View File
@@ -1,10 +1,6 @@
// 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 } from './types';
import { createLogger } from '../utils/logger';
import type { JsonValue } from './types';
const log = createLogger('MsgParser');
@@ -140,12 +136,12 @@ async function segmentToElement(type: string, data: Record<string, unknown>, opt
if (options?.resolveReplySequence) {
const resolved = options.resolveReplySequence(id);
if (typeof resolved === 'number' && resolved > 0) {
const element: MessageElement = {
type: 'reply',
const element: MessageElement = {
type: 'reply',
replySeq: resolved,
replyMessageId: id // Keep the original messageId for logging
};
// Try to get additional meta info for better reply display
if (options?.resolveReplyMeta) {
const meta = options.resolveReplyMeta(id);
@@ -155,7 +151,7 @@ async function segmentToElement(type: string, data: Record<string, unknown>, opt
element.replyRandom = meta.random;
}
}
return element;
}
}
+4 -7
View File
@@ -1,9 +1,6 @@
// 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 path from 'path';
import type { JsonObject, MessageMeta } from './types';
export class MessageStore {
@@ -82,7 +79,7 @@ export class MessageStore {
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;
@@ -123,7 +120,7 @@ export class MessageStore {
if (!Number.isInteger(sessionId) || sessionId <= 0 || !isValidMessageId(messageId)) {
return null;
}
// For private messages, we cannot rely on session_id matching because:
// - When receiving: session_id is the sender's UIN
// - When sending reply: sessionId parameter is the recipient's UIN (who we're sending to)
@@ -141,7 +138,7 @@ export class MessageStore {
WHERE is_group = 0 AND message_hash = ?
LIMIT 1`
).get(messageId) as { sequence: number } | undefined;
if (!row || !Number.isInteger(row.sequence) || row.sequence <= 0) {
return null;
}
+1 -10
View File
@@ -1,15 +1,6 @@
// Base abstractions for OneBot network adapters.
//
// Modeled on NapCat's `IOB11NetworkAdapter` so each entry under
// `config.networks.{httpServers,httpClients,wsServers,wsClients}` becomes
// exactly one adapter instance, identified by `name`. The previous design
// rolled multiple servers/clients into a single transport class; the
// per-entry split makes hot-reload, lifecycle, and event isolation much
// simpler to reason about.
import type { ApiHandler } from '../api-handler';
import type { JsonObject, NetworkBase } from '../types';
import type { DispatchPayload } from '../event-filter';
import type { JsonObject, NetworkBase } from '../types';
export interface NetworkAdapterContext {
/** Self UIN as string — written into outbound headers. */
@@ -1,16 +1,11 @@
// Outbound HTTP webhook adapter — one instance per `httpClients[]` entry.
//
// Forwards every event to the configured URL via HTTP POST and interprets
// any JSON response body as a OneBot v11 quick-operation.
import type { HttpClientNetwork, JsonObject } from '../types';
import { createLogger, type Logger } from '../../utils/logger';
import {
pickDispatchJson,
resolveReportOptions,
type DispatchPayload,
type EventReportOptions,
} from '../event-filter';
import { createLogger, type Logger } from '../../utils/logger';
import type { HttpClientNetwork, JsonObject } from '../types';
import { IOneBotNetworkAdapter, NetworkReloadType, type NetworkAdapterContext } from './adapter';
import { executeQuickOperation } from './quick-operation';
@@ -1,18 +1,12 @@
// Inbound HTTP API server — one instance per `httpServers[]` entry.
//
// Pure request/response: incoming POST/GET maps to `ApiHandler.handle`,
// the response body is JSON-serialized back. `onEvent` is a deliberate
// no-op since this transport never pushes events.
import {
createServer,
type IncomingMessage,
type Server,
type ServerResponse,
} from 'http';
import type { HttpServerNetwork, JsonObject, JsonValue } from '../types';
import type { DispatchPayload } from '../event-filter';
import { createLogger, type Logger } from '../../utils/logger';
import type { DispatchPayload } from '../event-filter';
import type { HttpServerNetwork, JsonObject, JsonValue } from '../types';
import { IOneBotNetworkAdapter, NetworkReloadType, type NetworkAdapterContext } from './adapter';
import { isAuthorized, normalizePath } from './utils';
@@ -263,4 +257,4 @@ function writeJson(res: ServerResponse, statusCode: number, data: unknown): void
res.statusCode = statusCode;
res.setHeader('Content-Type', 'application/json; charset=utf-8');
res.end(JSON.stringify(data));
}
}
+5 -6
View File
@@ -1,9 +1,8 @@
// Public surface for the OneBot network package.
export { IOneBotNetworkAdapter, NetworkReloadType, type NetworkAdapterContext } from './adapter';
export { OneBotNetworkManager } from './network-manager';
export { WsServerAdapter } from './ws-server-adapter';
export { WsClientAdapter } from './ws-client-adapter';
export { HttpServerAdapter } from './http-server-adapter';
export { HttpPostAdapter } from './http-post-adapter';
export { HttpServerAdapter } from './http-server-adapter';
export { OneBotNetworkManager } from './network-manager';
export { executeQuickOperation } from './quick-operation';
export { WsClientAdapter } from './ws-client-adapter';
export { WsServerAdapter } from './ws-server-adapter';
@@ -1,13 +1,7 @@
// OneBot network manager.
//
// Mirrors NapCat's `OB11NetworkManager`: holds a `Map<name, adapter>`, fans
// events out to every active adapter in parallel, and provides primitives
// the OneBot instance uses to register, hot-reload, and tear adapters down.
import type { JsonObject, NetworkBase } from '../types';
import { buildDispatchPayload } from '../event-filter';
import { IOneBotNetworkAdapter } from './adapter';
import { createLogger } from '../../utils/logger';
import { buildDispatchPayload } from '../event-filter';
import type { JsonObject, NetworkBase } from '../types';
import { IOneBotNetworkAdapter } from './adapter';
const log = createLogger('OneBot.Network');
@@ -1,10 +1,3 @@
// OneBot v11 hidden API: `.handle_quick_operation`.
//
// When an HTTP POST event report receives a JSON body in response, that body
// is interpreted as a "quick operation" — short-cuts to common follow-up
// API calls (reply, recall, ban, kick, approve/reject). Spec:
// https://github.com/botuniverse/onebot-11/blob/master/api/hidden.md
import type { ApiHandler } from '../api-handler';
import type { JsonObject, JsonValue } from '../types';
+1 -3
View File
@@ -1,7 +1,5 @@
// Helpers shared between OneBot network adapters.
import type { IncomingMessage } from 'http';
import type { WebSocket } from '@snowluma/websocket';
import type { IncomingMessage } from 'http';
/** Validate a request's bearer token / `?access_token=` query against the configured token. */
export function isAuthorized(request: IncomingMessage, token: string): boolean {
@@ -1,11 +1,5 @@
// Reverse (client) WebSocket adapter — one instance per `wsClients[]` entry.
//
// Connects out to a remote OneBot endpoint, manages reconnects, forwards
// pushed events on `onEvent`, and dispatches incoming API messages to the
// shared ApiHandler.
import { WebSocket } from '@snowluma/websocket';
import type { WsClientNetwork, WsRole, JsonObject } from '../types';
import { createLogger, type Logger } from '../../utils/logger';
import {
pickDispatchJson,
resolveReportOptions,
@@ -13,7 +7,7 @@ import {
type DispatchPayload,
type EventReportOptions,
} from '../event-filter';
import { createLogger, type Logger } from '../../utils/logger';
import type { JsonObject, WsClientNetwork, WsRole } from '../types';
import { IOneBotNetworkAdapter, NetworkReloadType, type NetworkAdapterContext } from './adapter';
import { rawDataToString, safeClose, safeSend } from './utils';
@@ -1,12 +1,6 @@
// Forward (server) WebSocket adapter — one instance per `wsServers[]` entry.
//
// Each adapter owns its own `WebSocketServer`, accepts inbound forward
// connections (api / event / universal roles), and pushes events to all live
// event-receiving sockets when `onEvent` fires.
import { WebSocket, WebSocketServer } from '@snowluma/websocket';
import type { IncomingMessage } from 'http';
import type { WsRole, WsServerNetwork, JsonObject } from '../types';
import { createLogger, type Logger } from '../../utils/logger';
import {
pickDispatchJson,
resolveReportOptions,
@@ -14,9 +8,9 @@ import {
type DispatchPayload,
type EventReportOptions,
} from '../event-filter';
import { createLogger, type Logger } from '../../utils/logger';
import type { JsonObject, WsRole, WsServerNetwork } from '../types';
import { IOneBotNetworkAdapter, NetworkReloadType, type NetworkAdapterContext } from './adapter';
import { isAuthorized, parseRequestPath, rawDataToString, safeClose, safeSend, normalizePath } from './utils';
import { isAuthorized, normalizePath, parseRequestPath, rawDataToString, safeClose, safeSend } from './utils';
const moduleLog = createLogger('OneBot.WS-Server');
-5
View File
@@ -8,9 +8,4 @@ export interface PacketInfo {
fromClient: boolean;
body: Uint8Array;
}
/**
* Packet sink injected into HookSession / HookManager. The default
* wiring forwards to BridgeManager.onPacket, but tests inject spies.
*/
export type PacketSink = (packet: PacketInfo) => void;
+1 -12
View File
@@ -1,16 +1,5 @@
// Identity-aware, one-line readable rendering for log output.
//
// Two layers consume this:
// - bridge/packet-pipeline.ts → notice events (recall / join / poke / …)
// - onebot/instance.ts → received-message log
//
// All formatters are defensive: any field lookup that throws falls
// back to the raw numeric form, so a malformed event or stale
// Identity cache never crashes the logger. Cache misses simply
// degrade to the previous "just print the uin / groupId" output.
import type { IdentityService } from '../bridge/identity-service';
import type { QQEventVariant } from '../bridge/events';
import type { IdentityService } from '../bridge/identity-service';
import type { MessageStore } from '../onebot/message-store';
import type { JsonObject, JsonValue } from '../onebot/types';
@@ -1,21 +1,3 @@
// File transport for the SnowLuma logger.
//
// Writes plain text (ANSI stripped) to:
// <SNOWLUMA_LOG_DIR>/snowluma-YYYY-MM-DD.log (shared, all UINs)
// <SNOWLUMA_LOG_DIR>/<uin>/snowluma-YYYY-MM-DD.log (per-account)
//
// Both pathways use the same daily rotation + per-file size cap. When the
// cap is hit the in-flight file is closed and writes continue in
// snowluma-YYYY-MM-DD.1.log, .2.log, ...
// at the same date. Files older than the retain window are unlinked on
// startup and on each day rollover.
//
// Disabled via SNOWLUMA_LOG_FILE=0. Per-UIN sub-files are additionally
// gated by SNOWLUMA_LOG_PER_UIN=0 (still keeps the shared file). Any I/O
// failure during init or write degrades silently to console-only — we
// deliberately do NOT use the logger from inside this module to avoid
// recursion.
import fs from 'node:fs';
import path from 'node:path';
-9
View File
@@ -1,12 +1,3 @@
// Compact one-line param summary for log output.
//
// OneBot action params can include large message arrays / nested
// payloads that would blow the line width to multiple kilobytes if we
// JSON.stringify them naively. This helper produces a flat
// `k1=v1 k2=v2 ...` rendering with per-field truncation and a hard
// total cap, designed to be grep-friendly without flooding the log
// file.
const MAX_FIELD = 40;
const MAX_TOTAL = 200;
+1 -4
View File
@@ -23,9 +23,6 @@ interface LogOptions {
meta?: Record<string, unknown>;
}
// Fixed-width slot for the UIN tag in rendered output so the [Scope]
// column stays vertically aligned across lines with and without a UIN.
// Width covers `[1234567890]` (12 chars); anything longer just won't pad.
const UIN_SLOT_WIDTH = 12;
const LEVEL_WEIGHT: Record<LogLevel, number> = {
@@ -205,7 +202,7 @@ export interface Logger {
* support (shown in the `[UIN]` slot and routed to a per-UIN file);
* other keys are preserved on the options bag for forward compat.
*/
child: (meta: { uin?: number; [k: string]: unknown }) => Logger;
child: (meta: { uin?: number;[k: string]: unknown }) => Logger;
}
function makeLogger(opts: LogOptions): Logger {
+1 -19
View File
@@ -1,6 +1,6 @@
import { randomBytes, scryptSync, timingSafeEqual } from 'crypto';
import fs from 'fs';
import path from 'path';
import { randomBytes, scryptSync, timingSafeEqual } from 'crypto';
import { createLogger } from '../utils/logger';
const log = createLogger('WebUI.Auth');
@@ -13,11 +13,6 @@ const SCRYPT_N = 16384; // cost
const SCRYPT_R = 8;
const SCRYPT_P = 1;
/**
* Fixed credentials used when SNOWLUMA_DEV_MODE=1 is set. The state is kept
* entirely in memory and never written to `config/webui.json`, so toggling
* dev mode on/off never disturbs the real persisted password.
*/
const DEV_PASSWORD = 'snowluma-dev';
export function isDevAuthMode(): boolean {
@@ -27,9 +22,6 @@ export function isDevAuthMode(): boolean {
function envBootstrapPassword(): string | null {
const raw = process.env.SNOWLUMA_WEBUI_BOOTSTRAP_PASSWORD;
if (!raw || typeof raw !== 'string') return null;
// Minimum sanity: avoid accidental empty / 1-char seeds. Strength
// rules still don't apply because we want trusted launchers to be
// able to pick a high-entropy random secret (e.g. base64(16)).
if (raw.length < 8) return null;
return raw;
}
@@ -111,7 +103,6 @@ function atomicWrite(state: WebuiAuthState): void {
ensureConfigDir();
const tmp = WEBUI_CONFIG_PATH + '.tmp';
fs.writeFileSync(tmp, JSON.stringify(state, null, 2), { encoding: 'utf8', mode: 0o600 });
// chmod again in case the file already existed with looser perms
try {
fs.chmodSync(tmp, 0o600);
} catch {
@@ -174,11 +165,6 @@ export class WebuiAuth {
backupCorruptConfig();
}
}
// SNOWLUMA_WEBUI_BOOTSTRAP_PASSWORD lets a trusted launcher seed the
// password on first run instead of having to scrape it from logs.
// Effect: write webui.json with the env-provided password, hashed,
// and mustChangePassword=false. Only honoured when there is NO existing
// webui.json — once persisted, password changes happen via the UI.
const envPassword = envBootstrapPassword();
if (envPassword !== null) {
const salt = randomBytes(16);
@@ -235,10 +221,6 @@ export class WebuiAuth {
}
}
/**
* Update password atomically. Throws if the new password fails strength rules.
* After success, mustChangePassword=false and the file is rewritten on disk.
*/
setPassword(newPassword: string): void {
if (this.devMode) {
throw new Error('开发模式 (SNOWLUMA_DEV_MODE=1) 已禁用密码修改');
+1 -35
View File
@@ -1,33 +1,5 @@
// Resolve the request's "real" client IP for per-IP rate limiting.
//
// Threat model:
// - By default we ONLY trust the TCP socket peer. `X-Forwarded-For` and
// `X-Real-IP` are client-controllable, so honoring them lets any
// client rotate the header to escape the 5-attempts/15-min login
// lockout.
// - Operators who actually run behind a reverse proxy (nginx, Caddy,
// a SaaS CDN) need a way to opt back into the real client IP. The
// `SNOWLUMA_WEBUI_TRUST_PROXY` env var lets them say "when the
// immediate TCP peer is THIS, treat the headers as authoritative".
//
// Supported values for SNOWLUMA_WEBUI_TRUST_PROXY:
// - unset / empty — default; ignore headers, use socket peer
// - "loopback" — trust headers when the socket peer is 127.0.0.1
// or ::1 (typical for nginx/Caddy on the same host)
// - "1" / "true" / — trust headers from any peer (only safe behind a
// "all" trusted SaaS CDN that strips client-set headers)
// - comma-separated — trust headers when the socket peer matches one
// IP list of these IPs (reverse proxy on another machine)
//
// When trusted, we prefer X-Real-IP (a single value the reverse proxy
// overwrites unconditionally) and fall back to the first hop of
// X-Forwarded-For. We never parse the FULL XFF chain — if the proxy
// chain isn't fully trusted, the leftmost value can still be spoofed
// by the original client, and a single-tier proxy is the only setup
// this app realistically sees.
import type { Context } from 'hono';
import { getConnInfo } from '@hono/node-server/conninfo';
import type { Context } from 'hono';
export type TrustProxyMode =
| { kind: 'none' }
@@ -69,12 +41,6 @@ function shouldTrustHeaders(mode: TrustProxyMode, socketIp: string): boolean {
}
}
/**
* Pick the right "client IP" for rate-limit keying.
*
* Exposed as a pure function over a small dependency surface so the
* unit tests can fabricate request shapes without spinning up a server.
*/
export function pickClientIp(
c: Pick<Context, 'req'>,
mode: TrustProxyMode,
+1 -1
View File
@@ -3,7 +3,7 @@ import type { SnowLumaEvent } from '../types/index';
import { isGroupMessageEvent, isPrivateMessageEvent, isRequestEvent } from './guards';
import type { SnowLumaEventContext } from './types';
/** Creates the helper context object used by WebSocket event handlers. */
export function createEventContext<TEvent extends SnowLumaEvent>(
event: TEvent,
client: SnowLumaApiClient,
+5 -12
View File
@@ -10,53 +10,46 @@ import type {
export type MaybePromise<T = void> = T | Promise<T>;
export type EventNext = () => Promise<void>;
/** Type guard or predicate used by client.when(). */
export type EventPredicate<TEvent extends SnowLumaEvent = SnowLumaEvent> = (event: SnowLumaEvent) => event is TEvent;
/** Handler for one narrowed SnowLuma event. */
export type EventHandler<TEvent extends SnowLumaEvent = SnowLumaEvent> = (
event: TEvent,
context: SnowLumaEventContext<TEvent>,
) => MaybePromise;
/** Middleware in the WebSocket event dispatch pipeline. */
export type EventMiddleware = (
event: SnowLumaEvent,
context: SnowLumaEventContext,
next: EventNext,
) => MaybePromise;
/** Options for accepting or rejecting OneBot request events. */
export interface RequestDecisionOptions extends RequestOptions {
reason?: string;
subType?: string;
}
/** Convenience context passed to event middleware and handlers. */
export interface SnowLumaEventContext<TEvent extends SnowLumaEvent = SnowLumaEvent> {
readonly event: TEvent;
readonly client: SnowLumaApiClient;
readonly stopped: boolean;
/** Prevents subsequent middleware and final onEvent listeners from running. */
stopPropagation(): void;
/** Replies to private or group message events with the correct API. */
reply(message: OutgoingMessage, options?: RequestOptions & { autoEscape?: boolean }): Promise<unknown>;
/** Approves a friend or group request event. */
approve(options?: RequestDecisionOptions): Promise<unknown>;
/** Rejects a friend or group request event. */
reject(reason?: string, options?: RequestDecisionOptions): Promise<unknown>;
/** Sends OneBot .handle_quick_operation with the current event as context. */
quickOperation(operation: JsonObject, options?: RequestOptions): Promise<unknown>;
}
/** Command matching options for WebSocketClient.command(). */
export interface CommandOptions {
prefixes?: string | string[];
trim?: boolean;
caseSensitive?: boolean;
}
/** Parsed command information passed to command handlers. */
export interface CommandMatch {
command: string;
text: string;
+3 -23
View File
@@ -1,5 +1,3 @@
import { segments } from './segments';
import { segmentsToCQString } from './cq-format';
import type {
AnyMessageSegment,
ContactSegment,
@@ -15,6 +13,8 @@ import type {
VideoSegment,
XmlSegment,
} from '../types/index';
import { segmentsToCQString } from './cq-format';
import { segments } from './segments';
export interface MessageChainSender {
sendGroupMessage(groupId: number, message: OutgoingMessage, options?: RequestOptions & { autoEscape?: boolean }): Promise<unknown>;
@@ -23,40 +23,30 @@ export interface MessageChainSender {
const SINGLE_USE_TYPES = new Set(['reply']);
/**
* Immutable fluent builder for OneBot message segments.
*
* The generic state tracks single-use segments such as reply(), so TypeScript
* can reject duplicate reply segments in normal chained calls.
*/
export class MessageChain<THasReply extends boolean = false> implements MessageChainLike {
private readonly replyStateBrand?: THasReply;
private constructor(
private readonly items: AnyMessageSegment[] = [],
private readonly used: ReadonlySet<string> = new Set(),
) {}
) { }
static empty(): MessageChain<false> {
return new MessageChain<false>();
}
/** Number of segments currently in the chain. */
get length(): number {
return this.items.length;
}
/** True when no segment has been appended. */
get isEmpty(): boolean {
return this.items.length === 0;
}
/** Appends a text segment. */
text(text = ''): MessageChain<THasReply> {
return this.addSegment(segments.text(text));
}
/** Appends a newline text segment. */
br(): MessageChain<THasReply> {
return this.text('\n');
}
@@ -65,7 +55,6 @@ export class MessageChain<THasReply extends boolean = false> implements MessageC
return this.addSegment(segments.face(id));
}
/** Mentions a user or everyone in a group. */
at(qq: number | 'all', options: { name?: string; uid?: string } = {}): MessageChain<THasReply> {
return this.addSegment(segments.at(qq, options));
}
@@ -74,12 +63,10 @@ export class MessageChain<THasReply extends boolean = false> implements MessageC
return this.at('all');
}
/** Adds a reply segment. A chain can contain at most one reply segment. */
reply(this: MessageChain<false>, id: number | string): MessageChain<true> {
return this.addSegment(segments.reply(id), 'reply') as MessageChain<true>;
}
/** Appends an image segment from a URL, local path, file id, or base64 URI. */
image(file: string, options: Omit<ImageSegment['data'], 'file'> = {}): MessageChain<THasReply> {
return this.addSegment(segments.image(file, options));
}
@@ -132,7 +119,6 @@ export class MessageChain<THasReply extends boolean = false> implements MessageC
return this.addSegment(segments.raw(type, data), type);
}
/** Appends another outgoing message while preserving single-use segment checks. */
append(messageInput: OutgoingMessage): MessageChain<THasReply> {
let next: MessageChain<THasReply> = this;
const normalized = normalizeMessage(messageInput);
@@ -145,7 +131,6 @@ export class MessageChain<THasReply extends boolean = false> implements MessageC
return next;
}
/** Returns a fresh segment array suitable for OneBot array message format. */
build(): AnyMessageSegment[] {
return this.toSegments();
}
@@ -166,7 +151,6 @@ export class MessageChain<THasReply extends boolean = false> implements MessageC
return segmentsToCQString(this.items);
}
/** Sends this chain to a group through a compatible SnowLuma client. */
sendToGroup(
client: MessageChainSender,
groupId: number,
@@ -175,7 +159,6 @@ export class MessageChain<THasReply extends boolean = false> implements MessageC
return client.sendGroupMessage(groupId, this, options);
}
/** Sends this chain to a private chat through a compatible SnowLuma client. */
sendToPrivate(
client: MessageChainSender,
userId: number,
@@ -212,7 +195,6 @@ export function chain(): MessageChain<false> {
return MessageChain.empty();
}
/** Starts a message chain with a text segment. */
export function text(value = ''): MessageChain<false> {
return chain().text(value);
}
@@ -237,7 +219,6 @@ export function reply(id: number | string): MessageChain<true> {
return chain().reply(id);
}
/** Starts a message chain with an image segment. */
export function image(file: string, options: Omit<ImageSegment['data'], 'file'> = {}): MessageChain<false> {
return chain().image(file, options);
}
@@ -290,7 +271,6 @@ export function raw<TType extends string, TData extends JsonObject>(type: TType,
return chain().raw(type, data);
}
/** Normalizes a string, segment, segment array, or MessageChain into OneBot output. */
export function normalizeMessage(input: OutgoingMessage): string | AnyMessageSegment[] {
if (typeof input === 'string') return input;
if (isMessageChainLike(input)) return input.toSegments();