Refactor Bridge APIs, slim Bridge and reorder imports

Move and standardize API implementations under bridge/apis, slim down the Bridge class (remove inline action implementations, caches and large comment blocks) and relocate related types/exports. Clean up and reorder imports across many bridge/api modules, normalize constructors, add logger imports where needed, and adjust WebUI routing/import ordering. These changes centralize API logic, reduce Bridge surface area, and tidy module boundaries and imports.
This commit is contained in:
手瓜一十雪 committed 2026-05-24 13:13:23 +08:00
1 parent a52a9724cb
commit a49e507e15
22 files changed
+144 -452

No files matched your search

+10 -17
View File
@@ -1,12 +1,10 @@
// ContactsApi — facade over the 6 contacts-related OIDB cmds (friend
// roster / group roster / member roster / user profile / group request
// list / download rkeys). Single-shot cmds forward straight to their
// namespace; pagination and the per-group cache + inflight coalescing
// for fetchGroupMemberList live here because they need cross-call
// state.
import type { BridgeContext } from '../bridge-context';
import type { DownloadRKeyInfo } from '../bridge';
import { FetchDownloadRkeys } from '@snowluma/protocol/oidb-services/contacts/fetch-download-rkeys';
import { FetchFriendListPage } from '@snowluma/protocol/oidb-services/contacts/fetch-friend-list-page';
import { FetchGroupList } from '@snowluma/protocol/oidb-services/contacts/fetch-group-list';
import { FetchGroupMemberListPage } from '@snowluma/protocol/oidb-services/contacts/fetch-group-member-list-page';
import { FetchGroupRequests } from '@snowluma/protocol/oidb-services/contacts/fetch-group-requests';
import { FetchUserProfile } from '@snowluma/protocol/oidb-services/contacts/fetch-user-profile';
import { FetchUserProfileByUid } from '@snowluma/protocol/oidb-services/contacts/fetch-user-profile-by-uid';
import type {
FriendInfo,
GroupMemberInfo,
@@ -14,13 +12,8 @@ import type {
QQGroupInfo,
UserProfileInfo,
} from '@snowluma/protocol/qq-info';
import { FetchFriendListPage } from '@snowluma/protocol/oidb-services/contacts/fetch-friend-list-page';
import { FetchGroupList } from '@snowluma/protocol/oidb-services/contacts/fetch-group-list';
import { FetchGroupMemberListPage } from '@snowluma/protocol/oidb-services/contacts/fetch-group-member-list-page';
import { FetchUserProfile } from '@snowluma/protocol/oidb-services/contacts/fetch-user-profile';
import { FetchUserProfileByUid } from '@snowluma/protocol/oidb-services/contacts/fetch-user-profile-by-uid';
import { FetchGroupRequests } from '@snowluma/protocol/oidb-services/contacts/fetch-group-requests';
import { FetchDownloadRkeys } from '@snowluma/protocol/oidb-services/contacts/fetch-download-rkeys';
import type { DownloadRKeyInfo } from '../bridge';
import type { BridgeContext } from '../bridge-context';
// ─── Helpers (previously in bridge-contacts.ts) ───────────────────
@@ -58,7 +51,7 @@ export class ContactsApi {
private memberListInflight = new Map<number, Promise<GroupMemberInfo[]>>();
private memberListLastFetch = new Map<number, { at: number; data: GroupMemberInfo[] }>();
constructor(private readonly ctx: BridgeContext) {}
constructor(private readonly ctx: BridgeContext) { }
async fetchFriendList(): Promise<FriendInfo[]> {
const friends: FriendInfo[] = [];
+6 -11
View File
@@ -1,17 +1,12 @@
// ExtrasApi — facade over Tier-2 napcat-parity OIDB cmds (group
// todo CRUD / stranger status decode / AI voice list + synthesis).
// Every method is a one-line forwarder to a self-contained namespace
// under @snowluma/protocol/oidb-services/extras.
import type { MediaIndexNode } from './shared';
import type { BridgeContext } from '../bridge-context';
import { GroupTodo } from '@snowluma/protocol/oidb-services/extras/group-todo';
import { GetStrangerStatus, type StrangerStatus as NamespaceStrangerStatus } from '@snowluma/protocol/oidb-services/extras/get-stranger-status';
import { FetchAiVoice } from '@snowluma/protocol/oidb-services/extras/fetch-ai-voice';
import {
FetchAiVoiceList,
type AiVoiceCategory as NamespaceAiVoiceCategory,
} from '@snowluma/protocol/oidb-services/extras/fetch-ai-voice-list';
import { FetchAiVoice } from '@snowluma/protocol/oidb-services/extras/fetch-ai-voice';
import { GetStrangerStatus, type StrangerStatus as NamespaceStrangerStatus } from '@snowluma/protocol/oidb-services/extras/get-stranger-status';
import { GroupTodo } from '@snowluma/protocol/oidb-services/extras/group-todo';
import type { BridgeContext } from '../bridge-context';
import type { MediaIndexNode } from './shared';
// ─────────────── public types (re-exported from bridge.ts as before) ───
@@ -32,7 +27,7 @@ export interface AiVoiceItem {
}
export class ExtrasApi {
constructor(private readonly ctx: BridgeContext) {}
constructor(private readonly ctx: BridgeContext) { }
// ─────────────── Group todo (0xF90) ───────────────
+7 -18
View File
@@ -1,17 +1,4 @@
// ForwardApi — long-message (聊天记录 / forward) upload + retrieval.
// Inlined from `actions/forward.ts` (deleted alongside actions/* in
// commit 13).
//
// The module-scoped `forwardResCache` stays at file scope (not on the
// class instance) because forward res_ids are globally unique, and an
// outbound upload often gets queried back through `fetch` on a
// different Bridge instance (e.g. a different OneBot connection
// hitting the same account). Keeping the cache shared across the
// process matches NapCat's behaviour.
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import { randomUUID } from 'crypto';
import { gunzipSync, gzipSync } from 'zlib';
import type { PacketInfo } from '@snowluma/common/protocol-types';
import type {
LongMsgResult,
RecvLongMsgReq,
@@ -20,12 +7,14 @@ import type {
SendLongMsgResp,
} from '@snowluma/proto-defs/longmsg';
import type { FileExtra, PushMsg, PushMsgBody } from '@snowluma/proto-defs/message';
import type { PacketInfo } from '@snowluma/common/protocol-types';
import type { BridgeContext } from '../bridge-context';
import type { Bridge } from '../bridge';
import { buildSendElems } from '@snowluma/protocol/element-builder';
import type { ForwardNodePayload, MessageElement } from '@snowluma/protocol/events';
import { parseMsgPush } from '@snowluma/protocol/msg-push';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import { randomUUID } from 'crypto';
import { gunzipSync, gzipSync } from 'zlib';
import type { Bridge } from '../bridge';
import type { BridgeContext } from '../bridge-context';
import { resolveSelfUid, toInt } from './shared';
function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; }
@@ -214,7 +203,7 @@ function previewFromElements(elements: MessageElement[]): string {
}
export class ForwardApi {
constructor(private readonly ctx: BridgeContext) {}
constructor(private readonly ctx: BridgeContext) { }
async upload(nodes: ForwardNodePayload[], groupId?: number, userId?: number): Promise<string> {
const { resId } = await this.uploadRecursive(nodes, groupId, userId);
+3 -11
View File
@@ -1,18 +1,10 @@
// FriendApi — facade over friend-roster OIDB cmds. Every method is a
// one-line forwarder to a self-contained namespace under
// @snowluma/protocol/oidb-services/friend. The `delete()` facade method
// adds a best-effort friend-list cache invalidation after the OIDB
// call succeeds — that side-effect stays on the facade because it
// reaches into `ctx.apis.contacts`, which the namespace deliberately
// can't see.
import type { BridgeContext } from '../bridge-context';
import { HandleFriendRequest } from '@snowluma/protocol/oidb-services/friend/handle-friend-request';
import { DeleteFriend } from '@snowluma/protocol/oidb-services/friend/delete-friend';
import { HandleFriendRequest } from '@snowluma/protocol/oidb-services/friend/handle-friend-request';
import { SetFriendRemark } from '@snowluma/protocol/oidb-services/friend/set-friend-remark';
import type { BridgeContext } from '../bridge-context';
export class FriendApi {
constructor(private readonly ctx: BridgeContext) {}
constructor(private readonly ctx: BridgeContext) { }
/**
* Accept or reject an inbound friend request. `uidOrFlag` is either a
+10 -20
View File
@@ -1,31 +1,21 @@
// GroupAdminApi — facade over Tier-2 napcat-parity group admin OIDB
// cmds (mute / kick / admin / card / name / title / leave / join-policy
// / add-request handling / @everyone budget). Every method is a
// one-line forwarder to a self-contained namespace under
// @snowluma/protocol/oidb-services/group-admin.
//
// The Apis facade keeps `bridge.apis.groupAdmin.X()` as the ergonomic
// call site; the per-(cmd, subcmd) namespaces own the wire shape and
// minimal capability surface.
import type { BridgeContext } from '../bridge-context';
import { MuteMember } from '@snowluma/protocol/oidb-services/group-admin/mute-member';
import { MuteAll } from '@snowluma/protocol/oidb-services/group-admin/mute-all';
import { SetAddOption } from '@snowluma/protocol/oidb-services/group-admin/set-add-option';
import { SetSearch } from '@snowluma/protocol/oidb-services/group-admin/set-search';
import { SetAddRequest } from '@snowluma/protocol/oidb-services/group-admin/set-add-request';
import { GetAtAllRemain } from '@snowluma/protocol/oidb-services/group-admin/get-at-all-remain';
import { KickMember } from '@snowluma/protocol/oidb-services/group-admin/kick-member';
import { KickMembers } from '@snowluma/protocol/oidb-services/group-admin/kick-members';
import { LeaveGroup } from '@snowluma/protocol/oidb-services/group-admin/leave-group';
import { MuteAll } from '@snowluma/protocol/oidb-services/group-admin/mute-all';
import { MuteMember } from '@snowluma/protocol/oidb-services/group-admin/mute-member';
import { SetAddOption } from '@snowluma/protocol/oidb-services/group-admin/set-add-option';
import { SetAddRequest } from '@snowluma/protocol/oidb-services/group-admin/set-add-request';
import { SetAdmin } from '@snowluma/protocol/oidb-services/group-admin/set-admin';
import { SetMemberCard } from '@snowluma/protocol/oidb-services/group-admin/set-member-card';
import { SetGroupName } from '@snowluma/protocol/oidb-services/group-admin/set-group-name';
import { SetSpecialTitle } from '@snowluma/protocol/oidb-services/group-admin/set-special-title';
import { SetGroupRemark } from '@snowluma/protocol/oidb-services/group-admin/set-group-remark';
import { GetAtAllRemain } from '@snowluma/protocol/oidb-services/group-admin/get-at-all-remain';
import { SetMemberCard } from '@snowluma/protocol/oidb-services/group-admin/set-member-card';
import { SetSearch } from '@snowluma/protocol/oidb-services/group-admin/set-search';
import { SetSpecialTitle } from '@snowluma/protocol/oidb-services/group-admin/set-special-title';
import type { BridgeContext } from '../bridge-context';
export class GroupAdminApi {
constructor(private readonly ctx: BridgeContext) {}
constructor(private readonly ctx: BridgeContext) { }
muteMember(groupId: number, userId: number, duration: number): Promise<void> {
return MuteMember.invoke(this.ctx, { groupId, userId, duration });
+4 -10
View File
@@ -1,10 +1,3 @@
// GroupAlbumApi — group photo album operations (list/upload/comment/
// like/delete + media listing). Inlined from `actions/group-album.ts`
// and `web-actions/group-album.ts` (both deleted alongside actions/*
// in commit 13). The pure-HTTP helpers in `web/group-album.ts` stay
// where they are — they're transport-layer code, not Bridge actions.
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type {
DeleteMediasRequest,
DeleteMediasResponse,
@@ -15,9 +8,10 @@ import type {
GetMediaListRequest,
GetMediaListResponse,
} from '@snowluma/proto-defs/oidb-actions/group-album';
import type { BridgeContext } from '../bridge-context';
import type { Bridge } from '../bridge';
import { getGroupAlbumList, uploadImageToGroupAlbum } from '@snowluma/protocol/web/group-album';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { Bridge } from '../bridge';
import type { BridgeContext } from '../bridge-context';
// `getCookies` is part of WebApi — go through the hub so we don't
// duplicate the cookie acquisition flow.
@@ -51,7 +45,7 @@ function convertBigIntToString(obj: any): any {
}
export class GroupAlbumApi {
constructor(private readonly ctx: BridgeContext) {}
constructor(private readonly ctx: BridgeContext) { }
/** List a group's albums (HTTP-cookie-based, qzone.qq.com). */
async list(groupId: number): Promise<any> {
+18 -28
View File
@@ -1,39 +1,29 @@
// GroupFileApi — group file CRUD + private (c2c) file upload + media
// download URL resolvers.
//
// Single-OIDB-call methods are one-line forwarders to namespaces
// under @snowluma/protocol/oidb-services/group-file. The multi-stage
// methods (`upload` / `uploadPrivate`) stay here because they
// orchestrate three discrete legs (OIDB preflight → highway PUT →
// follow-on OIDB publish or message send) plus the upload-cache
// bookkeeping the OneBot send path relies on.
import { protobuf_encode } from '@snowluma/proton';
import { toHexUpper } from '@snowluma/common/hex';
import { createLogger } from '@snowluma/common/logger';
import type { BridgeContext } from '../bridge-context';
import type { Bridge } from '../bridge';
import type { FileUploadExt } from '@snowluma/proto-defs/highway';
import { fetchHighwaySession, uploadHighwayHttp } from '@snowluma/protocol/highway';
import { computeHashes, computeMd5, FILE_UPLOAD_MAX_BYTES, loadBinarySource } from '@snowluma/protocol/highway/utils';
import type { FileUploadExt } from '@snowluma/proto-defs/highway';
import { protobuf_encode } from '@snowluma/proton';
import type { Bridge } from '../bridge';
import type { BridgeContext } from '../bridge-context';
import { resolveSelfUid, toInt, type MediaIndexNode } from './shared';
import { PublishGroupFile } from '@snowluma/protocol/oidb-services/group-file/publish-group-file';
import { CreateGroupFolder } from '@snowluma/protocol/oidb-services/group-file/create-group-folder';
import { DeleteGroupFile } from '@snowluma/protocol/oidb-services/group-file/delete-group-file';
import { DeleteGroupFolder } from '@snowluma/protocol/oidb-services/group-file/delete-group-folder';
import { GetGroupFileCount } from '@snowluma/protocol/oidb-services/group-file/get-group-file-count';
import { GetGroupFileUrl } from '@snowluma/protocol/oidb-services/group-file/get-group-file-url';
import { GetGroupPttUrl } from '@snowluma/protocol/oidb-services/group-file/get-group-ptt-url';
import { GetGroupVideoUrl } from '@snowluma/protocol/oidb-services/group-file/get-group-video-url';
import { GetPrivateFileUrl } from '@snowluma/protocol/oidb-services/group-file/get-private-file-url';
import { GetPrivatePttUrl } from '@snowluma/protocol/oidb-services/group-file/get-private-ptt-url';
import { GetPrivateVideoUrl } from '@snowluma/protocol/oidb-services/group-file/get-private-video-url';
import { ListGroupFilesPage } from '@snowluma/protocol/oidb-services/group-file/list-group-files-page';
import { MoveGroupFile } from '@snowluma/protocol/oidb-services/group-file/move-group-file';
import { PublishGroupFile } from '@snowluma/protocol/oidb-services/group-file/publish-group-file';
import { RenameGroupFolder } from '@snowluma/protocol/oidb-services/group-file/rename-group-folder';
import { UploadGroupFileRequest } from '@snowluma/protocol/oidb-services/group-file/upload-group-file-request';
import { UploadPrivateFileRequest } from '@snowluma/protocol/oidb-services/group-file/upload-private-file-request';
import { ListGroupFilesPage } from '@snowluma/protocol/oidb-services/group-file/list-group-files-page';
import { GetGroupFileUrl } from '@snowluma/protocol/oidb-services/group-file/get-group-file-url';
import { GetPrivateFileUrl } from '@snowluma/protocol/oidb-services/group-file/get-private-file-url';
import { DeleteGroupFile } from '@snowluma/protocol/oidb-services/group-file/delete-group-file';
import { MoveGroupFile } from '@snowluma/protocol/oidb-services/group-file/move-group-file';
import { CreateGroupFolder } from '@snowluma/protocol/oidb-services/group-file/create-group-folder';
import { DeleteGroupFolder } from '@snowluma/protocol/oidb-services/group-file/delete-group-folder';
import { RenameGroupFolder } from '@snowluma/protocol/oidb-services/group-file/rename-group-folder';
import { GetGroupPttUrl } from '@snowluma/protocol/oidb-services/group-file/get-group-ptt-url';
import { GetPrivatePttUrl } from '@snowluma/protocol/oidb-services/group-file/get-private-ptt-url';
import { GetGroupVideoUrl } from '@snowluma/protocol/oidb-services/group-file/get-group-video-url';
import { GetPrivateVideoUrl } from '@snowluma/protocol/oidb-services/group-file/get-private-video-url';
import { ensureRetCodeZero } from '@snowluma/protocol/oidb-services/shared';
const log = createLogger('GroupFile');
@@ -227,7 +217,7 @@ function buildPrivateFileUploadExt(
}
export class GroupFileApi {
constructor(private readonly ctx: BridgeContext) {}
constructor(private readonly ctx: BridgeContext) { }
// ─────────────── publish (group file → chat) ───────────────
+1 -20
View File
@@ -1,23 +1,3 @@
// ApiHub — the per-instance bag of typed Api classes hanging off
// `bridge.apis`. Mirrors NapCat's `NapCatCore.apis = { MsgApi, …}`
// pattern but uses camelCase keys (`apis.message.sendGroup`) to match
// the rest of the SnowLuma TypeScript style.
//
// Each Api class is constructed once when the parent `Bridge` is
// constructed (eager — every account that connects gets its own
// `apis.*` set immediately). Api classes receive a `BridgeContext`
// reference, NOT the concrete `Bridge`, so they remain easy to mock
// without standing up a full Bridge instance.
//
// Adding a new Api:
// 1. Create `bridge/apis/<name>.ts` exporting a `class XxxApi`.
// 2. Add a property here.
// 3. Construct it inside `buildApiHub(ctx)` below.
// 4. Move the relevant methods OFF Bridge and onto the new Api.
//
// All 12 Api hubs are now live (#6 commits 1-12). The interface lists
// every typed area an OneBot caller can reach via `bridge.apis.*`.
import type { BridgeContext } from '../bridge-context';
import { ContactsApi } from './contacts';
import { ExtrasApi } from './extras';
@@ -99,3 +79,4 @@ export { MessageApi } from './message';
export { MiscApi } from './misc';
export { ProfileApi } from './profile';
export { WebApi } from './web';
+4 -4
View File
@@ -6,16 +6,16 @@
// work (envelope build / encode / send / decode) lives in the
// namespace files.
import type { BridgeContext } from '../bridge-context';
import { SendPoke } from '@snowluma/protocol/oidb-services/interaction/send-poke';
import { SendLike } from '@snowluma/protocol/oidb-services/interaction/send-like';
import { SendPoke } from '@snowluma/protocol/oidb-services/interaction/send-poke';
import { SetEssence } from '@snowluma/protocol/oidb-services/interaction/set-essence';
import { SetReaction } from '@snowluma/protocol/oidb-services/reaction/set-reaction';
import { FetchReactionSummary } from '@snowluma/protocol/oidb-services/reaction/fetch-reaction-summary';
import { GetEmojiLikes } from '@snowluma/protocol/oidb-services/reaction/get-emoji-likes';
import { SetReaction } from '@snowluma/protocol/oidb-services/reaction/set-reaction';
import type { BridgeContext } from '../bridge-context';
export class InteractionApi {
constructor(private readonly ctx: BridgeContext) {}
constructor(private readonly ctx: BridgeContext) { }
sendPoke(isGroup: boolean, peerUin: number, targetUin?: number): Promise<void> {
return SendPoke.invoke(this.ctx, { isGroup, peerUin, targetUin });
+3 -16
View File
@@ -1,17 +1,3 @@
// MessageApi — send / recall / mark-read operations.
//
// Folds together the previous shapes:
// - `Bridge.sendGroupMessage` / `sendPrivateMessage` / `sendC2cFileMessage`
// (formerly inline on the Bridge class).
// - `actions/group-message.ts` (recallGroup / recallPrivate /
// markGroupRead / markPrivateRead).
//
// All implementations are inlined here — the previous indirection
// through `actions/group-message.ts` exported functions was just
// `(bridge, args) → method body`; once methods live on a typed Api
// class the wrapper layer doesn't earn its keep.
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type {
SendMessageRequest,
SendMessageResponse,
@@ -22,8 +8,9 @@ import type {
GroupRecallRequest,
SsoReadedReportReq,
} from '@snowluma/proto-defs/oidb-actions/base';
import type { MessageElement } from '@snowluma/protocol/events';
import { buildSendElems } from '@snowluma/protocol/element-builder';
import type { MessageElement } from '@snowluma/protocol/events';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { BridgeContext } from '../bridge-context';
// `Bridge` is imported as a type only so we can narrow `ctx` back to
// the concrete Bridge instance when passing it to `buildSendElems`
@@ -38,7 +25,7 @@ import type { Bridge, SendMessageReceipt } from '../bridge';
const SEND_MSG_CMD = 'MessageSvc.PbSendMsg';
export class MessageApi {
constructor(private readonly ctx: BridgeContext) {}
constructor(private readonly ctx: BridgeContext) { }
/**
* Send a message to a QQ group.
+3 -8
View File
@@ -1,21 +1,16 @@
// MiscApi — odds & ends that don't fit the other Apis: translation,
// mini-app ARK build, inline-keyboard button click, group sign-in.
// Inlined from `actions/misc.ts` (deleted alongside actions/* in
// commit 13).
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type {
MiniAppShareReq,
MiniAppShareResp,
} from '@snowluma/proto-defs/oidb-actions/base';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { BridgeContext } from '../bridge-context';
// Migrated OIDB cmds — facade methods are one-line forwarders.
import { TranslateEnToZh } from '@snowluma/protocol/oidb-services/misc/translate-en-to-zh';
import { ClickInlineKeyboardButton } from '@snowluma/protocol/oidb-services/misc/click-inline-keyboard-button';
import { SendGroupSign } from '@snowluma/protocol/oidb-services/misc/send-group-sign';
import { TranslateEnToZh } from '@snowluma/protocol/oidb-services/misc/translate-en-to-zh';
export class MiscApi {
constructor(private readonly ctx: BridgeContext) {}
constructor(private readonly ctx: BridgeContext) { }
translateEn2Zh(words: string[]): Promise<string[]> {
return TranslateEnToZh.invoke(this.ctx, { words });
+7 -12
View File
@@ -1,8 +1,3 @@
// ProfileApi — personal profile + status + avatar + likes + custom
// faces + unidirectional friend list. Inlined from
// `actions/profile.ts` (deleted alongside actions/* in commit 13).
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type {
FaceroamOpReq,
FaceroamOpResp,
@@ -10,21 +5,21 @@ import type {
SetStatusReq,
SetStatusResp,
} from '@snowluma/proto-defs/oidb-actions/base';
import type { BridgeContext } from '../bridge-context';
import type { Bridge } from '../bridge';
import { fetchHighwaySession, uploadHighwayHttp } from '@snowluma/protocol/highway';
import { computeHashes, loadBinarySource } from '@snowluma/protocol/highway/utils';
// Migrated OIDB cmds — facade methods are one-line forwarders.
import { SetProfile } from '@snowluma/protocol/oidb-services/profile/set-profile';
import { SetSelfLongNick } from '@snowluma/protocol/oidb-services/profile/set-self-long-nick';
import { SetInputStatus } from '@snowluma/protocol/oidb-services/profile/set-input-status';
import { GetLike } from '@snowluma/protocol/oidb-services/profile/get-like';
import { GetUnidirectionalFriendList } from '@snowluma/protocol/oidb-services/profile/get-unidirectional-friend-list';
import { SetInputStatus } from '@snowluma/protocol/oidb-services/profile/set-input-status';
import { SetProfile } from '@snowluma/protocol/oidb-services/profile/set-profile';
import { SetSelfLongNick } from '@snowluma/protocol/oidb-services/profile/set-self-long-nick';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { Bridge } from '../bridge';
import type { BridgeContext } from '../bridge-context';
function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; }
export class ProfileApi {
constructor(private readonly ctx: BridgeContext) {}
constructor(private readonly ctx: BridgeContext) { }
// ─────────────── status / profile setters ───────────────
-5
View File
@@ -1,10 +1,5 @@
import type { Bridge } from '../bridge';
/**
* Coerce numbers, strings, and bigints to a plain integer.
* Returns 0 for anything we can't interpret — every action that
* threads this through OIDB has an explicit `<=0` validation later.
*/
export function toInt(value: unknown): number {
if (typeof value === 'number' && Number.isFinite(value)) return Math.trunc(value);
if (typeof value === 'bigint') {
+5 -13
View File
@@ -1,11 +1,5 @@
// WebApi — cookie-backed HTTP wrappers (group essence / honor / notice /
// client-key / pskey / csrf-token / credentials). Inlined from the
// per-feature files in `web-actions/` (all deleted in commit 13).
// The pure HTTP transport stays in `web/*.ts` and stays unchanged —
// only the Bridge-binding helpers move here.
import type { BridgeContext } from '../bridge-context';
import type { Bridge } from '../bridge';
import { ForceFetchClientKey, type ClientKeyInfo as NamespaceClientKeyInfo } from '@snowluma/protocol/oidb-services/web/force-fetch-client-key';
import { GetPskey } from '@snowluma/protocol/oidb-services/web/get-pskey';
import { getGroupEssenceMsg, getGroupEssenceMsgAll } from '@snowluma/protocol/web/group-essence';
import { getHonorListWebAPI, WebHonorType } from '@snowluma/protocol/web/group-honor';
import {
@@ -15,10 +9,8 @@ import {
uploadGroupNoticeImage,
} from '@snowluma/protocol/web/group-notice';
import { RequestUtil } from '@snowluma/protocol/web/request-util';
// Migrated OIDB cmds — the two private helpers below are thin
// forwarders into the namespaces.
import { ForceFetchClientKey, type ClientKeyInfo as NamespaceClientKeyInfo } from '@snowluma/protocol/oidb-services/web/force-fetch-client-key';
import { GetPskey } from '@snowluma/protocol/oidb-services/web/get-pskey';
import type { Bridge } from '../bridge';
import type { BridgeContext } from '../bridge-context';
function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; }
@@ -101,7 +93,7 @@ function getBknFromSKey(skey: string): number {
}
export class WebApi {
constructor(private readonly ctx: BridgeContext) {}
constructor(private readonly ctx: BridgeContext) { }
// ─────────────── cookie / token primitives ───────────────
+1 -20
View File
@@ -1,27 +1,8 @@
// Api-layer extension of @snowluma/protocol's slim BridgeContext.
//
// The slim interface in @snowluma/protocol has the protocol-layer
// surface (identity / events / sendRawPacket / resolveUserUid / next*
// sequence helpers / upload-metadata cache). This file extends it
// with `apis: ApiHub` — the typed bag of Api classes that lives ONLY
// in @snowluma/core, so the bridge package never sees it (avoiding
// a bridge → core cycle).
//
// The 13 Api classes (apis/<area>.ts) import `BridgeContext` from
// here, which gives them `this.ctx.apis.message.sendGroup(...)` type-
// safety alongside the protocol-layer fields. Highway uploaders,
// element-builder, msg-push parsers (all in @snowluma/protocol) import
// the slim version directly from `@snowluma/protocol/bridge-context`.
import type { BridgeContext as BaseBridgeContext } from '@snowluma/protocol/bridge-context';
import type { ApiHub } from './apis';
export interface BridgeContext extends BaseBridgeContext {
readonly apis: ApiHub;
}
// Re-export `UploadedFileMeta` from the slim package so existing
// `import type { UploadedFileMeta } from '<…>/bridge-context'` (or
// from bridge.ts via re-export) keeps working without callers having
// to learn the new package path.
export type { UploadedFileMeta } from '@snowluma/protocol/bridge-context';
@@ -1,22 +1,5 @@
// BridgeInterface — the public Bridge surface for OneBot-side
// consumers. Slimmed down to BridgeContext + the few extra fields
// OneBot reaches into directly (most notably `activePid`).
//
// Most OneBot code paths reach business methods through
// `bridge.apis.<area>.method()` — those types come from `ApiHub`
// inside `bridge-context.ts`. The remaining members below are the
// non-Api state that doesn't fit into a typed Api hub.
//
// Internal Api implementations should depend on `BridgeContext`
// instead (the narrower contract). `BridgeInterface` is for callers
// that need the activePid hook or for backwards compatibility with
// pre-#6 code that imported `BridgeInterface` as the bridge type.
import type { BridgeContext } from './bridge-context';
export interface BridgeInterface extends BridgeContext {
/** Last-active process id — used by `OneBotManager` to thread
* per-process state into the right instance. `null` when no
* process has bound yet. */
readonly activePid: number | null;
}
+43 -193
View File
@@ -1,142 +1,32 @@
import type { PacketSender, SendPacketResult } from '@snowluma/common/packet-sender';
import type { PacketInfo } from '@snowluma/common/protocol-types';
import type { BridgeInterface } from './bridge-interface';
import { BridgeEventBus } from '@snowluma/protocol/event-bus';
import { IdentityService } from '@snowluma/protocol/identity-service';
import { MSG_PUSH_CMD, parseMsgPush } from '@snowluma/protocol/msg-push';
import { IncomingPacketPipeline, type CmdParser } from '@snowluma/protocol/packet-pipeline';
// qq-info types are no longer used directly in this file — they live
// inside the Api classes that own those fetches (apis/contacts.ts).
import { type ApiHub, buildApiHub } from './apis';
// Delegated modules
// Group-todo / stranger-status / AI-voice moved to apis/extras.ts.
// Public types stay re-exported through this file for backwards
// compatibility — the OneBot side imports them via `@snowluma/core`.
import { buildApiHub, type ApiHub } from './apis';
import {
AiVoiceChatType,
type AiVoiceCategory,
type StrangerStatus,
} from './apis/extras';
// actions/forward.ts removed — moved to apis/forward.ts::ForwardApi.
// actions/friend.ts removed — moved to apis/friend.ts::FriendApi.
// actions/group-admin.ts removed — moved to `apis/group-admin.ts::GroupAdminApi`.
// actions/group-album.ts removed — moved to `apis/group-album.ts::GroupAlbumApi`.
// Group file CRUD + private c2c upload + media URL resolvers moved to
// `apis.groupFile` (see `apis/group-file.ts::GroupFileApi`). The shared
// result type still lives here because the OneBot side imports it
// through bridge.ts.
import type { GroupFilesResult } from './apis/group-file';
// actions/group-message.ts removed — `setGroupEssence` moved to
// apis/interaction.ts::InteractionApi. The recall/markRead helpers
// were absorbed into MessageApi back in commit 1.
// actions/interaction.ts removed — sendPoke/sendLike/setReaction/
// getEmojiLikes moved to apis/interaction.ts::InteractionApi.
// actions/misc.ts removed — moved to apis/misc.ts::MiscApi.
// actions/profile.ts removed — moved to apis/profile.ts::ProfileApi.
// `bridge-contacts.ts` removed — its 6 functions are now methods on
// `apis.contacts` (see `apis/contacts.ts::ContactsApi`).
import { BridgeEventBus } from '@snowluma/protocol/event-bus';
// web-actions/* removed — moved to apis/web.ts::WebApi.
export { AiVoiceChatType };
export type { AiVoiceCategory, StrangerStatus };
import type { BridgeInterface } from './bridge-interface';
export interface SendMessageReceipt {
messageId: number;
sequence: number;
clientSequence: number;
random: number;
timestamp: number;
}
/**
* Metadata remembered after `upload_group_file` / `upload_private_file`
* succeeds. Lets the OneBot send-message path reconstruct the full
* payload when the caller only echoes the `file_id` back later. See
* `Bridge.rememberUploadedFile` / `recallUploadedFile`.
*/
export interface UploadedFileMeta {
fileId: string;
scope: 'group' | 'private';
/** Group id if scope='group', else `undefined`. */
groupId?: number;
/** Friend uin if scope='private', else `undefined`. */
userId?: number;
fileName: string;
fileSize: number;
fileMd5: Uint8Array;
fileSha1: Uint8Array;
/** Server-issued hash returned alongside the upload (private only). */
fileHash?: string;
/** Insert time — used to evict the oldest entry when the cache fills. */
rememberedAt: number;
}
export interface DownloadRKeyInfo {
rkey: string;
ttlSeconds: number;
storeId: number;
createTime: number;
type: number;
}
export interface ClientKeyInfo {
clientKey: string;
expireTime: string;
keyIndex: string
}
export class Bridge implements BridgeInterface {
readonly identity: IdentityService;
private pids_ = new Set<number>();
/**
* Per-kind event subscription. Replaces the legacy single-callback
* firehose: downstream consumers now register exactly the kinds they
* care about and the pipeline fans out in parallel.
*/
readonly events = new BridgeEventBus();
/**
* Typed Api hub. Each entry is a class encapsulating one logical
* area of the QQ protocol (sending messages, group admin, file
* uploads, etc.). Built eagerly in the constructor — every Bridge
* instance gets its own `apis.*` set with `this` (typed as
* `BridgeContext`) injected. See `apis/index.ts`.
*/
readonly apis: ApiHub;
private readonly pipeline: IncomingPacketPipeline;
private packetClient_: PacketSender | null = null;
// (fetchGroupMemberList throttle cache moved to ContactsApi — same
// 60s TTL + inflight coalesce semantics, just owned by the Api class
// that exposes the method.)
// ── Uploaded-file metadata cache ────────────────────────────────────
//
// After a file goes through `upload_group_file` / `upload_private_file`
// we remember the (fileName, fileSize, fileMd5, fileHash) tuple keyed
// by the returned file_id. The OneBot send-message paths consult this
// when the caller later passes `{type:'file', file_id:'xxx'}` without
// the rest of the metadata — c2c file send needs the size/md5/name
// for the wire packet (server-side rejection / "0 byte file" otherwise),
// and the group send path falls back to the name for the log line.
//
// Bounded at ~1024 entries with simple FIFO eviction. Files older
// than 7 days expire on QQ's side anyway, so this isn't load-bearing
// for correctness — just a UX convenience cache so the OneBot caller
// doesn't have to thread the metadata themselves between upload and
// send_msg.
private static readonly UPLOADED_FILE_CACHE_MAX = 1024;
private uploadedFileMeta_ = new Map<string, UploadedFileMeta>();
// Sequence and random generators for outgoing messages
private clientSeq_ = 100000000 + (Date.now() % 1000000000);
private msgRandom_ = (Date.now() & 0xFFFFFFFF) >>> 0;
constructor(identity: IdentityService) {
this.identity = identity;
// Build Api hub FIRST — `setFetcher` below installs callbacks
// that reach into `this.apis.contacts.*`, so the hub must exist
// by the time those callbacks could fire. The Bridge instance IS
// the BridgeContext (Bridge implements BridgeInterface which
// includes the BridgeContext surface).
this.apis = buildApiHub(this);
this.identity.setFetcher({
fetchProfile: (uin) => this.apis.contacts.fetchUserProfile(uin),
@@ -157,11 +47,6 @@ export class Bridge implements BridgeInterface {
}
},
resolveGroupJoinRequest: async (groupId, uid, subType) => {
// OIDB 0x10C0 pending-request queue holds (targetUid,
// invitorUid, comment, sequence, ...). For a plain join the
// requester is `targetUid`; for a forwarded invite it's
// `invitorUid`. Mirrors NapCat's `getGroupNotifies` →
// `notify.postscript` pipeline.
try {
const requests = await this.apis.contacts.fetchGroupRequests();
const match = requests.find(r => {
@@ -195,8 +80,6 @@ export class Bridge implements BridgeInterface {
return this.pipeline.handlesCmd(cmd);
}
// --- PID management ---
attachPid(pid: number): void {
this.pids_.add(pid);
}
@@ -209,9 +92,6 @@ export class Bridge implements BridgeInterface {
for (const pid of this.pids_) return pid;
return null;
}
// --- Packet dispatch ---
onPacket(pkt: PacketInfo): void {
this.pipeline.process(pkt);
}
@@ -224,18 +104,6 @@ export class Bridge implements BridgeInterface {
await this.apis.contacts.fetchGroupMemberList(groupId, { force: forceMemberList });
return true;
}
// --- Uploaded-file metadata cache ---
/**
* Remember a freshly-uploaded file so a later `send_*_msg` carrying
* just the file_id can reconstruct the full c2c-file packet (fileName
* / fileSize / fileMd5 are required by the QQ NT server's c2c file
* intake, even if only the uuid is needed for the OIDB lookup
* internally — without them the file shows as 0 B in the recipient's
* chat or is silently rejected). Insertion is FIFO; oldest entry is
* evicted when the cache hits `UPLOADED_FILE_CACHE_MAX`.
*/
rememberUploadedFile(meta: UploadedFileMeta): void {
if (!meta.fileId) return;
if (this.uploadedFileMeta_.size >= Bridge.UPLOADED_FILE_CACHE_MAX) {
@@ -246,24 +114,11 @@ export class Bridge implements BridgeInterface {
this.uploadedFileMeta_.set(meta.fileId, meta);
}
/**
* Recall metadata for a previously-uploaded file. Returns `undefined`
* if the file_id was never uploaded through this bridge instance, or
* if it's been evicted from the cache.
*/
recallUploadedFile(fileId: string): UploadedFileMeta | undefined {
if (!fileId) return undefined;
return this.uploadedFileMeta_.get(fileId);
}
// --- Sequence / random generators ---
//
// `public` (formerly `private`) because the Api classes in
// `apis/*.ts` need them to build `SendMessageRequest` packets. Part
// of the `BridgeContext` surface, so a third party that only sees
// `BridgeContext` can still synthesise wire packets without reaching
// into the concrete Bridge class.
nextClientSequence(): number {
return ++this.clientSeq_;
}
@@ -272,9 +127,6 @@ export class Bridge implements BridgeInterface {
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 {
@@ -284,50 +136,48 @@ export class Bridge implements BridgeInterface {
}
return this.packetClient_.sendPacket(serviceCmd, Buffer.from(body), timeoutMs);
}
// `Bridge.SEND_MSG_CMD` and the inline `sendGroupMessage` /
// `sendPrivateMessage` / `sendC2cFileMessage` implementations were
// moved to `apis/message.ts::MessageApi` as part of the #6
// Api-on-ctx refactor. Callers route through `bridge.apis.message.*`.
// --- Delegated: OIDB helpers ---
async resolveUserUid(uin: number, groupId?: number): Promise<string> {
return this.identity.resolveUid(uin, groupId);
}
// fetchFriendList / fetchGroupList / fetchGroupMemberList /
// fetchUserProfile / fetchGroupRequests / fetchDownloadRKeys
// moved to apis.contacts (see apis/contacts.ts::ContactsApi).
// --- Delegated: action methods ---
//
// GroupAdmin methods (mute/kick/admin/card/name/title/leave/
// add-option/search/add-request/remark/at-all-remain) moved to
// apis.groupAdmin (apis/group-admin.ts::GroupAdminApi).
// Friend methods (handleRequest/delete/setRemark) moved to
// apis.friend.
// GroupFile methods (upload/uploadPrivate/publish/list/getUrl/
// getPrivateUrl/{Ptt,Video}Url/getPrivate{Ptt,Video}Url/delete/move/
// createFolder/deleteFolder/renameFolder/getCount) moved to
// apis.groupFile (apis/group-file.ts::GroupFileApi).
// Forward methods (upload / fetch) moved to apis.forward.
// Interaction methods (sendPoke/sendLike/setReaction/setEssence/
// getEmojiLikes) moved to apis.interaction.
// recall* / markRead* moved to apis/message.ts::MessageApi.
// GroupAlbum methods (list/upload/getMediaList/comment/like/delete)
// moved to apis.groupAlbum (apis/group-album.ts::GroupAlbumApi).
// Web methods (getHonorInfo / forceFetchClientKey / getEssence /
// getEssenceAll / sendNotice / getNotice / deleteNotice /
// getCookiesStr / getCsrfToken / getCredentials) moved to apis.web.
// Profile methods (setOnlineStatus / setDiyOnlineStatus / setProfile /
// setSelfLongNick / setInputStatus / setAvatar / setGroupAvatar /
// fetchCustomFace / getLike / getUnidirectionalFriendList) moved to
// apis.profile.
// Misc methods (translateEn2Zh / getMiniAppArk /
// clickInlineKeyboardButton / sendGroupSign) moved to apis.misc.
// --- Tier-2 napcat-parity extras (group todo / stranger status /
// AI voice) moved to apis.extras. ---
}
export interface SendMessageReceipt {
messageId: number;
sequence: number;
clientSequence: number;
random: number;
timestamp: number;
}
export interface UploadedFileMeta {
fileId: string;
scope: 'group' | 'private';
/** Group id if scope='group', else `undefined`. */
groupId?: number;
/** Friend uin if scope='private', else `undefined`. */
userId?: number;
fileName: string;
fileSize: number;
fileMd5: Uint8Array;
fileSha1: Uint8Array;
/** Server-issued hash returned alongside the upload (private only). */
fileHash?: string;
/** Insert time — used to evict the oldest entry when the cache fills. */
rememberedAt: number;
}
export interface DownloadRKeyInfo {
rkey: string;
ttlSeconds: number;
storeId: number;
createTime: number;
type: number;
}
export interface ClientKeyInfo {
clientKey: string;
expireTime: string;
keyIndex: string
}
export { AiVoiceChatType };
export type { AiVoiceCategory, StrangerStatus };
+2 -2
View File
@@ -1,8 +1,8 @@
import { createLogger } from '@snowluma/common/logger';
import type { PacketSender } from '@snowluma/common/packet-sender';
import type { PacketInfo } from '@snowluma/common/protocol-types';
import { createLogger } from '@snowluma/common/logger';
import { Bridge } from './bridge';
import { IdentityService } from '@snowluma/protocol/identity-service';
import { Bridge } from './bridge';
export type SessionStartedCallback = (uin: string, bridge: Bridge) => void;
export type SessionClosedCallback = (uin: string) => void;
+4 -10
View File
@@ -1,8 +1,8 @@
import { BridgeManager } from './bridge/manager';
import { OneBotManager } from '@snowluma/onebot/manager';
import { loadRuntimeConfig } from '@snowluma/common/runtime';
import { closeLogger, createLogger } from '@snowluma/common/logger';
import { HookManager } from '@snowluma/bridge';
import { closeLogger, createLogger } from '@snowluma/common/logger';
import { loadRuntimeConfig } from '@snowluma/common/runtime';
import { OneBotManager } from '@snowluma/onebot/manager';
import { BridgeManager } from './bridge/manager';
const runtimeConfig = loadRuntimeConfig();
const log = createLogger('App');
@@ -12,12 +12,6 @@ async function main() {
const bridgeManager = new BridgeManager();
const oneBotManager = new OneBotManager();
// HookManager defaults its packet sink to bridgeManager.onPacket, so
// every parsed hook packet reaches the per-UIN bridge dispatcher with
// no intermediate layer.
// Env var SNOWLUMA_HOOK_AUTOLOAD wins over runtime.json so Docker /
// headless deployments can flip auto-injection on without touching the
// persisted user config volume.
const autoLoadOnDiscovery = resolveAutoLoad(runtimeConfig.hookAutoLoad);
const hookManager = new HookManager({ bridgeManager, autoLoadOnDiscovery });
if (autoLoadOnDiscovery) {
+1 -1
View File
@@ -1,7 +1,7 @@
import { createLogger } from '@snowluma/common/logger';
import { randomBytes, scryptSync, timingSafeEqual } from 'crypto';
import fs from 'fs';
import path from 'path';
import { createLogger } from '@snowluma/common/logger';
const log = createLogger('WebUI.Auth');
-4
View File
@@ -1,9 +1,5 @@
import net from 'net';
/**
* Probe whether a TCP port is bindable on the given host.
* Resolves to true when bind+listen succeed.
*/
function isPortAvailable(port: number, host = '0.0.0.0'): Promise<boolean> {
return new Promise((resolve) => {
const server = net.createServer();
+12 -12
View File
@@ -1,18 +1,18 @@
import { serve } from '@hono/node-server';
import { serveStatic } from '@hono/node-server/serve-static';
import { Hono, type Context } from 'hono';
import { describeTrustProxy, makeClientIpResolver, parseTrustProxy } from './client-ip';
import { createLogger, getLogLevel, getRecentLogs, LOG_LEVELS, setLogLevel, subscribeLogs } from '@snowluma/common/logger';
import { randomBytes } from 'crypto';
import type { OneBotManager } from '@snowluma/onebot/manager';
import { loadOneBotConfig, saveOneBotConfig } from '@snowluma/onebot/config';
import type { OneBotConfig } from '@snowluma/onebot/types';
import type { HookManager, HookProcessInfo } from '@snowluma/bridge';
import path from 'path';
import { createLogger, getLogLevel, getRecentLogs, LOG_LEVELS, setLogLevel, subscribeLogs } from '@snowluma/common/logger';
import { loadOneBotConfig, saveOneBotConfig } from '@snowluma/onebot/config';
import type { OneBotManager } from '@snowluma/onebot/manager';
import type { OneBotConfig } from '@snowluma/onebot/types';
import { randomBytes } from 'crypto';
import { existsSync, readFileSync } from 'fs';
import { fileURLToPath } from 'url';
import { Hono, type Context } from 'hono';
import os from 'os';
import { WebuiAuth, evaluatePasswordRules, isStrongPassword } from './auth';
import path from 'path';
import { fileURLToPath } from 'url';
import { evaluatePasswordRules, isStrongPassword, WebuiAuth } from './auth';
import { describeTrustProxy, makeClientIpResolver, parseTrustProxy } from './client-ip';
import { findAvailablePort } from './port';
const log = createLogger('WebUI');
@@ -446,8 +446,8 @@ export async function initWebUI(
}
};
}
app.post('/api/processes/:pid/load', processAction('load', (pid) => hookManager!.loadProcess(pid)));
app.post('/api/processes/:pid/unload', processAction('unload', (pid) => hookManager!.unloadProcess(pid)));
app.post('/api/processes/:pid/load', processAction('load', (pid) => hookManager!.loadProcess(pid)));
app.post('/api/processes/:pid/unload', processAction('unload', (pid) => hookManager!.unloadProcess(pid)));
app.post('/api/processes/:pid/refresh', processAction('refresh', (pid) => hookManager!.refreshProcess(pid)));
app.get('/api/processes/:pid/probe-login', async (c) => {