;
export interface SendContext {
- bridge: Bridge;
+ bridge: BridgeContext;
groupId?: number;
userUid?: string;
/**
@@ -95,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);
@@ -107,7 +99,7 @@ function makeReplyElem(element: MessageElement): ProtoElem {
if (element.replyTime) {
srcMsg.time = element.replyTime;
}
-
+
return { srcMsg };
}
@@ -264,18 +256,31 @@ async function makePttElem(ctx: SendContext, element: MessageElement): Promise = Extract;
diff --git a/packages/core/src/bridge/events.ts b/packages/bridge/src/events.ts
similarity index 98%
rename from packages/core/src/bridge/events.ts
rename to packages/bridge/src/events.ts
index dcfe20ac..6ca1cf51 100644
--- a/packages/core/src/bridge/events.ts
+++ b/packages/bridge/src/events.ts
@@ -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;
diff --git a/packages/core/src/utils/event-format.ts b/packages/bridge/src/format.ts
similarity index 91%
rename from packages/core/src/utils/event-format.ts
rename to packages/bridge/src/format.ts
index 243f098a..f6f641e3 100644
--- a/packages/core/src/utils/event-format.ts
+++ b/packages/bridge/src/format.ts
@@ -1,18 +1,18 @@
-// 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 { QQEventVariant } from './events';
+import type { IdentityService } from './identity-service';
+import type { JsonObject, JsonValue } from '@snowluma/common/json';
-import type { IdentityService } from '../bridge/identity-service';
-import type { QQEventVariant } from '../bridge/events';
-import type { MessageStore } from '../onebot/message-store';
-import type { JsonObject, JsonValue } from '../onebot/types';
+/**
+ * Minimal shape of the OneBot-side `MessageStore` that `formatReply`
+ * needs — just `findEvent(id)`. Defined inline (instead of importing
+ * the full `MessageStore` class from @snowluma/onebot) so this
+ * package doesn't depend on the OneBot layer above it. The OneBot
+ * `MessageStore` is structurally a superset of this interface, so
+ * callers pass it through with zero adaptation.
+ */
+export interface ReplyEventLookup {
+ findEvent(messageId: number): JsonObject | null;
+}
const MAX_TEXT_PREVIEW = 50;
const MAX_REPLY_BODY_PREVIEW = 30;
@@ -121,7 +121,7 @@ function truncate(s: string, max: number): string {
* to" questions.
*/
export function formatReply(
- messageStore: MessageStore,
+ messageStore: ReplyEventLookup,
identity: IdentityService,
replyId: number,
): string {
diff --git a/packages/core/src/bridge/highway/ffmpeg-addon.ts b/packages/bridge/src/highway/ffmpeg-addon.ts
similarity index 94%
rename from packages/core/src/bridge/highway/ffmpeg-addon.ts
rename to packages/bridge/src/highway/ffmpeg-addon.ts
index df5cde3f..c4b69ce5 100644
--- a/packages/core/src/bridge/highway/ffmpeg-addon.ts
+++ b/packages/bridge/src/highway/ffmpeg-addon.ts
@@ -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...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));
diff --git a/packages/core/src/bridge/highway/highway-client.ts b/packages/bridge/src/highway/highway-client.ts
similarity index 94%
rename from packages/core/src/bridge/highway/highway-client.ts
rename to packages/bridge/src/highway/highway-client.ts
index bab560f8..963a92dd 100644
--- a/packages/core/src/bridge/highway/highway-client.ts
+++ b/packages/bridge/src/highway/highway-client.ts
@@ -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 { BridgeContext } from '../bridge-context';
import type {
HttpConn0x6FF501Request,
HttpConn0x6FF501Response,
+ NTV2RichMediaHighwayExt,
ReqDataHighwayHead,
RespDataHighwayHead,
- NTV2RichMediaHighwayExt,
-} from '../proto/proton/highway';
-import { packHighwayFrame, unpackHighwayFrame, computeMd5 } from './utils';
+} from '@snowluma/proto-defs/highway';
+import { computeMd5, packHighwayFrame, unpackHighwayFrame } from './utils';
const HIGHWAY_APP_ID = 1600001604;
const HIGHWAY_BLOCK_SIZE = 1024 * 1024;
@@ -30,7 +27,7 @@ function ipv4ToString(value: number): string {
return `${value & 0xFF}.${(value >> 8) & 0xFF}.${(value >> 16) & 0xFF}.${(value >> 24) & 0xFF}`;
}
-export async function fetchHighwaySession(bridge: Bridge): Promise {
+export async function fetchHighwaySession(bridge: BridgeContext): Promise {
const request = protobuf_encode({
httpConn: {
field1: 0, field2: 0, field3: 16, field4: 1, field6: 3,
@@ -221,7 +218,7 @@ async function httpPostFrame(
}
export async function uploadHighwayHttp(
- bridge: Bridge, session: HighwaySession, commandId: number,
+ bridge: BridgeContext, session: HighwaySession, commandId: number,
bytes: Uint8Array, fileMd5: Uint8Array, extend: Uint8Array,
): Promise {
const pathStr = `/cgi-bin/httpconn?htcmd=0x6FF0087&uin=${bridge.identity.uin}`;
diff --git a/packages/core/src/bridge/highway/image-upload.ts b/packages/bridge/src/highway/image-upload.ts
similarity index 91%
rename from packages/core/src/bridge/highway/image-upload.ts
rename to packages/bridge/src/highway/image-upload.ts
index 6d43e303..dbdba3d4 100644
--- a/packages/core/src/bridge/highway/image-upload.ts
+++ b/packages/bridge/src/highway/image-upload.ts
@@ -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 type { Bridge } from '../bridge';
+import { createLogger } from '@snowluma/common/logger';
+import type { BridgeContext } from '../bridge-context';
import type { MessageElement } from '../events';
-import { createLogger } from '../../utils/logger';
import { GROUP_IMAGE_CMD_ID, PRIVATE_IMAGE_CMD_ID } from './highway-client';
import {
finalizeMediaMsgInfo,
@@ -19,7 +12,7 @@ import { computeHashes, detectImageFormat, loadBinarySource } from './utils';
const moduleLog = createLogger('Highway.Image');
-function loggerFor(bridge: Bridge) {
+function loggerFor(bridge: BridgeContext) {
const raw = bridge.identity?.uin;
const uin = typeof raw === 'string' ? Number.parseInt(raw, 10) : 0;
return Number.isFinite(uin) && uin > 0 ? moduleLog.child({ uin }) : moduleLog;
@@ -110,7 +103,7 @@ async function loadImageFromSource(source: string, fileName: string, subType: nu
* commonElem.
*/
export async function uploadImageMsgInfo(
- bridge: Bridge,
+ bridge: BridgeContext,
isGroup: boolean,
targetIdOrUid: string | number,
element: MessageElement,
diff --git a/packages/core/src/bridge/highway/pipeline.ts b/packages/bridge/src/highway/pipeline.ts
similarity index 88%
rename from packages/core/src/bridge/highway/pipeline.ts
rename to packages/bridge/src/highway/pipeline.ts
index 86b0be53..7eb0e551 100644
--- a/packages/core/src/bridge/highway/pipeline.ts
+++ b/packages/bridge/src/highway/pipeline.ts
@@ -1,31 +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 { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import crypto from 'crypto';
-
-import type { Bridge } from '../bridge';
-import { protobuf_encode } from '@snowluma/proton';
-import { makeOidbEnvelope, encodeOidbEnv, decodeOidbEnv } from '../bridge-oidb';
+import { createLogger } from '@snowluma/common/logger';
+import type { BridgeContext } from '../bridge-context';
+import { makeOidbEnvelope } from '../bridge-oidb';
import type {
EncodableMediaMsgInfo,
NTV2UploadRichMediaReq,
NTV2UploadRichMediaResp,
-} from '../proto/proton/highway';
+} from '@snowluma/proto-defs/highway';
+import { OidbBase } from '@snowluma/proto-defs/oidb';
import { buildHighwayExtend, fetchHighwaySession, uploadHighwayHttp } from './highway-client';
-import { createLogger } from '../../utils/logger';
const moduleLog = createLogger('Highway');
@@ -66,7 +50,7 @@ export interface MediaSubFileUpload {
}
export interface NtV2UploadParams {
- bridge: Bridge;
+ bridge: BridgeContext;
isGroup: boolean;
/** Group uin when isGroup, otherwise the recipient's uid string. */
targetIdOrUid: string | number;
@@ -160,14 +144,14 @@ export async function runNtv2Upload(params: NtV2UploadParams): Promise {
};
const env = makeOidbEnvelope(oidbCmd, 100, body, true);
- const requestBytes = encodeOidbEnv(env);
+ const requestBytes = protobuf_encode>(env);
const result = await bridge.sendRawPacket(serviceCmd, requestBytes);
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(result.errorMessage || `${label} upload request failed`);
}
- const resp = decodeOidbEnv(result.responseData);
+ const resp = protobuf_decode>(result.responseData);
if (!resp) throw new Error(`failed to decode ${label} upload response`);
if (resp.errorCode && resp.errorCode !== 0) {
throw new Error(`OIDB error ${resp.errorCode}: ${resp.errorMsg ?? ''}`);
diff --git a/packages/core/src/bridge/highway/ptt-upload.ts b/packages/bridge/src/highway/ptt-upload.ts
similarity index 92%
rename from packages/core/src/bridge/highway/ptt-upload.ts
rename to packages/bridge/src/highway/ptt-upload.ts
index b3cf868b..927e6d00 100644
--- a/packages/core/src/bridge/highway/ptt-upload.ts
+++ b/packages/bridge/src/highway/ptt-upload.ts
@@ -1,30 +1,22 @@
-// 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 type { Bridge } from '../bridge';
+import { createLogger } from '@snowluma/common/logger';
+import type { BridgeContext } from '../bridge-context';
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');
-function loggerFor(bridge: Bridge) {
+function loggerFor(bridge: BridgeContext) {
const raw = bridge.identity?.uin;
const uin = typeof raw === 'string' ? Number.parseInt(raw, 10) : 0;
return Number.isFinite(uin) && uin > 0 ? moduleLog.child({ uin }) : moduleLog;
@@ -142,7 +134,7 @@ async function loadPtt(element: MessageElement, tempDir: string): Promise= 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);
diff --git a/packages/core/src/bridge/highway/video-upload.ts b/packages/bridge/src/highway/video-upload.ts
similarity index 96%
rename from packages/core/src/bridge/highway/video-upload.ts
rename to packages/bridge/src/highway/video-upload.ts
index bc7568a6..2b003515 100644
--- a/packages/core/src/bridge/highway/video-upload.ts
+++ b/packages/bridge/src/highway/video-upload.ts
@@ -1,37 +1,27 @@
-// 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 type { Bridge } from '../bridge';
+import { createLogger } from '@snowluma/common/logger';
+import type { BridgeContext } from '../bridge-context';
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');
-function loggerFor(bridge: Bridge) {
+function loggerFor(bridge: BridgeContext) {
const raw = bridge.identity?.uin;
const uin = typeof raw === 'string' ? Number.parseInt(raw, 10) : 0;
return Number.isFinite(uin) && uin > 0 ? moduleLog.child({ uin }) : moduleLog;
@@ -431,7 +421,7 @@ async function loadVideo(element: MessageElement): Promise {
* (with per-1MB-block sha1) and a thumb (read off `upload.subFileInfos[0]`).
*/
export async function uploadVideoMsgInfo(
- bridge: Bridge,
+ bridge: BridgeContext,
isGroup: boolean,
targetIdOrUid: string | number,
element: MessageElement,
diff --git a/packages/core/src/bridge/identity-service.ts b/packages/bridge/src/identity-service.ts
similarity index 92%
rename from packages/core/src/bridge/identity-service.ts
rename to packages/bridge/src/identity-service.ts
index d5e41d3e..cf68358f 100644
--- a/packages/core/src/bridge/identity-service.ts
+++ b/packages/bridge/src/identity-service.ts
@@ -1,12 +1,12 @@
import fs from 'fs';
import path from 'path';
-import { DatabaseSync } from 'node:sqlite';
+import Database, { type Database as DatabaseType, type Statement } from '@snowluma/sqlite';
import type {
FriendInfo, GroupMemberInfo, QQGroupInfo,
UserProfileInfo, GroupRequestInfo,
} from './qq-info';
-import { createLogger, type Logger } from '../utils/logger';
+import { createLogger, type Logger } from '@snowluma/common/logger';
const moduleLogger = createLogger('Identity');
@@ -109,7 +109,14 @@ export class IdentityService {
private readonly uidByUin = new Map();
// ─── Persistence + fetcher ───
- private readonly db: DatabaseSync | null;
+ private readonly db: DatabaseType | null;
+ // Prepared-statement cache. Every `.prepare(sql)` call in this
+ // service re-parses the SQL — that's the SQLite anti-pattern
+ // RoadMap #5 is fixing. We memoize by the SQL string itself so the
+ // call sites stay readable (no need to enumerate 20+ named fields
+ // upfront); the Map lookup is O(1) hash + string-eq, which is
+ // negligible next to the SQL parse it replaces.
+ private readonly stmtCache_ = new Map();
private inTransaction = false;
private fetcher: IdentityFetcher | null = null;
private readonly log: Logger;
@@ -127,13 +134,23 @@ export class IdentityService {
}
fs.mkdirSync(path.dirname(dbPath), { recursive: true });
- this.db = new DatabaseSync(dbPath);
- this.db.exec('PRAGMA journal_mode = WAL');
- this.db.exec('PRAGMA synchronous = NORMAL');
+ this.db = new Database(dbPath);
+ this.db.pragma('journal_mode = WAL');
+ this.db.pragma('synchronous = NORMAL');
this.initSchema();
this.loadSnapshot();
}
+ /** Cached `prepare(sql)`. First call per unique SQL parses; later
+ * calls reuse the same `Statement` object. See `stmtCache_`. */
+ private pstmt(sql: string): Statement {
+ let cached = this.stmtCache_.get(sql);
+ if (cached !== undefined) return cached;
+ cached = this.db!.prepare(sql);
+ this.stmtCache_.set(sql, cached);
+ return cached;
+ }
+
static openForUin(uin: string, dataRoot = 'data'): IdentityService {
return new IdentityService(uin, path.join(dataRoot, uin, 'snowluma_identity.db'));
}
@@ -238,7 +255,7 @@ export class IdentityService {
if (!this.db) return null;
if (groupId !== undefined) {
- const row = this.db.prepare(
+ const row = this.pstmt(
`SELECT uin FROM group_members
WHERE group_id = ? AND uid = ? AND uin IS NOT NULL
ORDER BY active DESC, updated_at DESC
@@ -248,7 +265,7 @@ export class IdentityService {
if (uin !== null) return uin;
}
- const row = this.db.prepare(
+ const row = this.pstmt(
'SELECT uin FROM users WHERE uid = ? AND uin IS NOT NULL LIMIT 1',
).get(normalized) as { uin: number | null } | undefined;
return normalizeUin(row?.uin);
@@ -267,7 +284,7 @@ export class IdentityService {
if (!this.db) return null;
if (groupId !== undefined) {
- const row = this.db.prepare(
+ const row = this.pstmt(
`SELECT uid FROM group_members
WHERE group_id = ? AND uin = ? AND uid IS NOT NULL
ORDER BY active DESC, updated_at DESC
@@ -277,7 +294,7 @@ export class IdentityService {
if (uid) return uid;
}
- const row = this.db.prepare(
+ const row = this.pstmt(
'SELECT uid FROM users WHERE uin = ? AND uid IS NOT NULL LIMIT 1',
).get(normalized) as { uid: string | null } | undefined;
return normalizeUid(row?.uid) || null;
@@ -289,7 +306,7 @@ export class IdentityService {
this.friends_ = friends;
for (const friend of friends) this.rememberUidUin(friend.uid, friend.uin);
this.runWrite('friends', () => this.transaction(() => {
- this.db!.prepare('UPDATE users SET is_friend = 0, updated_at = ? WHERE is_friend = 1')
+ this.pstmt('UPDATE users SET is_friend = 0, updated_at = ? WHERE is_friend = 1')
.run(nowSeconds());
for (const friend of friends) {
this.upsertUser({
@@ -307,7 +324,7 @@ export class IdentityService {
rememberGroups(groups: QQGroupInfo[]): void {
this.setGroupsInMemory(groups);
this.runWrite('groups', () => this.transaction(() => {
- this.db!.prepare('UPDATE groups SET active = 0, updated_at = ? WHERE active = 1')
+ this.pstmt('UPDATE groups SET active = 0, updated_at = ? WHERE active = 1')
.run(nowSeconds());
for (const group of groups) {
this.upsertGroup({
@@ -327,7 +344,7 @@ export class IdentityService {
for (const member of members) this.rememberUidUin(member.uid, member.uin);
this.runWrite('group members', () => this.transaction(() => {
this.upsertGroup({ groupId, memberCount: members.length });
- this.db!.prepare('UPDATE group_members SET active = 0, updated_at = ? WHERE group_id = ?')
+ this.pstmt('UPDATE group_members SET active = 0, updated_at = ? WHERE group_id = ?')
.run(nowSeconds(), groupId);
for (const member of members) {
this.upsertGroupMember({
@@ -432,7 +449,7 @@ export class IdentityService {
const updatedAt = nowSeconds();
this.transaction(() => {
for (const row of rows) {
- this.db!.prepare('UPDATE group_members SET active = 0, updated_at = ? WHERE id = ?')
+ this.pstmt('UPDATE group_members SET active = 0, updated_at = ? WHERE id = ?')
.run(updatedAt, row.id);
}
});
@@ -541,7 +558,7 @@ export class IdentityService {
}
private loadSnapshot(): void {
- const friendRows = this.db!.prepare(
+ const friendRows = this.pstmt(
`SELECT uid, uin, nickname, remark
FROM users
WHERE is_friend = 1 AND uin IS NOT NULL`,
@@ -554,7 +571,7 @@ export class IdentityService {
}));
for (const friend of this.friends_) this.rememberUidUin(friend.uid, friend.uin);
- const groups = this.db!.prepare(
+ const groups = this.pstmt(
`SELECT group_id, group_name, remark, member_count, member_max
FROM groups
WHERE active = 1`,
@@ -579,7 +596,7 @@ export class IdentityService {
private hydrateActiveMembersForGroups(groupIds: number[]): void {
if (!this.db || groupIds.length === 0) return;
- const select = this.db.prepare(
+ const select = this.pstmt(
`SELECT group_id, uid, uin, nickname, card, role, level, title,
join_time, last_sent_time, shut_up_time
FROM group_members
@@ -626,9 +643,9 @@ export class IdentityService {
if (primary) {
for (const duplicate of rows.slice(1)) {
- this.db.prepare('DELETE FROM users WHERE id = ?').run(duplicate.id);
+ this.pstmt('DELETE FROM users WHERE id = ?').run(duplicate.id);
}
- this.db.prepare(
+ this.pstmt(
`UPDATE users
SET uid = ?, uin = ?, nickname = ?, remark = ?, is_friend = ?, source = ?, updated_at = ?
WHERE id = ?`,
@@ -645,7 +662,7 @@ export class IdentityService {
return;
}
- this.db.prepare(
+ this.pstmt(
`INSERT INTO users (uid, uin, nickname, remark, is_friend, source, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?)`,
).run(
@@ -662,7 +679,7 @@ export class IdentityService {
private upsertGroup(input: GroupInput): void {
if (!this.db || !Number.isInteger(input.groupId) || input.groupId <= 0) return;
- const existing = this.db.prepare(
+ const existing = this.pstmt(
'SELECT group_name, remark, member_count, member_max FROM groups WHERE group_id = ?',
).get(input.groupId) as {
group_name: string;
@@ -671,7 +688,7 @@ export class IdentityService {
member_max: number;
} | undefined;
- this.db.prepare(
+ this.pstmt(
`INSERT INTO groups (group_id, group_name, remark, member_count, member_max, active, updated_at)
VALUES (?, ?, ?, ?, ?, 1, ?)
ON CONFLICT(group_id) DO UPDATE SET
@@ -725,9 +742,9 @@ export class IdentityService {
if (primary) {
for (const duplicate of rows.slice(1)) {
- this.db.prepare('DELETE FROM group_members WHERE id = ?').run(duplicate.id);
+ this.pstmt('DELETE FROM group_members WHERE id = ?').run(duplicate.id);
}
- this.db.prepare(
+ this.pstmt(
`UPDATE group_members
SET uid = ?, uin = ?, nickname = ?, card = ?, role = ?, level = ?, title = ?,
join_time = ?, last_sent_time = ?, shut_up_time = ?, active = ?, updated_at = ?
@@ -750,7 +767,7 @@ export class IdentityService {
return;
}
- this.db.prepare(
+ this.pstmt(
`INSERT INTO group_members
(group_id, uid, uin, nickname, card, role, level, title,
join_time, last_sent_time, shut_up_time, active, updated_at)
@@ -775,17 +792,17 @@ export class IdentityService {
private findUserRows(uid: string, uin: number | null): UserRow[] {
if (!this.db) return [];
if (uid && uin !== null) {
- return this.db.prepare(
+ return this.pstmt(
'SELECT id, uid, uin, nickname, remark, is_friend, source FROM users WHERE uid = ? OR uin = ? ORDER BY id',
).all(uid, uin) as unknown as UserRow[];
}
if (uid) {
- return this.db.prepare(
+ return this.pstmt(
'SELECT id, uid, uin, nickname, remark, is_friend, source FROM users WHERE uid = ? ORDER BY id',
).all(uid) as unknown as UserRow[];
}
if (uin !== null) {
- return this.db.prepare(
+ return this.pstmt(
'SELECT id, uid, uin, nickname, remark, is_friend, source FROM users WHERE uin = ? ORDER BY id',
).all(uin) as unknown as UserRow[];
}
@@ -795,7 +812,7 @@ export class IdentityService {
private findMemberRows(groupId: number, uid: string, uin: number | null): MemberRow[] {
if (!this.db) return [];
if (uid && uin !== null) {
- return this.db.prepare(
+ return this.pstmt(
`SELECT id, group_id, uid, uin, nickname, card, role, level, title,
join_time, last_sent_time, shut_up_time, active
FROM group_members
@@ -804,7 +821,7 @@ export class IdentityService {
).all(groupId, uid, uin) as unknown as MemberRow[];
}
if (uid) {
- return this.db.prepare(
+ return this.pstmt(
`SELECT id, group_id, uid, uin, nickname, card, role, level, title,
join_time, last_sent_time, shut_up_time, active
FROM group_members
@@ -813,7 +830,7 @@ export class IdentityService {
).all(groupId, uid) as unknown as MemberRow[];
}
if (uin !== null) {
- return this.db.prepare(
+ return this.pstmt(
`SELECT id, group_id, uid, uin, nickname, card, role, level, title,
join_time, last_sent_time, shut_up_time, active
FROM group_members
diff --git a/packages/core/src/bridge/msg-push/context.ts b/packages/bridge/src/msg-push/context.ts
similarity index 66%
rename from packages/core/src/bridge/msg-push/context.ts
rename to packages/bridge/src/msg-push/context.ts
index 556be152..463fc087 100644
--- a/packages/core/src/bridge/msg-push/context.ts
+++ b/packages/bridge/src/msg-push/context.ts
@@ -1,18 +1,11 @@
-// 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 { protoDecode } from '../../protobuf/decode';
-import type { ProtoDecoded } from '../../protobuf/decode';
-import {
- PushMsgSchema, MessageBodySchema, ResponseHeadSchema, ContentHeadSchema,
-} from '../proto/message';
-import type { PacketInfo } from '../../protocol/types';
+import { protobuf_decode } from '@snowluma/proton';
+import type { PacketInfo } from '@snowluma/common/protocol-types';
import type { IdentityService } from '../identity-service';
+import type { ContentHead, MessageBody, PushMsg, ResponseHead } from '@snowluma/proto-defs/message';
-export type PushMsgBody = ProtoDecoded;
-export type PushMsgResponseHead = ProtoDecoded;
-export type PushMsgContentHead = ProtoDecoded;
+export type PushMsgBody = MessageBody;
+export type PushMsgResponseHead = ResponseHead;
+export type PushMsgContentHead = ContentHead;
export interface MsgPushHead {
readonly msgType: number;
@@ -36,7 +29,12 @@ export interface MsgPushContext {
export function buildContext(pkt: PacketInfo, identity: IdentityService): MsgPushContext | null {
if (pkt.body.length === 0) return null;
- const push = protoDecode(Buffer.from(pkt.body), PushMsgSchema);
+ // `pkt.body` is already a `Uint8Array` (see `PacketInfo` in
+ // @snowluma/common/protocol-types). The legacy `Buffer.from(uint8)`
+ // wrap was a no-op copy — Buffer is a Uint8Array subclass and
+ // proton's decoder accepts the parent type directly. Dropping the
+ // wrap saves one allocation per incoming push packet.
+ const push = protobuf_decode(pkt.body);
if (!push?.message) return null;
const msg = push.message;
diff --git a/packages/core/src/bridge/msg-push/decoders/event-0x210.ts b/packages/bridge/src/msg-push/decoders/event-0x210.ts
similarity index 83%
rename from packages/core/src/bridge/msg-push/decoders/event-0x210.ts
rename to packages/bridge/src/msg-push/decoders/event-0x210.ts
index 9c3ebd1e..31d94e56 100644
--- a/packages/core/src/bridge/msg-push/decoders/event-0x210.ts
+++ b/packages/bridge/src/msg-push/decoders/event-0x210.ts
@@ -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(...)` 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 '@snowluma/common/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;
-import type { MsgPushDecoder } from '../registry';
+} from '@snowluma/proto-defs/notify';
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;
const unknownLog = createLogger('MsgPush.Unknown');
diff --git a/packages/core/src/bridge/msg-push/decoders/event-0x2dc.ts b/packages/bridge/src/msg-push/decoders/event-0x2dc.ts
similarity index 93%
rename from packages/core/src/bridge/msg-push/decoders/event-0x2dc.ts
rename to packages/bridge/src/msg-push/decoders/event-0x2dc.ts
index e16205ae..ca0b4dbe 100644
--- a/packages/core/src/bridge/msg-push/decoders/event-0x2dc.ts
+++ b/packages/bridge/src/msg-push/decoders/event-0x2dc.ts
@@ -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 '@snowluma/common/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 '@snowluma/proto-defs/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');
diff --git a/packages/core/src/bridge/msg-push/decoders/friend-message.ts b/packages/bridge/src/msg-push/decoders/friend-message.ts
similarity index 70%
rename from packages/core/src/bridge/msg-push/decoders/friend-message.ts
rename to packages/bridge/src/msg-push/decoders/friend-message.ts
index c07a28bc..d0bedd21 100644
--- a/packages/core/src/bridge/msg-push/decoders/friend-message.ts
+++ b/packages/bridge/src/msg-push/decoders/friend-message.ts
@@ -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';
diff --git a/packages/core/src/bridge/msg-push/decoders/group-admin.ts b/packages/bridge/src/msg-push/decoders/group-admin.ts
similarity index 82%
rename from packages/core/src/bridge/msg-push/decoders/group-admin.ts
rename to packages/bridge/src/msg-push/decoders/group-admin.ts
index d5c75087..b82a80cc 100644
--- a/packages/core/src/bridge/msg-push/decoders/group-admin.ts
+++ b/packages/bridge/src/msg-push/decoders/group-admin.ts
@@ -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 '@snowluma/proto-defs/notify';
import { resolveUidToUin } from '../helpers';
+import type { MsgPushDecoder } from '../registry';
export const decodeGroupAdmin: MsgPushDecoder = (ctx) => {
const admin = protobuf_decode(ctx.content);
diff --git a/packages/core/src/bridge/msg-push/decoders/group-join-request.ts b/packages/bridge/src/msg-push/decoders/group-join-request.ts
similarity index 87%
rename from packages/core/src/bridge/msg-push/decoders/group-join-request.ts
rename to packages/bridge/src/msg-push/decoders/group-join-request.ts
index 50c589bc..67d87aea 100644
--- a/packages/core/src/bridge/msg-push/decoders/group-join-request.ts
+++ b/packages/bridge/src/msg-push/decoders/group-join-request.ts
@@ -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 '@snowluma/proto-defs/notify';
import { resolveUidToUin } from '../helpers';
+import type { MsgPushDecoder } from '../registry';
export const decodeGroupJoinRequest: MsgPushDecoder = (ctx) => {
const join = protobuf_decode(ctx.content);
diff --git a/packages/core/src/bridge/msg-push/decoders/group-member-change.ts b/packages/bridge/src/msg-push/decoders/group-member-change.ts
similarity index 74%
rename from packages/core/src/bridge/msg-push/decoders/group-member-change.ts
rename to packages/bridge/src/msg-push/decoders/group-member-change.ts
index 4d371620..e9aa3736 100644
--- a/packages/core/src/bridge/msg-push/decoders/group-member-change.ts
+++ b/packages/bridge/src/msg-push/decoders/group-member-change.ts
@@ -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 '@snowluma/proto-defs/notify';
import { decodeOperatorUid, resolveUidToUin } from '../helpers';
+import type { MsgPushDecoder } from '../registry';
export const decodeGroupMemberJoin: MsgPushDecoder = (ctx) => {
const change = protobuf_decode(ctx.content);
diff --git a/packages/core/src/bridge/msg-push/decoders/group-message.ts b/packages/bridge/src/msg-push/decoders/group-message.ts
similarity index 89%
rename from packages/core/src/bridge/msg-push/decoders/group-message.ts
rename to packages/bridge/src/msg-push/decoders/group-message.ts
index 6def3b67..3ab677a5 100644
--- a/packages/core/src/bridge/msg-push/decoders/group-message.ts
+++ b/packages/bridge/src/msg-push/decoders/group-message.ts
@@ -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';
diff --git a/packages/core/src/bridge/msg-push/decoders/temp-message.ts b/packages/bridge/src/msg-push/decoders/temp-message.ts
similarity index 87%
rename from packages/core/src/bridge/msg-push/decoders/temp-message.ts
rename to packages/bridge/src/msg-push/decoders/temp-message.ts
index f2c89f72..a61046ed 100644
--- a/packages/core/src/bridge/msg-push/decoders/temp-message.ts
+++ b/packages/bridge/src/msg-push/decoders/temp-message.ts
@@ -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';
diff --git a/packages/core/src/bridge/msg-push/enums.ts b/packages/bridge/src/msg-push/enums.ts
similarity index 95%
rename from packages/core/src/bridge/msg-push/enums.ts
rename to packages/bridge/src/msg-push/enums.ts
index 30f28279..74422733 100644
--- a/packages/core/src/bridge/msg-push/enums.ts
+++ b/packages/bridge/src/msg-push/enums.ts
@@ -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,
diff --git a/packages/core/src/bridge/msg-push/helpers.ts b/packages/bridge/src/msg-push/helpers.ts
similarity index 90%
rename from packages/core/src/bridge/msg-push/helpers.ts
rename to packages/bridge/src/msg-push/helpers.ts
index dc8cd1ec..200d1abe 100644
--- a/packages/core/src/bridge/msg-push/helpers.ts
+++ b/packages/bridge/src/msg-push/helpers.ts
@@ -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 '@snowluma/proto-defs/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 {
+export function buildTemplateMap(params: Array<{ name?: string; value?: string }>): Map {
const map = new Map();
for (const p of params) {
if (p.name !== undefined) map.set(p.name, p.value ?? '');
diff --git a/packages/core/src/bridge/msg-push/index.ts b/packages/bridge/src/msg-push/index.ts
similarity index 86%
rename from packages/core/src/bridge/msg-push/index.ts
rename to packages/bridge/src/msg-push/index.ts
index 71766e90..d69f00cd 100644
--- a/packages/core/src/bridge/msg-push/index.ts
+++ b/packages/bridge/src/msg-push/index.ts
@@ -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 { PacketInfo } from '@snowluma/common/protocol-types';
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';
diff --git a/packages/core/src/bridge/msg-push/registry.ts b/packages/bridge/src/msg-push/registry.ts
similarity index 80%
rename from packages/core/src/bridge/msg-push/registry.ts
rename to packages/bridge/src/msg-push/registry.ts
index 4a3e9a18..cf00479d 100644
--- a/packages/core/src/bridge/msg-push/registry.ts
+++ b/packages/bridge/src/msg-push/registry.ts
@@ -1,9 +1,4 @@
-// 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 { createLogger } from '@snowluma/common/logger';
import type { QQEventVariant } from '../events';
import type { MsgPushContext } from './context';
import type { PkgType } from './enums';
diff --git a/packages/core/src/bridge/msg-push/rich-body-decoder.ts b/packages/bridge/src/msg-push/rich-body-decoder.ts
similarity index 90%
rename from packages/core/src/bridge/msg-push/rich-body-decoder.ts
rename to packages/bridge/src/msg-push/rich-body-decoder.ts
index c980d23b..2f1840e1 100644
--- a/packages/core/src/bridge/msg-push/rich-body-decoder.ts
+++ b/packages/bridge/src/msg-push/rich-body-decoder.ts
@@ -1,26 +1,21 @@
-// 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 { protoDecode } from '../../protobuf/decode';
-import type { ProtoDecoded } from '../../protobuf/decode';
-import { ElemSchema } from '../proto/element';
-import {
- MentionExtraSchema, QFaceExtraSchema, QSmallFaceExtraSchema,
- MsgInfoSchema, GroupFileExtraSchema, NotOnlineImageSchema,
-} from '../proto/element';
-import {
- MessageBodySchema, RichTextSchema, FileExtraSchema,
-} from '../proto/message';
+import { protobuf_decode } from '@snowluma/proton';
+import { toHexUpper } from '@snowluma/common/hex';
import type { MessageElement } from '../events';
-import { toHexUpper } from '../../utils/hex';
+import type {
+ Elem,
+ GroupFileExtra,
+ MentionExtra,
+ MsgInfo,
+ NotOnlineImage,
+ QFaceExtra,
+ QSmallFaceExtra,
+} from '@snowluma/proto-defs/element';
+import type { FileExtra, MessageBody, RichText } from '@snowluma/proto-defs/message';
import { decompressData, makeImageUrl } from './helpers';
-type ElemDecoded = ProtoDecoded;
-type RichTextDecoded = ProtoDecoded;
-export type PushMsgBody = ProtoDecoded;
+type ElemDecoded = Elem;
+type RichTextDecoded = RichText;
+export type PushMsgBody = MessageBody;
export function decodeRichBody(body: PushMsgBody | undefined, isGroup: boolean): MessageElement[] {
const elements: MessageElement[] = [];
@@ -50,9 +45,9 @@ function convertElements(elems: ElemDecoded[]): MessageElement[] {
// Text (with possible @ detection)
if (elem.text) {
const t = elem.text;
- let mention: ProtoDecoded | null = null;
+ let mention: MentionExtra | null = null;
if (t.pbReserve && t.pbReserve.length > 0) {
- mention = protoDecode(t.pbReserve, MentionExtraSchema);
+ mention = protobuf_decode(t.pbReserve);
}
const hasAttr6 = t.attr6Buf && t.attr6Buf.length > 11;
const hasMention = mention && (mention.type === 1 || mention.type === 2);
@@ -172,7 +167,7 @@ function convertElements(elems: ElemDecoded[]): MessageElement[] {
const val = te.elemValue;
const len = (val[1] << 8) | val[2];
if (val.length >= 3 + len) {
- const extra = protoDecode(val.subarray(3, 3 + len), GroupFileExtraSchema);
+ const extra = protobuf_decode(val.subarray(3, 3 + len));
if (extra?.inner?.info) {
const info = extra.inner.info;
result.push({
@@ -243,7 +238,7 @@ function convertElements(elems: ElemDecoded[]): MessageElement[] {
if ((b & 0x80) === 0) break;
}
if (pos + length <= pb.length) {
- const img = protoDecode(pb.subarray(pos, pos + length), NotOnlineImageSchema);
+ const img = protobuf_decode(pb.subarray(pos, pos + length));
if (img) {
const me: MessageElement = {
type: 'image', fileId: img.filePath ?? '',
@@ -260,7 +255,7 @@ function convertElements(elems: ElemDecoded[]): MessageElement[] {
skipNext = true;
} else if (ce.pbElem && (svcType === 48 || bizType === 10 || bizType === 20 || bizType === 11 || bizType === 21 || bizType === 12 || bizType === 22)) {
// NTQQ new protocol image/record/video
- const info = protoDecode(ce.pbElem, MsgInfoSchema);
+ const info = protobuf_decode(ce.pbElem);
if (info?.msgInfoBody && info.msgInfoBody.length > 0) {
const body = info.msgInfoBody[0];
if (body.index?.info) {
@@ -368,11 +363,11 @@ function convertElements(elems: ElemDecoded[]): MessageElement[] {
}
} else if (svcType === 33 && ce.pbElem) {
// Small face
- const extra = protoDecode(ce.pbElem, QSmallFaceExtraSchema);
+ const extra = protobuf_decode(ce.pbElem);
if (extra) result.push({ type: 'face', faceId: extra.faceId ?? 0 });
} else if (svcType === 37 && ce.pbElem) {
// Big face
- const extra = protoDecode(ce.pbElem, QFaceExtraSchema);
+ const extra = protobuf_decode(ce.pbElem);
if (extra?.qsid !== undefined) result.push({ type: 'face', faceId: extra.qsid });
skipNext = true;
}
@@ -443,7 +438,7 @@ function extractMsgContent(msgContent: Uint8Array, elements: MessageElement[]):
// "incomplete metadata". After consolidating FileExtra to wrap
// `NotOnlineFile` (Lagrange.Core's `FileExtra { File: NotOnlineFile }`),
// this reads the right tags.
- const extra = protoDecode(msgContent, FileExtraSchema);
+ const extra = protobuf_decode(msgContent);
if (!extra?.file) return;
const f = extra.file;
if (!f.fileUuid) return;
diff --git a/packages/core/src/bridge/packet-pipeline.ts b/packages/bridge/src/packet-pipeline.ts
similarity index 89%
rename from packages/core/src/bridge/packet-pipeline.ts
rename to packages/bridge/src/packet-pipeline.ts
index 1697a15e..89861ee3 100644
--- a/packages/core/src/bridge/packet-pipeline.ts
+++ b/packages/bridge/src/packet-pipeline.ts
@@ -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 type { PacketInfo } from '@snowluma/common/protocol-types';
+import { formatEvent } from './format';
+import { createLogger, type Logger } from '@snowluma/common/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');
diff --git a/packages/core/src/bridge/qq-info.ts b/packages/bridge/src/qq-info.ts
similarity index 79%
rename from packages/core/src/bridge/qq-info.ts
rename to packages/bridge/src/qq-info.ts
index 549788a3..e3302539 100644
--- a/packages/core/src/bridge/qq-info.ts
+++ b/packages/bridge/src/qq-info.ts
@@ -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;
diff --git a/packages/core/src/bridge/web/group-album.ts b/packages/bridge/src/web/group-album.ts
similarity index 96%
rename from packages/core/src/bridge/web/group-album.ts
rename to packages/bridge/src/web/group-album.ts
index 321e9790..830ec25e 100644
--- a/packages/core/src/bridge/web/group-album.ts
+++ b/packages/bridge/src/web/group-album.ts
@@ -1,6 +1,6 @@
import { RequestUtil, cookieToString, getBknFromCookie } from './request-util';
import { createHash } from 'crypto';
-import { readFileSync, statSync, createReadStream, writeFileSync, unlinkSync } from 'fs';
+import { statSync, createReadStream, writeFileSync, unlinkSync } from 'fs';
import { basename, join } from 'path';
import { tmpdir } from 'os';
@@ -147,13 +147,13 @@ async function createAlbumUploadSession(
* 修复后的上传图片分片方法
*/
async function uploadAlbumSlice(
- session: string,
- filePath: string,
- // 移除 offset 和 chunkSize 参数,改为在内部控制
- imgMd5: string,
- skey: string,
- pskey: string,
- uin: string
+ session: string,
+ filePath: string,
+ // 移除 offset 和 chunkSize 参数,改为在内部控制
+ imgMd5: string,
+ skey: string,
+ pskey: string,
+ uin: string
): Promise {
const img_size = statSync(filePath).size;
const slice_size = 16384; // 严格使用 16KB
diff --git a/packages/bridge/src/web/group-essence.ts b/packages/bridge/src/web/group-essence.ts
new file mode 100644
index 00000000..cf46eff7
--- /dev/null
+++ b/packages/bridge/src/web/group-essence.ts
@@ -0,0 +1,71 @@
+import { RequestUtil, cookieToString, getBknFromCookie } from './request-util';
+import { createLogger } from '@snowluma/common/logger';
+
+const log = createLogger('Bridge.Web');
+
+// 定义接口返回类型
+export interface GroupEssenceMsgRet {
+ retcode: number;
+ data: {
+ is_end: boolean;
+ msg_list: any[]; // 具体结构视需要补充
+ [key: string]: any;
+ };
+ [key: string]: any;
+}
+
+
+/**
+ * 分页获取群精华消息
+ */
+export async function getGroupEssenceMsg(
+ cookieObject: Record,
+ groupCode: string,
+ pageStart: number = 0,
+ pageLimit: number = 50
+): Promise {
+ const bkn = getBknFromCookie(cookieObject);
+
+ const url = `https://qun.qq.com/cgi-bin/group_digest/digest_list?${new URLSearchParams({
+ bkn: bkn,
+ page_start: pageStart.toString(),
+ page_limit: pageLimit.toString(),
+ group_code: groupCode,
+ }).toString()}`;
+
+ try {
+ const ret = await RequestUtil.HttpGetJson(
+ url,
+ 'GET',
+ '',
+ { Cookie: cookieToString(cookieObject) }
+ );
+ return ret.retcode === 0 ? ret : undefined;
+ } catch (e) {
+ log.warn('getGroupEssenceMsg failed (group=%s page=%d/%d): %s',
+ groupCode, pageStart, pageLimit, e instanceof Error ? (e.stack ?? e.message) : String(e));
+ return undefined;
+ }
+}
+
+/**
+ * 获取所有群精华消息 (最多循环 20 页)
+ */
+export async function getGroupEssenceMsgAll(
+ cookieObject: Record,
+ groupCode: string
+): Promise {
+ const ret: GroupEssenceMsgRet[] = [];
+
+ for (let i = 0; i < 20; i++) {
+ const data = await getGroupEssenceMsg(cookieObject, groupCode, i, 50);
+
+ if (!data) break;
+
+ ret.push(data);
+
+ if (data.data?.is_end) break;
+ }
+
+ return ret;
+}
\ No newline at end of file
diff --git a/packages/bridge/src/web/group-honor.ts b/packages/bridge/src/web/group-honor.ts
new file mode 100644
index 00000000..133e4f9d
--- /dev/null
+++ b/packages/bridge/src/web/group-honor.ts
@@ -0,0 +1,53 @@
+import { RequestUtil, cookieToString } from './request-util';
+import { createLogger } from '@snowluma/common/logger';
+
+const log = createLogger('Bridge.Web');
+
+export enum WebHonorType {
+ TALKATIVE = 'talkative',
+ PERFORMER = 'performer',
+ LEGEND = 'legend',
+ EMOTION = 'emotion',
+ ALL = 'all',
+}
+
+
+async function fetchHonorData(cookieObject: Record, groupCode: string, type: number) {
+ let resJson;
+ try {
+ const res = await RequestUtil.HttpGetText(
+ `https://qun.qq.com/interactive/honorlist?${new URLSearchParams({
+ gc: groupCode,
+ type: type.toString(),
+ }).toString()}`,
+ 'GET',
+ '',
+ { Cookie: cookieToString(cookieObject) }
+ );
+ const match = /window\.__INITIAL_STATE__=(.*?);/.exec(res);
+ if (match?.[1]) {
+ resJson = JSON.parse(match[1].trim());
+ }
+ return type === 1 ? resJson?.talkativeList : resJson?.actorList;
+ } catch (e) {
+ throw new Error(`获取群 ${groupCode} 类型 ${type} 的荣誉信息失败: ${e}`);
+ }
+}
+
+export async function getHonorListWebAPI(cookieObject: Record, groupCode: string, type: number) {
+ try {
+ const data = await fetchHonorData(cookieObject, groupCode, type);
+ if (!data) return [];
+
+ return data.map((item: any) => ({
+ user_id: item?.uin,
+ nickname: item?.name,
+ avatar: item?.avatar,
+ description: item?.desc,
+ }));
+ } catch (e) {
+ log.warn('getHonorListWebAPI failed (group=%s type=%d): %s',
+ groupCode, type, e instanceof Error ? (e.stack ?? e.message) : String(e));
+ return [];
+ }
+}
\ No newline at end of file
diff --git a/packages/bridge/src/web/group-notice.ts b/packages/bridge/src/web/group-notice.ts
new file mode 100644
index 00000000..2fc3b8fa
--- /dev/null
+++ b/packages/bridge/src/web/group-notice.ts
@@ -0,0 +1,273 @@
+import { RequestUtil, cookieToString } from './request-util';
+import https from 'node:https';
+import { createLogger } from '@snowluma/common/logger';
+
+const log = createLogger('Bridge.Web');
+
+export interface SetNoticeRetSuccess {
+ ec?: number;
+ em?: string;
+ [key: string]: any;
+}
+
+export interface UploadImageRetSuccess {
+ ec?: number;
+ id?: string;
+ [key: string]: any;
+}
+
+export interface WebApiGroupNoticeFeed {
+ fid: string;
+ u: number;
+ pubt: number;
+ msg: {
+ text: string;
+ pics?: Array<{ id: string; w: number; h: number }>;
+ };
+ settings: any;
+ read_num: number;
+ [key: string]: any;
+}
+
+export interface WebApiGroupNoticeRet {
+ ec: number;
+ em?: string;
+ feeds?: Record;
+ [key: string]: any;
+}
+
+export function calculateBkn(key: string): string {
+ let hash = 5381;
+ for (let i = 0; i < key.length; i++) {
+ const code = key.charCodeAt(i);
+ hash = hash + (hash << 5) + code;
+ }
+ return (hash & 0x7FFFFFFF).toString();
+}
+
+/**
+ * 发送群公告 Web API
+ */
+export async function setGroupNoticeWebAPI(
+ cookieObject: Record,
+ groupCode: string,
+ content: string,
+ pinned: number = 0,
+ type: number = 1,
+ isShowEditCard: number = 1,
+ tipWindowType: number = 1,
+ confirmRequired: number = 1,
+ picId: string = '',
+ imgWidth: number = 540,
+ imgHeight: number = 300
+): Promise {
+ try {
+ // 分别获取 skey 和 p_skey
+ const skey = cookieObject['skey'] || '';
+ const pskey = cookieObject['p_skey'] || skey;
+
+ const bodyBkn = calculateBkn(skey);
+ const urlBkn = calculateBkn(pskey);
+ //
+ // console.log(skey)
+ // console.log(pskey)
+ //
+ // console.log(urlBkn);
+ // console.log(bodyBkn)
+
+ const settings = JSON.stringify({
+ is_show_edit_card: isShowEditCard,
+ tip_window_type: tipWindowType,
+ confirm_required: confirmRequired,
+ });
+
+ const bodyParams: Record = {
+ qid: groupCode,
+ bkn: bodyBkn,
+ text: content,
+ pinned: pinned.toString(),
+ type: type.toString(),
+ settings,
+ };
+
+ if (picId !== '') {
+ bodyParams.pic = picId;
+ bodyParams.imgWidth = imgWidth.toString();
+ bodyParams.imgHeight = imgHeight.toString();
+ }
+
+ // 注意这里:URL 必须使用 skey 算出来的 bkn
+ const url = `https://web.qun.qq.com/cgi-bin/announce/add_qun_notice?bkn=${urlBkn}`;
+ const body = new URLSearchParams(bodyParams).toString();
+
+ const ret = await RequestUtil.HttpGetJson(
+ url,
+ 'POST',
+ body,
+ {
+ Cookie: cookieToString(cookieObject),
+ 'Content-Type': 'application/x-www-form-urlencoded'
+ },
+ true,
+ false
+ );
+ return ret;
+ } catch (e) {
+ log.warn('group-notice add failed: %s', e instanceof Error ? (e.stack ?? e.message) : String(e));
+ return undefined;
+ }
+}
+
+/**
+ * 获取群公告列表 Web API
+ */
+export async function getGroupNoticeWebAPI(
+ cookieObject: Record,
+ groupCode: string,
+ start: number = -1, // -1 表示第一页
+ count: number = 20 // 抓包中是 10,你可以根据需要调整
+): Promise {
+ try {
+ const skey = cookieObject['skey'] || '';
+ const pskey = cookieObject['p_skey'] || skey;
+
+ const bodyBkn = calculateBkn(skey); // URL 使用 skey 算出的 bkn
+ const urlBkn = calculateBkn(pskey); // Body 使用 p_skey 算出的 bkn
+
+ const bodyParams = new URLSearchParams({
+ qid: groupCode,
+ bkn: bodyBkn, // Body 中传入 p_skey 计算结果
+ ft: '23',
+ s: start.toString(), // 分页游标
+ n: count.toString(), // 获取数量
+ i: '1',
+ ni: '1'
+ }).toString();
+
+ const url = `https://web.qun.qq.com/cgi-bin/announce/list_announce?bkn=${urlBkn}`;
+
+ const ret = await RequestUtil.HttpGetJson(
+ url,
+ 'POST',
+ bodyParams,
+ {
+ Cookie: cookieToString(cookieObject),
+ 'Content-Type': 'application/x-www-form-urlencoded',
+ 'Referer': 'https://web.qun.qq.com/mannounce/index.html?_wv=1031&_bid=148'
+ },
+ true,
+ false
+ );
+ // console.log(JSON.stringify(ret, null, 2));
+ return ret?.ec === 0 ? ret : undefined;
+ } catch (e) {
+ log.warn('getGroupNoticeList failed: %s', e instanceof Error ? (e.stack ?? e.message) : String(e));
+ return undefined;
+ }
+}
+/**
+ * 上传群公告图片 Web API
+ */
+export async function uploadGroupNoticeImage(
+ cookieObject: Record,
+ imageBuffer: Buffer
+): Promise<{ id: string; width: number; height: number } | undefined> {
+ try {
+ const bkn = calculateBkn(cookieObject['skey']);
+ const boundary = `-----------------------------${Date.now()}`;
+
+ const parts: Buffer[] = [];
+ parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="bkn"\r\n\r\n${bkn}\r\n`));
+ parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="source"\r\n\r\ntroopNotice\r\n`));
+ parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="m"\r\n\r\n0\r\n`));
+ parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="pic_up"; filename="image.jpg"\r\nContent-Type: image/jpeg\r\n\r\n`));
+ parts.push(imageBuffer);
+ parts.push(Buffer.from(`\r\n--${boundary}--\r\n`));
+
+ const body = Buffer.concat(parts);
+
+ const options = {
+ hostname: 'web.qun.qq.com',
+ path: '/cgi-bin/announce/upload_img',
+ method: 'POST',
+ headers: {
+ 'Content-Type': `multipart/form-data; boundary=${boundary}`,
+ 'Content-Length': body.length,
+ 'Cookie': cookieToString(cookieObject),
+ },
+ };
+
+ return new Promise((resolve) => {
+ const req = https.request(options, (res) => {
+ let data = '';
+ res.on('data', (chunk) => { data += chunk; });
+ res.on('end', () => {
+ try {
+ const result = JSON.parse(data) as UploadImageRetSuccess;
+ if (result.ec === 0 && result.id) {
+ const unescapedIdStr = result.id.replace(/"/g, '"');
+
+ const idObj = JSON.parse(unescapedIdStr);
+ resolve({ id: idObj.id, width: parseInt(idObj.w), height: parseInt(idObj.h) });
+ } else {
+ resolve(undefined);
+ }
+ } catch {
+ resolve(undefined);
+ }
+ });
+ });
+ req.on('error', (err) => {
+ log.warn('uploadGroupNoticeImage transport error: %s', err.message);
+ resolve(undefined);
+ });
+ req.write(body);
+ req.end();
+ });
+ } catch (e) {
+ log.warn('uploadGroupNoticeImage failed: %s', e instanceof Error ? (e.stack ?? e.message) : String(e));
+ return undefined;
+ }
+}
+
+/**
+ * 删除群公告 Web API
+ */
+export async function deleteGroupNotice(
+ cookieObject: Record,
+ groupCode: string,
+ fid: string
+): Promise {
+ try {
+ const skey = cookieObject['skey'] || '';
+ const pskey = cookieObject['p_skey'] || skey;
+
+ const bodyBkn = calculateBkn(skey); // Body 使用 skey 算出的 bkn
+ const urlBkn = calculateBkn(pskey); // URL 使用 p_skey 算出的 bkn
+
+ const params = new URLSearchParams({
+ bkn: bodyBkn, // 注意这里:POST Body 放入 bodyBkn
+ fid: fid,
+ qid: groupCode,
+ }).toString();
+
+ // 注意这里:URL 拼接 urlBkn
+ const url = `https://web.qun.qq.com/cgi-bin/announce/del_feed?bkn=${urlBkn}`;
+
+ const ret = await RequestUtil.HttpGetJson(
+ url,
+ 'POST',
+ params,
+ {
+ Cookie: cookieToString(cookieObject),
+ 'Content-Type': 'application/x-www-form-urlencoded'
+ },
+ true,
+ false
+ );
+ return ret?.ec === 0;
+ } catch (e) {
+ log.warn('deleteGroupNotice failed (group=%s fid=%s): %s', groupCode, fid, e instanceof Error ? (e.stack ?? e.message) : String(e));
+ return false;
+ }
+}
\ No newline at end of file
diff --git a/packages/bridge/src/web/request-util.ts b/packages/bridge/src/web/request-util.ts
new file mode 100644
index 00000000..60f28d8f
--- /dev/null
+++ b/packages/bridge/src/web/request-util.ts
@@ -0,0 +1,127 @@
+import https from 'node:https';
+import http from 'node:http';
+
+export class RequestUtil {
+ static async HttpsGetCookies(url: string): Promise<{ [key: string]: string; }> {
+ const client = url.startsWith('https') ? https : http;
+ return new Promise((resolve, reject) => {
+ const req = client.get(url, (res) => {
+ const cookies: { [key: string]: string; } = {};
+
+ res.on('data', () => { }); // 必须消耗流
+ res.on('end', () => {
+ this.handleRedirect(res, url, cookies)
+ .then(resolve)
+ .catch(reject);
+ });
+
+ if (res.headers['set-cookie']) {
+ this.extractCookies(res.headers['set-cookie'], cookies);
+ }
+ });
+
+ req.on('error', (error: Error) => {
+ reject(error);
+ });
+ });
+ }
+
+ private static async handleRedirect(res: http.IncomingMessage, url: string, cookies: { [key: string]: string; }): Promise<{ [key: string]: string; }> {
+ if (res.statusCode === 301 || res.statusCode === 302) {
+ if (res.headers.location) {
+ const redirectUrl = new URL(res.headers.location, url);
+ const redirectCookies = await this.HttpsGetCookies(redirectUrl.href);
+ return { ...cookies, ...redirectCookies };
+ }
+ }
+ return cookies;
+ }
+
+ private static extractCookies(setCookieHeaders: string[], cookies: { [key: string]: string; }) {
+ setCookieHeaders.forEach((cookie) => {
+ const parts = cookie.split(';')[0]?.split('=');
+ if (parts) {
+ const key = parts[0];
+ const value = parts[1];
+ if (key && value && key.length > 0 && value.length > 0) {
+ cookies[key] = value;
+ }
+ }
+ });
+ }
+
+ static async HttpGetJson(url: string, method: string = 'GET', data?: any, headers: {
+ [key: string]: string;
+ } = {}, isJsonRet: boolean = true, isArgJson: boolean = true, maxRedirects: number = 5): Promise {
+ const option = new URL(url);
+ const protocol = url.startsWith('https://') ? https : http;
+ const options = {
+ hostname: option.hostname,
+ port: option.port,
+ path: option.pathname + option.search,
+ method,
+ headers,
+ };
+
+ return new Promise((resolve, reject) => {
+ const req = protocol.request(options, (res: http.IncomingMessage) => {
+ if ((res.statusCode === 301 || res.statusCode === 302 || res.statusCode === 307 || res.statusCode === 308) && res.headers.location) {
+ if (maxRedirects <= 0) {
+ reject(new Error('Too many redirects'));
+ return;
+ }
+ const redirectUrl = new URL(res.headers.location, url).href;
+ this.HttpGetJson(redirectUrl, method, data, headers, isJsonRet, isArgJson, maxRedirects - 1)
+ .then(resolve)
+ .catch(reject);
+ return;
+ }
+
+ let responseBody = '';
+ res.on('data', (chunk: string | Buffer) => { responseBody += chunk.toString(); });
+
+ res.on('end', () => {
+ try {
+ if (res.statusCode && res.statusCode >= 200 && res.statusCode < 300) {
+ if (isJsonRet) {
+ resolve(JSON.parse(responseBody) as T);
+ } else {
+ resolve(responseBody as T);
+ }
+ } else {
+ reject(new Error(`Unexpected status code: ${res.statusCode}`));
+ }
+ } catch (parseError: any) {
+ reject(new Error(parseError.message));
+ }
+ });
+ });
+
+ req.on('error', (error: Error) => reject(error));
+ if (method === 'POST' || method === 'PUT' || method === 'PATCH') {
+ req.write(isArgJson ? JSON.stringify(data) : data);
+ }
+ req.end();
+ });
+ }
+
+ static async HttpGetText(url: string, method: string = 'GET', data?: any, headers: { [key: string]: string; } = {}) {
+ return this.HttpGetJson(url, method, data, headers, false, false);
+ }
+}
+
+export function cookieToString(cookieObject: Record): string {
+ return Object.entries(cookieObject)
+ .map(([key, value]) => `${key}=${value}`)
+ .join('; ');
+}
+
+
+export function getBknFromCookie(cookieObject: Record): string {
+ const skey = cookieObject['p_skey'] || cookieObject['skey'] || '';
+ let hash = 5381;
+ for (let i = 0; i < skey.length; i++) {
+ hash += (hash << 5) + skey.charCodeAt(i);
+ }
+ return (hash & 2147483647).toString();
+}
diff --git a/packages/bridge/tsconfig.json b/packages/bridge/tsconfig.json
new file mode 100644
index 00000000..4cd329d7
--- /dev/null
+++ b/packages/bridge/tsconfig.json
@@ -0,0 +1,13 @@
+{
+ "extends": "../../tsconfig.base.json",
+ "compilerOptions": {
+ "types": ["node"],
+ "noEmit": true
+ },
+ "include": [
+ "src/**/*"
+ ],
+ "exclude": [
+ "node_modules"
+ ]
+}
diff --git a/packages/bridge/vitest.config.ts b/packages/bridge/vitest.config.ts
new file mode 100644
index 00000000..57df30aa
--- /dev/null
+++ b/packages/bridge/vitest.config.ts
@@ -0,0 +1,21 @@
+// Vitest config — only used by `pnpm bench` to drive the perf
+// micro-benchmarks under `bench/`. There are no `*.test.ts` files in
+// this package (bridge tests live in @snowluma/core's test suite by
+// historical accident); if/when they migrate over, point
+// `test.include` at them here.
+import protobufVitePlugin from '@snowluma/proton/vite';
+import { defineConfig } from 'vitest/config';
+
+export default defineConfig({
+ // proton's vite plugin inlines `protobuf_encode` / `protobuf_decode`
+ // call sites at build time. Required for tinybench-driven benches to
+ // hit the production code path rather than proton's runtime-fallback
+ // (which throws unless a runtime-map JSON is loaded).
+ plugins: [protobufVitePlugin()],
+ test: {
+ benchmark: {
+ include: ['bench/**/*.bench.ts'],
+ },
+ environment: 'node',
+ },
+});
diff --git a/packages/common/package.json b/packages/common/package.json
new file mode 100644
index 00000000..4e378c72
--- /dev/null
+++ b/packages/common/package.json
@@ -0,0 +1,54 @@
+{
+ "name": "@snowluma/common",
+ "version": "1.9.1",
+ "private": true,
+ "type": "module",
+ "description": "SnowLuma shared infrastructure — leaf-package utilities with zero business dependencies. Logger / hex codec / log file transport / log line summariser / packet sender wire-protocol types / runtime config loader. Consumed by @snowluma/bridge, @snowluma/core, and @snowluma/onebot. Per-file subpath exports keep import sites unambiguous and let the bundler tree-shake aggressively (importing `@snowluma/common/hex` doesn't pull in `node:fs` from the logger transport).",
+ "main": "./src/index.ts",
+ "types": "./src/index.ts",
+ "exports": {
+ ".": {
+ "types": "./src/index.ts",
+ "default": "./src/index.ts"
+ },
+ "./logger": {
+ "types": "./src/logger.ts",
+ "default": "./src/logger.ts"
+ },
+ "./hex": {
+ "types": "./src/hex.ts",
+ "default": "./src/hex.ts"
+ },
+ "./json": {
+ "types": "./src/json.ts",
+ "default": "./src/json.ts"
+ },
+ "./log-file-transport": {
+ "types": "./src/log-file-transport.ts",
+ "default": "./src/log-file-transport.ts"
+ },
+ "./log-summary": {
+ "types": "./src/log-summary.ts",
+ "default": "./src/log-summary.ts"
+ },
+ "./packet-sender": {
+ "types": "./src/packet-sender.ts",
+ "default": "./src/packet-sender.ts"
+ },
+ "./protocol-types": {
+ "types": "./src/protocol-types.ts",
+ "default": "./src/protocol-types.ts"
+ },
+ "./runtime": {
+ "types": "./src/runtime.ts",
+ "default": "./src/runtime.ts"
+ }
+ },
+ "scripts": {
+ "typecheck": "tsc --noEmit"
+ },
+ "devDependencies": {
+ "@types/node": "^24.12.2",
+ "typescript": "catalog:"
+ }
+}
diff --git a/packages/core/src/utils/hex.ts b/packages/common/src/hex.ts
similarity index 100%
rename from packages/core/src/utils/hex.ts
rename to packages/common/src/hex.ts
diff --git a/packages/common/src/json.ts b/packages/common/src/json.ts
new file mode 100644
index 00000000..1097fa01
--- /dev/null
+++ b/packages/common/src/json.ts
@@ -0,0 +1,16 @@
+// Plain JSON value types — defined here (not in @snowluma/onebot/types
+// where they used to live) so @snowluma/bridge can talk about JSON-shaped
+// payloads without importing OneBot. The OneBot types module keeps the
+// names exported via re-export, so existing call sites that say
+// `import type { JsonValue } from '<…>/onebot/types'` continue to work
+// unchanged after Phase 3.
+//
+// Anything actually OneBot-specific (ApiResponse, OneBotRequest, …)
+// stays in @snowluma/onebot — only the plain JSON quartet moves here.
+
+export type JsonPrimitive = string | number | boolean | null;
+export type JsonValue = JsonPrimitive | JsonObject | JsonArray;
+export interface JsonObject {
+ [key: string]: JsonValue;
+}
+export type JsonArray = JsonValue[];
diff --git a/packages/core/src/utils/log-file-transport.ts b/packages/common/src/log-file-transport.ts
similarity index 88%
rename from packages/core/src/utils/log-file-transport.ts
rename to packages/common/src/log-file-transport.ts
index e716c35e..d028d6c4 100644
--- a/packages/core/src/utils/log-file-transport.ts
+++ b/packages/common/src/log-file-transport.ts
@@ -1,21 +1,3 @@
-// File transport for the SnowLuma logger.
-//
-// Writes plain text (ANSI stripped) to:
-// /snowluma-YYYY-MM-DD.log (shared, all UINs)
-// //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';
@@ -81,7 +63,6 @@ class FileWriter {
fs.mkdirSync(dir, { recursive: true });
} catch (err) {
this.disabled = true;
- // eslint-disable-next-line no-console
console.error(
`[logger] failed to create log dir ${dir}: ${err instanceof Error ? err.message : String(err)}`,
);
@@ -170,12 +151,10 @@ class FileWriter {
}
const stream = fs.createWriteStream(p, { flags: 'a' });
stream.on('error', (err) => {
- // eslint-disable-next-line no-console
console.error(`[logger] file write error on ${p}: ${err.message}`);
});
return { stream, bytes, date, splitIndex, path: p };
} catch (err) {
- // eslint-disable-next-line no-console
console.error(
`[logger] failed to open log file ${p}: ${err instanceof Error ? err.message : String(err)}`,
);
diff --git a/packages/core/src/utils/log-summary.ts b/packages/common/src/log-summary.ts
similarity index 80%
rename from packages/core/src/utils/log-summary.ts
rename to packages/common/src/log-summary.ts
index 94ef38b1..dcec49d6 100644
--- a/packages/core/src/utils/log-summary.ts
+++ b/packages/common/src/log-summary.ts
@@ -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;
diff --git a/packages/core/src/utils/logger.ts b/packages/common/src/logger.ts
similarity index 96%
rename from packages/core/src/utils/logger.ts
rename to packages/common/src/logger.ts
index ce25d0b0..d5eabc93 100644
--- a/packages/core/src/utils/logger.ts
+++ b/packages/common/src/logger.ts
@@ -23,9 +23,6 @@ interface LogOptions {
meta?: Record;
}
-// 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 = {
@@ -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 {
diff --git a/packages/core/src/protocol/packet-sender.ts b/packages/common/src/packet-sender.ts
similarity index 100%
rename from packages/core/src/protocol/packet-sender.ts
rename to packages/common/src/packet-sender.ts
diff --git a/packages/core/src/protocol/types.ts b/packages/common/src/protocol-types.ts
similarity index 62%
rename from packages/core/src/protocol/types.ts
rename to packages/common/src/protocol-types.ts
index 8364ff87..ce34f342 100644
--- a/packages/core/src/protocol/types.ts
+++ b/packages/common/src/protocol-types.ts
@@ -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;
diff --git a/packages/core/src/common/runtime.ts b/packages/common/src/runtime.ts
similarity index 100%
rename from packages/core/src/common/runtime.ts
rename to packages/common/src/runtime.ts
diff --git a/packages/common/tsconfig.json b/packages/common/tsconfig.json
new file mode 100644
index 00000000..4cd329d7
--- /dev/null
+++ b/packages/common/tsconfig.json
@@ -0,0 +1,13 @@
+{
+ "extends": "../../tsconfig.base.json",
+ "compilerOptions": {
+ "types": ["node"],
+ "noEmit": true
+ },
+ "include": [
+ "src/**/*"
+ ],
+ "exclude": [
+ "node_modules"
+ ]
+}
diff --git a/packages/core/bench/proton-vs-legacy.ts b/packages/core/bench/proton-vs-legacy.ts
deleted file mode 100644
index 3f8eb304..00000000
--- a/packages/core/bench/proton-vs-legacy.ts
+++ /dev/null
@@ -1,172 +0,0 @@
-// Proton vs legacy runtime ProtoSchema encoder/decoder benchmark.
-//
-// Compares the codec functions generated at build time by @snowluma/proton
-// against the runtime schema-walking implementation in src/protobuf/decode.ts,
-// using the actual long-message schemas already in the codebase.
-//
-// Methodology:
-// - Proton codecs are produced by calling its `analyzeSource` + `generateCode`
-// API on the existing proto/proton/longmsg.ts source file, then `new
-// Function`-eval'd into a callable. This is identical to what the Vite
-// plugin does at build time, minus the file-replacement step.
-// - Legacy codecs are the existing `protoEncode` / `protoDecode` functions
-// called against the existing `*Schema` constants.
-// - Each measurement does 2 000 warmup iterations, then N timed iterations.
-// - Operation cost is reported as ops/sec and ns/op. The first row's
-// ops/sec is the relative baseline.
-//
-// Run:
-// pnpm --filter @snowluma/core exec tsx bench/proton-vs-legacy.ts
-
-import { readFileSync } from 'fs';
-import { resolve, dirname } from 'path';
-import { fileURLToPath } from 'url';
-import { analyzeSource, generateCode } from '@snowluma/proton/vite';
-import { protoEncode, protoDecode } from '../src/protobuf/decode';
-import {
- LongMsgSettingsSchema,
- SendLongMsgRespSchema,
- SendLongMsgReqSchema,
- RecvLongMsgRespSchema,
-} from '../src/bridge/proto/longmsg';
-
-// ── proton codec materialisation ─────────────────────────────────────
-
-const __dirname = dirname(fileURLToPath(import.meta.url));
-const protonSchemaPath = resolve(__dirname, '..', 'src', 'bridge', 'proto', 'proton', 'longmsg.ts');
-const protonSchemaSource = readFileSync(protonSchemaPath, 'utf-8');
-
-function materialiseProton(messageNames: readonly string[]): Record Uint8Array; decode: (b: Uint8Array) => unknown }> {
- // Append synthetic call sites so the registry actually contains the messages
- // we want — `selectUsedRegistry` only retains call-site roots, and the
- // proton/longmsg.ts source itself has no `protobuf_encode` calls.
- const callSites = messageNames
- .map((n) => `protobuf_encode<${n}>({} as any); protobuf_decode<${n}>(new Uint8Array());`)
- .join('\n');
- const sourceWithCallSites = protonSchemaSource + `\n\n// synthetic call sites for bench codegen\n` + callSites;
-
- const registry = analyzeSource(sourceWithCallSites, protonSchemaPath);
- const code = generateCode(registry);
- const factoryBody = `
- ${code}
- const out = {};
- ${messageNames.map(n => `out.${n} = { encode: protobuf_encode_${n}, decode: protobuf_decode_${n} };`).join('\n')}
- return out;
- `;
- return new Function(factoryBody)() as Record Uint8Array; decode: (b: Uint8Array) => unknown }>;
-}
-
-const proton = materialiseProton([
- 'LongMsgSettings',
- 'SendLongMsgResp',
- 'SendLongMsgReq',
- 'RecvLongMsgResp',
-]);
-
-// ── bench harness ────────────────────────────────────────────────────
-
-interface BenchResult { name: string; opsPerSec: number; nsPerOp: number; }
-
-function bench(name: string, fn: () => void, iterations: number): BenchResult {
- for (let i = 0; i < 2000; i++) fn();
- const start = performance.now();
- for (let i = 0; i < iterations; i++) fn();
- const ms = performance.now() - start;
- return {
- name,
- opsPerSec: Math.round((iterations / ms) * 1000),
- nsPerOp: Math.round((ms / iterations) * 1_000_000),
- };
-}
-
-function printSection(title: string, results: BenchResult[]) {
- console.log(`\n## ${title}`);
- console.log('| Encoder | ops/sec | ns/op | relative |');
- console.log('|------------|-------------|--------|----------|');
- const baseline = results[0].opsPerSec;
- for (const r of results) {
- const rel = r.opsPerSec / baseline;
- const relStr = r === results[0] ? '1.00×' : `${rel.toFixed(2)}×`;
- console.log(
- `| ${r.name.padEnd(10)} | ${r.opsPerSec.toLocaleString().padStart(11)} | ${String(r.nsPerOp).padStart(6)} | ${relStr.padStart(8)} |`,
- );
- }
-}
-
-// ── workloads ────────────────────────────────────────────────────────
-
-const settingsObj = { field1: 4, field2: 1, field3: 7, field4: 2 };
-
-const sendRespObj = { result: { resId: 'res-001' } };
-
-const sendReqObj = {
- info: {
- type: 1,
- uid: { uid: 'u_test' },
- groupUin: 123456,
- payload: new Uint8Array([0xde, 0xad, 0xbe, 0xef]),
- },
- settings: { field1: 4, field2: 1, field3: 7, field4: 2 },
-};
-
-const recvRespObj = {
- result: { resId: 'r-1', payload: new Uint8Array(64).fill(0x42) },
- settings: { field1: 4, field2: 1, field3: 7, field4: 2 },
-};
-
-// Pre-encoded bytes for decode benches (use proton output so both sides see
-// identical, proto3-conforming input).
-const settingsBytes = proton.LongMsgSettings.encode(settingsObj);
-const sendRespBytes = proton.SendLongMsgResp.encode(sendRespObj);
-const sendReqBytes = proton.SendLongMsgReq.encode(sendReqObj);
-const recvRespBytes = proton.RecvLongMsgResp.encode(recvRespObj);
-
-// ── run ──────────────────────────────────────────────────────────────
-
-console.log('# @snowluma/proton vs legacy runtime benchmark\n');
-console.log(`Node ${process.version} | ${process.platform} ${process.arch}`);
-console.log(`Date: ${new Date().toISOString().slice(0, 19).replace('T', ' ')}`);
-
-const N = 300_000;
-
-printSection('Encode — LongMsgSettings (4× uint32)', [
- { ...bench('proton', () => proton.LongMsgSettings.encode(settingsObj), N) },
- { ...bench('legacy', () => protoEncode(settingsObj, LongMsgSettingsSchema), N) },
-]);
-
-printSection('Decode — LongMsgSettings (4× uint32)', [
- { ...bench('proton', () => proton.LongMsgSettings.decode(settingsBytes), N) },
- { ...bench('legacy', () => protoDecode(settingsBytes, LongMsgSettingsSchema), N) },
-]);
-
-printSection('Encode — SendLongMsgResp (1 nested message, 1 string)', [
- { ...bench('proton', () => proton.SendLongMsgResp.encode(sendRespObj), N) },
- { ...bench('legacy', () => protoEncode(sendRespObj, SendLongMsgRespSchema), N) },
-]);
-
-printSection('Decode — SendLongMsgResp', [
- { ...bench('proton', () => proton.SendLongMsgResp.decode(sendRespBytes), N) },
- { ...bench('legacy', () => protoDecode(sendRespBytes, SendLongMsgRespSchema), N) },
-]);
-
-printSection('Encode — SendLongMsgReq (deeply nested, bytes + uint32 + string)', [
- { ...bench('proton', () => proton.SendLongMsgReq.encode(sendReqObj), N) },
- { ...bench('legacy', () => protoEncode(sendReqObj, SendLongMsgReqSchema), N) },
-]);
-
-printSection('Decode — SendLongMsgReq', [
- { ...bench('proton', () => proton.SendLongMsgReq.decode(sendReqBytes), N) },
- { ...bench('legacy', () => protoDecode(sendReqBytes, SendLongMsgReqSchema), N) },
-]);
-
-printSection('Encode — RecvLongMsgResp (64-byte payload + settings)', [
- { ...bench('proton', () => proton.RecvLongMsgResp.encode(recvRespObj), N) },
- { ...bench('legacy', () => protoEncode(recvRespObj, RecvLongMsgRespSchema), N) },
-]);
-
-printSection('Decode — RecvLongMsgResp', [
- { ...bench('proton', () => proton.RecvLongMsgResp.decode(recvRespBytes), N) },
- { ...bench('legacy', () => protoDecode(recvRespBytes, RecvLongMsgRespSchema), N) },
-]);
-
-console.log('');
diff --git a/packages/core/package.json b/packages/core/package.json
index 62b4008d..0a2b6dd1 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -1,10 +1,36 @@
{
"name": "@snowluma/core",
- "version": "1.9.0",
+ "version": "1.9.1",
"description": "SnowLuma core - NTQQ packet sniffer with Node.js native addon",
"private": true,
"type": "module",
"main": "../../dist/index.mjs",
+ "exports": {
+ ".": {
+ "types": "./src/index.ts",
+ "default": "../../dist/index.mjs"
+ },
+ "./bridge": {
+ "types": "./src/bridge/bridge.ts",
+ "default": "./src/bridge/bridge.ts"
+ },
+ "./bridge-interface": {
+ "types": "./src/bridge/bridge-interface.ts",
+ "default": "./src/bridge/bridge-interface.ts"
+ },
+ "./bridge-context": {
+ "types": "./src/bridge/bridge-context.ts",
+ "default": "./src/bridge/bridge-context.ts"
+ },
+ "./manager": {
+ "types": "./src/bridge/manager.ts",
+ "default": "./src/bridge/manager.ts"
+ },
+ "./apis": {
+ "types": "./src/bridge/apis/index.ts",
+ "default": "./src/bridge/apis/index.ts"
+ }
+ },
"scripts": {
"build": "vite build",
"build:all": "cross-env BUILD_WEBUI=true vite build",
@@ -14,7 +40,12 @@
"typecheck": "tsc --noEmit"
},
"dependencies": {
+ "@snowluma/bridge": "workspace:*",
+ "@snowluma/common": "workspace:*",
+ "@snowluma/onebot": "workspace:*",
+ "@snowluma/proto-defs": "workspace:*",
"@snowluma/proton": "workspace:*",
+ "@snowluma/sqlite": "workspace:*",
"@snowluma/websocket": "workspace:*"
},
"devDependencies": {
diff --git a/packages/core/src/bridge/actions/extras.ts b/packages/core/src/bridge/actions/extras.ts
deleted file mode 100644
index ae8e2a6f..00000000
--- a/packages/core/src/bridge/actions/extras.ts
+++ /dev/null
@@ -1,137 +0,0 @@
-// 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 type { Bridge } from '../bridge';
-import { runOidb, makeOidbEnvelope, encodeOidbEnv, decodeOidbEnv } from '../bridge-oidb';
-import type {
- OidbAiVoiceListReq,
- OidbAiVoiceListResp,
- OidbAiVoiceReq,
- OidbAiVoiceResp,
- OidbGroupTodo,
- OidbStrangerStatusReq,
- OidbStrangerStatusResp,
-} from '../proto/proton/oidb-action';
-import type { MediaIndexNode } from './shared';
-
-// ─────────────── Group todo (0xF90) ───────────────
-
-export async function setGroupTodo(bridge: Bridge, groupId: number, msgSeq: bigint): Promise {
- const env = makeOidbEnvelope(0xF90, 1, { groupUin: groupId, msgSeq });
- await runOidb(bridge, 'OidbSvcTrpcTcp.0xf90_1', encodeOidbEnv(env));
-}
-
-export async function completeGroupTodo(bridge: Bridge, groupId: number, msgSeq: bigint): Promise {
- const env = makeOidbEnvelope(0xF90, 2, { groupUin: groupId, msgSeq });
- await runOidb(bridge, 'OidbSvcTrpcTcp.0xf90_2', encodeOidbEnv(env));
-}
-
-export async function cancelGroupTodo(bridge: Bridge, groupId: number, msgSeq: bigint): Promise {
- const env = makeOidbEnvelope(0xF90, 3, { groupUin: groupId, msgSeq });
- await runOidb(bridge, 'OidbSvcTrpcTcp.0xf90_3', encodeOidbEnv(env));
-}
-
-// ─────────────── Stranger online/ext status (0xFE1_2) ───────────────
-
-export interface StrangerStatus {
- status: number;
- ext_status: number;
-}
-
-/**
- * Mirror napcat's GetStrangerStatus: decode the extBigInt status word.
- * Values ≤10 fold into a 10×status; everything else is split into the
- * high-byte / low-byte ext_status the OneBot dialect uses.
- *
- * Returns null on transport / decode failure rather than throwing, so
- * the OneBot action can produce a clean retcode without try/catch
- * gymnastics.
- */
-export async function getStrangerStatus(bridge: Bridge, uin: number): Promise {
- try {
- const env = makeOidbEnvelope(
- 0xFE1, 2,
- { uin, key: [{ key: 27372 }] } as any,
- // Same UIN-form flag fetchUserProfile sets — without it newer
- // QQ NT rejects with `[oidb] one of uid/openid is invaild`.
- true,
- );
- const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xfe1_2', encodeOidbEnv(env));
- const resp = decodeOidbEnv(respBytes).body;
- const raw = resp?.data?.status?.value;
- if (raw === undefined || raw === null) return null;
- const extBig = typeof raw === 'bigint' ? raw : BigInt(raw);
- if (extBig <= 10n) {
- return { status: Number(extBig) * 10, ext_status: 0 };
- }
- const status = Number((extBig & 0xff00n) + ((extBig >> 16n) & 0xffn));
- return { status: 10, ext_status: status };
- } catch {
- return null;
- }
-}
-
-// ─────────────── AI voice (0x929D / 0x929B) ───────────────
-
-export const AiVoiceChatType = {
- Unknown: 0,
- Sound: 1,
- Sing: 2,
-} as const;
-export type AiVoiceChatType = typeof AiVoiceChatType[keyof typeof AiVoiceChatType];
-
-export interface AiVoiceItem {
- voiceId: string;
- voiceDisplayName: string;
- voiceExampleUrl: string;
-}
-
-export interface AiVoiceCategory {
- category: string;
- voices: AiVoiceItem[];
-}
-
-export async function fetchAiVoiceList(
- bridge: Bridge,
- groupId: number,
- chatType: AiVoiceChatType,
-): Promise {
- const env = makeOidbEnvelope(0x929D, 0, { groupUin: groupId, chatType });
- const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x929d_0', encodeOidbEnv(env));
- const resp = decodeOidbEnv(respBytes).body;
- return (resp?.content as AiVoiceCategory[] | undefined) ?? [];
-}
-
-/**
- * Trigger AI voice synthesis. Server may return an empty msgInfo while
- * the render is in-flight; we retry until a node materialises or the
- * cap is hit. napcat uses the same 30-retry budget.
- *
- * The returned MediaIndexNode plugs directly into
- * `bridge.fetchGroupPttUrlByNode`, which already handles every other
- * download-URL fetch in SnowLuma.
- */
-export async function fetchAiVoice(
- bridge: Bridge,
- groupId: number,
- voiceId: string,
- text: string,
- chatType: AiVoiceChatType,
- maxRetries = 30,
-): Promise {
- // Random 32-bit session id — server uses this to deduplicate polls.
- const sessionId = Math.floor(Math.random() * 0xFFFFFFFF) >>> 0;
- for (let i = 0; i < maxRetries; i++) {
- const env = makeOidbEnvelope(
- 0x929B, 0,
- { groupUin: groupId, voiceId, text, chatType, session: { sessionId } },
- );
- const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x929b_0', encodeOidbEnv(env));
- const resp = decodeOidbEnv(respBytes).body;
- const node = resp?.msgInfo?.msgInfoBody?.[0]?.index as MediaIndexNode | undefined;
- if (node) return node;
- }
- throw new Error(`AI voice synthesis did not complete after ${maxRetries} polls`);
-}
diff --git a/packages/core/src/bridge/actions/forward.ts b/packages/core/src/bridge/actions/forward.ts
deleted file mode 100644
index ddca085b..00000000
--- a/packages/core/src/bridge/actions/forward.ts
+++ /dev/null
@@ -1,480 +0,0 @@
-// 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 { 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 type { PacketInfo } from '../../protocol/types';
-import type {
- LongMsgResult,
- RecvLongMsgReq,
- RecvLongMsgResp,
- SendLongMsgReq,
- SendLongMsgResp,
-} from '../proto/proton/longmsg';
-import type { FileExtra, PushMsg, PushMsgBody } from '../proto/proton/message';
-import { resolveSelfUid, toInt } from './shared';
-
-// Module-scoped cache, keyed by res_id. Survives only for the lifetime
-// of the process — that's enough because OneBot clients typically
-// resolve a forward immediately after receiving the parent message.
-const forwardResCache = new Map();
-
-async function buildForwardPushBody(
- bridge: Bridge,
- node: ForwardNodePayload,
- groupId?: number,
- userUid?: string,
-): Promise {
- const fromUin = node.userUin > 0 ? node.userUin : toInt(bridge.identity.uin);
- if (fromUin <= 0) throw new Error('forward node user uin is invalid');
-
- const nickname = node.nickname.trim() || String(fromUin);
- // image/record/video upload inside a forward node must be scoped to the
- // forward's recipient: group → groupId, private → recipient uid.
- // Without this the OIDB upload (0x11c4/0x11c5) has no scene and the
- // element builder throws "private image target uid is missing".
- //
- // `forwardFake: true` keeps `{type:'file'}` segments in the
- // long-msg payload: group → emitted as transElem(24) in elems[],
- // c2c → handled below via msgContent (FileExtra { file: NotOnlineFile }).
- // The QQ-NT live-send pipeline would reject these (transElem(24) →
- // result=79; notOnlineFile via PbSendMsg doesn't render), but the
- // long-msg upload service stores the bytes verbatim and the
- // receiver decodes them through the normal msg-push path.
- const sendCtx = groupId !== undefined
- ? { bridge, groupId, forwardFake: true }
- : userUid
- ? { bridge, userUid, forwardFake: true }
- : { bridge, forwardFake: true };
- const elems = await buildSendElems(node.elements, sendCtx);
- const now = Math.floor(Date.now() / 1000);
- const random = Math.floor(Math.random() * 0x7fffffff) >>> 0;
- const seq = Math.floor(Math.random() * 9000000) + 1000000;
-
- // c2c-file in a forward node — element-builder intentionally skips
- // it (RichText.notOnlineFile + msgContent live outside elems[]). For
- // forward fake-send we mirror what an inbound c2c file message looks
- // like on the wire: serialise the FileExtra blob and ride it on
- // `body.msgContent`. The receiver's rich-body-decoder reads from
- // `msgContent` first (see msg-push/rich-body-decoder.ts:446+), so
- // the bubble renders with the right file name + size when the
- // forward is expanded. Only the FIRST c2c file in a node ships —
- // QQ NT's bubble can only carry one msgContent payload, same as
- // a live c2c send. Group nodes ignore this branch entirely (the
- // transElem(24) elems[] entry above covers them).
- let msgContent: Uint8Array | undefined;
- if (groupId === undefined) {
- const fileEl = node.elements.find(e => e.type === 'file' && e.fileId);
- if (fileEl) {
- // Honour inline segment fields first; fall back to the upload
- // metadata cache (populated by upload_private_file). Without
- // size/md5 the receiver would render "0 B" so prefer recovering
- // them — see same logic in modules/message-actions.ts.
- const cached = bridge.recallUploadedFile(fileEl.fileId ?? '');
- const fileMd5 = fileEl.md5Hex
- ? hexToBytesLocal(fileEl.md5Hex)
- : (cached?.fileMd5 ?? new Uint8Array(0));
- const fileSize = fileEl.fileSize ?? cached?.fileSize ?? 0;
- const fileName = fileEl.fileName ?? cached?.fileName ?? 'file';
- const fileHash = fileEl.fileHash ?? cached?.fileHash ?? '';
- const sevenDays = 7 * 24 * 60 * 60;
- msgContent = protobuf_encode({
- file: {
- fileType: 0,
- fileUuid: fileEl.fileId!,
- fileMd5,
- fileName,
- fileSize: BigInt(fileSize),
- subcmd: 1,
- dangerEvel: 0,
- expireTime: now + sevenDays,
- fileHash,
- },
- });
- }
- }
-
- return {
- responseHead: {
- fromUin,
- toUid: bridge.identity.selfUid ?? '',
- forward: {
- friendName: nickname,
- },
- },
- contentHead: {
- msgType: 9,
- subType: 4,
- msgId: random,
- sequence: seq,
- timestamp: now,
- divSeq: 0,
- },
- body: {
- richText: {
- elems,
- },
- ...(msgContent ? { msgContent } : {}),
- },
- };
-}
-
-// Local hex-decode helper — avoids importing the heavyweight `pipeline`
-// module just for one call. Mirrors `highway/pipeline.ts::hexToBytes`.
-function hexToBytesLocal(hex: string): Uint8Array {
- const s = hex.trim();
- if (!s) return new Uint8Array(0);
- const len = s.length >> 1;
- const out = new Uint8Array(len);
- for (let i = 0; i < len; i++) {
- out[i] = parseInt(s.substr(i * 2, 2), 16);
- }
- return out;
-}
-
-// Per-layer piggyback entry. Each level of a nested forward attaches
-// its own msgBody under a uuid `actionCommand`, so when the receiver
-// fetches the outermost res_id it gets every layer in one shot
-// (modelled on NapCat's `uploadForwardedNodesPacket` — see
-// `dev/NapCatQQ/.../SendMsg.ts:208-347`). Lagrange.Core master + V2
-// both ship a single-action model and silently break when the
-// recipient is a NapCat instance trying to walk the tree.
-interface ForwardInnerAction {
- uuid: string;
- msgBody: PushMsgBody[];
-}
-
-interface ForwardUploadResult {
- resId: string;
- // The current level's msgBody + uuid — what an outer caller would
- // piggyback to expose this layer through the tree.
- msgBody: PushMsgBody[];
- uuid: string;
- // All accumulated piggyback entries from deeper levels. Outer
- // callers concatenate these to their own actions list so the
- // outermost upload carries the full tree.
- innerActions: ForwardInnerAction[];
-}
-
-export async function uploadForwardNodes(
- bridge: Bridge,
- nodes: ForwardNodePayload[],
- groupId?: number,
- userId?: number,
-): Promise {
- const { resId } = await uploadForwardNodesRecursive(bridge, nodes, groupId, userId);
- return resId;
-}
-
-/**
- * Recursive upload with NapCat-style piggyback. Each invocation:
- * 1. Walks `nodes`. For any node whose `innerForward` is set,
- * recursively uploads that inner chain first (which itself runs
- * this same recursion).
- * 2. Replaces the node's `elements` with an ARK preview pointing at
- * the inner res_id (and inner uuid for receiver-side walking).
- * 3. Accumulates the inner level's `{uuid, msgBody}` plus all of
- * ITS accumulated `innerActions` into this level's piggyback list.
- * 4. Encodes this level's long-msg payload as
- * `[MultiMsg + thisMsgBody, ...innerActions]`, uploads it,
- * returns `{resId, msgBody, uuid, innerActions}` so an outer
- * caller can keep piggybacking up the tree.
- */
-async function uploadForwardNodesRecursive(
- bridge: Bridge,
- nodes: ForwardNodePayload[],
- groupId?: number,
- userId?: number,
-): Promise {
- if (!Array.isArray(nodes) || nodes.length === 0) {
- throw new Error('forward nodes are required');
- }
-
- // For a private forward to `userId`, any image/record/video inside a node
- // needs the recipient's uid as upload scene. Resolve it once up-front,
- // and only when at least one node actually contains media (saves an RPC
- // for text-only forwards). Also need it when a node is itself a nested
- // forward — the inner upload uses the same scene.
- let userUid: string | undefined;
- if (groupId === undefined && userId !== undefined && userId > 0) {
- const needsUid = nodes.some(node => !!node.innerForward
- || node.elements.some(e => e.type === 'image' || e.type === 'record' || e.type === 'video'));
- if (needsUid) {
- const resolved = await bridge.resolveUserUid(userId);
- if (resolved) userUid = resolved;
- }
- }
-
- // Walk nodes and resolve nested forwards first (so we know their
- // res_id / uuid before encoding the outer ARK previews). Build
- // `processedNodes` with elements rewritten for nested layers,
- // and collect every inner level's piggyback in `myInnerActions`.
- const myInnerActions: ForwardInnerAction[] = [];
- const processedNodes: ForwardNodePayload[] = [];
- const isGroup = groupId !== undefined;
- for (const node of nodes) {
- if (node.innerForward && node.innerForward.length > 0) {
- const inner = await uploadForwardNodesRecursive(bridge, node.innerForward, groupId, userId);
- // NapCat piggybacks `{uuid: inner.uuid, packetMsg: inner.packetMsg}`
- // + the entire `inner.innerPacketMsg` array up to its caller. We
- // mirror that — `inner.uuid` indexes the inner level itself,
- // and `inner.innerActions` already contains deeper layers.
- myInnerActions.push({ uuid: inner.uuid, msgBody: inner.msgBody });
- myInnerActions.push(...inner.innerActions);
- // Replace the inner placeholder element with a forward preview
- // pointing at the inner res_id. The wire-side element builder
- // turns this into the same XML m_resid blob it already produced
- // for top-level forwards — see `makeForwardElem` in
- // element-builder.ts:153.
- const previewElement: MessageElement = {
- type: 'forward',
- resId: inner.resId,
- forwardSource: deriveInnerSource(node.innerForward, isGroup),
- forwardSummary: `查看${node.innerForward.length}条转发消息`,
- forwardPrompt: '[聊天记录]',
- forwardNews: previewLinesFromNodes(node.innerForward),
- forwardTSum: node.innerForward.length,
- };
- processedNodes.push({
- userUin: node.userUin,
- nickname: node.nickname,
- elements: [previewElement],
- time: node.time,
- msgId: node.msgId,
- msgSeq: node.msgSeq,
- groupId: node.groupId,
- senderCard: node.senderCard,
- messageType: node.messageType,
- });
- } else {
- processedNodes.push(node);
- }
- }
-
- // Encode this level's msgBody.
- const msgBody = await Promise.all(processedNodes.map(
- node => buildForwardPushBody(bridge, node, groupId, userUid),
- ));
-
- // Compose the action list: own MultiMsg + piggybacked inner actions.
- const longMsgResult = protobuf_encode({
- action: [
- { actionCommand: 'MultiMsg', actionData: { msgBody } },
- ...myInnerActions.map(a => ({
- actionCommand: a.uuid,
- actionData: { msgBody: a.msgBody },
- })),
- ],
- });
-
- const selfUid = await resolveSelfUid(bridge);
- const info: SendLongMsgReq['info'] = {
- type: groupId ? 3 : 1,
- uid: { uid: groupId ? String(groupId) : selfUid },
- payload: gzipSync(Buffer.from(longMsgResult)),
- };
- if (groupId) info.groupUin = groupId;
-
- const request = protobuf_encode({
- info,
- settings: {
- field1: 4,
- field2: 1,
- field3: 7,
- field4: 0,
- },
- });
-
- const result = await bridge.sendRawPacket('trpc.group.long_msg_interface.MsgService.SsoSendLongMsg', request);
- if (!result.success || !result.gotResponse || !result.responseData) {
- throw new Error(result.errorMessage || 'upload forward message failed');
- }
-
- const resp = protobuf_decode(result.responseData);
- const resId = typeof resp?.result?.resId === 'string' ? resp.result.resId : '';
- if (!resId) {
- throw new Error('upload forward message response missing res_id');
- }
-
- forwardResCache.set(resId, processedNodes.map(node => ({
- userUin: node.userUin,
- nickname: node.nickname,
- elements: [...node.elements],
- time: node.time,
- msgId: node.msgId,
- msgSeq: node.msgSeq,
- groupId: node.groupId ?? groupId,
- senderCard: node.senderCard,
- messageType: node.messageType ?? (groupId ? 'group' : 'private'),
- })));
-
- return {
- resId,
- msgBody,
- uuid: randomUUID(),
- innerActions: myInnerActions,
- };
-}
-
-// Inner forward preview metadata — kept minimal here (the OneBot
-// `parseForwardNodes` caller can override these on the top-level
-// node by passing custom forwardSource/forwardSummary on the
-// non-nested send path; nested levels just get sensible defaults
-// since they're synthesised by us and never reach OneBot input).
-function deriveInnerSource(innerNodes: ForwardNodePayload[], isGroup: boolean): string {
- const nicks: string[] = [];
- const seen = new Set();
- for (const node of innerNodes) {
- const name = (node.nickname ?? '').trim();
- if (name && !seen.has(name)) {
- seen.add(name);
- nicks.push(name);
- }
- if (nicks.length >= 4) break;
- }
- if (nicks.length === 0) return isGroup ? '群聊的聊天记录' : '聊天记录';
- return `${nicks.join('和')}的聊天记录`;
-}
-
-function previewLinesFromNodes(innerNodes: ForwardNodePayload[]): Array<{ text: string }> {
- return innerNodes.slice(0, 4).map(node => {
- const name = (node.nickname ?? '').trim() || String(node.userUin || 'QQ用户');
- const previewText = previewFromElements(node.elements);
- return { text: previewText ? `${name}: ${previewText}` : name };
- });
-}
-
-function previewFromElements(elements: MessageElement[]): string {
- for (const elem of elements) {
- if (elem.type === 'text' && elem.text) return elem.text.slice(0, 30);
- if (elem.type === 'image') return '[图片]';
- if (elem.type === 'record') return '[语音]';
- if (elem.type === 'video') return '[视频]';
- if (elem.type === 'file') return '[文件]';
- if (elem.type === 'forward') return '[聊天记录]';
- if (elem.type === 'face') return '[表情]';
- }
- return '';
-}
-
-export async function fetchForwardNodes(bridge: Bridge, resId: string): Promise {
- const cached = forwardResCache.get(resId);
- if (cached) {
- return cached.map(node => ({
- userUin: node.userUin,
- nickname: node.nickname,
- elements: [...node.elements],
- time: node.time,
- msgId: node.msgId,
- msgSeq: node.msgSeq,
- groupId: node.groupId,
- senderCard: node.senderCard,
- messageType: node.messageType,
- }));
- }
-
- const selfUid = await resolveSelfUid(bridge);
- const request = protobuf_encode({
- info: {
- uid: { uid: selfUid },
- resId,
- acquire: true,
- },
- settings: {
- field1: 2,
- field2: 0,
- field3: 0,
- field4: 0,
- },
- });
-
- const result = await bridge.sendRawPacket('trpc.group.long_msg_interface.MsgService.SsoRecvLongMsg', request);
- if (!result.success || !result.gotResponse || !result.responseData) {
- throw new Error(result.errorMessage || 'download forward message failed');
- }
-
- const resp = protobuf_decode(result.responseData);
- const payload = resp?.result?.payload;
- if (!(payload instanceof Uint8Array) || payload.length === 0) {
- throw new Error('download forward message payload is empty');
- }
-
- const inflate = gunzipSync(Buffer.from(payload));
- const longMsg = protobuf_decode(inflate);
- const action = longMsg?.action?.find((item) => item?.actionCommand === 'MultiMsg');
- const msgBodyList = Array.isArray(action?.actionData?.msgBody) ? action.actionData.msgBody : [];
-
- const nodes: ForwardNodePayload[] = [];
- for (const msgBody of msgBodyList) {
- const wrapped = protobuf_encode({ message: msgBody });
- const pkt: PacketInfo = {
- pid: 0,
- uin: bridge.identity.uin,
- serviceCmd: 'trpc.msg.olpush.OlPushService.MsgPush',
- seqId: 0,
- retCode: 0,
- fromClient: false,
- body: wrapped,
- };
- const events = parseMsgPush(pkt, bridge.identity);
- const event = events.find(e =>
- e.kind === 'friend_message' || e.kind === 'group_message' || e.kind === 'temp_message');
- if (!event) continue;
-
- if (event.kind === 'group_message') {
- nodes.push({
- userUin: event.senderUin,
- nickname: event.senderCard || event.senderNick,
- elements: event.elements,
- time: event.time,
- msgId: event.msgId,
- msgSeq: event.msgSeq,
- groupId: event.groupId,
- senderCard: event.senderCard,
- messageType: 'group',
- });
- } else if (event.kind === 'friend_message') {
- nodes.push({
- userUin: event.senderUin,
- nickname: event.senderNick,
- elements: event.elements,
- time: event.time,
- msgId: event.msgId,
- msgSeq: event.msgSeq,
- messageType: 'private',
- });
- } else {
- nodes.push({
- userUin: event.senderUin,
- nickname: event.senderNick,
- elements: event.elements,
- time: event.time,
- msgSeq: event.msgSeq,
- groupId: event.groupId,
- messageType: 'private',
- });
- }
- }
-
- if (nodes.length > 0) {
- forwardResCache.set(resId, nodes.map(node => ({
- userUin: node.userUin,
- nickname: node.nickname,
- elements: [...node.elements],
- time: node.time,
- msgId: node.msgId,
- msgSeq: node.msgSeq,
- groupId: node.groupId,
- senderCard: node.senderCard,
- messageType: node.messageType,
- })));
- }
- return nodes;
-}
diff --git a/packages/core/src/bridge/actions/friend.ts b/packages/core/src/bridge/actions/friend.ts
deleted file mode 100644
index c4ff1510..00000000
--- a/packages/core/src/bridge/actions/friend.ts
+++ /dev/null
@@ -1,52 +0,0 @@
-// 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 type { Bridge } from '../bridge';
-import { runOidb, makeOidbEnvelope, encodeOidbEnv } from '../bridge-oidb';
-import type {
- OidbDeleteFriend,
- OidbFriendRequestAction,
- OidbSetFriendRemark,
-} from '../proto/proton/oidb-action';
-
-export async function setFriendAddRequest(bridge: Bridge, uidOrFlag: string, approve: boolean): Promise {
- let targetUid = uidOrFlag;
- if (/^\d+$/.test(uidOrFlag)) {
- targetUid = await bridge.resolveUserUid(parseInt(uidOrFlag, 10));
- }
- const env = makeOidbEnvelope(0xB5D, 44, { accept: approve ? 3 : 5, targetUid });
- await runOidb(bridge, 'OidbSvcTrpcTcp.0xb5d_44', encodeOidbEnv(env));
-}
-
-export async function deleteFriend(bridge: Bridge, userId: number, block = false): Promise {
- const targetUid = await bridge.resolveUserUid(userId);
- const env = makeOidbEnvelope(0x126B, 0, {
- field1: {
- targetUid,
- field2: {
- field1: 130,
- field2: 109,
- field3: {
- field1: 8,
- field2: 8,
- field3: 50,
- },
- },
- block,
- field4: false,
- },
- });
- await runOidb(bridge, 'OidbSvcTrpcTcp.0x126b_0', encodeOidbEnv(env));
-
- // Refresh friend cache after deletion so subsequent reads don't
- // surface a ghost entry. Best-effort: a transient OIDB hiccup here
- // shouldn't make the delete itself look failed.
- try { await bridge.fetchFriendList(); } catch { /* ignore */ }
-}
-
-export async function setFriendRemark(bridge: Bridge, userId: number, remark: string): Promise {
- const uid = await bridge.resolveUserUid(userId);
- const env = makeOidbEnvelope(0xB6E, 2, { targetUid: uid, remark });
- await runOidb(bridge, 'OidbSvcTrpcTcp.0xb6e_2', encodeOidbEnv(env));
-}
diff --git a/packages/core/src/bridge/actions/group-admin.ts b/packages/core/src/bridge/actions/group-admin.ts
deleted file mode 100644
index 25b2eafd..00000000
--- a/packages/core/src/bridge/actions/group-admin.ts
+++ /dev/null
@@ -1,165 +0,0 @@
-// 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 type { Bridge } from '../bridge';
-import { runOidb, makeOidbEnvelope, encodeOidbEnv, decodeOidbEnv } from '../bridge-oidb';
-import type {
- Oidb0x89a_0AddOption,
- Oidb0x89a_0Search,
- Oidb0x8a0Req,
- Oidb0x8a7Req,
- Oidb0x8a7Resp,
- Oidb0xf16Req,
- OidbGroupRequestAction,
- OidbKickMember,
- OidbLeaveGroup,
- OidbMuteAll,
- OidbMuteMember,
- OidbRenameGroup,
- OidbRenameMember,
- OidbSetAdmin,
- OidbSpecialTitle,
-} from '../proto/proton/oidb-action';
-
-// ─────────────── mute / un-mute ───────────────
-
-export async function muteGroupMember(bridge: Bridge, groupId: number, userId: number, duration: number): Promise {
- const uid = await bridge.resolveUserUid(userId, groupId);
- const env = makeOidbEnvelope(0x1253, 1, {
- groupUin: groupId, type: 1, body: { targetUid: uid, duration },
- });
- await runOidb(bridge, 'OidbSvcTrpcTcp.0x1253_1', encodeOidbEnv(env));
-}
-
-export async function muteGroupAll(bridge: Bridge, groupId: number, enable: boolean): Promise {
- const env = makeOidbEnvelope(0x89A, 0, {
- groupUin: groupId, muteState: { state: enable ? 0xFFFFFFFF : 0 },
- });
- await runOidb(bridge, 'OidbSvcTrpcTcp.0x89a_0', encodeOidbEnv(env));
-}
-
-// ─────────────── join-policy ───────────────
-
-export async function setGroupAddOption(bridge: Bridge, groupId: number, addType: number): Promise {
- const env = makeOidbEnvelope(0x89A, 0, {
- groupUin: BigInt(groupId), settings: { addType }, field12: 0,
- });
- await runOidb(bridge, 'OidbSvcTrpcTcp.0x89a_0', encodeOidbEnv(env));
-}
-
-export async function setGroupSearch(bridge: Bridge, groupId: number): Promise {
- const env = makeOidbEnvelope(0x89A, 0, {
- groupUin: BigInt(groupId), settings: new Uint8Array(0), field12: 0,
- });
- await runOidb(bridge, 'OidbSvcTrpcTcp.0x89a_0', encodeOidbEnv(env));
-}
-
-export async function setGroupAddRequest(
- bridge: Bridge, groupId: number, sequence: number, eventType: number,
- approve: boolean, reason = '', filtered = false,
-): Promise {
- const subCmd = filtered ? 2 : 1;
- const cmd = filtered ? 'OidbSvcTrpcTcp.0x10c8_2' : 'OidbSvcTrpcTcp.0x10c8_1';
- const env = makeOidbEnvelope(
- 0x10C8, subCmd,
- { accept: approve ? 1 : 2, body: { sequence: BigInt(sequence), eventType, groupUin: groupId, message: reason } },
- true,
- );
- await runOidb(bridge, cmd, encodeOidbEnv(env));
-}
-
-// ─────────────── kick / leave ───────────────
-
-export async function kickGroupMember(bridge: Bridge, groupId: number, userId: number, reject: boolean, reason = ''): Promise {
- const uid = await bridge.resolveUserUid(userId, groupId);
- const env = makeOidbEnvelope(0x8A0, 1, {
- groupUin: groupId, targetUid: uid, rejectAddRequest: reject, reason,
- });
- await runOidb(bridge, 'OidbSvcTrpcTcp.0x8a0_1', encodeOidbEnv(env));
-}
-
-export async function kickGroupMembers(bridge: Bridge, groupId: number, userIds: number[], reject: boolean): Promise {
- const targetUids = await Promise.all(userIds.map(userId => bridge.resolveUserUid(userId, groupId)));
- const env = makeOidbEnvelope(0x8A0, 1, {
- groupId: BigInt(groupId), targetUids, rejectAddRequest: reject ? 1 : 0, kickReason: new Uint8Array(0), field12: 0,
- });
- await runOidb(bridge, 'OidbSvcTrpcTcp.0x8a0_1', encodeOidbEnv(env));
-}
-
-export async function leaveGroup(bridge: Bridge, groupId: number): Promise {
- const env = makeOidbEnvelope(0x1097, 1, { groupUin: groupId });
- await runOidb(bridge, 'OidbSvcTrpcTcp.0x1097_1', encodeOidbEnv(env));
-}
-
-// ─────────────── role / display name ───────────────
-
-export async function setGroupAdmin(bridge: Bridge, groupId: number, userId: number, enable: boolean): Promise {
- const uid = await bridge.resolveUserUid(userId, groupId);
- const env = makeOidbEnvelope(0x1096, 1, { groupUin: groupId, uid, isAdmin: enable });
- await runOidb(bridge, 'OidbSvcTrpcTcp.0x1096_1', encodeOidbEnv(env));
-}
-
-export async function setGroupCard(bridge: Bridge, groupId: number, userId: number, card: string): Promise {
- const uid = await bridge.resolveUserUid(userId, groupId);
- const env = makeOidbEnvelope(0x8FC, 3, {
- groupUin: groupId, body: { targetUid: uid, targetName: card },
- });
- await runOidb(bridge, 'OidbSvcTrpcTcp.0x8fc_3', encodeOidbEnv(env));
-}
-
-export async function setGroupName(bridge: Bridge, groupId: number, name: string): Promise {
- const env = makeOidbEnvelope(0x89A, 15, { groupUin: groupId, body: { targetName: name } });
- await runOidb(bridge, 'OidbSvcTrpcTcp.0x89a_15', encodeOidbEnv(env));
-}
-
-export async function setGroupSpecialTitle(bridge: Bridge, groupId: number, userId: number, title: string): Promise {
- const uid = await bridge.resolveUserUid(userId, groupId);
- const env = makeOidbEnvelope(0x8FC, 2, {
- groupUin: groupId, body: { targetUid: uid, specialTitle: title, expireTime: -1 },
- });
- await runOidb(bridge, 'OidbSvcTrpcTcp.0x8fc_2', encodeOidbEnv(env));
-}
-
-// ─────────────── personal-side metadata ───────────────
-
-// setGroupRemark is the bot's local-only label for the group; it lives
-// here rather than in friend.ts because the semantic is "operate on a
-// group" rather than "operate on a contact list".
-export async function setGroupRemark(bridge: Bridge, groupId: number, remark: string): Promise {
- const env = makeOidbEnvelope(0xF16, 1, { inner: { groupId: BigInt(groupId), remark }, field12: 0 });
- await runOidb(bridge, 'OidbSvcTrpcTcp.0xf16_1', encodeOidbEnv(env));
-}
-
-// ─────────────── group-level quota query ───────────────
-
-export async function getGroupAtAllRemain(
- bridge: Bridge,
- groupId: number,
-) {
- const req = {
- basic1: 1,
- basic2: 2,
- basic3: 1,
- uin: BigInt(bridge.identity.uin),
- groupId: BigInt(groupId),
- type: 0,
- };
-
- const env = makeOidbEnvelope(0x8A7, 0, req);
- const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x8a7_0', encodeOidbEnv(env));
- const result = decodeOidbEnv(respBytes).body;
-
- if (!result) {
- throw new Error('get group at all remain result empty');
- }
-
- // Cast numbers to plain Number: the OIDB layer may surface uint32 as
- // BigInt and the WebUI JSON serializer chokes on those.
- return {
- can_at_all: !!result.canAtAll,
- remain_at_all_count_for_group: Number(result.groupRemain || 0),
- remain_at_all_count_for_uin: Number(result.uinRemain || 0),
- };
-}
diff --git a/packages/core/src/bridge/actions/group-album.ts b/packages/core/src/bridge/actions/group-album.ts
deleted file mode 100644
index 75c8e135..00000000
--- a/packages/core/src/bridge/actions/group-album.ts
+++ /dev/null
@@ -1,289 +0,0 @@
-// 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` envelope. We hit `bridge.sendRawPacket` directly with
-// proton-encoded bodies and decode the responses through proton's
-// monomorphized codecs.
-
-import type { Bridge } from '../bridge';
-import { protobuf_encode, protobuf_decode } from '@snowluma/proton';
-import type {
- GetMediaListRequest,
- GetMediaListResponse,
- DoQunCommentRequest,
- DoQunCommentResponse,
- DoQunLikeRequest,
- DoQunLikeResponse,
- DeleteMediasRequest,
- DeleteMediasResponse,
-} from '../proto/proton/oidb-action';
-
-export interface GroupAlbumMediaResult {
- mediaList: any[];
- nextAttachInfo: string;
-}
-
-export interface GroupAlbumCommentResult {
- id: string;
- user: { uin: string };
- content: Array<{ type: number; content: string }>;
- time: string;
- clientKey: string;
-}
-
-function convertBigIntToString(obj: any): any {
- if (obj === null || obj === undefined) return obj;
- if (typeof obj === 'bigint') return obj.toString();
- if (Array.isArray(obj)) return obj.map(convertBigIntToString);
- if (typeof obj === 'object') {
- const result: any = {};
- for (const key in obj) {
- result[key] = convertBigIntToString(obj[key]);
- }
- return result;
- }
- return obj;
-}
-
-export async function getGroupAlbumMediaList(
- bridge: Bridge,
- groupId: number,
- albumId: string,
- attachInfo: string = ''
-): Promise {
- const traceId = `_${Date.now()}_${Math.floor(Math.random() * 100000)}`;
-
- const body = protobuf_encode({
- field1: 0,
- field2: new Uint8Array(0),
- field3: new Uint8Array(0),
- reqInfo: {
- groupId: groupId.toString(),
- albumId: albumId,
- field3: 0,
- attachInfo: attachInfo,
- field5: '',
- },
- traceId: traceId,
- extMap: [{ key: 'fc-appid', value: '100' }],
- });
-
- const result = await bridge.sendRawPacket(
- 'QunAlbum.trpc.qzone.webapp_qun_media.QunMedia.GetMediaList',
- body,
- 15000
- );
-
- if (!result.success || !result.gotResponse || !result.responseData) {
- throw new Error(result.errorMessage || 'failed to get album media list');
- }
-
- const resp = protobuf_decode(result.responseData);
-
- if (resp.field1 !== 0) {
- throw new Error(`fetch album media list error: retCode ${resp.field1 ?? 'unknown'}`);
- }
-
- const data = resp.data ?? {};
- const mediaList = data.mediaList ?? [];
- const nextAttachInfo = data.nextAttachInfo ?? '';
-
- return convertBigIntToString({
- mediaList,
- nextAttachInfo,
- });
-}
-
-
-
-export async function commentGroupAlbumMedia(
- bridge: Bridge,
- groupId: number,
- albumId: string,
- lloc: string,
- content: string
-): Promise {
- const traceId = `_${Date.now()}_${Math.floor(Math.random() * 100000)}`;
- const clientKey = Date.now().toString();
- const uin = bridge.identity.uin;
-
- const body = protobuf_encode({
- field1: 8527,
- field2: new Uint8Array(0),
- field3: new Uint8Array(0),
- body: {
- groupId: groupId.toString(),
- field3: 2,
- reqBody: {
- field1: { field3: 0, field4: "" },
- field2: {
- field1: { uin }
- },
- field5: {
- field1: {
- field2: {
- field1: 0, field2: "",
- lloc,
- field4: "", field6: "", field7: 0, field8: 0, field9: 0, field14: 0, field15: 0, field17: 0
- }
- },
- albumId,
- field5: 0
- },
- },
- field5: {
- field2: { uin },
- field3: {
- field1: 0,
- field2: content,
- field3: "", field4: "", field5: 0, field6: ""
- },
- clientKey,
- }
- },
- traceId,
- extMap: [{ key: 'fc-appid', value: '100' }],
- });
-
- const result = await bridge.sendRawPacket(
- 'QunAlbum.trpc.qzone.webapp_qun_operation.FeedsWriter.DoQunComment',
- body,
- 15000
- );
-
- if (!result.success || !result.gotResponse || !result.responseData) {
- throw new Error(result.errorMessage || 'failed to comment on album media');
- }
-
- const resp = protobuf_decode(result.responseData);
-
- const resCode = resp.field1;
- if (resCode !== 0 && resCode !== 8527 && !resp.comment) {
- throw new Error(`comment album media error: retCode ${resCode ?? 'unknown'}`);
- }
-
- const commentData = resp.comment?.data ?? {};
-
- return convertBigIntToString({
- id: commentData.id ?? '',
- user: { uin: commentData.user?.uin ?? '' },
- content: commentData.content ?? [],
- time: commentData.time ?? '0',
- clientKey: commentData.clientKey ?? '',
- });
-}
-
-export async function likeGroupAlbumMedia(
- bridge: Bridge,
- groupId: number,
- albumId: string,
- batchId: string,
- lloc: string | undefined,
- isLike: boolean
-): Promise {
- const uin = bridge.identity.uin;
- const clientKey = `${uin}_${Date.now()}_${Math.floor(Math.random() * 100000)}`;
-
- const type = isLike ? 2 : 1;
- const status = isLike ? 0 : 1;
-
- let id = '';
- if (lloc) {
- id = `421_1_0_${groupId}|${albumId}|${batchId}^||^421_1_0_${groupId}|${albumId}|${lloc}^||^0`;
- } else {
- id = `421_1_0_${groupId}|${albumId}|${batchId}`;
- }
-
- const body = protobuf_encode({
- field1: 5495,
- field2: "h5_test",
- field3: "h5_test",
- body: {
- type,
- like: { id, status },
- publish: {
- cellCommon: {
- time: BigInt(Date.now()),
- feedId: `422_0_${batchId}`
- },
- cellUserInfo: {
- user: { uin }
- },
- cellMedia: {
- albumId: albumId,
- batchId: BigInt(batchId)
- },
- cellQunInfo: {
- qunId: groupId.toString()
- }
- },
- clientKey
- },
- extMap: [{ key: 'fc-appid', value: '100' }],
- });
-
- const result = await bridge.sendRawPacket(
- 'QunAlbum.trpc.qzone.webapp_qun_operation.FeedsWriter.DoQunLike',
- body,
- 15000
- );
-
- if (!result.success || !result.gotResponse || !result.responseData) {
- throw new Error(result.errorMessage || 'failed to like album media');
- }
-
- const resp = protobuf_decode(result.responseData);
- const resCode = resp.field1;
-
- if (resCode !== 5495) {
- throw new Error(`like album media error: retCode ${resCode ?? 'unknown'}`);
- }
-
- return convertBigIntToString(resp.body?.like ?? {});
-}
-
-export async function deleteGroupAlbumMedia(
- bridge: Bridge,
- groupId: number,
- albumId: string,
- lloc: string
-): Promise {
- const uin = bridge.identity.uin;
- const clientKey = `${uin}_${Date.now()}_${Math.floor(Math.random() * 100000)}`;
-
- const body = protobuf_encode({
- field1: 8694,
- field2: "h5_test",
- field3: "h5_test",
- body: {
- groupId: groupId.toString(),
- albumId: albumId,
- lloc: lloc,
- },
- traceId: clientKey,
- extMap: [{ key: 'fc-appid', value: '100' }],
- });
-
- const result = await bridge.sendRawPacket(
- 'QunAlbum.trpc.qzone.webapp_qun_media.QunMedia.DeleteMedias',
- body,
- 15000
- );
-
- if (!result.success || !result.gotResponse || !result.responseData) {
- throw new Error(result.errorMessage || 'failed to delete album media');
- }
-
- const resp = protobuf_decode(result.responseData);
- const resCode = resp.field1;
- const errCode = resp.field2;
- const errMsg = resp.field3;
-
- if (resCode !== 8694 || errCode) {
- throw new Error(`delete album media error [${errCode ?? 'unknown'}]: ${errMsg ?? 'unknown'}`);
- }
-
- return { success: true };
-}
-
diff --git a/packages/core/src/bridge/actions/group-file.ts b/packages/core/src/bridge/actions/group-file.ts
deleted file mode 100644
index 4d3aab82..00000000
--- a/packages/core/src/bridge/actions/group-file.ts
+++ /dev/null
@@ -1,983 +0,0 @@
-// 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_encode } from '@snowluma/proton';
-import { runOidb, makeOidbEnvelope, encodeOidbEnv, decodeOidbEnv } from '../bridge-oidb';
-import { fetchHighwaySession, uploadHighwayHttp } from '../highway/highway-client';
-import { computeHashes, computeMd5, FILE_UPLOAD_MAX_BYTES, loadBinarySource } from '../highway/utils';
-import type {
- OidbGroupFileCountViewReq,
- OidbGroupFileCountViewResp,
- OidbGroupFileFolderReq,
- OidbGroupFileFolderResp,
- OidbGroupFileReq,
- OidbGroupFileResp,
- OidbGroupFileViewReq,
- OidbGroupFileViewResp,
- OidbGroupSendFileReq,
- OidbPrivateFileDownloadReq,
- OidbPrivateFileDownloadResp,
- OidbPrivateFileUploadReq,
- OidbPrivateFileUploadResp,
- NTV2RichMediaReq,
- NTV2RichMediaResp,
-} from '../proto/proton/oidb-action';
-import type { FileUploadExt } from '../proto/proton/highway';
-import { toHexUpper } from '../../utils/hex';
-import { createLogger } from '../../utils/logger';
-import { ensureRetCodeZero, resolveSelfUid, toInt, type MediaIndexNode } from './shared';
-
-const log = createLogger('GroupFile');
-
-// ─────────────── public result types ───────────────
-
-export interface GroupFileInfo {
- fileId: string;
- fileName: string;
- busId: number;
- fileSize: number;
- uploadTime: number;
- deadTime: number;
- modifyTime: number;
- downloadTimes: number;
- uploader: number;
- uploaderName: string;
-}
-
-export interface GroupFolderInfo {
- folderId: string;
- folderName: string;
- createTime: number;
- creator: number;
- creatorName: string;
- totalFileCount: number;
-}
-
-export interface GroupFilesResult {
- files: GroupFileInfo[];
- folders: GroupFolderInfo[];
-}
-
-export interface UploadFileResult {
- fileId: string | null;
- fileHash?: string | null;
-}
-
-// Re-export so this file is a one-stop-shop for the file API surface
-// (bridge.ts imports MediaIndexNode through here for type symmetry).
-export type { MediaIndexNode } from './shared';
-
-// ─────────────── file-specific helpers ───────────────
-
-function normalizeDirectory(dir?: string): string {
- if (!dir || !dir.trim()) return '/';
- return dir;
-}
-
-function bytesToHexUpper(data: unknown): string {
- if (!(data instanceof Uint8Array) || data.length === 0) return '';
- return toHexUpper(data);
-}
-
-// Reverses acidify's `Int.toIpString()`: the 32-bit IP arrives
-// little-endian-packed (byte0 = first dotted octet) and we unpack it the
-// same way. Force-unsigned the shift to keep negative ints (high bit set)
-// rendering correctly — JS `>>` is arithmetic and would turn 0xFF000000
-// into a negative number.
-function int32ToIpv4Dotted(value: number): string {
- const b1 = value & 0xFF;
- const b2 = (value >>> 8) & 0xFF;
- const b3 = (value >>> 16) & 0xFF;
- const b4 = (value >>> 24) & 0xFF;
- return `${b1}.${b2}.${b3}.${b4}`;
-}
-
-function normalizeUploadFileName(name: string, fallback: string): string {
- const trimmed = name.trim();
- if (trimmed) return trimmed;
- const safeFallback = fallback.trim();
- return safeFallback || 'file.bin';
-}
-
-function md5First10MB(bytes: Uint8Array): Uint8Array {
- const limit = Math.min(bytes.length, 10 * 1024 * 1024);
- return computeMd5(bytes.subarray(0, limit));
-}
-
-function buildGroupFileUploadExt(
- senderUin: number,
- groupId: number,
- fileName: string,
- fileSize: number,
- md5: Uint8Array,
- fileId: string,
- uploadKey: Uint8Array,
- checkKey: Uint8Array,
- uploadHost: string,
- uploadPort: number,
-): Uint8Array {
- return protobuf_encode({
- unknown1: 100,
- unknown2: 1,
- entry: {
- busiBuff: {
- busId: 102,
- senderUin: BigInt(senderUin),
- receiverUin: BigInt(groupId),
- groupCode: BigInt(groupId),
- },
- fileEntry: {
- fileSize: BigInt(Math.max(0, fileSize)),
- md5,
- md5S2: md5,
- checkKey,
- fileId,
- uploadKey,
- },
- clientInfo: {
- clientType: 3,
- appId: '100',
- terminalType: 3,
- clientVer: '1.1.1',
- unknown: 4,
- },
- fileNameInfo: {
- fileName,
- },
- host: {
- hosts: [
- {
- url: {
- host: uploadHost,
- unknown: 1,
- },
- port: uploadPort,
- },
- ],
- },
- },
- unknown200: 0,
- });
-}
-
-function buildPrivateFileUploadExt(
- senderUin: number,
- fileName: string,
- fileSize: number,
- md5: Uint8Array,
- sha1: Uint8Array,
- fileId: string,
- uploadKey: Uint8Array,
- uploadHost: string,
- uploadPort: number,
-): Uint8Array {
- return protobuf_encode({
- unknown1: 100,
- unknown2: 1,
- entry: {
- busiBuff: {
- busId: 102,
- senderUin: BigInt(senderUin),
- receiverUin: 0n,
- groupCode: 0n,
- },
- fileEntry: {
- fileSize: BigInt(Math.max(0, fileSize)),
- md5,
- md5S2: md5,
- checkKey: sha1,
- fileId,
- uploadKey,
- },
- clientInfo: {
- clientType: 3,
- appId: '100',
- terminalType: 3,
- clientVer: '1.1.1',
- unknown: 4,
- },
- fileNameInfo: {
- fileName,
- },
- host: {
- hosts: [
- {
- url: {
- host: uploadHost,
- unknown: 1,
- },
- port: uploadPort,
- },
- ],
- },
- },
- unknown3: 0,
- unknown200: 1,
- });
-}
-
-function normalizeMediaNode(node: MediaIndexNode): Record {
- const fileUuid = typeof node.fileUuid === 'string' ? node.fileUuid : '';
- if (!fileUuid) throw new Error('media node fileUuid is required');
-
- const info = node.info ?? {};
- const type = info.type ?? {};
-
- return {
- info: {
- fileSize: toInt(info.fileSize),
- fileHash: typeof info.fileHash === 'string' ? info.fileHash : '',
- fileSha1: typeof info.fileSha1 === 'string' ? info.fileSha1 : '',
- fileName: typeof info.fileName === 'string' ? info.fileName : '',
- type: {
- type: toInt(type.type),
- picFormat: toInt(type.picFormat),
- videoFormat: toInt(type.videoFormat),
- voiceFormat: toInt(type.voiceFormat),
- },
- width: toInt(info.width),
- height: toInt(info.height),
- time: toInt(info.time),
- original: toInt(info.original),
- },
- fileUuid,
- storeId: toInt(node.storeId),
- uploadTime: toInt(node.uploadTime),
- ttl: toInt(node.ttl),
- subType: toInt(node.subType),
- };
-}
-
-async function fetchNtv2DownloadUrl(
- bridge: Bridge,
- serviceCmd: string,
- oidbCmd: number,
- payload: Record,
-): Promise {
- const env = makeOidbEnvelope(oidbCmd, 200, payload as any, true);
- const respBytes = await runOidb(bridge, serviceCmd, encodeOidbEnv(env));
- const resp = decodeOidbEnv(respBytes).body;
-
- ensureRetCodeZero('ntv2 download', resp?.respHead?.retCode, resp?.respHead?.message, undefined);
- const domain = typeof resp?.download?.info?.domain === 'string' ? resp.download.info.domain : '';
- const path = typeof resp?.download?.info?.urlPath === 'string' ? resp.download.info.urlPath : '';
- const rKeyParam = typeof resp?.download?.rKeyParam === 'string' ? resp.download.rKeyParam : '';
-
- if (!domain || !path) {
- throw new Error('ntv2 download response invalid');
- }
- return `https://${domain}${path}${rKeyParam}`;
-}
-
-// ─────────────── publish (group file → chat) ───────────────
-
-/**
- * Publish a previously-uploaded group file as a chat message.
- *
- * Wire is OIDB `OidbSvcTrpcTcp.0x6d9_4` — NOT `MessageSvc.PbSendMsg`.
- * Lagrange.Core V2 splits these two roles: the file UPLOAD path goes
- * via 0x6D6_0 + highway PUT, then a SECOND OIDB hop (this one) tells
- * the QQ server "now publish that staged blob as a chat message" so
- * everyone in the group can see the file bubble.
- *
- * The old approach — wrap the file as `TransElem(elemType=24)` inside
- * `richText.elems[]` and ship it via PbSendMsg — works for INCOMING
- * messages (the receive decoder unpacks transElem(24) into a
- * FileEntity) but the QQ-NT server REJECTS it on outgoing with
- * `result=79` ("invalid element on send-side"). Mirror Lagrange's
- * dedicated GroupSendFileService instead.
- *
- * The unused `field4` slot and the `field3=random` value match
- * Lagrange's send-side defaults (`OidbSvcTrpcTcp0x6D9_4.cs` + the
- * `Random.Shared.Next()` call in `GroupSendFileService.cs`). Field 5
- * is the `Field5=true` flag the receiver's deserializer expects.
- */
-export async function sendGroupFileMessage(bridge: Bridge, groupId: number, fileId: string): Promise {
- if (!fileId) throw new Error('sendGroupFileMessage requires fileId');
- const env = makeOidbEnvelope(0x6D9, 4, {
- body: {
- groupUin: groupId,
- type: 2,
- info: {
- busiType: 102,
- fileId,
- field3: Math.floor(Math.random() * 0x7fffffff) >>> 0,
- field5: true,
- },
- },
- });
- // The envelope-level errorCode peek inside `runOidb` covers the
- // happy-path validation; failures surface as a thrown OIDB error.
- await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d9_4', encodeOidbEnv(env));
-}
-
-// ─────────────── file count ───────────────
-
-export async function fetchGroupFileCount(bridge: Bridge, groupId: number): Promise<{ fileCount: number; maxCount: number }> {
- const env = makeOidbEnvelope(
- 0x6D8, 3,
- { count: { groupUin: groupId, appId: 7, busId: 0 } },
- );
- const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d8_3', encodeOidbEnv(env));
- const resp = decodeOidbEnv(respBytes).body;
- return {
- fileCount: toInt(resp?.count?.fileCount ?? 0),
- maxCount: toInt(resp?.count?.maxCount ?? 10000),
- };
-}
-
-// ─────────────── upload ───────────────
-
-export async function uploadGroupFile(
- bridge: Bridge,
- groupId: number,
- source: string,
- name = '',
- folderId = '/',
- uploadFile = true,
-): Promise {
- // Group/private files may legitimately be up to 4 GiB on QQ's wire,
- // so override the default 1 GiB cap with the protocol ceiling.
- const loaded = await loadBinarySource(source, 'file', FILE_UPLOAD_MAX_BYTES);
- if (!loaded.bytes.length) throw new Error('group file is empty');
-
- const fileName = normalizeUploadFileName(name, loaded.fileName);
- const hashes = computeHashes(loaded.bytes);
-
- const env = makeOidbEnvelope(
- 0x6D6, 0,
- {
- file: {
- groupUin: groupId,
- appId: 4,
- busId: 102,
- entrance: 6,
- targetDirectory: normalizeDirectory(folderId),
- fileName,
- localDirectory: `/${fileName}`,
- fileSize: BigInt(loaded.bytes.length),
- fileSha1: hashes.sha1,
- fileSha3: new Uint8Array(0),
- fileMd5: hashes.md5,
- field15: true,
- },
- },
- true,
- );
- const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d6_0', encodeOidbEnv(env));
- const resp = decodeOidbEnv(respBytes).body;
-
- const upload = resp?.upload;
- if (!upload) throw new Error('group file upload response missing');
- ensureRetCodeZero('group file upload', upload.retCode, upload.retMsg, upload.clientWording);
-
- const fileId = typeof upload.fileId === 'string' && upload.fileId ? upload.fileId : null;
- if (!fileId) throw new Error('group file upload response missing file_id');
-
- // Remember the upload so a later `send_group_msg` carrying just the
- // file_id can route via `sendGroupFileMessage` without forcing the
- // OneBot caller to thread fileName/size/md5 separately. For groups
- // the wire publish (OIDB 0x6d9_4) only needs the file_id itself, so
- // this is mainly for log-line correctness; the c2c counterpart in
- // `uploadPrivateFile` is where the cache is actually load-bearing.
- bridge.rememberUploadedFile({
- fileId,
- scope: 'group',
- groupId,
- fileName,
- fileSize: loaded.bytes.length,
- fileMd5: hashes.md5,
- fileSha1: hashes.sha1,
- rememberedAt: Date.now(),
- });
-
- if (!upload.boolFileExist && uploadFile) {
- const senderUin = toInt(bridge.identity.uin);
- if (senderUin <= 0) throw new Error('invalid self uin for group file upload');
-
- const uploadHost = (typeof upload.uploadIp === 'string' && upload.uploadIp)
- || (typeof upload.serverDns === 'string' && upload.serverDns)
- || '';
- const uploadPort = toInt(upload.uploadPort);
- if (!uploadHost || uploadPort <= 0) {
- throw new Error('group file upload host is invalid');
- }
-
- const ext = buildGroupFileUploadExt(
- senderUin,
- groupId,
- fileName,
- loaded.bytes.length,
- hashes.md5,
- fileId,
- upload.fileKey instanceof Uint8Array ? upload.fileKey : new Uint8Array(0),
- upload.checkKey instanceof Uint8Array ? upload.checkKey : new Uint8Array(0),
- uploadHost,
- uploadPort,
- );
-
- const session = await fetchHighwaySession(bridge);
- await uploadHighwayHttp(bridge, session, 71, loaded.bytes, hashes.md5, ext);
- }
-
- // Stage 3: file is on the server, now publish it as a chat message.
- //
- // Without this, OIDB 0x6D6_0 + highway PUT only stages the bytes —
- // the chat shows nothing. The publish step goes via a dedicated OIDB
- // call (0x6D9_4), NOT via `MessageSvc.PbSendMsg` with a transElem(24)
- // payload — the QQ-NT server rejects that with `result=79`. Mirrors
- // Lagrange.Core V2's `GroupSendFileService.cs`. Suppressed when the
- // caller opts out via `uploadFile=false` (treat that as "I only
- // wanted the slot allocated, hold the chat post"). Routes through
- // the public bridge method (rather than the local `sendGroupFileMessage`)
- // so tests can mock at the bridge boundary, matching the pattern
- // `uploadPrivateFile` uses with `bridge.sendC2cFileMessage`.
- if (uploadFile) {
- try {
- await bridge.sendGroupFileMessage(groupId, fileId);
- } catch (err) {
- // The bytes are already on the server and the fileId is valid —
- // fail loud but don't lose the upload result the action handler
- // committed to returning. Callers can still resolve the file by
- // id; they'll just have to re-publish it themselves.
- log.warn('group file uploaded (fileId=%s) but chat post failed: %s',
- fileId, err instanceof Error ? err.message : String(err));
- }
- }
-
- return { fileId };
-}
-
-export async function uploadPrivateFile(
- bridge: Bridge,
- userId: number,
- source: string,
- name = '',
- uploadFile = true,
-): Promise {
- // Group/private files may legitimately be up to 4 GiB on QQ's wire,
- // so override the default 1 GiB cap with the protocol ceiling.
- const loaded = await loadBinarySource(source, 'file', FILE_UPLOAD_MAX_BYTES);
- if (!loaded.bytes.length) throw new Error('private file is empty');
-
- const targetUid = await bridge.resolveUserUid(userId);
- let selfUid = bridge.identity.selfUid;
- if (!selfUid) {
- const selfUin = toInt(bridge.identity.uin);
- if (selfUin > 0) {
- selfUid = await bridge.resolveUserUid(selfUin);
- }
- }
- if (!selfUid) throw new Error('self uid is unavailable');
-
- const senderUin = toInt(bridge.identity.uin);
- if (senderUin <= 0) throw new Error('invalid self uin for private file upload');
-
- const fileName = normalizeUploadFileName(name, loaded.fileName);
- const hashes = computeHashes(loaded.bytes);
-
- const env = makeOidbEnvelope(0xE37, 1700, {
- command: 1700,
- seq: 0,
- upload: {
- senderUid: selfUid,
- receiverUid: targetUid,
- fileSize: loaded.bytes.length,
- fileName,
- md510MCheckSum: md5First10MB(loaded.bytes),
- sha1CheckSum: hashes.sha1,
- localPath: '/',
- md5CheckSum: hashes.md5,
- sha3CheckSum: new Uint8Array(0),
- },
- businessId: 3,
- clientType: 1,
- flagSupportMediaPlatform: 1,
- });
- const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xe37_1700', encodeOidbEnv(env));
- const resp = decodeOidbEnv(respBytes).body;
-
- const upload = resp?.upload;
- if (!upload) throw new Error('private file upload response missing');
- ensureRetCodeZero('private file upload', upload.retCode, upload.retMsg, undefined);
-
- const fileId = typeof upload.uuid === 'string' && upload.uuid ? upload.uuid : null;
- const fileHash = typeof upload.fileAddon === 'string' && upload.fileAddon ? upload.fileAddon : null;
- if (!fileId) throw new Error('private file upload response missing file_id');
-
- // Cache the metadata so a later `send_private_msg` carrying just
- // `{type:'file', file_id}` can resurrect the full c2c-file packet
- // (NotOnlineFile { fileSize, fileMd5, fileName, fileHash }). Without
- // this the recipient sees a 0-byte file because the OneBot send path
- // has no way to recover those fields from the file_id alone.
- bridge.rememberUploadedFile({
- fileId,
- scope: 'private',
- userId,
- fileName,
- fileSize: loaded.bytes.length,
- fileMd5: hashes.md5,
- fileSha1: hashes.sha1,
- fileHash: fileHash ?? '',
- rememberedAt: Date.now(),
- });
-
- if (!upload.boolFileExist && uploadFile) {
- // Host selection.
- //
- // Current QQ-NT server rollout has stopped populating the legacy
- // `uploadIp` (field 60) entirely. The host now arrives as the first
- // entry of `rtpMediaPlatformUploadAddress` (field 210, repeated
- // IPv4 message) — same place acidify reads it from since their
- // 2026-04 protobuf refactor. Each IPv4 has paired `inIP`/`inPort`
- // (LAN, same DC as the OIDB endpoint) and `outIP`/`outPort` (WAN);
- // acidify uses `inIP`/`inPort` exclusively and so do we, because
- // that's the address the highway PUT actually needs to reach.
- //
- // The 32-bit IPs are little-endian-packed (byte0 = first octet)
- // per acidify's `Int.toIpString()`. Cross-checked the byte order
- // by inspecting their highway flow — there's no separate htonl
- // step, so the integer is already in network-octet-first order.
- //
- // Older server versions still populate the legacy string fields
- // (uploadIp / uploadDomain / uploadIpList[0] / uploadHttpsDomain /
- // uploadDns), so we fall through to those after rtpMediaPlatform.
- // Pair an HTTPS-flavored host with `uploadHttpsPort` if that's
- // what we picked.
- const rtpFirst = (Array.isArray(upload.rtpMediaPlatformUploadAddress)
- && upload.rtpMediaPlatformUploadAddress[0])
- ? upload.rtpMediaPlatformUploadAddress[0] : null;
- const rtpInIP = rtpFirst && typeof rtpFirst.inIP === 'number' && rtpFirst.inIP !== 0
- ? int32ToIpv4Dotted(rtpFirst.inIP) : '';
- const rtpInPort = rtpFirst && typeof rtpFirst.inPort === 'number'
- ? rtpFirst.inPort : 0;
- const ipListFirst = (Array.isArray(upload.uploadIpList) && upload.uploadIpList[0])
- ? upload.uploadIpList[0] : '';
- const uploadHost = (rtpInIP)
- || (typeof upload.uploadIp === 'string' && upload.uploadIp)
- || (typeof upload.uploadDomain === 'string' && upload.uploadDomain)
- || (ipListFirst)
- || (typeof upload.uploadHttpsDomain === 'string' && upload.uploadHttpsDomain)
- || (typeof upload.uploadDns === 'string' && upload.uploadDns)
- || '';
- const httpsHostUsed = !rtpInIP && !upload.uploadIp && !upload.uploadDomain && !ipListFirst
- && typeof upload.uploadHttpsDomain === 'string' && !!upload.uploadHttpsDomain;
- const uploadPort = rtpInIP && rtpInPort > 0
- ? rtpInPort
- : httpsHostUsed && toInt(upload.uploadHttpsPort) > 0
- ? toInt(upload.uploadHttpsPort)
- : toInt(upload.uploadPort);
- if (!uploadHost || uploadPort <= 0) {
- // Surface every host-bearing field we know about so a user
- // hitting this can show us exactly which slot the server filled
- // (or whether it returned nothing at all — which would point at
- // a request mismatch rather than a missing decoder).
- const rtpDump = Array.isArray(upload.rtpMediaPlatformUploadAddress)
- ? JSON.stringify(upload.rtpMediaPlatformUploadAddress.map((e) => ({
- outIP: e.outIP, outPort: e.outPort, inIP: e.inIP, inPort: e.inPort,
- iPType: e.iPType,
- })))
- : '[]';
- log.warn(
- 'private file upload host missing — rtp=%s ip=%s domain=%s ipList=%s httpsDomain=%s dns=%s lanip=%s port=%s httpsPort=%s',
- rtpDump,
- upload.uploadIp ?? '', upload.uploadDomain ?? '',
- JSON.stringify(upload.uploadIpList ?? []),
- upload.uploadHttpsDomain ?? '', upload.uploadDns ?? '',
- upload.uploadLanip ?? '', upload.uploadPort ?? 0,
- upload.uploadHttpsPort ?? 0,
- );
- throw new Error('private file upload host is invalid');
- }
-
- const ext = buildPrivateFileUploadExt(
- senderUin,
- fileName,
- loaded.bytes.length,
- hashes.md5,
- hashes.sha1,
- fileId,
- upload.mediaPlatformUploadKey instanceof Uint8Array
- ? upload.mediaPlatformUploadKey
- : (upload.uploadKey instanceof Uint8Array ? upload.uploadKey : new Uint8Array(0)),
- uploadHost,
- uploadPort,
- );
-
- const session = await fetchHighwaySession(bridge);
- await uploadHighwayHttp(bridge, session, 95, loaded.bytes, hashes.md5, ext);
- }
-
- // Stage 3: publish the file as a c2c chat message. C2C files use
- // `RichText.notOnlineFile` (parallel to `elems`), so we go through
- // the dedicated `sendC2cFileMessage` instead of `sendPrivateMessage`
- // which only knows about elems[]. NapCat does the same atomic
- // upload+send dance — without it the file sits on the server and
- // the recipient sees nothing.
- if (uploadFile) {
- try {
- await bridge.sendC2cFileMessage(userId, targetUid, {
- fileId,
- fileName,
- fileSize: loaded.bytes.length,
- fileMd5: hashes.md5,
- fileHash: fileHash ?? '',
- });
- } catch (err) {
- log.warn('private file uploaded (fileId=%s) but chat post failed: %s',
- fileId, err instanceof Error ? err.message : String(err));
- }
- }
-
- return { fileId, fileHash };
-}
-
-// ─────────────── list ───────────────
-
-export async function fetchGroupFiles(bridge: Bridge, groupId: number, folderId = '/'): Promise {
- const targetDirectory = normalizeDirectory(folderId);
- const files: GroupFileInfo[] = [];
- const folders: GroupFolderInfo[] = [];
-
- const pageSize = 20;
- let startIndex = 0;
- for (let page = 0; page < 200; page++) {
- const env = makeOidbEnvelope(
- 0x6D8, 1,
- {
- list: {
- groupUin: groupId,
- appId: 7,
- targetDirectory,
- fileCount: pageSize,
- sortBy: 1,
- startIndex,
- field17: 2,
- field18: 0,
- },
- },
- true,
- );
- const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d8_1', encodeOidbEnv(env));
- const resp = decodeOidbEnv(respBytes).body;
-
- const list = resp?.list;
- if (!list) break;
- ensureRetCodeZero('group file list', list.retCode, list.retMsg, list.clientWording);
-
- for (const item of list.items ?? []) {
- const type = toInt(item?.type);
- if (type === 1 && item?.fileInfo) {
- const file = item.fileInfo;
- const uploader = toInt(file.uploaderUin);
- const cached = bridge.identity.findGroupMember(groupId, uploader);
- files.push({
- fileId: typeof file.fileId === 'string' ? file.fileId : '',
- fileName: typeof file.fileName === 'string' ? file.fileName : '',
- busId: toInt(file.busId),
- fileSize: toInt(file.fileSize),
- uploadTime: toInt(file.uploadedTime),
- deadTime: toInt(file.expireTime),
- modifyTime: toInt(file.modifiedTime),
- downloadTimes: toInt(file.downloadedTimes),
- uploader,
- uploaderName: (typeof file.uploaderName === 'string' && file.uploaderName)
- || cached?.card
- || cached?.nickname
- || '',
- });
- } else if (type === 2 && item?.folderInfo) {
- const folder = item.folderInfo;
- const creator = toInt(folder.creatorUin);
- const cached = bridge.identity.findGroupMember(groupId, creator);
- folders.push({
- folderId: typeof folder.folderId === 'string' ? folder.folderId : '',
- folderName: typeof folder.folderName === 'string' ? folder.folderName : '',
- createTime: toInt(folder.createTime),
- creator,
- creatorName: (typeof folder.creatorName === 'string' && folder.creatorName)
- || cached?.card
- || cached?.nickname
- || '',
- totalFileCount: toInt(folder.totalFileCount),
- });
- }
- }
-
- if (list.isEnd) break;
- startIndex += pageSize;
- }
-
- return { files, folders };
-}
-
-// ─────────────── url fetch (group / private files) ───────────────
-
-export async function fetchGroupFileUrl(bridge: Bridge, groupId: number, fileId: string, busId = 102): Promise {
- const env = makeOidbEnvelope(
- 0x6D6, 2,
- {
- download: {
- groupUin: groupId,
- appId: 7,
- busId,
- fileId,
- },
- },
- true,
- );
- const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d6_2', encodeOidbEnv(env));
- const resp = decodeOidbEnv(respBytes).body;
-
- const download = resp?.download;
- if (!download) throw new Error('group file url response missing');
- ensureRetCodeZero('group file url', download.retCode, download.retMsg, download.clientWording);
-
- const dns = (typeof download.downloadDns === 'string' && download.downloadDns)
- || (typeof download.downloadIp === 'string' && download.downloadIp)
- || '';
- const hexUrl = bytesToHexUpper(download.downloadUrl);
- if (!dns || !hexUrl) {
- throw new Error('group file url response invalid');
- }
-
- // Keep the same behavior as Lagrange: append file_id after ?fname=
- return `https://${dns}/ftn_handler/${hexUrl}/?fname=${fileId}`;
-}
-
-export async function fetchPrivateFileUrl(bridge: Bridge, userId: number, fileId: string, fileHash: string): Promise {
- const uid = await bridge.resolveUserUid(userId);
- const env = makeOidbEnvelope(0xE37, 1200, {
- subCommand: 1200,
- field2: 1,
- body: {
- receiverUid: uid,
- fileUuid: fileId,
- type: 2,
- fileHash,
- t2: 0,
- },
- field101: 3,
- field102: 103,
- field200: 1,
- field99999: new Uint8Array([0xC0, 0x85, 0x2C, 0x01]),
- });
- const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xe37_1200', encodeOidbEnv(env));
- const resp = decodeOidbEnv(respBytes).body;
-
- const result = resp?.body?.result;
- const server = typeof result?.server === 'string' ? result.server : '';
- const port = toInt(result?.port);
- const url = typeof result?.url === 'string' ? result.url : '';
- if (!server || !port || !url) {
- throw new Error('private file url response invalid');
- }
- return `http://${server}:${port}${url}&isthumb=0`;
-}
-
-// ─────────────── delete / move ───────────────
-
-export async function deleteGroupFile(bridge: Bridge, groupId: number, fileId: string): Promise {
- const env = makeOidbEnvelope(
- 0x6D6, 3,
- {
- delete: {
- groupUin: groupId,
- busId: 102,
- fileId,
- },
- },
- true,
- );
- const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d6_3', encodeOidbEnv(env));
- const resp = decodeOidbEnv(respBytes).body;
-
- const result = resp?.delete;
- if (!result) throw new Error('group file delete response missing');
- ensureRetCodeZero('group file delete', result.retCode, result.retMsg, result.clientWording);
-}
-
-export async function moveGroupFile(
- bridge: Bridge,
- groupId: number,
- fileId: string,
- parentDirectory: string,
- targetDirectory: string,
-): Promise {
- const env = makeOidbEnvelope(
- 0x6D6, 5,
- {
- move: {
- groupUin: groupId,
- appId: 7,
- busId: 102,
- fileId,
- parentDirectory,
- targetDirectory,
- },
- },
- true,
- );
- const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d6_5', encodeOidbEnv(env));
- const resp = decodeOidbEnv(respBytes).body;
-
- const result = resp?.move;
- if (!result) throw new Error('group file move response missing');
- ensureRetCodeZero('group file move', result.retCode, result.retMsg, result.clientWording);
-}
-
-// ─────────────── folders ───────────────
-
-export async function createGroupFileFolder(bridge: Bridge, groupId: number, name: string, parentId = '/'): Promise {
- const env = makeOidbEnvelope(
- 0x6D7, 0,
- {
- create: {
- groupUin: groupId,
- rootDirectory: normalizeDirectory(parentId),
- folderName: name,
- },
- },
- true,
- );
- const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d7_0', encodeOidbEnv(env));
- const resp = decodeOidbEnv(respBytes).body;
-
- const result = resp?.create;
- if (!result) throw new Error('group folder create response missing');
- ensureRetCodeZero('group folder create', result.retcode, result.retMsg, result.clientWording);
-}
-
-export async function deleteGroupFileFolder(bridge: Bridge, groupId: number, folderId: string): Promise {
- const env = makeOidbEnvelope(
- 0x6D7, 1,
- {
- delete: {
- groupUin: groupId,
- folderId,
- },
- },
- true,
- );
- const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d7_1', encodeOidbEnv(env));
- const resp = decodeOidbEnv(respBytes).body;
-
- const result = resp?.delete;
- if (!result) throw new Error('group folder delete response missing');
- ensureRetCodeZero('group folder delete', result.retcode, result.retMsg, result.clientWording);
-}
-
-export async function renameGroupFileFolder(bridge: Bridge, groupId: number, folderId: string, newFolderName: string): Promise {
- const env = makeOidbEnvelope(
- 0x6D7, 2,
- {
- rename: {
- groupUin: groupId,
- folderId,
- newFolderName,
- },
- },
- true,
- );
- const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d7_2', encodeOidbEnv(env));
- const resp = decodeOidbEnv(respBytes).body;
-
- const result = resp?.rename;
- if (!result) throw new Error('group folder rename response missing');
- ensureRetCodeZero('group folder rename', result.retcode, result.retMsg, result.clientWording);
-}
-
-// ─────────────── rich-media URL by node ───────────────
-
-export async function fetchGroupPttUrlByNode(bridge: Bridge, groupId: number, node: MediaIndexNode): Promise {
- const normalizedNode = normalizeMediaNode(node);
- return fetchNtv2DownloadUrl(bridge, 'OidbSvcTrpcTcp.0x126e_200', 0x126E, {
- reqHead: {
- common: { requestId: 4, command: 200 },
- scene: {
- requestType: 1,
- businessType: 3,
- sceneType: 2,
- group: { groupUin: groupId },
- },
- client: { agentType: 2 },
- },
- download: {
- node: normalizedNode,
- download: { video: { busiType: 0, sceneType: 0 } },
- },
- });
-}
-
-export async function fetchPrivatePttUrlByNode(bridge: Bridge, node: MediaIndexNode): Promise {
- const selfUid = await resolveSelfUid(bridge);
- const normalizedNode = normalizeMediaNode(node);
- return fetchNtv2DownloadUrl(bridge, 'OidbSvcTrpcTcp.0x126d_200', 0x126D, {
- reqHead: {
- common: { requestId: 1, command: 200 },
- scene: {
- requestType: 1,
- businessType: 3,
- sceneType: 1,
- c2c: {
- accountType: 2,
- targetUid: selfUid,
- },
- },
- client: { agentType: 2 },
- },
- download: {
- node: normalizedNode,
- download: { video: { busiType: 0, sceneType: 0 } },
- },
- });
-}
-
-export async function fetchGroupVideoUrlByNode(bridge: Bridge, groupId: number, node: MediaIndexNode): Promise {
- const normalizedNode = normalizeMediaNode(node);
- return fetchNtv2DownloadUrl(bridge, 'OidbSvcTrpcTcp.0x11ea_200', 0x11EA, {
- reqHead: {
- common: { requestId: 1, command: 200 },
- scene: {
- requestType: 2,
- businessType: 2,
- sceneType: 2,
- group: { groupUin: groupId },
- },
- client: { agentType: 2 },
- },
- download: {
- node: normalizedNode,
- download: { video: { busiType: 0, sceneType: 0 } },
- },
- });
-}
-
-export async function fetchPrivateVideoUrlByNode(bridge: Bridge, node: MediaIndexNode): Promise {
- const selfUid = await resolveSelfUid(bridge);
- const normalizedNode = normalizeMediaNode(node);
- return fetchNtv2DownloadUrl(bridge, 'OidbSvcTrpcTcp.0x11e9_200', 0x11E9, {
- reqHead: {
- common: { requestId: 1, command: 200 },
- scene: {
- requestType: 2,
- businessType: 2,
- sceneType: 1,
- c2c: {
- accountType: 2,
- targetUid: selfUid,
- },
- },
- client: { agentType: 2 },
- },
- download: {
- node: normalizedNode,
- download: { video: { busiType: 0, sceneType: 0 } },
- },
- });
-}
diff --git a/packages/core/src/bridge/actions/group-message.ts b/packages/core/src/bridge/actions/group-message.ts
deleted file mode 100644
index 13da8dc2..00000000
--- a/packages/core/src/bridge/actions/group-message.ts
+++ /dev/null
@@ -1,101 +0,0 @@
-// 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 { protoEncode } from '../../protobuf/decode';
-import { runOidb, makeOidbEnvelope, encodeOidbEnv } from '../bridge-oidb';
-import {
- C2CRecallRequestSchema,
- GroupRecallRequestSchema,
- SsoReadedReportReqSchema,
-} from '../proto/oidb-action';
-import type { OidbEssence } from '../proto/proton/oidb-action';
-
-export async function recallGroupMessage(bridge: Bridge, groupId: number, sequence: number): Promise