Merge pull request #66 from SnowLuma/dev

chore: promote dev → main (5924346)
This commit is contained in:
snowluma-bot[bot] authored and GitHub committed 2026-05-24 10:02:15 +00:00
commit 54c4641a0e
297 files changed
+10996 -3510

No files matched your search

+29 -4
View File
@@ -1,9 +1,9 @@
import js from '@eslint/js';
import globals from 'globals';
import reactHooks from 'eslint-plugin-react-hooks';
import reactRefresh from 'eslint-plugin-react-refresh';
import tseslint from 'typescript-eslint';
import { defineConfig, globalIgnores } from 'eslint/config';
import globals from 'globals';
import tseslint from 'typescript-eslint';
const tsconfigRootDir = decodeURIComponent(new URL('.', import.meta.url).pathname).replace(/^\/(.:\/)/, '$1');
@@ -48,7 +48,7 @@ export default defineConfig([
rules: {
'indent': ['error', 2, { SwitchCase: 1 }],
'prefer-const': 'off',
'@typescript-eslint/no-explicit-any': 'off',
'@typescript-eslint/no-explicit-any': 'error',
'@typescript-eslint/no-empty-object-type': 'off',
'@typescript-eslint/no-this-alias': 'off',
'@typescript-eslint/no-unused-vars': [
@@ -61,6 +61,31 @@ export default defineConfig([
],
},
},
{
files: ['**/tests/**/*.{ts,tsx}', '**/*.test.{ts,tsx}'],
rules: {
'@typescript-eslint/no-explicit-any': 'off',
},
},
{
files: ['**/bench/**/*.{ts,tsx}', 'packages/proton/test/**/*.{ts,tsx}'],
rules: {
'@typescript-eslint/no-explicit-any': 'off',
},
},
{
// OIDB service layer is namespace-per-cmd by design — the
// structural-typing contract (namespace IS the OidbCallSpec) and
// the file:cmd 1:1 mapping are the whole point. Disable the
// module-syntax preference here only.
files: [
'packages/protocol/src/oidb-services/**/*.ts',
'packages/protocol/tests/oidb-services/**/*.ts',
],
rules: {
'@typescript-eslint/no-namespace': 'off',
},
},
{
files: ['packages/webui/src/**/*.{ts,tsx}', 'packages/ui/src/**/*.{ts,tsx}'],
extends: [reactHooks.configs.flat.recommended, reactRefresh.configs.vite],
@@ -77,4 +102,4 @@ export default defineConfig([
'react-hooks/set-state-in-effect': 'off',
},
},
]);
]);
+3 -1
View File
@@ -1,6 +1,6 @@
{
"name": "snowluma-monorepo",
"version": "1.9.1",
"version": "1.9.2",
"description": "SnowLuma monorepo workspace (pnpm)",
"private": true,
"type": "module",
@@ -23,6 +23,8 @@
},
"devDependencies": {
"@eslint/js": "^10.0.1",
"@vitest/coverage-istanbul": "4.1.4",
"@vitest/coverage-v8": "^4.1.4",
"cross-env": "^10.1.0",
"eslint": "^10.2.0",
"eslint-plugin-react-hooks": "^7.0.1",
+28 -99
View File
@@ -1,9 +1,9 @@
{
"name": "@snowluma/bridge",
"version": "1.9.1",
"version": "1.9.2",
"private": true,
"type": "module",
"description": "SnowLuma bridge — the protocol-layer between QQ wire bytes and typed events. Owns: identity service (uid↔uin cache with SQLite persistence), event bus, packet pipeline (incoming SSO packet → QQEventVariant), msg-push decoders, element-builder (MessageElement → wire elems[]), highway upload protocol (file/image/video/ptt), OIDB envelope helper, and the event/notice/request type vocabulary. Consumers (@snowluma/core, @snowluma/onebot) talk to this package through `BridgeContext` for runtime calls and the standalone classes (IdentityService, BridgeEventBus, IncomingPacketPipeline) for composition. Per-file subpath exports mirror the legacy `core/src/bridge/*` layout 1:1 so the previous `import { …} from '../bridge/<x>'` collapses to `import { … } from '@snowluma/bridge/<x>'`.",
"description": "SnowLuma bridge — QQ NT desktop client lifecycle: hook injection (via native addon), per-PID HookSession orchestration, pipe-watcher for process discovery, and the BridgeManagerSink interface that lets the hook layer call back into a UIN-keyed session router without depending on @snowluma/core. Consumed by the top-level app entry (which constructs the BridgeManager from @snowluma/core and injects it as the sink) and by the WebUI server (read-only HookProcessInfo views).",
"main": "./src/index.ts",
"types": "./src/index.ts",
"exports": {
@@ -11,116 +11,45 @@
"types": "./src/index.ts",
"default": "./src/index.ts"
},
"./events": {
"types": "./src/events.ts",
"default": "./src/events.ts"
"./hook-manager": {
"types": "./src/hook-manager.ts",
"default": "./src/hook-manager.ts"
},
"./event-bus": {
"types": "./src/event-bus.ts",
"default": "./src/event-bus.ts"
"./hook-session": {
"types": "./src/hook-session.ts",
"default": "./src/hook-session.ts"
},
"./identity-service": {
"types": "./src/identity-service.ts",
"default": "./src/identity-service.ts"
"./hook-packet-client": {
"types": "./src/hook-packet-client.ts",
"default": "./src/hook-packet-client.ts"
},
"./packet-pipeline": {
"types": "./src/packet-pipeline.ts",
"default": "./src/packet-pipeline.ts"
"./injector": {
"types": "./src/injector.ts",
"default": "./src/injector.ts"
},
"./element-builder": {
"types": "./src/element-builder.ts",
"default": "./src/element-builder.ts"
"./pipe-watcher": {
"types": "./src/pipe-watcher.ts",
"default": "./src/pipe-watcher.ts"
},
"./bridge-oidb": {
"types": "./src/bridge-oidb.ts",
"default": "./src/bridge-oidb.ts"
"./qq-hook-client": {
"types": "./src/qq-hook-client.ts",
"default": "./src/qq-hook-client.ts"
},
"./bridge-context": {
"types": "./src/bridge-context.ts",
"default": "./src/bridge-context.ts"
"./qq-port-probe": {
"types": "./src/qq-port-probe.ts",
"default": "./src/qq-port-probe.ts"
},
"./qq-info": {
"types": "./src/qq-info.ts",
"default": "./src/qq-info.ts"
},
"./format": {
"types": "./src/format.ts",
"default": "./src/format.ts"
},
"./msg-push": {
"types": "./src/msg-push/index.ts",
"default": "./src/msg-push/index.ts"
},
"./msg-push/registry": {
"types": "./src/msg-push/registry.ts",
"default": "./src/msg-push/registry.ts"
},
"./msg-push/context": {
"types": "./src/msg-push/context.ts",
"default": "./src/msg-push/context.ts"
},
"./msg-push/decoders/event-0x2dc": {
"types": "./src/msg-push/decoders/event-0x2dc.ts",
"default": "./src/msg-push/decoders/event-0x2dc.ts"
},
"./highway": {
"types": "./src/highway/highway-client.ts",
"default": "./src/highway/highway-client.ts"
},
"./highway/utils": {
"types": "./src/highway/utils.ts",
"default": "./src/highway/utils.ts"
},
"./highway/pipeline": {
"types": "./src/highway/pipeline.ts",
"default": "./src/highway/pipeline.ts"
},
"./highway/image-upload": {
"types": "./src/highway/image-upload.ts",
"default": "./src/highway/image-upload.ts"
},
"./highway/ptt-upload": {
"types": "./src/highway/ptt-upload.ts",
"default": "./src/highway/ptt-upload.ts"
},
"./highway/video-upload": {
"types": "./src/highway/video-upload.ts",
"default": "./src/highway/video-upload.ts"
},
"./highway/ffmpeg-addon": {
"types": "./src/highway/ffmpeg-addon.ts",
"default": "./src/highway/ffmpeg-addon.ts"
},
"./web/group-album": {
"types": "./src/web/group-album.ts",
"default": "./src/web/group-album.ts"
},
"./web/group-essence": {
"types": "./src/web/group-essence.ts",
"default": "./src/web/group-essence.ts"
},
"./web/group-honor": {
"types": "./src/web/group-honor.ts",
"default": "./src/web/group-honor.ts"
},
"./web/group-notice": {
"types": "./src/web/group-notice.ts",
"default": "./src/web/group-notice.ts"
},
"./web/request-util": {
"types": "./src/web/request-util.ts",
"default": "./src/web/request-util.ts"
"./types": {
"types": "./src/types.ts",
"default": "./src/types.ts"
}
},
"scripts": {
"bench": "vitest bench --run",
"test": "vitest run",
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@snowluma/common": "workspace:*",
"@snowluma/proto-defs": "workspace:*",
"@snowluma/proton": "workspace:*",
"@snowluma/sqlite": "workspace:*"
"@snowluma/common": "workspace:*"
},
"devDependencies": {
"@types/node": "^24.12.2",
@@ -1,25 +1,36 @@
import fs from 'fs';
import type { BridgeManager } from '../bridge/manager';
import type { PacketSink } from '@snowluma/common/protocol-types';
import { createLogger, type Logger } from '@snowluma/common/logger';
import type { PacketSender } from '@snowluma/common/packet-sender';
import type { PacketInfo, PacketSink } from '@snowluma/common/protocol-types';
import fs from 'fs';
import { HookSession, type HookSessionDeps } from './hook-session';
import {
injectHookProcess,
listHookProcesses,
unloadHookProcess,
type HookProcessBaseInfo,
} from './injector';
import { HookSession, type HookSessionDeps } from './hook-session';
import { PipeWatcher } from './pipe-watcher';
import { QqHookClient } from './qq-hook-client';
import type { HookProcessInfo } from './types';
import { probeQqLoginInfo, type QqPortLoginInfo } from './qq-port-probe';
import type { HookProcessInfo } from './types';
export type { HookProcessInfo, HookProcessStatus } from './types';
export type { HookProcessBaseInfo } from './injector';
export type { QqPortLoginInfo } from './qq-port-probe';
/**
* Sink that the hook layer calls back into when it observes a new login,
* a parsed packet, or a PID disconnect. The concrete implementation lives
* in @snowluma/core (`BridgeManager`), which is wired in by the top-level
* app entry. Declaring it here keeps @snowluma/bridge free of any
* dependency on @snowluma/core — the hook package is self-contained.
*/
export interface BridgeManagerSink {
onHookLogin(pid: number, uin: string, packetClient: PacketSender): void;
onPacket(pkt: PacketInfo): void;
onPidDisconnected(pid: number): void;
}
export type HookManagerDeps = {
bridgeManager: BridgeManager;
bridgeManager: BridgeManagerSink;
/** Sink for parsed packets from any live HookSession. Defaults to
* `bridgeManager.onPacket` — every packet flows straight into the
* per-UIN bridge dispatcher with no intermediate event emitter. */
@@ -57,7 +68,7 @@ export type HookManagerDeps = {
* real QQ.exe or a native addon.
*/
export class HookManager {
private readonly bridgeManager: BridgeManager;
private readonly bridgeManager: BridgeManagerSink;
private readonly onPacket: PacketSink;
private readonly injector: HookSessionDeps['injector'];
private readonly makeClient: HookSessionDeps['makeClient'];
@@ -216,7 +227,7 @@ export class HookManager {
if (this.disposed) return;
for (const session of this.sessions.values()) {
if ((session.status === 'connecting' || session.status === 'disconnected')
&& this.pipeWatcher.isPipeLive(session.pid)) {
&& this.pipeWatcher.isPipeLive(session.pid)) {
session.onPipeUp();
}
}
@@ -298,3 +309,6 @@ export function shouldAutoLoadPid(pid: number, log: Logger): boolean {
}
return true;
}
export type { HookProcessBaseInfo } from './injector';
export type { QqPortLoginInfo } from './qq-port-probe';
export type { HookProcessInfo, HookProcessStatus } from './types';
@@ -2,7 +2,7 @@ import type { PacketSender, SendPacketResult } from '@snowluma/common/packet-sen
import { QqHookClient, type QqHookSendReply } from './qq-hook-client';
export class HookPacketClient implements PacketSender {
constructor(private readonly client: QqHookClient) {}
constructor(private readonly client: QqHookClient) { }
async sendPacket(serviceCmd: string, body: Buffer, timeoutMs = 15000): Promise<SendPacketResult> {
if (!this.client.isLoggedIn) {
@@ -1,6 +1,6 @@
import { EventEmitter } from 'events';
import type { PacketSink } from '@snowluma/common/protocol-types';
import { createLogger, type Logger } from '@snowluma/common/logger';
import type { PacketSink } from '@snowluma/common/protocol-types';
import { EventEmitter } from 'events';
import { HookPacketClient } from './hook-packet-client';
import type { HookInjectResult } from './injector';
import type { QqHookClient, QqHookLoginState, QqHookPacket } from './qq-hook-client';
+5
View File
@@ -0,0 +1,5 @@
export {
HookManager, type BridgeManagerSink, type HookManagerDeps, type HookProcessBaseInfo, type HookProcessInfo,
type HookProcessStatus, type QqPortLoginInfo
} from './hook-manager';
@@ -55,12 +55,13 @@ function defaultProcessName(): string {
function nativeSearchDirs(): string[] {
// Several layouts must be supported:
// 1. Released zip (flattened dist/): __dirname=<extracted>/, native at <extracted>/native
// 2. Repo bundled build (dist/index.mjs): __dirname=<root>/dist, native at <root>/dist/native
// 3. Dev via tsx (packages/core/src/hook/injector.ts): __dirname=<root>/packages/core/src/hook
// 2. Dev via tsx (packages/bridge/src/injector.ts): __dirname=<root>/packages/bridge/src
// → walk up to <root>/packages and append runtime/native
// Same offset works for `packages/bridge/dist/index.mjs` after build.
// 3. cwd-based fallback when neither __dirname-relative path resolves.
return [
path.resolve(__dirname, 'native'),
path.resolve(__dirname, '..', '..', '..', 'runtime', 'native'),
path.resolve(__dirname, '..', '..', 'runtime', 'native'),
path.resolve(process.cwd(), 'dist', 'native'),
path.resolve(process.cwd(), 'packages', 'runtime', 'native'),
];
@@ -1,5 +1,5 @@
import { EventEmitter } from 'events';
import { createLogger, type Logger } from '@snowluma/common/logger';
import { EventEmitter } from 'events';
import type { HookProcessBaseInfo } from './injector';
const DEFAULT_INTERVAL_MS = 1500;
@@ -1,8 +1,8 @@
import { EventEmitter } from 'events';
import { promises as fs } from 'fs';
import net from 'net';
import os from 'os';
import path from 'path';
import { promises as fs } from 'fs';
import { EventEmitter } from 'events';
export const PIPE_MAGIC = 0x31504851;
export const PIPE_VERSION = 1;
@@ -235,7 +235,7 @@ function encodeFrame({
class FrameReader {
private buffer = Buffer.alloc(0);
constructor(private readonly onFrame: (frame: PipeFrame) => void) {}
constructor(private readonly onFrame: (frame: PipeFrame) => void) { }
push(chunk: Buffer): void {
this.buffer = Buffer.concat([this.buffer, chunk]);
@@ -513,7 +513,7 @@ export class QqHookClient extends EventEmitter {
const workerCount = Math.max(1, Math.min(concurrency | 0, items.length || 1));
const worker = async () => {
for (;;) {
for (; ;) {
const index = nextIndex;
nextIndex += 1;
if (index >= items.length) return;
@@ -624,7 +624,7 @@ export class QqHookClient extends EventEmitter {
else resolve();
});
}));
this.controlWriteChain = writePromise.catch(() => {});
this.controlWriteChain = writePromise.catch(() => { });
return writePromise;
}
@@ -1,5 +1,5 @@
import net from 'net';
import { exec } from 'child_process';
import net from 'net';
import { promisify } from 'util';
const execAsync = promisify(exec);
File renamed without changes.
@@ -3,11 +3,11 @@ import { EventEmitter } from 'events';
import fs from 'fs';
import os from 'os';
import path from 'path';
import { HookManager, shouldAutoLoadPid } from '../src/hook/hook-manager';
import { PipeWatcher } from '../src/hook/pipe-watcher';
import type { ManualMapHandle } from '../src/hook/injector';
import type { BridgeManager } from '../src/bridge/manager';
import type { QqHookClient } from '../src/hook/qq-hook-client';
import { HookManager, shouldAutoLoadPid } from '../src/hook-manager';
import { PipeWatcher } from '../src/pipe-watcher';
import type { ManualMapHandle } from '../src/injector';
import type { BridgeManagerSink } from '../src/hook-manager';
import type { QqHookClient } from '../src/qq-hook-client';
import { createLogger } from '@snowluma/common/logger';
const DUMMY_HANDLE: ManualMapHandle = { base: 0n, entry: 0n, exceptionTable: 0n, size: 0 };
@@ -41,7 +41,7 @@ function makeManager(opts: {
onPacket: vi.fn(),
onHookLogin: vi.fn(),
onPidDisconnected: vi.fn(),
} as unknown as BridgeManager;
} as unknown as BridgeManagerSink;
const manager = new HookManager({
bridgeManager,
pipeWatcher,
@@ -6,11 +6,11 @@
import { describe, it, expect, vi } from 'vitest';
import { EventEmitter } from 'events';
import { HookManager } from '../src/hook/hook-manager';
import { PipeWatcher } from '../src/hook/pipe-watcher';
import type { ManualMapHandle } from '../src/hook/injector';
import type { BridgeManager } from '../src/bridge/manager';
import type { QqHookClient } from '../src/hook/qq-hook-client';
import { HookManager } from '../src/hook-manager';
import { PipeWatcher } from '../src/pipe-watcher';
import type { ManualMapHandle } from '../src/injector';
import type { BridgeManagerSink } from '../src/hook-manager';
import type { QqHookClient } from '../src/qq-hook-client';
const DUMMY_HANDLE: ManualMapHandle = { base: 0n, entry: 0n, exceptionTable: 0n, size: 0 };
const flush = () => new Promise<void>(r => setImmediate(r));
@@ -45,7 +45,7 @@ describe('HookManager — Docker reconnect-without-login leak guard', () => {
onPacket: vi.fn(),
onHookLogin: vi.fn(),
onPidDisconnected: vi.fn(),
} as unknown as BridgeManager;
} as unknown as BridgeManagerSink;
const manager = new HookManager({
bridgeManager,
@@ -17,9 +17,9 @@
import { describe, it, expect, vi } from 'vitest';
import { EventEmitter } from 'events';
import { HookSession } from '../src/hook/hook-session';
import type { ManualMapHandle } from '../src/hook/injector';
import type { QqHookClient } from '../src/hook/qq-hook-client';
import { HookSession } from '../src/hook-session';
import type { ManualMapHandle } from '../src/injector';
import type { QqHookClient } from '../src/qq-hook-client';
const DUMMY_HANDLE: ManualMapHandle = { base: 0n, entry: 0n, exceptionTable: 0n, size: 0 };
@@ -1,8 +1,8 @@
import { describe, it, expect, vi } from 'vitest';
import { EventEmitter } from 'events';
import { HookSession } from '../src/hook/hook-session';
import type { ManualMapHandle } from '../src/hook/injector';
import type { QqHookClient, QqHookPacket } from '../src/hook/qq-hook-client';
import { HookSession } from '../src/hook-session';
import type { ManualMapHandle } from '../src/injector';
import type { QqHookClient, QqHookPacket } from '../src/qq-hook-client';
import type { PacketSink } from '@snowluma/common/protocol-types';
const DUMMY_HANDLE: ManualMapHandle = { base: 0n, entry: 0n, exceptionTable: 0n, size: 0 };
@@ -1,6 +1,6 @@
import { describe, it, expect } from 'vitest';
import { PipeWatcher } from '../src/hook/pipe-watcher';
import type { HookProcessBaseInfo } from '../src/hook/injector';
import { PipeWatcher } from '../src/pipe-watcher';
import type { HookProcessBaseInfo } from '../src/injector';
function setupWatcher(initial: { processes: HookProcessBaseInfo[]; live: Set<number> }) {
let processes = initial.processes;
@@ -2,7 +2,7 @@ import { mkdtemp, rm, writeFile } from 'fs/promises';
import os from 'os';
import path from 'path';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { listLiveLinuxPipePids } from '../src/hook/qq-hook-client';
import { listLiveLinuxPipePids } from '../src/qq-hook-client';
let tmpDir: string | null = null;
+1 -14
View File
@@ -1,21 +1,8 @@
// 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<T>` / `protobuf_decode<T>`
// 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'],
},
include: ['tests/**/*.test.ts'],
environment: 'node',
},
});
+2 -2
View File
@@ -1,9 +1,9 @@
{
"name": "@snowluma/common",
"version": "1.9.1",
"version": "1.9.2",
"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).",
"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/protocol, @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": {
-10
View File
@@ -1,13 +1,3 @@
// 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 {
+2 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@snowluma/core",
"version": "1.9.1",
"version": "1.9.2",
"description": "SnowLuma core - NTQQ packet sniffer with Node.js native addon",
"private": true,
"type": "module",
@@ -43,6 +43,7 @@
"@snowluma/bridge": "workspace:*",
"@snowluma/common": "workspace:*",
"@snowluma/onebot": "workspace:*",
"@snowluma/protocol": "workspace:*",
"@snowluma/proto-defs": "workspace:*",
"@snowluma/proton": "workspace:*",
"@snowluma/sqlite": "workspace:*",
+80 -253
View File
@@ -1,51 +1,35 @@
// ContactsApi — friend / group / member roster + user-profile +
// group-request-list + download-rkey OIDB calls.
//
// All implementations inlined from the previous `bridge-contacts.ts`
// (which gets removed alongside the rest of the actions/* facade
// shim in commit 13). The single non-trivial piece carried over is
// the per-group inflight + TTL cache for `fetchGroupMemberList`:
// without it a busy OneBot client (e.g. MaiBot calling
// `get_group_member_info` once per inbound message) would trigger
// one OIDB 0xfe7_3 per chat message, sustained >1k/h, which trips
// Tencent risk-control and gets the account banned for 7 days.
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type {
OidbBase,
OidbSvcTrpcTcp0x10C0Response,
OidbSvcTrpcTcp0xFD4_1Response,
OidbSvcTrpcTcp0xFE5_2Response,
OidbSvcTrpcTcp0xFE7_3Response,
} from '@snowluma/proto-defs/oidb';
import type {
AvatarInfo,
OidbFriendListRequest,
OidbGroupListRequest,
OidbGroupMemberListRequest,
OidbGroupRequestList,
OidbUserInfoRequest,
OidbUserInfoResponse,
} from '@snowluma/proto-defs/oidb-actions/base';
import type {
NTV2RichMediaReq,
NTV2RichMediaResp,
} from '@snowluma/proto-defs/oidb-actions/media';
import type { BridgeContext } from '../bridge-context';
import type { DownloadRKeyInfo } from '../bridge';
import { makeOidbEnvelope, runOidb } from '@snowluma/bridge/bridge-oidb';
import type { Bridge } from '../bridge';
import { FetchDownloadRkeys } from '@snowluma/protocol/oidb-services/contacts/fetch-download-rkeys';
import { FetchFriendListPage } from '@snowluma/protocol/oidb-services/contacts/fetch-friend-list-page';
import { FetchGroupList } from '@snowluma/protocol/oidb-services/contacts/fetch-group-list';
import { FetchGroupMemberListPage } from '@snowluma/protocol/oidb-services/contacts/fetch-group-member-list-page';
import { FetchGroupRequests } from '@snowluma/protocol/oidb-services/contacts/fetch-group-requests';
import { FetchUserProfile } from '@snowluma/protocol/oidb-services/contacts/fetch-user-profile';
import { FetchUserProfileByUid } from '@snowluma/protocol/oidb-services/contacts/fetch-user-profile-by-uid';
import type {
FriendInfo,
GroupMemberInfo,
GroupRequestInfo,
QQGroupInfo,
UserProfileInfo,
} from '@snowluma/bridge/qq-info';
} from '@snowluma/protocol/qq-info';
import type { DownloadRKeyInfo } from '../bridge';
import type { BridgeContext } from '../bridge-context';
// ─── Helpers (previously in bridge-contacts.ts) ───────────────────
export function buildFriendProperties(raw: any): Map<number, string> {
type FriendPropertySource = {
additional?: Array<{
type?: number;
layer1?: {
properties?: Array<{
code?: number;
value?: string;
}>;
};
}>;
};
export function buildFriendProperties(raw: FriendPropertySource): Map<number, string> {
const props = new Map<number, string>();
for (const additional of raw.additional ?? []) {
if ((additional.type ?? 0) !== 1 || !additional.layer1) continue;
@@ -64,68 +48,38 @@ export function permissionToRole(permission: number): string {
}
}
// `runOidb` and the proto-defs helpers take `Bridge` (deep dependency
// inside the highway / sendRawPacket plumbing). At runtime `ctx` IS
// the Bridge that constructed this Api, so narrowing back via
// `ctx as Bridge` is safe — see the same pattern in `MessageApi`
// where buildSendElems also expects a Bridge.
function asBridge(ctx: BridgeContext): Bridge {
return ctx as unknown as Bridge;
}
const MEMBER_LIST_TTL_MS = 60_000;
export class ContactsApi {
/**
* Per-group inflight + last-fetch cache for `fetchGroupMemberList`.
* Keyed by groupId, lives for the lifetime of the Bridge (so the
* cache resets per account, as you'd expect for multi-account
* runtimes — `BridgeManager` builds one Bridge per uin and each
* gets its own ContactsApi).
* Keyed by groupId, lives for the lifetime of the Bridge.
*
* Without this, a busy OneBot client (e.g. MaiBot calling
* `get_group_member_info` once per inbound message) triggers one
* OIDB 0xfe7_3 per chat message — sustained >1k/h, which trips
* Tencent risk-control and gets the account banned for 7 days.
*/
private memberListInflight = new Map<number, Promise<GroupMemberInfo[]>>();
private memberListLastFetch = new Map<number, { at: number; data: GroupMemberInfo[] }>();
constructor(private readonly ctx: BridgeContext) {}
constructor(private readonly ctx: BridgeContext) { }
async fetchFriendList(): Promise<FriendInfo[]> {
const bridge = asBridge(this.ctx);
const friends: FriendInfo[] = [];
let nextUin: number | null = null;
do {
const body: any = {
friendCount: 300,
field4: 0,
field6: 1,
field7: 0x7FFFFFFF,
body: [
{ type: 1, number: { numbers: [103, 102, 20002, 27394] } },
{ type: 4, number: { numbers: [100, 101, 102] } },
],
field10002: [13578, 13579, 13573, 13572, 13568],
field10003: 4051,
};
if (nextUin !== null) {
body.nextUin = { uin: nextUin };
const resp = await FetchFriendListPage.invoke(this.ctx, { nextUin });
for (const raw of resp.friends ?? []) {
const props = buildFriendProperties(raw);
friends.push({
uin: raw.uin ?? 0,
uid: raw.uid ?? '',
nickname: props.get(20002) ?? String(raw.uin ?? 0),
remark: props.get(103) ?? '',
});
}
const env = makeOidbEnvelope<OidbFriendListRequest>(0xFD4, 1, body);
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xfd4_1', protobuf_encode<OidbBase<OidbFriendListRequest>>(env));
const resp = protobuf_decode<OidbBase<OidbSvcTrpcTcp0xFD4_1Response>>(respBytes).body;
if (resp?.friends) {
for (const raw of resp.friends) {
const props = buildFriendProperties(raw);
friends.push({
uin: raw.uin ?? 0,
uid: raw.uid ?? '',
nickname: props.get(20002) ?? String(raw.uin ?? 0),
remark: props.get(103) ?? '',
});
}
}
nextUin = resp?.next?.uin ?? null;
nextUin = resp.next?.uin ?? null;
if (nextUin === 0) nextUin = null;
} while (nextUin !== null);
@@ -134,50 +88,17 @@ export class ContactsApi {
}
async fetchGroupList(): Promise<QQGroupInfo[]> {
const bridge = asBridge(this.ctx);
// The config flags ask QQ which per-group fields to include in
// the response. Asking for everything looks innocent on small
// accounts but on ~200+ groups it makes the QQ NT process write
// a payload large enough to blow the named-pipe write buffer —
// we then read EPIPE and the whole session dies. See issue #42.
// Keep `config1.*` mostly on but turn off the costly groups of
// bools that never map back to a decoded field.
const allTrue = true;
const body = {
config: {
config1: {
groupOwner: allTrue, field2: allTrue, memberMax: allTrue, memberCount: allTrue,
groupName: allTrue, field8: allTrue, field9: allTrue, field10: allTrue,
field11: allTrue, field12: allTrue, field13: allTrue, field14: allTrue,
field15: allTrue, field16: allTrue, field17: allTrue, field18: allTrue,
question: allTrue, field20: allTrue, field22: allTrue, field23: allTrue,
field24: allTrue, field25: allTrue, field26: allTrue, field27: allTrue,
field28: allTrue, field29: allTrue, field30: allTrue, field31: allTrue,
field32: allTrue, field5001: allTrue, field5002: false, field5003: false,
},
config2: {
field1: false, field2: false, field3: false, field4: false,
field5: false, field6: false, field7: false, field8: false,
},
config3: { field5: allTrue, field6: allTrue },
},
};
const env = makeOidbEnvelope<OidbGroupListRequest>(0xFE5, 2, body, true);
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xfe5_2', protobuf_encode<OidbBase<OidbGroupListRequest>>(env));
const resp = protobuf_decode<OidbBase<OidbSvcTrpcTcp0xFE5_2Response>>(respBytes).body;
const resp = await FetchGroupList.invoke(this.ctx);
const groups: QQGroupInfo[] = [];
if (resp?.groups) {
for (const raw of resp.groups) {
groups.push({
groupId: raw.groupUin ?? 0,
groupName: raw.info?.groupName ?? '',
remark: raw.customInfo?.remark ?? '',
memberCount: raw.info?.memberCount ?? 0,
memberMax: raw.info?.memberMax ?? 0,
members: new Map(),
});
}
for (const raw of resp.groups ?? []) {
groups.push({
groupId: raw.groupUin ?? 0,
groupName: raw.info?.groupName ?? '',
remark: raw.customInfo?.remark ?? '',
memberCount: raw.info?.memberCount ?? 0,
memberMax: raw.info?.memberMax ?? 0,
members: new Map(),
});
}
this.ctx.identity.rememberGroups(groups);
return groups;
@@ -187,9 +108,6 @@ export class ContactsApi {
groupId: number,
options: { force?: boolean } = {},
): Promise<GroupMemberInfo[]> {
// Coalesce in-flight calls + serve a 60s-cached result. Without
// this, a busy OneBot client gets the bot 7-day banned within
// hours via Tencent risk-control.
const now = Date.now();
const last = this.memberListLastFetch.get(groupId);
if (!options.force && last && now - last.at < MEMBER_LIST_TTL_MS) {
@@ -211,45 +129,25 @@ export class ContactsApi {
}
private async fetchGroupMemberListUncached(groupId: number): Promise<GroupMemberInfo[]> {
const bridge = asBridge(this.ctx);
const members: GroupMemberInfo[] = [];
let token = '';
do {
const body: any = {
groupUin: groupId,
field2: 5,
field3: 2,
body: {
memberName: true, memberCard: true, level: true, field13: true,
field16: true, specialTitle: true, field18: true, field20: true,
field21: true, joinTimestamp: true, lastMsgTimestamp: true,
shutUpTimestamp: true, field103: true, field104: true, field105: true,
field106: true, permission: true, field200: true, field201: true,
},
};
if (token) body.token = token;
const env = makeOidbEnvelope<OidbGroupMemberListRequest>(0xFE7, 3, body);
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xfe7_3', protobuf_encode<OidbBase<OidbGroupMemberListRequest>>(env));
const resp = protobuf_decode<OidbBase<OidbSvcTrpcTcp0xFE7_3Response>>(respBytes).body;
if (resp?.members) {
for (const raw of resp.members) {
members.push({
uin: raw.uin?.uin ?? 0,
uid: raw.uin?.uid ?? '',
nickname: raw.memberName ?? '',
card: raw.memberCard?.memberCard ?? '',
role: permissionToRole(raw.permission ?? 0),
level: raw.level?.level ?? 0,
title: raw.specialTitle ?? '',
joinTime: raw.joinTimestamp ?? 0,
lastSentTime: raw.lastMsgTimestamp ?? 0,
shutUpTime: raw.shutUpTimestamp ?? 0,
});
}
const resp = await FetchGroupMemberListPage.invoke(this.ctx, { groupId, token });
for (const raw of resp.members ?? []) {
members.push({
uin: raw.uin?.uin ?? 0,
uid: raw.uin?.uid ?? '',
nickname: raw.memberName ?? '',
card: raw.memberCard?.memberCard ?? '',
role: permissionToRole(raw.permission ?? 0),
level: raw.level?.level ?? 0,
title: raw.specialTitle ?? '',
joinTime: raw.joinTimestamp ?? 0,
lastSentTime: raw.lastMsgTimestamp ?? 0,
shutUpTime: raw.shutUpTimestamp ?? 0,
});
}
token = resp?.token ?? '';
token = resp.token ?? '';
} while (token);
this.ctx.identity.rememberGroupMembers(groupId, members);
@@ -257,75 +155,25 @@ export class ContactsApi {
}
async fetchUserProfile(uin: number): Promise<UserProfileInfo> {
const bridge = asBridge(this.ctx);
const keys = [20002, 27394, 20009, 20031, 101, 103, 102, 20020, 20003, 20026, 105, 27372, 27406, 20037];
// Only `uin` and `keys` — see OidbUserInfoRequestSchema for why
// sending field 2 makes the server reject the request.
const body = {
uin,
keys: keys.map(k => ({ key: k })),
};
// Set OIDB envelope `reserved = 1` (the `isUid: true` flag — the
// name is historical, the wire semantic is "this is the UIN-form
// variant of the call"). Without it newer QQ NT versions take the
// UID-form validation path, find neither uid nor openid in the
// body and bounce the request with
// `[oidb] one of uid/openid is invaild`. Matches Lagrange.Core's
// FetchStrangerByUin (Reserved = 1).
const env = makeOidbEnvelope<OidbUserInfoRequest>(0xFE1, 2, body, true);
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xfe1_2', protobuf_encode<OidbBase<OidbUserInfoRequest>>(env));
const resp = protobuf_decode<OidbBase<OidbUserInfoResponse>>(respBytes).body;
if (!resp?.body) throw new Error('user info response body missing');
const info: UserProfileInfo = {
uin: resp.body.uin ?? uin,
uid: resp.body.uid ?? '',
nickname: '', remark: '', qid: '', sex: 'unknown', age: 0, sign: '', avatar: '',
};
if (resp.body.properties) {
const bytesMap = new Map<number, Uint8Array>();
const numMap = new Map<number, number>();
for (const bp of resp.body.properties.bytesProperties ?? []) {
bytesMap.set(bp.code ?? 0, bp.value ?? new Uint8Array(0));
}
for (const np of resp.body.properties.numberProperties ?? []) {
numMap.set(np.number1 ?? 0, np.number2 ?? 0);
}
const getString = (code: number) => {
const b = bytesMap.get(code);
return b ? Buffer.from(b).toString('utf8') : '';
};
info.nickname = getString(20002);
info.remark = getString(103);
info.qid = getString(27394);
info.sign = getString(102);
const avatarBytes = bytesMap.get(101);
if (avatarBytes) {
const av = protobuf_decode<AvatarInfo>(avatarBytes);
if (av?.url) info.avatar = av.url + '640';
}
const sexNum = numMap.get(20009) ?? 0;
info.sex = sexNum === 1 ? 'male' : sexNum === 2 ? 'female' : 'unknown';
info.age = numMap.get(20037) ?? 0;
}
const info = await FetchUserProfile.invoke(this.ctx, { uin });
this.ctx.identity.rememberUserProfile(info);
return info;
}
async fetchGroupRequests(filtered = false): Promise<GroupRequestInfo[]> {
const bridge = asBridge(this.ctx);
const subCmd = filtered ? 2 : 1;
const cmd = filtered ? 'OidbSvcTrpcTcp.0x10c0_2' : 'OidbSvcTrpcTcp.0x10c0_1';
const env = makeOidbEnvelope<OidbGroupRequestList>(0x10C0, subCmd, { count: 20, field2: 0 });
const respBytes = await runOidb(bridge, cmd, protobuf_encode<OidbBase<OidbGroupRequestList>>(env));
const resp = protobuf_decode<OidbBase<OidbSvcTrpcTcp0x10C0Response>>(respBytes).body;
/** Look up a user profile by UID (string form). Used for strangers
* whose UIN we don't have yet — typically the requester on a
* group join request push. Mirrors Lagrange's `FetchUserInfoEvent
* .Create(targetUid)` path. */
async fetchUserProfileByUid(uid: string): Promise<UserProfileInfo> {
const info = await FetchUserProfileByUid.invoke(this.ctx, { uid });
if (info.uin > 0) this.ctx.identity.rememberUserProfile(info);
return info;
}
async fetchGroupRequests(filtered = false): Promise<GroupRequestInfo[]> {
const resp = await FetchGroupRequests.invoke(this.ctx, { filtered });
const requests: GroupRequestInfo[] = [];
for (const raw of resp?.requests ?? []) {
for (const raw of resp.requests ?? []) {
requests.push({
groupId: raw.group?.groupUin ?? 0,
groupName: raw.group?.groupName ?? '',
@@ -350,31 +198,10 @@ export class ContactsApi {
}
async fetchDownloadRKeys(): Promise<DownloadRKeyInfo[]> {
const bridge = asBridge(this.ctx);
const PRIVATE_IMAGE = 10;
const GROUP_IMAGE = 20;
const FALLBACK_IMAGE = 2;
const body = {
reqHead: {
common: { requestId: 1, command: 202 },
scene: { requestType: 2, businessType: 1, sceneType: 0 },
client: { agentType: 2 },
},
downloadRkey: {
types: [PRIVATE_IMAGE, GROUP_IMAGE, FALLBACK_IMAGE],
},
};
const env = makeOidbEnvelope<NTV2RichMediaReq>(0x9067, 202, body, true);
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x9067_202', protobuf_encode<OidbBase<NTV2RichMediaReq>>(env));
const resp = protobuf_decode<OidbBase<NTV2RichMediaResp>>(respBytes).body;
if (resp?.respHead?.retCode && resp.respHead.retCode !== 0) {
throw new Error(resp.respHead.message ?? 'fetch download rkey failed');
}
const resp = await FetchDownloadRkeys.invoke(this.ctx);
const result: DownloadRKeyInfo[] = [];
for (const entry of resp?.downloadRkey?.rkeys ?? []) {
for (const entry of resp.downloadRkey?.rkeys ?? []) {
const rkey = entry.rkey ?? '';
const type = entry.type ?? 0;
if (rkey && type) {
+25 -85
View File
@@ -1,34 +1,16 @@
// ExtrasApi — Tier-2 napcat-parity surfaces that don't fit anywhere
// else: group todo CRUD, stranger online/ext status decode, AI voice
// list + synthesis. Inlined from `actions/extras.ts` (deleted alongside
// actions/* in commit 13).
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
OidbGroupTodo,
OidbStrangerStatusReq,
OidbStrangerStatusResp,
} from '@snowluma/proto-defs/oidb-actions/base';
import type {
OidbAiVoiceListReq,
OidbAiVoiceListResp,
OidbAiVoiceReq,
OidbAiVoiceResp,
} from '@snowluma/proto-defs/oidb-actions/media';
import type { MediaIndexNode } from './shared';
import { FetchAiVoice } from '@snowluma/protocol/oidb-services/extras/fetch-ai-voice';
import {
FetchAiVoiceList,
type AiVoiceCategory as NamespaceAiVoiceCategory,
} from '@snowluma/protocol/oidb-services/extras/fetch-ai-voice-list';
import { GetStrangerStatus, type StrangerStatus as NamespaceStrangerStatus } from '@snowluma/protocol/oidb-services/extras/get-stranger-status';
import { GroupTodo } from '@snowluma/protocol/oidb-services/extras/group-todo';
import type { BridgeContext } from '../bridge-context';
import type { Bridge } from '../bridge';
import { makeOidbEnvelope, runOidb } from '@snowluma/bridge/bridge-oidb';
function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; }
import type { MediaIndexNode } from './shared';
// ─────────────── public types (re-exported from bridge.ts as before) ───
export interface StrangerStatus {
status: number;
ext_status: number;
}
export type StrangerStatus = NamespaceStrangerStatus;
export const AiVoiceChatType = {
Unknown: 0,
@@ -37,71 +19,40 @@ export const AiVoiceChatType = {
} as const;
export type AiVoiceChatType = typeof AiVoiceChatType[keyof typeof AiVoiceChatType];
export type AiVoiceCategory = NamespaceAiVoiceCategory;
export interface AiVoiceItem {
voiceId: string;
voiceDisplayName: string;
voiceExampleUrl: string;
}
export interface AiVoiceCategory {
category: string;
voices: AiVoiceItem[];
}
export class ExtrasApi {
constructor(private readonly ctx: BridgeContext) {}
constructor(private readonly ctx: BridgeContext) { }
// ─────────────── Group todo (0xF90) ───────────────
async setGroupTodo(groupId: number, msgSeq: bigint): Promise<void> {
const bridge = asBridge(this.ctx);
const env = makeOidbEnvelope<OidbGroupTodo>(0xF90, 1, { groupUin: groupId, msgSeq });
await runOidb(bridge, 'OidbSvcTrpcTcp.0xf90_1', protobuf_encode<OidbBase<OidbGroupTodo>>(env));
setGroupTodo(groupId: number, msgSeq: bigint): Promise<void> {
return GroupTodo.invoke(this.ctx, { groupId, msgSeq, action: 'set' });
}
async completeGroupTodo(groupId: number, msgSeq: bigint): Promise<void> {
const bridge = asBridge(this.ctx);
const env = makeOidbEnvelope<OidbGroupTodo>(0xF90, 2, { groupUin: groupId, msgSeq });
await runOidb(bridge, 'OidbSvcTrpcTcp.0xf90_2', protobuf_encode<OidbBase<OidbGroupTodo>>(env));
completeGroupTodo(groupId: number, msgSeq: bigint): Promise<void> {
return GroupTodo.invoke(this.ctx, { groupId, msgSeq, action: 'complete' });
}
async cancelGroupTodo(groupId: number, msgSeq: bigint): Promise<void> {
const bridge = asBridge(this.ctx);
const env = makeOidbEnvelope<OidbGroupTodo>(0xF90, 3, { groupUin: groupId, msgSeq });
await runOidb(bridge, 'OidbSvcTrpcTcp.0xf90_3', protobuf_encode<OidbBase<OidbGroupTodo>>(env));
cancelGroupTodo(groupId: number, msgSeq: bigint): Promise<void> {
return GroupTodo.invoke(this.ctx, { groupId, msgSeq, action: 'cancel' });
}
// ─────────────── Stranger online/ext status (0xFE1_2) ───────────────
/**
* 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.
* Returns `null` on transport / decode failure rather than throwing,
* so the OneBot action can produce a clean retcode without try/catch
* gymnastics. Namespace throws on transport failure → swallow here.
*/
async getStrangerStatus(uin: number): Promise<StrangerStatus | null> {
const bridge = asBridge(this.ctx);
try {
const env = makeOidbEnvelope<OidbStrangerStatusReq>(
0xFE1, 2,
{ uin, key: [{ key: 27372 }] } as any,
// Same UIN-form flag fetchUserProfile sets — without it newer
// QQ NT rejects with `[oidb] one of uid/openid is invaild`.
true,
);
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xfe1_2', protobuf_encode<OidbBase<OidbStrangerStatusReq>>(env));
const resp = protobuf_decode<OidbBase<OidbStrangerStatusResp>>(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 };
return await GetStrangerStatus.invoke(this.ctx, { uin });
} catch {
return null;
}
@@ -109,12 +60,8 @@ export class ExtrasApi {
// ─────────────── AI voice (0x929D / 0x929B) ───────────────
async fetchAiVoiceList(groupId: number, chatType: AiVoiceChatType | number): Promise<AiVoiceCategory[]> {
const bridge = asBridge(this.ctx);
const env = makeOidbEnvelope<OidbAiVoiceListReq>(0x929D, 0, { groupUin: groupId, chatType });
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x929d_0', protobuf_encode<OidbBase<OidbAiVoiceListReq>>(env));
const resp = protobuf_decode<OidbBase<OidbAiVoiceListResp>>(respBytes).body;
return (resp?.content as AiVoiceCategory[] | undefined) ?? [];
fetchAiVoiceList(groupId: number, chatType: AiVoiceChatType | number): Promise<AiVoiceCategory[]> {
return FetchAiVoiceList.invoke(this.ctx, { groupId, chatType });
}
/**
@@ -133,18 +80,11 @@ export class ExtrasApi {
chatType: AiVoiceChatType | number,
maxRetries = 30,
): Promise<MediaIndexNode> {
const bridge = asBridge(this.ctx);
// 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<OidbAiVoiceReq>(
0x929B, 0,
{ groupUin: groupId, voiceId, text, chatType, session: { sessionId } },
);
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x929b_0', protobuf_encode<OidbBase<OidbAiVoiceReq>>(env));
const resp = protobuf_decode<OidbBase<OidbAiVoiceResp>>(respBytes).body;
const node = resp?.msgInfo?.msgInfoBody?.[0]?.index as MediaIndexNode | undefined;
if (node) return node;
const node = await FetchAiVoice.invoke(this.ctx, { groupId, voiceId, text, chatType, sessionId });
if (node) return node as MediaIndexNode;
}
throw new Error(`AI voice synthesis did not complete after ${maxRetries} polls`);
}
+116 -44
View File
@@ -1,17 +1,4 @@
// ForwardApi — long-message (聊天记录 / forward) upload + retrieval.
// Inlined from `actions/forward.ts` (deleted alongside actions/* in
// commit 13).
//
// The module-scoped `forwardResCache` stays at file scope (not on the
// class instance) because forward res_ids are globally unique, and an
// outbound upload often gets queried back through `fetch` on a
// different Bridge instance (e.g. a different OneBot connection
// hitting the same account). Keeping the cache shared across the
// process matches NapCat's behaviour.
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import { randomUUID } from 'crypto';
import { gunzipSync, gzipSync } from 'zlib';
import type { PacketInfo } from '@snowluma/common/protocol-types';
import type {
LongMsgResult,
RecvLongMsgReq,
@@ -20,12 +7,14 @@ import type {
SendLongMsgResp,
} from '@snowluma/proto-defs/longmsg';
import type { FileExtra, PushMsg, PushMsgBody } from '@snowluma/proto-defs/message';
import type { PacketInfo } from '@snowluma/common/protocol-types';
import type { BridgeContext } from '../bridge-context';
import { buildSendElems } from '@snowluma/protocol/element-builder';
import type { ForwardNodePayload, MessageElement } from '@snowluma/protocol/events';
import { parseMsgPush } from '@snowluma/protocol/msg-push';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import { randomUUID } from 'crypto';
import { gunzipSync, gzipSync } from 'zlib';
import type { Bridge } from '../bridge';
import { buildSendElems } from '@snowluma/bridge/element-builder';
import type { ForwardNodePayload, MessageElement } from '@snowluma/bridge/events';
import { parseMsgPush } from '@snowluma/bridge/msg-push';
import type { BridgeContext } from '../bridge-context';
import { resolveSelfUid, toInt } from './shared';
function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; }
@@ -214,7 +203,7 @@ function previewFromElements(elements: MessageElement[]): string {
}
export class ForwardApi {
constructor(private readonly ctx: BridgeContext) {}
constructor(private readonly ctx: BridgeContext) { }
async upload(nodes: ForwardNodePayload[], groupId?: number, userId?: number): Promise<string> {
const { resId } = await this.uploadRecursive(nodes, groupId, userId);
@@ -265,6 +254,14 @@ export class ForwardApi {
// 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`.
//
// CRITICAL: the same uuid (`inner.uuid`) MUST be baked into the
// outer's preview element as `forwardUuid` AND used as the
// `actionCommand` for the outer's piggyback entry. That's the
// alignment the QQ-NT receiver uses to find the inner layer
// inside the outer's LongMsgResult without a second server fetch
// — see `dev/NapCatQQ/.../SendMsg.ts:241-246` + the `uniseq` round-
// trip in `dev/NapCatQQ/.../forward-msg-builder.ts:94`.
const myInnerActions: ForwardInnerAction[] = [];
const processedNodes: ForwardNodePayload[] = [];
const isGroup = groupId !== undefined;
@@ -278,13 +275,13 @@ export class ForwardApi {
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.
// pointing at the inner res_id. `forwardUuid: inner.uuid`
// baked into the LightApp JSON's `meta.detail.uniseq` is what
// closes the loop with our piggyback action above.
const previewElement: MessageElement = {
type: 'forward',
resId: inner.resId,
forwardUuid: inner.uuid,
forwardSource: deriveInnerSource(node.innerForward, isGroup),
forwardSummary: `查看${node.innerForward.length}条转发消息`,
forwardPrompt: '[聊天记录]',
@@ -367,6 +364,14 @@ export class ForwardApi {
return {
resId,
msgBody,
// UUID generated here so the OUTER caller can use it as both
// (1) the `actionCommand` for its piggyback entry carrying our
// msgBody, and
// (2) the `forwardUuid` baked into its forward-preview element
// pointing at our resId.
// Receivers walking the outer's LongMsgResult find the inner
// layer by matching `uniseq` from (2) against `actionCommand`
// from (1) — no separate fetch needed.
uuid: randomUUID(),
innerActions: myInnerActions,
};
@@ -417,10 +422,46 @@ export class ForwardApi {
const inflate = gunzipSync(Buffer.from(payload));
const longMsg = protobuf_decode<LongMsgResult>(inflate);
const action = longMsg?.action?.find((item) => item?.actionCommand === 'MultiMsg');
const msgBodyList = Array.isArray(action?.actionData?.msgBody) ? action.actionData.msgBody : [];
const actions = Array.isArray(longMsg?.action) ? longMsg!.action! : [];
const mainAction = actions.find(item => item?.actionCommand === 'MultiMsg');
const msgBodyList = Array.isArray(mainAction?.actionData?.msgBody) ? mainAction!.actionData!.msgBody : [];
const nodes: ForwardNodePayload[] = [];
// Piggyback index: any non-`MultiMsg` action carries an inner
// layer keyed by the uuid the sender baked into its forward
// preview's `uniseq`. Build a lookup so we can resolve inner
// forwards (via their uniseq → inner msgBody) without a second
// server roundtrip — matches the sender-side piggyback emitted in
// `uploadRecursive` above.
const piggybackByUuid = new Map<string, PushMsgBody[]>();
for (const action of actions) {
const cmd = action?.actionCommand;
if (!cmd || cmd === 'MultiMsg') continue;
const body = Array.isArray(action.actionData?.msgBody) ? action.actionData.msgBody : [];
piggybackByUuid.set(cmd, body);
}
const nodes = this.decodeMsgBodiesToNodes(msgBodyList);
// Walk the decoded outer nodes for inner-forward previews
// (`type: 'forward', forwardUuid: <uniseq>`). For each, pull the
// matching piggyback body, decode it into inner nodes, and seed
// the cache by the inner resId so a follow-up `fetch(innerResId)`
// hits the cache instead of the wire.
if (piggybackByUuid.size > 0) {
this.consumePiggybacks(nodes, piggybackByUuid);
}
if (nodes.length > 0) {
forwardResCache.set(resId, cloneNodes(nodes));
}
return nodes;
}
/** Walk a list of PushMsgBody, run each through the regular msg-push
* pipeline, and shape the result into ForwardNodePayloads. Extracted
* so both the outer + piggyback decode paths share one implementation. */
private decodeMsgBodiesToNodes(msgBodyList: PushMsgBody[]): ForwardNodePayload[] {
const out: ForwardNodePayload[] = [];
for (const msgBody of msgBodyList) {
const wrapped = protobuf_encode<PushMsg>({ message: msgBody });
const pkt: PacketInfo = {
@@ -438,7 +479,7 @@ export class ForwardApi {
if (!event) continue;
if (event.kind === 'group_message') {
nodes.push({
out.push({
userUin: event.senderUin,
nickname: event.senderCard || event.senderNick,
elements: event.elements,
@@ -450,7 +491,7 @@ export class ForwardApi {
messageType: 'group',
});
} else if (event.kind === 'friend_message') {
nodes.push({
out.push({
userUin: event.senderUin,
nickname: event.senderNick,
elements: event.elements,
@@ -460,7 +501,7 @@ export class ForwardApi {
messageType: 'private',
});
} else {
nodes.push({
out.push({
userUin: event.senderUin,
nickname: event.senderNick,
elements: event.elements,
@@ -471,20 +512,51 @@ export class ForwardApi {
});
}
}
return out;
}
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;
/** Recursively resolve forward previews against the piggyback table.
* For every `{type: 'forward', resId, forwardUuid}` element we find,
* look up the uniseq in the piggyback map; if hit, decode the
* inner msgBody and cache it by inner resId, then descend into that
* inner layer to resolve deeper nestings carried in the SAME
* piggyback set (NapCat hoists the entire tree's piggybacks onto
* the outermost action list). */
private consumePiggybacks(
nodes: ForwardNodePayload[],
piggybackByUuid: Map<string, PushMsgBody[]>,
): void {
const seen = new Set<string>();
const visit = (chain: ForwardNodePayload[]): void => {
for (const node of chain) {
for (const elem of node.elements) {
if (elem.type !== 'forward') continue;
const uuid = elem.forwardUuid;
const innerResId = elem.resId;
if (!uuid || !innerResId || seen.has(uuid)) continue;
const body = piggybackByUuid.get(uuid);
if (!body) continue;
seen.add(uuid);
const innerNodes = this.decodeMsgBodiesToNodes(body);
forwardResCache.set(innerResId, cloneNodes(innerNodes));
visit(innerNodes);
}
}
};
visit(nodes);
}
}
function cloneNodes(nodes: ForwardNodePayload[]): ForwardNodePayload[] {
return 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,
}));
}
+9 -50
View File
@@ -1,59 +1,21 @@
// FriendApi — friend roster mutations (handle add request /
// delete / set remark). Inlined from `actions/friend.ts` (deleted
// alongside actions/* in commit 13). The READ side of friends
// (fetchFriendList) lives on ContactsApi because friends/groups
// share the same roster pipeline.
import { protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
OidbDeleteFriend,
OidbFriendRequestAction,
OidbSetFriendRemark,
} from '@snowluma/proto-defs/oidb-actions/base';
import { DeleteFriend } from '@snowluma/protocol/oidb-services/friend/delete-friend';
import { HandleFriendRequest } from '@snowluma/protocol/oidb-services/friend/handle-friend-request';
import { SetFriendRemark } from '@snowluma/protocol/oidb-services/friend/set-friend-remark';
import type { BridgeContext } from '../bridge-context';
import type { Bridge } from '../bridge';
import { makeOidbEnvelope, runOidb } from '@snowluma/bridge/bridge-oidb';
function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; }
export class FriendApi {
constructor(private readonly ctx: BridgeContext) {}
constructor(private readonly ctx: BridgeContext) { }
/**
* Accept or reject an inbound friend request. `uidOrFlag` is either a
* pre-resolved UID string or a numeric uin (then resolved on the fly).
*/
async handleRequest(uidOrFlag: string, approve: boolean): Promise<void> {
const bridge = asBridge(this.ctx);
let targetUid = uidOrFlag;
if (/^\d+$/.test(uidOrFlag)) {
targetUid = await this.ctx.resolveUserUid(parseInt(uidOrFlag, 10));
}
const env = makeOidbEnvelope<OidbFriendRequestAction>(0xB5D, 44, { accept: approve ? 3 : 5, targetUid });
await runOidb(bridge, 'OidbSvcTrpcTcp.0xb5d_44', protobuf_encode<OidbBase<OidbFriendRequestAction>>(env));
handleRequest(uidOrFlag: string, approve: boolean): Promise<void> {
return HandleFriendRequest.invoke(this.ctx, { uidOrFlag, approve });
}
async delete(userId: number, block = false): Promise<void> {
const bridge = asBridge(this.ctx);
const targetUid = await this.ctx.resolveUserUid(userId);
const env = makeOidbEnvelope<OidbDeleteFriend>(0x126B, 0, {
field1: {
targetUid,
field2: {
field1: 130,
field2: 109,
field3: {
field1: 8,
field2: 8,
field3: 50,
},
},
block,
field4: false,
},
});
await runOidb(bridge, 'OidbSvcTrpcTcp.0x126b_0', protobuf_encode<OidbBase<OidbDeleteFriend>>(env));
await DeleteFriend.invoke(this.ctx, { userId, block });
// Refresh friend cache after deletion so subsequent reads don't
// surface a ghost entry. Best-effort: a transient OIDB hiccup here
@@ -61,10 +23,7 @@ export class FriendApi {
try { await this.ctx.apis.contacts.fetchFriendList(); } catch { /* ignore */ }
}
async setRemark(userId: number, remark: string): Promise<void> {
const bridge = asBridge(this.ctx);
const uid = await this.ctx.resolveUserUid(userId);
const env = makeOidbEnvelope<OidbSetFriendRemark>(0xB6E, 2, { targetUid: uid, remark });
await runOidb(bridge, 'OidbSvcTrpcTcp.0xb6e_2', protobuf_encode<OidbBase<OidbSetFriendRemark>>(env));
setRemark(userId: number, remark: string): Promise<void> {
return SetFriendRemark.invoke(this.ctx, { userId, remark });
}
}
+43 -131
View File
@@ -1,137 +1,71 @@
// GroupAdminApi — mute/kick/admin/card/name/title/leave + join-policy
// + add-request handling. Inlined from the previous
// `actions/group-admin.ts` (deleted alongside the rest of the
// actions/* facade in commit 13).
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
Oidb0x89a_0AddOption,
Oidb0x89a_0Search,
Oidb0x8a0Req,
Oidb0x8a7Req,
Oidb0x8a7Resp,
Oidb0xf16Req,
OidbGroupRequestAction,
OidbKickMember,
OidbLeaveGroup,
OidbMuteAll,
OidbMuteMember,
OidbRenameGroup,
OidbRenameMember,
OidbSetAdmin,
OidbSpecialTitle,
} from '@snowluma/proto-defs/oidb-actions/base';
import { GetAtAllRemain } from '@snowluma/protocol/oidb-services/group-admin/get-at-all-remain';
import { KickMember } from '@snowluma/protocol/oidb-services/group-admin/kick-member';
import { KickMembers } from '@snowluma/protocol/oidb-services/group-admin/kick-members';
import { LeaveGroup } from '@snowluma/protocol/oidb-services/group-admin/leave-group';
import { MuteAll } from '@snowluma/protocol/oidb-services/group-admin/mute-all';
import { MuteMember } from '@snowluma/protocol/oidb-services/group-admin/mute-member';
import { SetAddOption } from '@snowluma/protocol/oidb-services/group-admin/set-add-option';
import { SetAddRequest } from '@snowluma/protocol/oidb-services/group-admin/set-add-request';
import { SetAdmin } from '@snowluma/protocol/oidb-services/group-admin/set-admin';
import { SetGroupName } from '@snowluma/protocol/oidb-services/group-admin/set-group-name';
import { SetGroupRemark } from '@snowluma/protocol/oidb-services/group-admin/set-group-remark';
import { SetMemberCard } from '@snowluma/protocol/oidb-services/group-admin/set-member-card';
import { SetSearch } from '@snowluma/protocol/oidb-services/group-admin/set-search';
import { SetSpecialTitle } from '@snowluma/protocol/oidb-services/group-admin/set-special-title';
import type { BridgeContext } from '../bridge-context';
import type { Bridge } from '../bridge';
import { makeOidbEnvelope, runOidb } from '@snowluma/bridge/bridge-oidb';
function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; }
export class GroupAdminApi {
constructor(private readonly ctx: BridgeContext) {}
constructor(private readonly ctx: BridgeContext) { }
async muteMember(groupId: number, userId: number, duration: number): Promise<void> {
const bridge = asBridge(this.ctx);
const uid = await this.ctx.resolveUserUid(userId, groupId);
const env = makeOidbEnvelope<OidbMuteMember>(0x1253, 1, {
groupUin: groupId, type: 1, body: { targetUid: uid, duration },
});
await runOidb(bridge, 'OidbSvcTrpcTcp.0x1253_1', protobuf_encode<OidbBase<OidbMuteMember>>(env));
muteMember(groupId: number, userId: number, duration: number): Promise<void> {
return MuteMember.invoke(this.ctx, { groupId, userId, duration });
}
async muteAll(groupId: number, enable: boolean): Promise<void> {
const bridge = asBridge(this.ctx);
const env = makeOidbEnvelope<OidbMuteAll>(0x89A, 0, {
groupUin: groupId, muteState: { state: enable ? 0xFFFFFFFF : 0 },
});
await runOidb(bridge, 'OidbSvcTrpcTcp.0x89a_0', protobuf_encode<OidbBase<OidbMuteAll>>(env));
muteAll(groupId: number, enable: boolean): Promise<void> {
return MuteAll.invoke(this.ctx, { groupId, enable });
}
async setAddOption(groupId: number, addType: number): Promise<void> {
const bridge = asBridge(this.ctx);
const env = makeOidbEnvelope<Oidb0x89a_0AddOption>(0x89A, 0, {
groupUin: BigInt(groupId), settings: { addType }, field12: 0,
});
await runOidb(bridge, 'OidbSvcTrpcTcp.0x89a_0', protobuf_encode<OidbBase<Oidb0x89a_0AddOption>>(env));
setAddOption(groupId: number, addType: number): Promise<void> {
return SetAddOption.invoke(this.ctx, { groupId, addType });
}
async setSearch(groupId: number): Promise<void> {
const bridge = asBridge(this.ctx);
const env = makeOidbEnvelope<Oidb0x89a_0Search>(0x89A, 0, {
groupUin: BigInt(groupId), settings: new Uint8Array(0), field12: 0,
});
await runOidb(bridge, 'OidbSvcTrpcTcp.0x89a_0', protobuf_encode<OidbBase<Oidb0x89a_0Search>>(env));
setSearch(groupId: number): Promise<void> {
return SetSearch.invoke(this.ctx, { groupId });
}
async setAddRequest(
setAddRequest(
groupId: number, sequence: number, eventType: number,
approve: boolean, reason = '', filtered = false,
): Promise<void> {
const bridge = asBridge(this.ctx);
const subCmd = filtered ? 2 : 1;
const cmd = filtered ? 'OidbSvcTrpcTcp.0x10c8_2' : 'OidbSvcTrpcTcp.0x10c8_1';
const env = makeOidbEnvelope<OidbGroupRequestAction>(
0x10C8, subCmd,
{ accept: approve ? 1 : 2, body: { sequence: BigInt(sequence), eventType, groupUin: groupId, message: reason } },
true,
);
await runOidb(bridge, cmd, protobuf_encode<OidbBase<OidbGroupRequestAction>>(env));
return SetAddRequest.invoke(this.ctx, { groupId, sequence, eventType, approve, reason, filtered });
}
async kickMember(groupId: number, userId: number, reject: boolean, reason = ''): Promise<void> {
const bridge = asBridge(this.ctx);
const uid = await this.ctx.resolveUserUid(userId, groupId);
const env = makeOidbEnvelope<OidbKickMember>(0x8A0, 1, {
groupUin: groupId, targetUid: uid, rejectAddRequest: reject, reason,
});
await runOidb(bridge, 'OidbSvcTrpcTcp.0x8a0_1', protobuf_encode<OidbBase<OidbKickMember>>(env));
kickMember(groupId: number, userId: number, reject: boolean, reason = ''): Promise<void> {
return KickMember.invoke(this.ctx, { groupId, userId, reject, reason });
}
async kickMembers(groupId: number, userIds: number[], reject: boolean): Promise<void> {
const bridge = asBridge(this.ctx);
const targetUids = await Promise.all(userIds.map(userId => this.ctx.resolveUserUid(userId, groupId)));
const env = makeOidbEnvelope<Oidb0x8a0Req>(0x8A0, 1, {
groupId: BigInt(groupId), targetUids, rejectAddRequest: reject ? 1 : 0, kickReason: new Uint8Array(0), field12: 0,
});
await runOidb(bridge, 'OidbSvcTrpcTcp.0x8a0_1', protobuf_encode<OidbBase<Oidb0x8a0Req>>(env));
kickMembers(groupId: number, userIds: number[], reject: boolean): Promise<void> {
return KickMembers.invoke(this.ctx, { groupId, userIds, reject });
}
async leave(groupId: number): Promise<void> {
const bridge = asBridge(this.ctx);
const env = makeOidbEnvelope<OidbLeaveGroup>(0x1097, 1, { groupUin: groupId });
await runOidb(bridge, 'OidbSvcTrpcTcp.0x1097_1', protobuf_encode<OidbBase<OidbLeaveGroup>>(env));
leave(groupId: number): Promise<void> {
return LeaveGroup.invoke(this.ctx, { groupId });
}
async setAdmin(groupId: number, userId: number, enable: boolean): Promise<void> {
const bridge = asBridge(this.ctx);
const uid = await this.ctx.resolveUserUid(userId, groupId);
const env = makeOidbEnvelope<OidbSetAdmin>(0x1096, 1, { groupUin: groupId, uid, isAdmin: enable });
await runOidb(bridge, 'OidbSvcTrpcTcp.0x1096_1', protobuf_encode<OidbBase<OidbSetAdmin>>(env));
setAdmin(groupId: number, userId: number, enable: boolean): Promise<void> {
return SetAdmin.invoke(this.ctx, { groupId, userId, enable });
}
async setCard(groupId: number, userId: number, card: string): Promise<void> {
const bridge = asBridge(this.ctx);
const uid = await this.ctx.resolveUserUid(userId, groupId);
const env = makeOidbEnvelope<OidbRenameMember>(0x8FC, 3, {
groupUin: groupId, body: { targetUid: uid, targetName: card },
});
await runOidb(bridge, 'OidbSvcTrpcTcp.0x8fc_3', protobuf_encode<OidbBase<OidbRenameMember>>(env));
setCard(groupId: number, userId: number, card: string): Promise<void> {
return SetMemberCard.invoke(this.ctx, { groupId, userId, card });
}
async setName(groupId: number, name: string): Promise<void> {
const bridge = asBridge(this.ctx);
const env = makeOidbEnvelope<OidbRenameGroup>(0x89A, 15, { groupUin: groupId, body: { targetName: name } });
await runOidb(bridge, 'OidbSvcTrpcTcp.0x89a_15', protobuf_encode<OidbBase<OidbRenameGroup>>(env));
setName(groupId: number, name: string): Promise<void> {
return SetGroupName.invoke(this.ctx, { groupId, name });
}
async setSpecialTitle(groupId: number, userId: number, title: string): Promise<void> {
const bridge = asBridge(this.ctx);
const uid = await this.ctx.resolveUserUid(userId, groupId);
const env = makeOidbEnvelope<OidbSpecialTitle>(0x8FC, 2, {
groupUin: groupId, body: { targetUid: uid, specialTitle: title, expireTime: -1 },
});
await runOidb(bridge, 'OidbSvcTrpcTcp.0x8fc_2', protobuf_encode<OidbBase<OidbSpecialTitle>>(env));
setSpecialTitle(groupId: number, userId: number, title: string): Promise<void> {
return SetSpecialTitle.invoke(this.ctx, { groupId, userId, title });
}
/**
@@ -139,37 +73,15 @@ export class GroupAdminApi {
* `FriendApi` because the semantic is "operate on a group" rather
* than "operate on a contact list".
*/
async setRemark(groupId: number, remark: string): Promise<void> {
const bridge = asBridge(this.ctx);
const env = makeOidbEnvelope<Oidb0xf16Req>(0xF16, 1, { inner: { groupId: BigInt(groupId), remark }, field12: 0 });
await runOidb(bridge, 'OidbSvcTrpcTcp.0xf16_1', protobuf_encode<OidbBase<Oidb0xf16Req>>(env));
setRemark(groupId: number, remark: string): Promise<void> {
return SetGroupRemark.invoke(this.ctx, { groupId, remark });
}
async getAtAllRemain(groupId: number): Promise<{
getAtAllRemain(groupId: number): Promise<{
can_at_all: boolean;
remain_at_all_count_for_group: number;
remain_at_all_count_for_uin: number;
}> {
const bridge = asBridge(this.ctx);
const req = {
basic1: 1,
basic2: 2,
basic3: 1,
uin: BigInt(this.ctx.identity.uin),
groupId: BigInt(groupId),
type: 0,
};
const env = makeOidbEnvelope<Oidb0x8a7Req>(0x8A7, 0, req);
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x8a7_0', protobuf_encode<OidbBase<Oidb0x8a7Req>>(env));
const result = protobuf_decode<OidbBase<Oidb0x8a7Resp>>(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),
};
return GetAtAllRemain.invoke(this.ctx, { groupId });
}
}
+33 -39
View File
@@ -1,10 +1,4 @@
// GroupAlbumApi — group photo album operations (list/upload/comment/
// like/delete + media listing). Inlined from `actions/group-album.ts`
// and `web-actions/group-album.ts` (both deleted alongside actions/*
// in commit 13). The pure-HTTP helpers in `web/group-album.ts` stay
// where they are — they're transport-layer code, not Bridge actions.
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { JsonObject, JsonValue } from '@snowluma/common/json';
import type {
DeleteMediasRequest,
DeleteMediasResponse,
@@ -14,47 +8,33 @@ import type {
DoQunLikeResponse,
GetMediaListRequest,
GetMediaListResponse,
MediaInfo,
} from '@snowluma/proto-defs/oidb-actions/group-album';
import { getGroupAlbumList, uploadImageToGroupAlbum } from '@snowluma/protocol/web/group-album';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { BridgeContext } from '../bridge-context';
import type { Bridge } from '../bridge';
import { getGroupAlbumList, uploadImageToGroupAlbum } from '@snowluma/bridge/web/group-album';
// `getCookies` is part of WebApi — go through the hub so we don't
// duplicate the cookie acquisition flow.
function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; }
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;
function convertBigIntToString(obj: unknown): JsonValue {
if (obj === null || obj === undefined) return null;
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]);
const result: JsonObject = {};
for (const [key, value] of Object.entries(obj)) {
result[key] = convertBigIntToString(value);
}
return result;
}
return obj;
if (typeof obj === 'string' || typeof obj === 'number' || typeof obj === 'boolean') return obj;
return null;
}
export class GroupAlbumApi {
constructor(private readonly ctx: BridgeContext) {}
constructor(private readonly ctx: BridgeContext) { }
/** List a group's albums (HTTP-cookie-based, qzone.qq.com). */
async list(groupId: number): Promise<any> {
// 列出群相册(基于 qzone.qq.com 的 HTTP Cookie)。
async list(groupId: number): Promise<GroupAlbumList> {
const groupCode = groupId.toString();
const uin = this.ctx.identity.uin;
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
@@ -62,7 +42,7 @@ export class GroupAlbumApi {
return albumData?.album || [];
}
/** Upload an image into an existing album (HTTP slice-upload). */
// 上传图片到现有相册(HTTP 分片上传)。
async upload(groupId: number, albumId: string, albumName: string, filePath: string): Promise<void> {
const groupCode = groupId.toString();
const uin = this.ctx.identity.uin;
@@ -108,7 +88,7 @@ export class GroupAlbumApi {
const mediaList = data.mediaList ?? [];
const nextAttachInfo = data.nextAttachInfo ?? '';
return convertBigIntToString({ mediaList, nextAttachInfo });
return convertBigIntToString({ mediaList, nextAttachInfo }) as unknown as GroupAlbumMediaResult;
}
async comment(groupId: number, albumId: string, lloc: string, content: string): Promise<GroupAlbumCommentResult> {
@@ -179,10 +159,10 @@ export class GroupAlbumApi {
content: commentData.content ?? [],
time: commentData.time ?? '0',
clientKey: commentData.clientKey ?? '',
});
}) as unknown as GroupAlbumCommentResult;
}
async like(groupId: number, albumId: string, batchId: string, lloc: string | undefined, isLike: boolean): Promise<any> {
async like(groupId: number, albumId: string, batchId: string, lloc: string | undefined, isLike: boolean): Promise<JsonValue> {
const uin = this.ctx.identity.uin;
const clientKey = `${uin}_${Date.now()}_${Math.floor(Math.random() * 100000)}`;
@@ -244,7 +224,7 @@ export class GroupAlbumApi {
return convertBigIntToString(resp.body?.like ?? {});
}
async delete(groupId: number, albumId: string, lloc: string): Promise<any> {
async delete(groupId: number, albumId: string, lloc: string): Promise<{ success: true }> {
const uin = this.ctx.identity.uin;
const clientKey = `${uin}_${Date.now()}_${Math.floor(Math.random() * 100000)}`;
@@ -283,3 +263,17 @@ export class GroupAlbumApi {
return { success: true };
}
}
export interface GroupAlbumMediaResult {
mediaList: Array<JsonValue & Partial<MediaInfo>>;
nextAttachInfo: string;
}
export type GroupAlbumList = NonNullable<Awaited<ReturnType<typeof getGroupAlbumList>>>['album'];
export interface GroupAlbumCommentResult {
id: string;
user: { uin: string };
content: Array<{ type: number; content: string }>;
time: string;
clientKey: string;
}
+71 -433
View File
@@ -1,44 +1,30 @@
// GroupFileApi — group file CRUD + private (c2c) file upload + media
// download URL resolvers. Inlined from `actions/group-file.ts`
// (deleted alongside the rest of actions/* in commit 13).
//
// Naming: methods drop the redundant `Group`/`File` suffix where the
// area name already says it. The `Private`/`Group` axis stays
// explicit because some methods only exist for one side
// (`publish` only makes sense for group, `getPrivateUrl` only for
// c2c) — keeping them in one Api lets the few shared private helpers
// (`fetchNtv2DownloadUrl`, the upload-ext builder) live in one file.
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import { toHexUpper } from '@snowluma/common/hex';
import { createLogger } from '@snowluma/common/logger';
import type { BridgeContext } from '../bridge-context';
import type { Bridge } from '../bridge';
import { makeOidbEnvelope, runOidb } from '@snowluma/bridge/bridge-oidb';
import { fetchHighwaySession, uploadHighwayHttp } from '@snowluma/bridge/highway';
import { computeHashes, computeMd5, FILE_UPLOAD_MAX_BYTES, loadBinarySource } from '@snowluma/bridge/highway/utils';
import type { FileUploadExt } from '@snowluma/proto-defs/highway';
import { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
OidbGroupFileCountViewReq,
OidbGroupFileCountViewResp,
OidbGroupFileFolderReq,
OidbGroupFileFolderResp,
OidbGroupFileReq,
OidbGroupFileResp,
OidbGroupFileViewReq,
OidbGroupFileViewResp,
OidbGroupSendFileReq,
} from '@snowluma/proto-defs/oidb-actions/group-file';
import type {
NTV2RichMediaReq,
NTV2RichMediaResp,
OidbPrivateFileDownloadReq,
OidbPrivateFileDownloadResp,
OidbPrivateFileUploadReq,
OidbPrivateFileUploadResp,
} from '@snowluma/proto-defs/oidb-actions/media';
import { ensureRetCodeZero, resolveSelfUid, toInt, type MediaIndexNode } from './shared';
import { fetchHighwaySession, uploadHighwayHttp } from '@snowluma/protocol/highway';
import { computeHashes, computeMd5, FILE_UPLOAD_MAX_BYTES, loadBinarySource } from '@snowluma/protocol/highway/utils';
import { protobuf_encode } from '@snowluma/proton';
import type { Bridge } from '../bridge';
import type { BridgeContext } from '../bridge-context';
import { resolveSelfUid, toInt, type MediaIndexNode } from './shared';
import { CreateGroupFolder } from '@snowluma/protocol/oidb-services/group-file/create-group-folder';
import { DeleteGroupFile } from '@snowluma/protocol/oidb-services/group-file/delete-group-file';
import { DeleteGroupFolder } from '@snowluma/protocol/oidb-services/group-file/delete-group-folder';
import { GetGroupFileCount } from '@snowluma/protocol/oidb-services/group-file/get-group-file-count';
import { GetGroupFileUrl } from '@snowluma/protocol/oidb-services/group-file/get-group-file-url';
import { GetGroupPttUrl } from '@snowluma/protocol/oidb-services/group-file/get-group-ptt-url';
import { GetGroupVideoUrl } from '@snowluma/protocol/oidb-services/group-file/get-group-video-url';
import { GetPrivateFileUrl } from '@snowluma/protocol/oidb-services/group-file/get-private-file-url';
import { GetPrivatePttUrl } from '@snowluma/protocol/oidb-services/group-file/get-private-ptt-url';
import { GetPrivateVideoUrl } from '@snowluma/protocol/oidb-services/group-file/get-private-video-url';
import { ListGroupFilesPage } from '@snowluma/protocol/oidb-services/group-file/list-group-files-page';
import { MoveGroupFile } from '@snowluma/protocol/oidb-services/group-file/move-group-file';
import { PublishGroupFile } from '@snowluma/protocol/oidb-services/group-file/publish-group-file';
import { RenameGroupFolder } from '@snowluma/protocol/oidb-services/group-file/rename-group-folder';
import { UploadGroupFileRequest } from '@snowluma/protocol/oidb-services/group-file/upload-group-file-request';
import { UploadPrivateFileRequest } from '@snowluma/protocol/oidb-services/group-file/upload-private-file-request';
import { ensureRetCodeZero } from '@snowluma/protocol/oidb-services/shared';
const log = createLogger('GroupFile');
@@ -230,120 +216,23 @@ function buildPrivateFileUploadExt(
});
}
function normalizeMediaNode(node: MediaIndexNode): Record<string, unknown> {
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<string, unknown>,
): Promise<string> {
const env = makeOidbEnvelope<NTV2RichMediaReq>(oidbCmd, 200, payload as any, true);
const respBytes = await runOidb(bridge, serviceCmd, protobuf_encode<OidbBase<NTV2RichMediaReq>>(env));
const resp = protobuf_decode<OidbBase<NTV2RichMediaResp>>(respBytes).body;
ensureRetCodeZero('ntv2 download', resp?.respHead?.retCode, resp?.respHead?.message, undefined);
const domain = typeof resp?.download?.info?.domain === 'string' ? resp.download.info.domain : '';
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}`;
}
export class GroupFileApi {
constructor(private readonly ctx: BridgeContext) {}
constructor(private readonly ctx: BridgeContext) { }
// ─────────────── 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.
*/
async publish(groupId: number, fileId: string): Promise<void> {
publish(groupId: number, fileId: string): Promise<void> {
if (!fileId) throw new Error('publish requires fileId');
const bridge = asBridge(this.ctx);
const env = makeOidbEnvelope<OidbGroupSendFileReq>(0x6D9, 4, {
body: {
groupUin: groupId,
type: 2,
info: {
busiType: 102,
fileId,
field3: Math.floor(Math.random() * 0x7fffffff) >>> 0,
field5: true,
},
},
});
await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d9_4', protobuf_encode<OidbBase<OidbGroupSendFileReq>>(env));
return PublishGroupFile.invoke(this.ctx, { groupId, fileId });
}
// ─────────────── count ───────────────
async getCount(groupId: number): Promise<{ fileCount: number; maxCount: number }> {
const bridge = asBridge(this.ctx);
const env = makeOidbEnvelope<OidbGroupFileCountViewReq>(
0x6D8, 3,
{ count: { groupUin: groupId, appId: 7, busId: 0 } },
);
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d8_3', protobuf_encode<OidbBase<OidbGroupFileCountViewReq>>(env));
const resp = protobuf_decode<OidbBase<OidbGroupFileCountViewResp>>(respBytes).body;
return {
fileCount: toInt(resp?.count?.fileCount ?? 0),
maxCount: toInt(resp?.count?.maxCount ?? 10000),
};
getCount(groupId: number): Promise<{ fileCount: number; maxCount: number }> {
return GetGroupFileCount.invoke(this.ctx, { groupId });
}
// ─────────────── upload ───────────────
// ─────────────── upload (3-stage: OIDB preflight → highway → publish) ───────────────
async upload(
groupId: number,
@@ -361,31 +250,14 @@ export class GroupFileApi {
const fileName = normalizeUploadFileName(name, loaded.fileName);
const hashes = computeHashes(loaded.bytes);
const env = makeOidbEnvelope<OidbGroupFileReq>(
0x6D6, 0,
{
file: {
groupUin: groupId,
appId: 4,
busId: 102,
entrance: 6,
targetDirectory: normalizeDirectory(folderId),
fileName,
localDirectory: `/${fileName}`,
fileSize: BigInt(loaded.bytes.length),
fileSha1: hashes.sha1,
fileSha3: new Uint8Array(0),
fileMd5: hashes.md5,
field15: true,
},
},
true,
);
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d6_0', protobuf_encode<OidbBase<OidbGroupFileReq>>(env));
const resp = protobuf_decode<OidbBase<OidbGroupFileResp>>(respBytes).body;
const upload = resp?.upload;
if (!upload) throw new Error('group file upload response missing');
const upload = await UploadGroupFileRequest.invoke(this.ctx, {
groupId,
fileName,
folderId: normalizeDirectory(folderId),
fileSize: loaded.bytes.length,
fileSha1: hashes.sha1,
fileMd5: hashes.md5,
});
ensureRetCodeZero('group file upload', upload.retCode, upload.retMsg, upload.clientWording);
const fileId = typeof upload.fileId === 'string' && upload.fileId ? upload.fileId : null;
@@ -470,8 +342,6 @@ export class GroupFileApi {
uploadFile = true,
): Promise<UploadFileResult> {
const bridge = asBridge(this.ctx);
// 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');
@@ -491,29 +361,15 @@ export class GroupFileApi {
const fileName = normalizeUploadFileName(name, loaded.fileName);
const hashes = computeHashes(loaded.bytes);
const env = makeOidbEnvelope<OidbPrivateFileUploadReq>(0xE37, 1700, {
command: 1700,
seq: 0,
upload: {
senderUid: selfUid,
receiverUid: targetUid,
fileSize: loaded.bytes.length,
fileName,
md510MCheckSum: md5First10MB(loaded.bytes),
sha1CheckSum: hashes.sha1,
localPath: '/',
md5CheckSum: hashes.md5,
sha3CheckSum: new Uint8Array(0),
},
businessId: 3,
clientType: 1,
flagSupportMediaPlatform: 1,
const upload = await UploadPrivateFileRequest.invoke(this.ctx, {
senderUid: selfUid,
receiverUid: targetUid,
fileName,
fileSize: loaded.bytes.length,
fileSha1: hashes.sha1,
fileMd5: hashes.md5,
md510MCheckSum: md5First10MB(loaded.bytes),
});
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xe37_1700', protobuf_encode<OidbBase<OidbPrivateFileUploadReq>>(env));
const resp = protobuf_decode<OidbBase<OidbPrivateFileUploadResp>>(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;
@@ -583,12 +439,8 @@ export class GroupFileApi {
? 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: any) => ({
? JSON.stringify(upload.rtpMediaPlatformUploadAddress.map((e) => ({
outIP: e.outIP, outPort: e.outPort, inIP: e.inIP, inPort: e.inPort,
iPType: e.iPType,
})))
@@ -647,10 +499,9 @@ export class GroupFileApi {
return { fileId, fileHash };
}
// ─────────────── list ───────────────
// ─────────────── list (paginated loop) ───────────────
async list(groupId: number, folderId = '/'): Promise<GroupFilesResult> {
const bridge = asBridge(this.ctx);
const targetDirectory = normalizeDirectory(folderId);
const files: GroupFileInfo[] = [];
const folders: GroupFolderInfo[] = [];
@@ -658,26 +509,9 @@ export class GroupFileApi {
const pageSize = 20;
let startIndex = 0;
for (let page = 0; page < 200; page++) {
const env = makeOidbEnvelope<OidbGroupFileViewReq>(
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', protobuf_encode<OidbBase<OidbGroupFileViewReq>>(env));
const resp = protobuf_decode<OidbBase<OidbGroupFileViewResp>>(respBytes).body;
const list = resp?.list;
const list = await ListGroupFilesPage.invoke(this.ctx, {
groupId, targetDirectory, startIndex, pageSize,
});
if (!list) break;
ensureRetCodeZero('group file list', list.retCode, list.retMsg, list.clientWording);
@@ -730,24 +564,7 @@ export class GroupFileApi {
// ─────────────── url fetch (group / private files) ───────────────
async getUrl(groupId: number, fileId: string, busId = 102): Promise<string> {
const bridge = asBridge(this.ctx);
const env = makeOidbEnvelope<OidbGroupFileReq>(
0x6D6, 2,
{
download: {
groupUin: groupId,
appId: 7,
busId,
fileId,
},
},
true,
);
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d6_2', protobuf_encode<OidbBase<OidbGroupFileReq>>(env));
const resp = protobuf_decode<OidbBase<OidbGroupFileResp>>(respBytes).body;
const download = resp?.download;
if (!download) throw new Error('group file url response missing');
const download = await GetGroupFileUrl.invoke(this.ctx, { groupId, fileId, busId });
ensureRetCodeZero('group file url', download.retCode, download.retMsg, download.clientWording);
const dns = (typeof download.downloadDns === 'string' && download.downloadDns)
@@ -766,25 +583,8 @@ export class GroupFileApi {
const bridge = asBridge(this.ctx);
const selfUid = await resolveSelfUid(bridge);
void userId;
const env = makeOidbEnvelope<OidbPrivateFileDownloadReq>(0xE37, 1200, {
subCommand: 1200,
field2: 1,
body: {
receiverUid: selfUid,
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', protobuf_encode<OidbBase<OidbPrivateFileDownloadReq>>(env), 5000);
const resp = protobuf_decode<OidbBase<OidbPrivateFileDownloadResp>>(respBytes).body;
const result = await GetPrivateFileUrl.invoke(this.ctx, { selfUid, fileId, fileHash });
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 : '';
@@ -796,211 +596,49 @@ export class GroupFileApi {
// ─────────────── delete / move ───────────────
async delete(groupId: number, fileId: string): Promise<void> {
const bridge = asBridge(this.ctx);
const env = makeOidbEnvelope<OidbGroupFileReq>(
0x6D6, 3,
{
delete: {
groupUin: groupId,
busId: 102,
fileId,
},
},
true,
);
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d6_3', protobuf_encode<OidbBase<OidbGroupFileReq>>(env));
const resp = protobuf_decode<OidbBase<OidbGroupFileResp>>(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);
delete(groupId: number, fileId: string): Promise<void> {
return DeleteGroupFile.invoke(this.ctx, { groupId, fileId });
}
async move(
groupId: number,
fileId: string,
parentDirectory: string,
targetDirectory: string,
): Promise<void> {
const bridge = asBridge(this.ctx);
const env = makeOidbEnvelope<OidbGroupFileReq>(
0x6D6, 5,
{
move: {
groupUin: groupId,
appId: 7,
busId: 102,
fileId,
parentDirectory,
targetDirectory,
},
},
true,
);
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d6_5', protobuf_encode<OidbBase<OidbGroupFileReq>>(env));
const resp = protobuf_decode<OidbBase<OidbGroupFileResp>>(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);
move(groupId: number, fileId: string, parentDirectory: string, targetDirectory: string): Promise<void> {
return MoveGroupFile.invoke(this.ctx, { groupId, fileId, parentDirectory, targetDirectory });
}
// ─────────────── folders ───────────────
async createFolder(groupId: number, name: string, parentId = '/'): Promise<void> {
const bridge = asBridge(this.ctx);
const env = makeOidbEnvelope<OidbGroupFileFolderReq>(
0x6D7, 0,
{
create: {
groupUin: groupId,
rootDirectory: normalizeDirectory(parentId),
folderName: name,
},
},
true,
);
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d7_0', protobuf_encode<OidbBase<OidbGroupFileFolderReq>>(env));
const resp = protobuf_decode<OidbBase<OidbGroupFileFolderResp>>(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);
createFolder(groupId: number, name: string, parentId = '/'): Promise<void> {
return CreateGroupFolder.invoke(this.ctx, {
groupId, parentId: normalizeDirectory(parentId), folderName: name,
});
}
async deleteFolder(groupId: number, folderId: string): Promise<void> {
const bridge = asBridge(this.ctx);
const env = makeOidbEnvelope<OidbGroupFileFolderReq>(
0x6D7, 1,
{
delete: {
groupUin: groupId,
folderId,
},
},
true,
);
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d7_1', protobuf_encode<OidbBase<OidbGroupFileFolderReq>>(env));
const resp = protobuf_decode<OidbBase<OidbGroupFileFolderResp>>(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);
deleteFolder(groupId: number, folderId: string): Promise<void> {
return DeleteGroupFolder.invoke(this.ctx, { groupId, folderId });
}
async renameFolder(groupId: number, folderId: string, newFolderName: string): Promise<void> {
const bridge = asBridge(this.ctx);
const env = makeOidbEnvelope<OidbGroupFileFolderReq>(
0x6D7, 2,
{
rename: {
groupUin: groupId,
folderId,
newFolderName,
},
},
true,
);
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d7_2', protobuf_encode<OidbBase<OidbGroupFileFolderReq>>(env));
const resp = protobuf_decode<OidbBase<OidbGroupFileFolderResp>>(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);
renameFolder(groupId: number, folderId: string, newFolderName: string): Promise<void> {
return RenameGroupFolder.invoke(this.ctx, { groupId, folderId, newFolderName });
}
// ─────────────── rich-media URL by node ───────────────
async getPttUrl(groupId: number, node: MediaIndexNode): Promise<string> {
const bridge = asBridge(this.ctx);
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 } },
},
});
getPttUrl(groupId: number, node: MediaIndexNode): Promise<string> {
return GetGroupPttUrl.invoke(this.ctx, { groupId, node });
}
async getPrivatePttUrl(node: MediaIndexNode): Promise<string> {
const bridge = asBridge(this.ctx);
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 } },
},
});
return GetPrivatePttUrl.invoke(this.ctx, { selfUid, node });
}
async getVideoUrl(groupId: number, node: MediaIndexNode): Promise<string> {
const bridge = asBridge(this.ctx);
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 } },
},
});
getVideoUrl(groupId: number, node: MediaIndexNode): Promise<string> {
return GetGroupVideoUrl.invoke(this.ctx, { groupId, node });
}
async getPrivateVideoUrl(node: MediaIndexNode): Promise<string> {
const bridge = asBridge(this.ctx);
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 } },
},
});
return GetPrivateVideoUrl.invoke(this.ctx, { selfUid, node });
}
}
+1 -20
View File
@@ -1,23 +1,3 @@
// ApiHub — the per-instance bag of typed Api classes hanging off
// `bridge.apis`. Mirrors NapCat's `NapCatCore.apis = { MsgApi, …}`
// pattern but uses camelCase keys (`apis.message.sendGroup`) to match
// the rest of the SnowLuma TypeScript style.
//
// Each Api class is constructed once when the parent `Bridge` is
// constructed (eager — every account that connects gets its own
// `apis.*` set immediately). Api classes receive a `BridgeContext`
// reference, NOT the concrete `Bridge`, so they remain easy to mock
// without standing up a full Bridge instance.
//
// Adding a new Api:
// 1. Create `bridge/apis/<name>.ts` exporting a `class XxxApi`.
// 2. Add a property here.
// 3. Construct it inside `buildApiHub(ctx)` below.
// 4. Move the relevant methods OFF Bridge and onto the new Api.
//
// All 12 Api hubs are now live (#6 commits 1-12). The interface lists
// every typed area an OneBot caller can reach via `bridge.apis.*`.
import type { BridgeContext } from '../bridge-context';
import { ContactsApi } from './contacts';
import { ExtrasApi } from './extras';
@@ -99,3 +79,4 @@ export { MessageApi } from './message';
export { MiscApi } from './misc';
export { ProfileApi } from './profile';
export { WebApi } from './web';
+45 -72
View File
@@ -1,70 +1,43 @@
// InteractionApi — interactive engagement primitives (poke / like /
// reaction / essence / emoji-like-list). Inlined from
// `actions/interaction.ts` + the lone-survivor `setGroupEssence` from
// `actions/group-message.ts` (both deleted alongside actions/* in
// commit 13). The recall+markRead halves of `group-message.ts` were
// already absorbed into `MessageApi` back in commit 1.
// InteractionApi — facade over interactive-engagement OIDB cmds
// (poke / like / reaction / essence / emoji-like-list). Every method
// is a one-line forwarder to a self-contained namespace under
// @snowluma/protocol/oidb-services. The facade exists purely to keep
// the `bridge.apis.interaction.X(...)` ergonomic call style; all wire
// work (envelope build / encode / send / decode) lives in the
// namespace files.
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
Oidb0x9083Req,
Oidb0x9083Resp,
OidbEssence,
OidbGroupReaction,
OidbLike,
OidbPoke,
} from '@snowluma/proto-defs/oidb-actions/base';
import { SendLike } from '@snowluma/protocol/oidb-services/interaction/send-like';
import { SendPoke } from '@snowluma/protocol/oidb-services/interaction/send-poke';
import { SetEssence } from '@snowluma/protocol/oidb-services/interaction/set-essence';
import { FetchReactionSummary } from '@snowluma/protocol/oidb-services/reaction/fetch-reaction-summary';
import { GetEmojiLikes } from '@snowluma/protocol/oidb-services/reaction/get-emoji-likes';
import { SetReaction } from '@snowluma/protocol/oidb-services/reaction/set-reaction';
import type { BridgeContext } from '../bridge-context';
import type { Bridge } from '../bridge';
import { makeOidbEnvelope, runOidb } from '@snowluma/bridge/bridge-oidb';
function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; }
export class InteractionApi {
constructor(private readonly ctx: BridgeContext) {}
constructor(private readonly ctx: BridgeContext) { }
async sendPoke(isGroup: boolean, peerUin: number, targetUin?: number): Promise<void> {
const bridge = asBridge(this.ctx);
const env = makeOidbEnvelope<OidbPoke>(0xED3, 1, {
uin: targetUin ?? peerUin,
groupUin: isGroup ? peerUin : 0,
friendUin: isGroup ? 0 : peerUin,
ext: 0,
});
await runOidb(bridge, 'OidbSvcTrpcTcp.0xed3_1', protobuf_encode<OidbBase<OidbPoke>>(env));
sendPoke(isGroup: boolean, peerUin: number, targetUin?: number): Promise<void> {
return SendPoke.invoke(this.ctx, { isGroup, peerUin, targetUin });
}
async sendLike(userId: number, count: number): Promise<void> {
const bridge = asBridge(this.ctx);
const env = makeOidbEnvelope<OidbLike>(0x7E5, 104, { targetUin: userId, count });
await runOidb(bridge, 'OidbSvcTrpcTcp.0x7e5_104', protobuf_encode<OidbBase<OidbLike>>(env));
sendLike(userId: number, count: number): Promise<void> {
return SendLike.invoke(this.ctx, { userId, count });
}
async setReaction(groupId: number, sequence: number, code: string, isSet: boolean): Promise<void> {
const bridge = asBridge(this.ctx);
const subCmd = isSet ? 1 : 2;
const cmd = isSet ? 'OidbSvcTrpcTcp.0x9082_1' : 'OidbSvcTrpcTcp.0x9082_2';
// Same heuristic Lagrange.Core V2 uses (`GroupAddReactionEvent.IsEmoji`):
// QQ face ids are 1–3 digits ("76") → type=1, unicode codepoints are
// longer ("128516") → type=2. Server reads the type at field 5; sending
// it at the wrong field number triggers
// "invalid ReqBody.EmojiType: value must be greater than 0".
const type = code.length > 3 ? 2 : 1;
const env = makeOidbEnvelope<OidbGroupReaction>(0x9082, subCmd, {
groupUin: groupId, sequence, code, type, field6: false, field7: false,
});
await runOidb(bridge, cmd, protobuf_encode<OidbBase<OidbGroupReaction>>(env));
setReaction(groupId: number, sequence: number, code: string, isSet: boolean): Promise<void> {
return SetReaction.invoke(this.ctx, { groupId, sequence, code, isSet });
}
async setEssence(groupId: number, sequence: number, random: number, enable: boolean): Promise<void> {
const bridge = asBridge(this.ctx);
const subCmd = enable ? 1 : 2;
const cmd = enable ? 'OidbSvcTrpcTcp.0xeac_1' : 'OidbSvcTrpcTcp.0xeac_2';
const env = makeOidbEnvelope<OidbEssence>(0xEAC, subCmd, { groupUin: groupId, sequence, random });
await runOidb(bridge, cmd, protobuf_encode<OidbBase<OidbEssence>>(env));
setEssence(groupId: number, sequence: number, random: number, enable: boolean): Promise<void> {
return SetEssence.invoke(this.ctx, { groupId, sequence, random, enable });
}
/**
* Legacy stub: see `GetEmojiLikes` namespace comment for why this
* SSO path can never surface the user list. Real data lives in
* ReactionStore on the OneBot side.
*/
async getEmojiLikes(
groupId: number,
sequence: number,
@@ -73,23 +46,23 @@ export class InteractionApi {
count = 10,
cookie = '',
): Promise<{ users: Array<{ uin: number }>; cookie: string; isLast: boolean }> {
const bridge = asBridge(this.ctx);
const req: any = {
groupId: BigInt(groupId),
sequence,
emojiType,
emojiId,
cookie: cookie ? Buffer.from(cookie, 'base64') : new Uint8Array(0),
field7: 0,
count,
field12: 1,
};
const env = makeOidbEnvelope<Oidb0x9083Req>(0x9083, 1, req);
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x9083_1', protobuf_encode<OidbBase<Oidb0x9083Req>>(env));
const resp = protobuf_decode<OidbBase<Oidb0x9083Resp>>(respBytes).body;
const uin = resp?.inner?.userInfo?.uin;
const users = uin ? [{ uin: Number(uin) }] : [];
const respCookie = resp?.cookie ? Buffer.from(resp.cookie).toString('base64') : '';
return { users, cookie: respCookie, isLast: !respCookie };
try {
return await GetEmojiLikes.invoke(this.ctx, { groupId, sequence, emojiId, emojiType, count, cookie });
} catch {
return { users: [], cookie: '', isLast: true };
}
}
/**
* Fetch the per-emoji reaction summary on a group message via
* 0x9084_1 — emoji_id + reactor count + last-reaction timestamp.
* Cross-checked against the local ReactionStore cache for callers
* that need to detect cache gaps.
*/
fetchReactionSummary(
groupId: number,
sequence: number,
): Promise<Array<{ emojiId: string; emojiType: number; count: number; lastReactionTime: number }>> {
return FetchReactionSummary.invoke(this.ctx, { groupId, sequence });
}
}
+6 -19
View File
@@ -1,17 +1,3 @@
// MessageApi — send / recall / mark-read operations.
//
// Folds together the previous shapes:
// - `Bridge.sendGroupMessage` / `sendPrivateMessage` / `sendC2cFileMessage`
// (formerly inline on the Bridge class).
// - `actions/group-message.ts` (recallGroup / recallPrivate /
// markGroupRead / markPrivateRead).
//
// All implementations are inlined here — the previous indirection
// through `actions/group-message.ts` exported functions was just
// `(bridge, args) → method body`; once methods live on a typed Api
// class the wrapper layer doesn't earn its keep.
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type {
SendMessageRequest,
SendMessageResponse,
@@ -22,8 +8,9 @@ import type {
GroupRecallRequest,
SsoReadedReportReq,
} from '@snowluma/proto-defs/oidb-actions/base';
import type { MessageElement } from '@snowluma/bridge/events';
import { buildSendElems } from '@snowluma/bridge/element-builder';
import { buildSendElems } from '@snowluma/protocol/element-builder';
import type { MessageElement } from '@snowluma/protocol/events';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { BridgeContext } from '../bridge-context';
// `Bridge` is imported as a type only so we can narrow `ctx` back to
// the concrete Bridge instance when passing it to `buildSendElems`
@@ -38,7 +25,7 @@ import type { Bridge, SendMessageReceipt } from '../bridge';
const SEND_MSG_CMD = 'MessageSvc.PbSendMsg';
export class MessageApi {
constructor(private readonly ctx: BridgeContext) {}
constructor(private readonly ctx: BridgeContext) { }
/**
* Send a message to a QQ group.
@@ -68,7 +55,7 @@ export class MessageApi {
richText: {
elems: protoElems,
},
} as any,
},
clientSequence: 0,
random,
syncCookie: new Uint8Array(0),
@@ -130,7 +117,7 @@ export class MessageApi {
richText: {
elems: protoElems,
},
} as any,
},
clientSequence: clientSeq,
random,
syncCookie: new Uint8Array(0),
+16 -84
View File
@@ -1,54 +1,23 @@
// MiscApi — odds & ends that don't fit the other Apis: translation,
// mini-app ARK build, inline-keyboard button click, group sign-in.
// Inlined from `actions/misc.ts` (deleted alongside actions/* in
// commit 13).
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { JsonObject, JsonValue } from '@snowluma/common/json';
import type {
MiniAppShareReq,
MiniAppShareResp,
Oidb0x112eReq,
Oidb0x112eResp,
Oidb0x990Req,
Oidb0x990Resp,
Oidb0xeb7Req,
Oidb0xeb7Resp,
} from '@snowluma/proto-defs/oidb-actions/base';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { BridgeContext } from '../bridge-context';
import type { Bridge } from '../bridge';
import { makeOidbEnvelope, runOidb } from '@snowluma/bridge/bridge-oidb';
function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; }
// Migrated OIDB cmds — facade methods are one-line forwarders.
import { ClickInlineKeyboardButton } from '@snowluma/protocol/oidb-services/misc/click-inline-keyboard-button';
import { SendGroupSign } from '@snowluma/protocol/oidb-services/misc/send-group-sign';
import { TranslateEnToZh } from '@snowluma/protocol/oidb-services/misc/translate-en-to-zh';
export class MiscApi {
constructor(private readonly ctx: BridgeContext) {}
constructor(private readonly ctx: BridgeContext) { }
async translateEn2Zh(words: string[]): Promise<string[]> {
const bridge = asBridge(this.ctx);
const req = {
translateReq: {
srcLang: 'en',
dstLang: 'zh',
words,
},
tag10: 1,
tag12: 1,
};
const env = makeOidbEnvelope<Oidb0x990Req>(0x990, 2, req);
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x990_2', protobuf_encode<OidbBase<Oidb0x990Req>>(env));
const result = protobuf_decode<OidbBase<Oidb0x990Resp>>(respBytes).body;
const resp = result?.translateResp;
if (!resp) {
throw new Error('translate response empty');
}
return resp.dstWords || [];
translateEn2Zh(words: string[]): Promise<string[]> {
return TranslateEnToZh.invoke(this.ctx, { words });
}
async getMiniAppArk(type: string, title: string, desc: string, picUrl: string, jumpUrl: string): Promise<any> {
async getMiniAppArk(type: string, title: string, desc: string, picUrl: string, jumpUrl: string): Promise<JsonObject> {
let appid = '1109937557'; // default: bilibili
let iconUrl = 'http://miniapp.gtimg.cn/public/appicon/51f90239b78a2e4994c11215f4c4ba15_200.jpg';
@@ -77,7 +46,7 @@ export class MiscApi {
throw new Error('mini app share json empty');
}
const parsed = JSON.parse(jsonStr);
const parsed = JSON.parse(jsonStr) as Record<string, JsonObject | string | number | boolean | null>;
return {
data: {
@@ -93,54 +62,17 @@ export class MiscApi {
};
}
async clickInlineKeyboardButton(
clickInlineKeyboardButton(
groupId: number,
botAppid: number,
buttonId: string,
callbackData: string,
msgSeq: number,
): Promise<any> {
const bridge = asBridge(this.ctx);
const req = {
botAppid: BigInt(botAppid),
msgSeq: BigInt(msgSeq),
buttonId: String(buttonId),
callbackData: String(callbackData || ''),
unknown7: 0,
groupId: BigInt(groupId),
unknown9: 1,
};
const env = makeOidbEnvelope<Oidb0x112eReq>(0x112E, 1, req);
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x112e_1', protobuf_encode<OidbBase<Oidb0x112eReq>>(env));
const result = protobuf_decode<OidbBase<Oidb0x112eResp>>(respBytes).body;
if (!result) {
throw new Error('click inline keyboard button result empty');
}
return {
result: Number(result.result || 0),
errMsg: result.errMsg || '',
status: 0,
promptText: result.promptText || '',
promptType: 0,
promptIcon: 0,
};
): Promise<JsonValue> {
return ClickInlineKeyboardButton.invoke(this.ctx, { groupId, botAppid, buttonId, callbackData, msgSeq });
}
async sendGroupSign(groupId: number): Promise<void> {
const bridge = asBridge(this.ctx);
const req = {
signInInfo: {
uin: String(this.ctx.identity.uin),
groupId: String(groupId),
version: '9.0.90',
},
};
const env = makeOidbEnvelope<Oidb0xeb7Req>(0xEB7, 1, req);
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xEB7_1', protobuf_encode<OidbBase<Oidb0xeb7Req>>(env));
protobuf_decode<OidbBase<Oidb0xeb7Resp>>(respBytes);
sendGroupSign(groupId: number): Promise<void> {
return SendGroupSign.invoke(this.ctx, { groupId });
}
}
+23 -144
View File
@@ -1,36 +1,25 @@
// ProfileApi — personal profile + status + avatar + likes + custom
// faces + unidirectional friend list. Inlined from
// `actions/profile.ts` (deleted alongside actions/* in commit 13).
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
FaceroamOpReq,
FaceroamOpResp,
GroupAvatarExtra,
Oidb0x112aReq,
Oidb0x112aResp,
Oidb0x7edReq,
Oidb0x7edResp,
Oidb0xcd4Req,
Oidb0xcd4Resp,
Oidb0xe17Req,
Oidb0xe17Resp,
OidbSetProfile,
SetStatusReq,
SetStatusResp,
} from '@snowluma/proto-defs/oidb-actions/base';
import type { BridgeContext } from '../bridge-context';
import { fetchHighwaySession, uploadHighwayHttp } from '@snowluma/protocol/highway';
import { computeHashes, loadBinarySource } from '@snowluma/protocol/highway/utils';
import { GetLike, type LikeInfo } from '@snowluma/protocol/oidb-services/profile/get-like';
import { GetUnidirectionalFriendList, type UnidirectionalFriendEntry } from '@snowluma/protocol/oidb-services/profile/get-unidirectional-friend-list';
import { SetInputStatus } from '@snowluma/protocol/oidb-services/profile/set-input-status';
import { SetProfile } from '@snowluma/protocol/oidb-services/profile/set-profile';
import { SetSelfLongNick } from '@snowluma/protocol/oidb-services/profile/set-self-long-nick';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { Bridge } from '../bridge';
import { makeOidbEnvelope, runOidb } from '@snowluma/bridge/bridge-oidb';
import { fetchHighwaySession, uploadHighwayHttp } from '@snowluma/bridge/highway';
import { computeHashes, loadBinarySource } from '@snowluma/bridge/highway/utils';
import { resolveSelfUid } from './shared';
import type { BridgeContext } from '../bridge-context';
function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; }
export class ProfileApi {
constructor(private readonly ctx: BridgeContext) {}
constructor(private readonly ctx: BridgeContext) { }
// ─────────────── status / profile setters ───────────────
@@ -80,64 +69,16 @@ export class ProfileApi {
}
}
async setProfile(nickname?: string, personalNote?: string): Promise<void> {
const bridge = asBridge(this.ctx);
const uin = BigInt(this.ctx.identity.uin);
const stringProfiles: any[] = [];
const intProfiles: any[] = [];
if (nickname !== undefined) {
stringProfiles.push({ fieldId: 20002, value: nickname });
}
if (personalNote !== undefined) {
stringProfiles.push({ fieldId: 102, value: personalNote });
}
if (stringProfiles.length === 0 && intProfiles.length === 0) {
return;
}
const req = { uin, stringProfiles };
const env = makeOidbEnvelope<OidbSetProfile>(0x112A, 2, req);
await runOidb(bridge, 'OidbSvcTrpcTcp.0x112a_2', protobuf_encode<OidbBase<OidbSetProfile>>(env));
setProfile(nickname?: string, personalNote?: string): Promise<void> {
return SetProfile.invoke(this.ctx, { nickname, personalNote });
}
async setSelfLongNick(longNick: string): Promise<void> {
const bridge = asBridge(this.ctx);
const req = {
uin: BigInt(this.ctx.identity.uin),
profile: {
tag: 102,
value: String(longNick),
},
};
const env = makeOidbEnvelope<Oidb0x112aReq>(0x112A, 2, req);
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x112a_2', protobuf_encode<OidbBase<Oidb0x112aReq>>(env));
// Decode just to maintain the original behaviour of "consume the response".
protobuf_decode<OidbBase<Oidb0x112aResp>>(respBytes);
setSelfLongNick(longNick: string): Promise<void> {
return SetSelfLongNick.invoke(this.ctx, { longNick });
}
async setInputStatus(userId: number, eventType: number): Promise<void> {
const bridge = asBridge(this.ctx);
const targetUid = await this.ctx.resolveUserUid(userId);
if (!targetUid) {
throw new Error('target uid not found');
}
const req = {
reqBody: {
uid: targetUid,
chatType: 0,
eventType,
},
};
const env = makeOidbEnvelope<Oidb0xcd4Req>(0xCD4, 1, req);
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xcd4_1', protobuf_encode<OidbBase<Oidb0xcd4Req>>(env));
protobuf_decode<OidbBase<Oidb0xcd4Resp>>(respBytes);
setInputStatus(userId: number, eventType: number): Promise<void> {
return SetInputStatus.invoke(this.ctx, { userId, eventType });
}
async setAvatar(source: string): Promise<void> {
@@ -179,74 +120,12 @@ export class ProfileApi {
// ─────────────── queries on me / my contacts ───────────────
async getLike(userId?: number, start = 0, limit = 10): Promise<any> {
const bridge = asBridge(this.ctx);
const isSelf = !userId;
const targetUid = isSelf
? await resolveSelfUid(bridge)
: await this.ctx.resolveUserUid(userId);
if (!targetUid) {
throw new Error('target uid not found');
}
const req = {
targetUid,
basic: 1,
vote: 1,
favorite: 1,
start,
limit,
};
const env = makeOidbEnvelope<Oidb0x7edReq>(0x7ED, 12, req);
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x7ed_12', protobuf_encode<OidbBase<Oidb0x7edReq>>(env));
const result = protobuf_decode<OidbBase<Oidb0x7edResp>>(respBytes).body;
const data = result?.userLikeInfos?.[0];
if (!data) {
throw new Error('get profile like info empty');
}
return {
uid: data.uid,
time: Number(data.time),
favoriteInfo: {
total_count: data.favoriteInfo?.totalCount || 0,
last_time: Number(data.favoriteInfo?.lastTime || 0),
today_count: data.favoriteInfo?.newCount || 0,
userInfos: [],
},
voteInfo: {
total_count: data.voteInfo?.totalCount || 0,
new_count: data.voteInfo?.newCount || 0,
new_nearby_count: 0,
last_visit_time: Number(data.voteInfo?.lastTime || 0),
userInfos: [],
},
};
getLike(userId?: number, start = 0, limit = 10): Promise<LikeInfo> {
return GetLike.invoke(this.ctx, { userId, start, limit });
}
async getUnidirectionalFriendList(): Promise<any> {
const bridge = asBridge(this.ctx);
const reqObj = {
uint64_uin: String(this.ctx.identity.uin),
uint64_top: 0,
uint32_req_num: 99,
bytes_cookies: '',
};
const req = { jsonBody: JSON.stringify(reqObj) };
const env = makeOidbEnvelope<Oidb0xe17Req>(0xE17, 0, req);
const respBytes = await runOidb(bridge, 'MQUpdateSvc_com_qq_ti.web.OidbSvc.0xe17_0', protobuf_encode<OidbBase<Oidb0xe17Req>>(env));
const result = protobuf_decode<OidbBase<Oidb0xe17Resp>>(respBytes).body;
if (!result || !result.jsonBody) {
throw new Error('get unidirectional friend list empty');
}
const parsed = JSON.parse(result.jsonBody);
return parsed.rpt_block_list || [];
getUnidirectionalFriendList(): Promise<UnidirectionalFriendEntry[]> {
return GetUnidirectionalFriendList.invoke(this.ctx);
}
async fetchCustomFace(count = 10): Promise<string[]> {
@@ -262,10 +141,10 @@ export class ProfileApi {
throw new Error(result.errorMessage || 'fetch custom face failed');
}
const resp = protobuf_decode<FaceroamOpResp>(result.responseData);
if (!resp || (resp as any).retCode !== 0) {
throw new Error(`fetch custom face error: ${(resp as any)?.message || 'unknown'}`);
if (!resp || resp.retCode !== 0) {
throw new Error(`fetch custom face error: ${resp?.message || 'unknown'}`);
}
const faceIds = (resp as any).item?.faceIds || [];
const faceIds = resp.item?.faceIds || [];
return faceIds.slice(0, count).map((id: string) => `https://p.qpic.cn/qq_expression/${this.ctx.identity.uin}/${id}/0`);
}
}
-5
View File
@@ -1,10 +1,5 @@
import type { Bridge } from '../bridge';
/**
* Coerce numbers, strings, and bigints to a plain integer.
* Returns 0 for anything we can't interpret — every action that
* threads this through OIDB has an explicit `<=0` validation later.
*/
export function toInt(value: unknown): number {
if (typeof value === 'number' && Number.isFinite(value)) return Math.trunc(value);
if (typeof value === 'bigint') {
+46 -63
View File
@@ -1,72 +1,55 @@
// WebApi — cookie-backed HTTP wrappers (group essence / honor / notice /
// client-key / pskey / csrf-token / credentials). Inlined from the
// per-feature files in `web-actions/` (all deleted in commit 13).
// The pure HTTP transport stays in `web/*.ts` and stays unchanged —
// only the Bridge-binding helpers move here.
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
OidbClientKeyReq,
OidbClientKeyResp,
OidbGetPskeyReq,
OidbGetPskeyResp,
} from '@snowluma/proto-defs/oidb-actions/base';
import type { BridgeContext } from '../bridge-context';
import type { Bridge } from '../bridge';
import { makeOidbEnvelope, runOidb } from '@snowluma/bridge/bridge-oidb';
import { getGroupEssenceMsg, getGroupEssenceMsgAll } from '@snowluma/bridge/web/group-essence';
import { getHonorListWebAPI, WebHonorType } from '@snowluma/bridge/web/group-honor';
import { ForceFetchClientKey, type ClientKeyInfo as NamespaceClientKeyInfo } from '@snowluma/protocol/oidb-services/web/force-fetch-client-key';
import { GetPskey } from '@snowluma/protocol/oidb-services/web/get-pskey';
import { getGroupEssenceMsg, getGroupEssenceMsgAll, type GroupEssenceMsgRet } from '@snowluma/protocol/web/group-essence';
import { getHonorListWebAPI, WebHonorType, type WebHonorItem } from '@snowluma/protocol/web/group-honor';
import {
deleteGroupNotice as deleteGroupNoticeHttp,
getGroupNoticeWebAPI,
setGroupNoticeWebAPI,
uploadGroupNoticeImage,
} from '@snowluma/bridge/web/group-notice';
import { RequestUtil } from '@snowluma/bridge/web/request-util';
type SetNoticeRetSuccess,
} from '@snowluma/protocol/web/group-notice';
import { RequestUtil } from '@snowluma/protocol/web/request-util';
import type { Bridge } from '../bridge';
import type { BridgeContext } from '../bridge-context';
function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; }
export interface ClientKeyInfo {
clientKey: string;
keyIndex: string;
expireTime: string;
export type ClientKeyInfo = NamespaceClientKeyInfo;
export interface WebHonorInfo {
[key: string]: import('@snowluma/common/json').JsonValue;
group_id: number;
current_talkative: WebHonorItem | null;
talkative_list: WebHonorItem[];
performer_list: WebHonorItem[];
legend_list: WebHonorItem[];
emotion_list: WebHonorItem[];
strong_newbie_list: WebHonorItem[];
}
export interface WebNoticeInfo {
[key: string]: import('@snowluma/common/json').JsonValue;
notice_id: string;
sender_id: number;
publish_time: number;
message: {
text: string;
image: Array<{ id: string; height: number; width: number }>;
images: Array<{ id: string; height: number; width: number }>;
};
settings: import('@snowluma/common/json').JsonValue;
read_num: number;
}
// ─────────────── private helpers (cookie acquisition) ───────────────
async function forceFetchClientKeyInner(bridge: Bridge): Promise<ClientKeyInfo> {
const env = makeOidbEnvelope<OidbClientKeyReq>(0x102A, 1, {});
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x102a_1', protobuf_encode<OidbBase<OidbClientKeyReq>>(env));
const resp = protobuf_decode<OidbBase<OidbClientKeyResp>>(respBytes).body;
const clientKey = resp?.clientKey || '';
// keyIndex falls back to "19" — origin unknown but the value is what
// every NapCat-derived implementation uses when the server omits it.
const keyIndex = String(resp?.keyIndex || '19');
return {
clientKey,
keyIndex,
expireTime: String(resp?.expireTime || '1800'),
};
function forceFetchClientKeyInner(bridge: Bridge): Promise<ClientKeyInfo> {
return ForceFetchClientKey.invoke(bridge);
}
async function getPSkey(bridge: Bridge, domainList: string[]): Promise<{ domainPskeyMap: Map<string, string> }> {
const env = makeOidbEnvelope<OidbGetPskeyReq>(0x102A, 0, { domainList });
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x102a_0', protobuf_encode<OidbBase<OidbGetPskeyReq>>(env));
const resp = protobuf_decode<OidbBase<OidbGetPskeyResp>>(respBytes).body;
const domainPskeyMap = new Map<string, string>();
if (resp?.pskeyItems && Array.isArray(resp.pskeyItems)) {
for (const item of resp.pskeyItems) {
if (item.domain && item.pskey) {
domainPskeyMap.set(item.domain, item.pskey);
}
}
}
return { domainPskeyMap };
function getPSkey(bridge: Bridge, domainList: string[]): Promise<{ domainPskeyMap: Map<string, string> }> {
return GetPskey.invoke(bridge, { domainList });
}
async function getCookies(bridge: Bridge, domain: string): Promise<Record<string, string>> {
@@ -136,7 +119,7 @@ function getBknFromSKey(skey: string): number {
}
export class WebApi {
constructor(private readonly ctx: BridgeContext) {}
constructor(private readonly ctx: BridgeContext) { }
// ─────────────── cookie / token primitives ───────────────
@@ -187,7 +170,7 @@ export class WebApi {
// ─────────────── group essence ───────────────
/** Paginated fetch — `pageStart` is 0-indexed, `pageLimit` is server-capped at 50. */
async getEssence(groupId: number, pageStart = 0, pageLimit = 50): Promise<any> {
async getEssence(groupId: number, pageStart = 0, pageLimit = 50): Promise<GroupEssenceMsgRet> {
const bridge = asBridge(this.ctx);
const groupCode = groupId.toString();
const cookieObject = await getCookies(bridge, 'qun.qq.com');
@@ -196,7 +179,7 @@ export class WebApi {
}
/** Walks every page and returns the concatenated result. */
async getEssenceAll(groupId: number): Promise<any> {
async getEssenceAll(groupId: number): Promise<GroupEssenceMsgRet[]> {
const bridge = asBridge(this.ctx);
const groupCode = groupId.toString();
const cookieObject = await getCookies(bridge, 'qun.qq.com');
@@ -205,12 +188,12 @@ export class WebApi {
// ─────────────── group honor ───────────────
async getHonorInfo(groupId: number, type: WebHonorType | string): Promise<any> {
async getHonorInfo(groupId: number, type: WebHonorType | string): Promise<WebHonorInfo> {
const bridge = asBridge(this.ctx);
const groupCode = groupId.toString();
const cookieObject = await getCookies(bridge, 'qun.qq.com');
const honorInfo: any = {
const honorInfo: WebHonorInfo = {
group_id: groupId,
current_talkative: null,
talkative_list: [],
@@ -254,7 +237,7 @@ export class WebApi {
type?: number;
confirm_required?: number;
},
): Promise<any> {
): Promise<SetNoticeRetSuccess> {
const bridge = asBridge(this.ctx);
const groupCode = groupId.toString();
const cookieObject = await getCookies(bridge, 'qun.qq.com');
@@ -304,7 +287,7 @@ export class WebApi {
return ret;
}
async getNotice(groupId: number): Promise<any[]> {
async getNotice(groupId: number): Promise<WebNoticeInfo[]> {
const bridge = asBridge(this.ctx);
const groupCode = groupId.toString();
const cookieObject = await getCookies(bridge, 'qun.qq.com');
@@ -314,7 +297,7 @@ export class WebApi {
throw new Error('获取公告失败');
}
const retNotices: any[] = [];
const retNotices: WebNoticeInfo[] = [];
if (ret.feeds) {
for (const key in ret.feeds) {
+2 -21
View File
@@ -1,27 +1,8 @@
// Api-layer extension of @snowluma/bridge's slim BridgeContext.
//
// The slim interface in @snowluma/bridge has the protocol-layer
// surface (identity / events / sendRawPacket / resolveUserUid / next*
// sequence helpers / upload-metadata cache). This file extends it
// with `apis: ApiHub` — the typed bag of Api classes that lives ONLY
// in @snowluma/core, so the bridge package never sees it (avoiding
// a bridge → core cycle).
//
// The 13 Api classes (apis/<area>.ts) import `BridgeContext` from
// here, which gives them `this.ctx.apis.message.sendGroup(...)` type-
// safety alongside the protocol-layer fields. Highway uploaders,
// element-builder, msg-push parsers (all in @snowluma/bridge) import
// the slim version directly from `@snowluma/bridge/bridge-context`.
import type { BridgeContext as BaseBridgeContext } from '@snowluma/bridge/bridge-context';
import type { BridgeContext as BaseBridgeContext } from '@snowluma/protocol/bridge-context';
import type { ApiHub } from './apis';
export interface BridgeContext extends BaseBridgeContext {
readonly apis: ApiHub;
}
export type { UploadedFileMeta } from '@snowluma/protocol/bridge-context';
// Re-export `UploadedFileMeta` from the slim package so existing
// `import type { UploadedFileMeta } from '<…>/bridge-context'` (or
// from bridge.ts via re-export) keeps working without callers having
// to learn the new package path.
export type { UploadedFileMeta } from '@snowluma/bridge/bridge-context';
@@ -1,22 +1,5 @@
// BridgeInterface — the public Bridge surface for OneBot-side
// consumers. Slimmed down to BridgeContext + the few extra fields
// OneBot reaches into directly (most notably `activePid`).
//
// Most OneBot code paths reach business methods through
// `bridge.apis.<area>.method()` — those types come from `ApiHub`
// inside `bridge-context.ts`. The remaining members below are the
// non-Api state that doesn't fit into a typed Api hub.
//
// Internal Api implementations should depend on `BridgeContext`
// instead (the narrower contract). `BridgeInterface` is for callers
// that need the activePid hook or for backwards compatibility with
// pre-#6 code that imported `BridgeInterface` as the bridge type.
import type { BridgeContext } from './bridge-context';
export interface BridgeInterface extends BridgeContext {
/** Last-active process id — used by `OneBotManager` to thread
* per-process state into the right instance. `null` when no
* process has bound yet. */
readonly activePid: number | null;
}
+136 -259
View File
@@ -1,45 +1,145 @@
import type { PacketSender, SendPacketResult } from '@snowluma/common/packet-sender';
import type { PacketInfo } from '@snowluma/common/protocol-types';
import type { BridgeInterface } from './bridge-interface';
import { IdentityService } from '@snowluma/bridge/identity-service';
import { MSG_PUSH_CMD, parseMsgPush } from '@snowluma/bridge/msg-push';
import { IncomingPacketPipeline, type CmdParser } from '@snowluma/bridge/packet-pipeline';
// qq-info types are no longer used directly in this file — they live
// inside the Api classes that own those fetches (apis/contacts.ts).
import { type ApiHub, buildApiHub } from './apis';
// Delegated modules
// Group-todo / stranger-status / AI-voice moved to apis/extras.ts.
// Public types stay re-exported through this file for backwards
// compatibility — the OneBot side imports them via `@snowluma/core`.
import { BridgeEventBus } from '@snowluma/protocol/event-bus';
import { IdentityService } from '@snowluma/protocol/identity-service';
import { MSG_PUSH_CMD, parseMsgPush } from '@snowluma/protocol/msg-push';
import { IncomingPacketPipeline, type CmdParser } from '@snowluma/protocol/packet-pipeline';
import { buildApiHub, type ApiHub } from './apis';
import {
AiVoiceChatType,
type AiVoiceCategory,
type StrangerStatus,
} from './apis/extras';
// actions/forward.ts removed — moved to apis/forward.ts::ForwardApi.
// actions/friend.ts removed — moved to apis/friend.ts::FriendApi.
// actions/group-admin.ts removed — moved to `apis/group-admin.ts::GroupAdminApi`.
// actions/group-album.ts removed — moved to `apis/group-album.ts::GroupAlbumApi`.
// Group file CRUD + private c2c upload + media URL resolvers moved to
// `apis.groupFile` (see `apis/group-file.ts::GroupFileApi`). The shared
// result type still lives here because the OneBot side imports it
// through bridge.ts.
import type { GroupFilesResult } from './apis/group-file';
// actions/group-message.ts removed — `setGroupEssence` moved to
// apis/interaction.ts::InteractionApi. The recall/markRead helpers
// were absorbed into MessageApi back in commit 1.
// actions/interaction.ts removed — sendPoke/sendLike/setReaction/
// getEmojiLikes moved to apis/interaction.ts::InteractionApi.
// actions/misc.ts removed — moved to apis/misc.ts::MiscApi.
// actions/profile.ts removed — moved to apis/profile.ts::ProfileApi.
// `bridge-contacts.ts` removed — its 6 functions are now methods on
// `apis.contacts` (see `apis/contacts.ts::ContactsApi`).
import { BridgeEventBus } from '@snowluma/bridge/event-bus';
// web-actions/* removed — moved to apis/web.ts::WebApi.
export { AiVoiceChatType };
export type { AiVoiceCategory, StrangerStatus };
import type { BridgeInterface } from './bridge-interface';
export class Bridge implements BridgeInterface {
readonly identity: IdentityService;
private pids_ = new Set<number>();
readonly events = new BridgeEventBus();
readonly apis: ApiHub;
private readonly pipeline: IncomingPacketPipeline;
private packetClient_: PacketSender | null = null;
private static readonly UPLOADED_FILE_CACHE_MAX = 1024;
private uploadedFileMeta_ = new Map<string, UploadedFileMeta>();
private clientSeq_ = 100000000 + (Date.now() % 1000000000);
private msgRandom_ = (Date.now() & 0xFFFFFFFF) >>> 0;
constructor(identity: IdentityService) {
this.identity = identity;
this.apis = buildApiHub(this);
this.identity.setFetcher({
fetchProfile: (uin) => this.apis.contacts.fetchUserProfile(uin),
fetchGroupMemberList: (gid) => this.apis.contacts.fetchGroupMemberList(gid),
});
this.pipeline = new IncomingPacketPipeline({
identity: this.identity,
events: this.events,
refreshMemberCache: (groupId, refreshGroupList, forceMemberList) =>
this.refreshMemberCache(groupId, refreshGroupList, forceMemberList),
resolveStrangerProfile: async (uid) => {
try {
const p = await this.apis.contacts.fetchUserProfileByUid(uid);
if (p.uin <= 0) return null;
return { uin: p.uin, nickname: p.nickname };
} catch {
return null;
}
},
resolveGroupJoinRequest: async (groupId, uid, subType) => {
try {
const requests = await this.apis.contacts.fetchGroupRequests();
const match = requests.find(r => {
if (r.groupId !== groupId) return false;
return subType === 'invite' ? r.invitorUid === uid : r.targetUid === uid;
});
if (!match) return null;
return { comment: match.comment, sequence: match.sequence };
} catch {
return null;
}
},
});
this.pipeline.registerCmd(MSG_PUSH_CMD, parseMsgPush);
}
dispose(): void {
this.identity.close();
this.events.clear();
}
setPacketClient(client: PacketSender): void {
this.packetClient_ = client;
}
registerCmd(cmd: string, parser: CmdParser): void {
this.pipeline.registerCmd(cmd, parser);
}
handlesCmd(cmd: string): boolean {
return this.pipeline.handlesCmd(cmd);
}
attachPid(pid: number): void {
this.pids_.add(pid);
}
detachPid(pid: number): void {
this.pids_.delete(pid);
}
hasPid(pid: number): boolean { return this.pids_.has(pid); }
get empty(): boolean { return this.pids_.size === 0; }
get activePid(): number | null {
for (const pid of this.pids_) return pid;
return null;
}
onPacket(pkt: PacketInfo): void {
this.pipeline.process(pkt);
}
private async refreshMemberCache(groupId: number, refreshGroupList: boolean, forceMemberList: boolean): Promise<boolean> {
if (refreshGroupList) {
try { await this.apis.contacts.fetchGroupList(); } catch { /* ignore */ }
}
if (!this.identity.findGroup(groupId)) return false;
await this.apis.contacts.fetchGroupMemberList(groupId, { force: forceMemberList });
return true;
}
rememberUploadedFile(meta: UploadedFileMeta): void {
if (!meta.fileId) return;
if (this.uploadedFileMeta_.size >= Bridge.UPLOADED_FILE_CACHE_MAX) {
// Map iteration order is insertion order — drop the oldest.
const oldest = this.uploadedFileMeta_.keys().next().value;
if (oldest !== undefined) this.uploadedFileMeta_.delete(oldest);
}
this.uploadedFileMeta_.set(meta.fileId, meta);
}
recallUploadedFile(fileId: string): UploadedFileMeta | undefined {
if (!fileId) return undefined;
return this.uploadedFileMeta_.get(fileId);
}
nextClientSequence(): number {
return ++this.clientSeq_;
}
nextMessageRandom(): number {
this.msgRandom_ = (this.msgRandom_ + 0x9E3779B9) >>> 0;
return this.msgRandom_ & 0x7FFFFFFF;
}
async sendRawPacket(serviceCmd: string, body: Uint8Array, timeoutMs = 15000): Promise<SendPacketResult> {
if (!this.packetClient_) {
return {
success: false, gotResponse: false, errorCode: -1,
errorMessage: 'no packet sender attached', responseData: null,
};
}
return this.packetClient_.sendPacket(serviceCmd, Buffer.from(body), timeoutMs);
}
async resolveUserUid(uin: number, groupId?: number): Promise<string> {
return this.identity.resolveUid(uin, groupId);
}
}
export interface SendMessageReceipt {
messageId: number;
sequence: number;
@@ -48,12 +148,6 @@ export interface SendMessageReceipt {
timestamp: number;
}
/**
* Metadata remembered after `upload_group_file` / `upload_private_file`
* succeeds. Lets the OneBot send-message path reconstruct the full
* payload when the caller only echoes the `file_id` back later. See
* `Bridge.rememberUploadedFile` / `recallUploadedFile`.
*/
export interface UploadedFileMeta {
fileId: string;
scope: 'group' | 'private';
@@ -84,223 +178,6 @@ export interface ClientKeyInfo {
expireTime: string;
keyIndex: string
}
export class Bridge implements BridgeInterface {
readonly identity: IdentityService;
private pids_ = new Set<number>();
/**
* Per-kind event subscription. Replaces the legacy single-callback
* firehose: downstream consumers now register exactly the kinds they
* care about and the pipeline fans out in parallel.
*/
readonly events = new BridgeEventBus();
/**
* Typed Api hub. Each entry is a class encapsulating one logical
* area of the QQ protocol (sending messages, group admin, file
* uploads, etc.). Built eagerly in the constructor — every Bridge
* instance gets its own `apis.*` set with `this` (typed as
* `BridgeContext`) injected. See `apis/index.ts`.
*/
readonly apis: ApiHub;
private readonly pipeline: IncomingPacketPipeline;
private packetClient_: PacketSender | null = null;
// (fetchGroupMemberList throttle cache moved to ContactsApi — same
// 60s TTL + inflight coalesce semantics, just owned by the Api class
// that exposes the method.)
// ── Uploaded-file metadata cache ────────────────────────────────────
//
// After a file goes through `upload_group_file` / `upload_private_file`
// we remember the (fileName, fileSize, fileMd5, fileHash) tuple keyed
// by the returned file_id. The OneBot send-message paths consult this
// when the caller later passes `{type:'file', file_id:'xxx'}` without
// the rest of the metadata — c2c file send needs the size/md5/name
// for the wire packet (server-side rejection / "0 byte file" otherwise),
// and the group send path falls back to the name for the log line.
//
// Bounded at ~1024 entries with simple FIFO eviction. Files older
// than 7 days expire on QQ's side anyway, so this isn't load-bearing
// for correctness — just a UX convenience cache so the OneBot caller
// doesn't have to thread the metadata themselves between upload and
// send_msg.
private static readonly UPLOADED_FILE_CACHE_MAX = 1024;
private uploadedFileMeta_ = new Map<string, UploadedFileMeta>();
// Sequence and random generators for outgoing messages
private clientSeq_ = 100000000 + (Date.now() % 1000000000);
private msgRandom_ = (Date.now() & 0xFFFFFFFF) >>> 0;
constructor(identity: IdentityService) {
this.identity = identity;
// Build Api hub FIRST — `setFetcher` below installs callbacks
// that reach into `this.apis.contacts.*`, so the hub must exist
// by the time those callbacks could fire. The Bridge instance IS
// the BridgeContext (Bridge implements BridgeInterface which
// includes the BridgeContext surface).
this.apis = buildApiHub(this);
this.identity.setFetcher({
fetchProfile: (uin) => this.apis.contacts.fetchUserProfile(uin),
fetchGroupMemberList: (gid) => this.apis.contacts.fetchGroupMemberList(gid),
});
this.pipeline = new IncomingPacketPipeline({
identity: this.identity,
events: this.events,
refreshMemberCache: (groupId, refreshGroupList, forceMemberList) =>
this.refreshMemberCache(groupId, refreshGroupList, forceMemberList),
});
this.pipeline.registerCmd(MSG_PUSH_CMD, parseMsgPush);
}
dispose(): void {
this.identity.close();
this.events.clear();
}
setPacketClient(client: PacketSender): void {
this.packetClient_ = client;
}
registerCmd(cmd: string, parser: CmdParser): void {
this.pipeline.registerCmd(cmd, parser);
}
handlesCmd(cmd: string): boolean {
return this.pipeline.handlesCmd(cmd);
}
// --- PID management ---
attachPid(pid: number): void {
this.pids_.add(pid);
}
detachPid(pid: number): void {
this.pids_.delete(pid);
}
hasPid(pid: number): boolean { return this.pids_.has(pid); }
get empty(): boolean { return this.pids_.size === 0; }
get activePid(): number | null {
for (const pid of this.pids_) return pid;
return null;
}
// --- Packet dispatch ---
onPacket(pkt: PacketInfo): void {
this.pipeline.process(pkt);
}
private async refreshMemberCache(groupId: number, refreshGroupList: boolean, forceMemberList: boolean): Promise<boolean> {
if (refreshGroupList) {
try { await this.apis.contacts.fetchGroupList(); } catch { /* ignore */ }
}
if (!this.identity.findGroup(groupId)) return false;
await this.apis.contacts.fetchGroupMemberList(groupId, { force: forceMemberList });
return true;
}
// --- Uploaded-file metadata cache ---
/**
* Remember a freshly-uploaded file so a later `send_*_msg` carrying
* just the file_id can reconstruct the full c2c-file packet (fileName
* / fileSize / fileMd5 are required by the QQ NT server's c2c file
* intake, even if only the uuid is needed for the OIDB lookup
* internally — without them the file shows as 0 B in the recipient's
* chat or is silently rejected). Insertion is FIFO; oldest entry is
* evicted when the cache hits `UPLOADED_FILE_CACHE_MAX`.
*/
rememberUploadedFile(meta: UploadedFileMeta): void {
if (!meta.fileId) return;
if (this.uploadedFileMeta_.size >= Bridge.UPLOADED_FILE_CACHE_MAX) {
// Map iteration order is insertion order — drop the oldest.
const oldest = this.uploadedFileMeta_.keys().next().value;
if (oldest !== undefined) this.uploadedFileMeta_.delete(oldest);
}
this.uploadedFileMeta_.set(meta.fileId, meta);
}
/**
* Recall metadata for a previously-uploaded file. Returns `undefined`
* if the file_id was never uploaded through this bridge instance, or
* if it's been evicted from the cache.
*/
recallUploadedFile(fileId: string): UploadedFileMeta | undefined {
if (!fileId) return undefined;
return this.uploadedFileMeta_.get(fileId);
}
// --- Sequence / random generators ---
//
// `public` (formerly `private`) because the Api classes in
// `apis/*.ts` need them to build `SendMessageRequest` packets. Part
// of the `BridgeContext` surface, so a third party that only sees
// `BridgeContext` can still synthesise wire packets without reaching
// into the concrete Bridge class.
nextClientSequence(): number {
return ++this.clientSeq_;
}
nextMessageRandom(): number {
this.msgRandom_ = (this.msgRandom_ + 0x9E3779B9) >>> 0;
return this.msgRandom_ & 0x7FFFFFFF;
}
// --- Send packet (raw) ---
async sendRawPacket(serviceCmd: string, body: Uint8Array, timeoutMs = 15000): Promise<SendPacketResult> {
if (!this.packetClient_) {
return {
success: false, gotResponse: false, errorCode: -1,
errorMessage: 'no packet sender attached', responseData: null,
};
}
return this.packetClient_.sendPacket(serviceCmd, Buffer.from(body), timeoutMs);
}
// `Bridge.SEND_MSG_CMD` and the inline `sendGroupMessage` /
// `sendPrivateMessage` / `sendC2cFileMessage` implementations were
// moved to `apis/message.ts::MessageApi` as part of the #6
// Api-on-ctx refactor. Callers route through `bridge.apis.message.*`.
// --- Delegated: OIDB helpers ---
async resolveUserUid(uin: number, groupId?: number): Promise<string> {
return this.identity.resolveUid(uin, groupId);
}
// fetchFriendList / fetchGroupList / fetchGroupMemberList /
// fetchUserProfile / fetchGroupRequests / fetchDownloadRKeys
// moved to apis.contacts (see apis/contacts.ts::ContactsApi).
// --- Delegated: action methods ---
//
// GroupAdmin methods (mute/kick/admin/card/name/title/leave/
// add-option/search/add-request/remark/at-all-remain) moved to
// apis.groupAdmin (apis/group-admin.ts::GroupAdminApi).
// Friend methods (handleRequest/delete/setRemark) moved to
// apis.friend.
// GroupFile methods (upload/uploadPrivate/publish/list/getUrl/
// getPrivateUrl/{Ptt,Video}Url/getPrivate{Ptt,Video}Url/delete/move/
// createFolder/deleteFolder/renameFolder/getCount) moved to
// apis.groupFile (apis/group-file.ts::GroupFileApi).
// Forward methods (upload / fetch) moved to apis.forward.
// Interaction methods (sendPoke/sendLike/setReaction/setEssence/
// getEmojiLikes) moved to apis.interaction.
// recall* / markRead* moved to apis/message.ts::MessageApi.
// GroupAlbum methods (list/upload/getMediaList/comment/like/delete)
// moved to apis.groupAlbum (apis/group-album.ts::GroupAlbumApi).
// Web methods (getHonorInfo / forceFetchClientKey / getEssence /
// getEssenceAll / sendNotice / getNotice / deleteNotice /
// getCookiesStr / getCsrfToken / getCredentials) moved to apis.web.
// Profile methods (setOnlineStatus / setDiyOnlineStatus / setProfile /
// setSelfLongNick / setInputStatus / setAvatar / setGroupAvatar /
// fetchCustomFace / getLike / getUnidirectionalFriendList) moved to
// apis.profile.
// Misc methods (translateEn2Zh / getMiniAppArk /
// clickInlineKeyboardButton / sendGroupSign) moved to apis.misc.
// --- Tier-2 napcat-parity extras (group todo / stranger status /
// AI voice) moved to apis.extras. ---
}
export { AiVoiceChatType };
export type { AiVoiceCategory, StrangerStatus };
+2 -2
View File
@@ -1,8 +1,8 @@
import { createLogger } from '@snowluma/common/logger';
import type { PacketSender } from '@snowluma/common/packet-sender';
import type { PacketInfo } from '@snowluma/common/protocol-types';
import { createLogger } from '@snowluma/common/logger';
import { IdentityService } from '@snowluma/protocol/identity-service';
import { Bridge } from './bridge';
import { IdentityService } from '@snowluma/bridge/identity-service';
export type SessionStartedCallback = (uin: string, bridge: Bridge) => void;
export type SessionClosedCallback = (uin: string) => void;
+4 -10
View File
@@ -1,8 +1,8 @@
import { BridgeManager } from './bridge/manager';
import { OneBotManager } from '@snowluma/onebot/manager';
import { loadRuntimeConfig } from '@snowluma/common/runtime';
import { HookManager } from '@snowluma/bridge';
import { closeLogger, createLogger } from '@snowluma/common/logger';
import { HookManager } from './hook/hook-manager';
import { loadRuntimeConfig } from '@snowluma/common/runtime';
import { OneBotManager } from '@snowluma/onebot/manager';
import { BridgeManager } from './bridge/manager';
const runtimeConfig = loadRuntimeConfig();
const log = createLogger('App');
@@ -12,12 +12,6 @@ async function main() {
const bridgeManager = new BridgeManager();
const oneBotManager = new OneBotManager();
// HookManager defaults its packet sink to bridgeManager.onPacket, so
// every parsed hook packet reaches the per-UIN bridge dispatcher with
// no intermediate layer.
// Env var SNOWLUMA_HOOK_AUTOLOAD wins over runtime.json so Docker /
// headless deployments can flip auto-injection on without touching the
// persisted user config volume.
const autoLoadOnDiscovery = resolveAutoLoad(runtimeConfig.hookAutoLoad);
const hookManager = new HookManager({ bridgeManager, autoLoadOnDiscovery });
if (autoLoadOnDiscovery) {
+1 -1
View File
@@ -1,7 +1,7 @@
import { createLogger } from '@snowluma/common/logger';
import { randomBytes, scryptSync, timingSafeEqual } from 'crypto';
import fs from 'fs';
import path from 'path';
import { createLogger } from '@snowluma/common/logger';
const log = createLogger('WebUI.Auth');
-4
View File
@@ -1,9 +1,5 @@
import net from 'net';
/**
* Probe whether a TCP port is bindable on the given host.
* Resolves to true when bind+listen succeed.
*/
function isPortAvailable(port: number, host = '0.0.0.0'): Promise<boolean> {
return new Promise((resolve) => {
const server = net.createServer();
+10 -10
View File
@@ -1,18 +1,18 @@
import { serve } from '@hono/node-server';
import { serveStatic } from '@hono/node-server/serve-static';
import { Hono, type Context } from 'hono';
import { describeTrustProxy, makeClientIpResolver, parseTrustProxy } from './client-ip';
import type { HookManager, HookProcessInfo } from '@snowluma/bridge';
import { createLogger, getLogLevel, getRecentLogs, LOG_LEVELS, setLogLevel, subscribeLogs } from '@snowluma/common/logger';
import { randomBytes } from 'crypto';
import type { OneBotManager } from '@snowluma/onebot/manager';
import { loadOneBotConfig, saveOneBotConfig } from '@snowluma/onebot/config';
import type { OneBotManager } from '@snowluma/onebot/manager';
import type { OneBotConfig } from '@snowluma/onebot/types';
import type { HookManager, HookProcessInfo } from '../hook/hook-manager';
import path from 'path';
import { randomBytes } from 'crypto';
import { existsSync, readFileSync } from 'fs';
import { fileURLToPath } from 'url';
import { Hono, type Context } from 'hono';
import os from 'os';
import { WebuiAuth, evaluatePasswordRules, isStrongPassword } from './auth';
import path from 'path';
import { fileURLToPath } from 'url';
import { evaluatePasswordRules, isStrongPassword, WebuiAuth } from './auth';
import { describeTrustProxy, makeClientIpResolver, parseTrustProxy } from './client-ip';
import { findAvailablePort } from './port';
const log = createLogger('WebUI');
@@ -446,8 +446,8 @@ export async function initWebUI(
}
};
}
app.post('/api/processes/:pid/load', processAction('load', (pid) => hookManager!.loadProcess(pid)));
app.post('/api/processes/:pid/unload', processAction('unload', (pid) => hookManager!.unloadProcess(pid)));
app.post('/api/processes/:pid/load', processAction('load', (pid) => hookManager!.loadProcess(pid)));
app.post('/api/processes/:pid/unload', processAction('unload', (pid) => hookManager!.unloadProcess(pid)));
app.post('/api/processes/:pid/refresh', processAction('refresh', (pid) => hookManager!.refreshProcess(pid)));
app.get('/api/processes/:pid/probe-login', async (c) => {
+71 -98
View File
@@ -1,189 +1,162 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { protobuf_encode } from '@snowluma/proton';
import { describe, it, expect } from 'vitest';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
OidbGroupTodo,
OidbStrangerStatusReq,
OidbStrangerStatusResp,
} from '@snowluma/proto-defs/oidb-actions/base';
import type {
OidbAiVoiceListReq,
OidbAiVoiceListResp,
OidbAiVoiceReq,
OidbAiVoiceResp,
} from '@snowluma/proto-defs/oidb-actions/media';
// `encodeOidbEnv` / `decodeOidbEnv` are proton-bound pass-through wrappers
// (substituted at the call site with the inlined codec). Mocking them on
// the module object is a no-op — proton has already inlined the call.
// We mock `runOidb` (non-generic) to return real proton-encoded bytes
// that the production-side codec actually decodes.
vi.mock('@snowluma/bridge/bridge-oidb', async () => {
const actual = await vi.importActual<typeof import('@snowluma/bridge/bridge-oidb')>(
'@snowluma/bridge/bridge-oidb',
);
return {
...actual,
runOidb: vi.fn(async () => new Uint8Array()),
makeOidbEnvelope: vi.fn((_oidbCmd, _subCmd, body) => ({ body })),
};
});
import * as oidb from '@snowluma/bridge/bridge-oidb';
// Post-namespace migration: ExtrasApi forwards 6 OIDB cmds through
// namespaces under @snowluma/protocol/oidb-services/extras. Tests assert
// against bridge.sendRawPacket directly.
import { ExtrasApi, AiVoiceChatType } from '../../src/bridge/apis/extras';
import { mockBridge } from './_helpers';
describe('apis/extras / group todo (0xF90)', () => {
beforeEach(() => {
vi.mocked(oidb.runOidb).mockClear();
vi.mocked(oidb.makeOidbEnvelope).mockClear();
});
function packResponse(body: Uint8Array) {
return {
success: true, gotResponse: true, errorCode: 0, errorMessage: '',
responseData: Buffer.from(body),
};
}
describe('apis/extras / group todo (0xF90)', () => {
it.each([
['setGroupTodo', 'OidbSvcTrpcTcp.0xf90_1', 1] as const,
['completeGroupTodo', 'OidbSvcTrpcTcp.0xf90_2', 2] as const,
['cancelGroupTodo', 'OidbSvcTrpcTcp.0xf90_3', 3] as const,
])('%s dispatches the right subCmd with shared body', async (method, cmd, subCmd) => {
['setGroupTodo', 'OidbSvcTrpcTcp.0xf90_1'] as const,
['completeGroupTodo', 'OidbSvcTrpcTcp.0xf90_2'] as const,
['cancelGroupTodo', 'OidbSvcTrpcTcp.0xf90_3'] as const,
])('%s dispatches the right subCmd with shared body', async (method, cmd) => {
const bridge = mockBridge();
const api = new ExtrasApi(bridge as any);
await (api as any)[method](12345, 9876543210n);
const [, runCmd] = vi.mocked(oidb.runOidb).mock.calls[0]!;
expect(runCmd).toBe(cmd);
const [oidbCmd, sub, body] = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]!;
expect(oidbCmd).toBe(0xF90);
expect(sub).toBe(subCmd);
expect(body).toEqual({ groupUin: 12345, msgSeq: 9876543210n });
const [wireName, bytes] = bridge.sendRawPacket.mock.calls[0]!;
expect(wireName).toBe(cmd);
const env = protobuf_decode<OidbBase<OidbGroupTodo>>(bytes);
expect(env.body).toEqual({ groupUin: 12345, msgSeq: 9876543210n });
});
});
describe('apis/extras / getStrangerStatus (0xFE1_2)', () => {
beforeEach(() => {
vi.mocked(oidb.runOidb).mockReset();
vi.mocked(oidb.runOidb).mockResolvedValue(new Uint8Array());
vi.mocked(oidb.makeOidbEnvelope).mockClear();
});
it('issues the FE1_2 query with key=27372', async () => {
const bridge = mockBridge();
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
protobuf_encode<OidbBase<OidbStrangerStatusResp>>({ body: { data: { status: { value: 5n } } } }),
);
));
await new ExtrasApi(bridge as any).getStrangerStatus(100200);
const [, runCmd] = vi.mocked(oidb.runOidb).mock.calls[0]!;
expect(runCmd).toBe('OidbSvcTrpcTcp.0xfe1_2');
const [oidbCmd, sub, body] = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]!;
expect(oidbCmd).toBe(0xFE1);
expect(sub).toBe(2);
expect(body).toMatchObject({ uin: 100200, key: [{ key: 27372 }] });
const [wireName, bytes] = bridge.sendRawPacket.mock.calls[0]!;
expect(wireName).toBe('OidbSvcTrpcTcp.0xfe1_2');
const env = protobuf_decode<OidbBase<OidbStrangerStatusReq>>(bytes);
expect(env.command).toBe(0xFE1);
expect(env.subCommand).toBe(2);
expect(env.body).toMatchObject({ uin: 100200, key: [{ key: 27372 }] });
});
it('low-band values (≤10) map to status*10 with ext_status=0', async () => {
const bridge = mockBridge();
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
protobuf_encode<OidbBase<OidbStrangerStatusResp>>({ body: { data: { status: { value: 7n } } } }),
);
));
expect(await new ExtrasApi(bridge as any).getStrangerStatus(1)).toEqual({ status: 70, ext_status: 0 });
});
it('high-band values decompose into the (0xff00 + (>>16 & 0xff)) status word', async () => {
const bridge = mockBridge();
// value 0x42F100: bits 8-15 (the 0xff00 mask) = 0xF100;
// bits 16-23 (>>16 & 0xff) = 0x42.
// ext_status = 0xF100 + 0x42 = 0xF142.
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
protobuf_encode<OidbBase<OidbStrangerStatusResp>>({ body: { data: { status: { value: 0x42F100n } } } }),
);
));
const status = await new ExtrasApi(bridge as any).getStrangerStatus(1);
expect(status).toEqual({ status: 10, ext_status: 0xF142 });
});
it('returns null when the runner throws (transport error)', async () => {
const bridge = mockBridge();
vi.mocked(oidb.runOidb).mockRejectedValueOnce(new Error('boom'));
bridge.sendRawPacket.mockRejectedValueOnce(new Error('boom'));
expect(await new ExtrasApi(bridge as any).getStrangerStatus(1)).toBeNull();
});
it('returns null when the server omits the status field', async () => {
const bridge = mockBridge();
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
protobuf_encode<OidbBase<OidbStrangerStatusResp>>({ body: {} }),
);
));
expect(await new ExtrasApi(bridge as any).getStrangerStatus(1)).toBeNull();
});
});
describe('apis/extras / AI voice (0x929D / 0x929B)', () => {
beforeEach(() => {
vi.mocked(oidb.runOidb).mockReset();
vi.mocked(oidb.runOidb).mockResolvedValue(new Uint8Array());
vi.mocked(oidb.makeOidbEnvelope).mockClear();
});
it('fetchAiVoiceList sends 0x929D_0 and returns server content verbatim', async () => {
const bridge = mockBridge();
const fake = [
{ category: 'cute', voices: [{ voiceId: 'v1', voiceDisplayName: 'V1', voiceExampleUrl: 'http://x' }] },
];
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
protobuf_encode<OidbBase<OidbAiVoiceListResp>>({ body: { content: fake } } as any),
);
));
const out = await new ExtrasApi(bridge as any).fetchAiVoiceList(4242, AiVoiceChatType.Sound);
expect(out).toEqual(fake);
const [, runCmd] = vi.mocked(oidb.runOidb).mock.calls[0]!;
expect(runCmd).toBe('OidbSvcTrpcTcp.0x929d_0');
const body = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2];
expect(body).toEqual({ groupUin: 4242, chatType: 1 });
const [wireName, bytes] = bridge.sendRawPacket.mock.calls[0]!;
expect(wireName).toBe('OidbSvcTrpcTcp.0x929d_0');
const env = protobuf_decode<OidbBase<OidbAiVoiceListReq>>(bytes);
expect(env.body).toEqual({ groupUin: 4242, chatType: 1 });
});
it('fetchAiVoiceList returns [] when server replies with no content', async () => {
const bridge = mockBridge();
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
protobuf_encode<OidbBase<OidbAiVoiceListResp>>({ body: {} }),
);
));
const out = await new ExtrasApi(bridge as any).fetchAiVoiceList(1, 1);
expect(out).toEqual([]);
});
it('fetchAiVoice retries while msgInfo is empty, returns the first IndexNode it sees', async () => {
const bridge = mockBridge();
// subType is non-zero so proto3 doesn't omit it from the wire (the
// re-decoded object must include the field for the matcher to spot it).
const node = { fileUuid: 'uuid-1', subType: 1 };
vi.mocked(oidb.runOidb)
.mockResolvedValueOnce(protobuf_encode<OidbBase<OidbAiVoiceResp>>({ body: { statusCode: 2 } }))
.mockResolvedValueOnce(protobuf_encode<OidbBase<OidbAiVoiceResp>>({ body: { msgInfo: { msgInfoBody: [] } } as any }))
.mockResolvedValueOnce(protobuf_encode<OidbBase<OidbAiVoiceResp>>({ body: { msgInfo: { msgInfoBody: [{ index: node }] } } as any }));
bridge.sendRawPacket
.mockResolvedValueOnce(packResponse(protobuf_encode<OidbBase<OidbAiVoiceResp>>({ body: { statusCode: 2 } } as any)))
.mockResolvedValueOnce(packResponse(protobuf_encode<OidbBase<OidbAiVoiceResp>>({ body: { msgInfo: { msgInfoBody: [] } } as any })))
.mockResolvedValueOnce(packResponse(protobuf_encode<OidbBase<OidbAiVoiceResp>>({ body: { msgInfo: { msgInfoBody: [{ index: node }] } } as any })));
const out = await new ExtrasApi(bridge as any).fetchAiVoice(100, 'voice-id', 'hi', AiVoiceChatType.Sound);
expect(out).toMatchObject(node);
expect(vi.mocked(oidb.runOidb)).toHaveBeenCalledTimes(3);
const [, runCmd] = vi.mocked(oidb.runOidb).mock.calls[0]!;
expect(runCmd).toBe('OidbSvcTrpcTcp.0x929b_0');
const body = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2] as any;
expect(body).toMatchObject({
expect(bridge.sendRawPacket).toHaveBeenCalledTimes(3);
const [wireName, bytes] = bridge.sendRawPacket.mock.calls[0]!;
expect(wireName).toBe('OidbSvcTrpcTcp.0x929b_0');
const env = protobuf_decode<OidbBase<OidbAiVoiceReq>>(bytes);
expect(env.body).toMatchObject({
groupUin: 100, voiceId: 'voice-id', text: 'hi', chatType: 1,
});
// sessionId is randomized but must be a uint32.
expect(body.session.sessionId).toBeTypeOf('number');
expect(body.session.sessionId).toBeGreaterThanOrEqual(0);
expect(body.session.sessionId).toBeLessThanOrEqual(0xFFFFFFFF);
const sessionId = env.body?.session?.sessionId;
expect(typeof sessionId).toBe('number');
expect(sessionId).toBeGreaterThanOrEqual(0);
expect(sessionId).toBeLessThanOrEqual(0xFFFFFFFF);
});
it('fetchAiVoice throws after exhausting the retry budget', async () => {
const bridge = mockBridge();
vi.mocked(oidb.runOidb).mockResolvedValue(
protobuf_encode<OidbBase<OidbAiVoiceResp>>({ body: { statusCode: 1 } }),
);
bridge.sendRawPacket.mockResolvedValue(packResponse(
protobuf_encode<OidbBase<OidbAiVoiceResp>>({ body: { statusCode: 1 } as any }),
));
await expect(new ExtrasApi(bridge as any).fetchAiVoice(1, 'v', 't', 1, 3)).rejects.toThrow(
/AI voice synthesis did not complete/,
);
expect(vi.mocked(oidb.runOidb)).toHaveBeenCalledTimes(3);
expect(bridge.sendRawPacket).toHaveBeenCalledTimes(3);
});
it('fetchAiVoice keeps the same sessionId across retries', async () => {
const bridge = mockBridge();
const node = { fileUuid: 'uuid', subType: 0 };
vi.mocked(oidb.runOidb)
.mockResolvedValueOnce(protobuf_encode<OidbBase<OidbAiVoiceResp>>({ body: {} }))
.mockResolvedValueOnce(protobuf_encode<OidbBase<OidbAiVoiceResp>>({ body: { msgInfo: { msgInfoBody: [{ index: node }] } } as any }));
const node = { fileUuid: 'uuid', subType: 1 };
bridge.sendRawPacket
.mockResolvedValueOnce(packResponse(protobuf_encode<OidbBase<OidbAiVoiceResp>>({ body: {} })))
.mockResolvedValueOnce(packResponse(protobuf_encode<OidbBase<OidbAiVoiceResp>>({ body: { msgInfo: { msgInfoBody: [{ index: node }] } } as any })));
await new ExtrasApi(bridge as any).fetchAiVoice(1, 'v', 't', 1);
const first = (vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2] as any).session.sessionId;
const second = (vi.mocked(oidb.makeOidbEnvelope).mock.calls[1]![2] as any).session.sessionId;
expect(first).toBe(second);
const env1 = protobuf_decode<OidbBase<OidbAiVoiceReq>>(bridge.sendRawPacket.mock.calls[0]![1]);
const env2 = protobuf_decode<OidbBase<OidbAiVoiceReq>>(bridge.sendRawPacket.mock.calls[1]![1]);
expect(env1.body?.session?.sessionId).toBe(env2.body?.session?.sessionId);
});
});
@@ -25,7 +25,7 @@
import { describe, it, expect, vi } from 'vitest';
vi.mock('@snowluma/bridge/bridge-oidb', () => ({
vi.mock('@snowluma/protocol/bridge-oidb', () => ({
runOidb: vi.fn(async () => new Uint8Array()),
makeOidbEnvelope: vi.fn((_oidbCmd, _subCmd, body) => ({ body })),
encodeOidbEnv: vi.fn(() => new Uint8Array()),
@@ -40,7 +40,7 @@ vi.mock('@snowluma/bridge/bridge-oidb', () => ({
const { buildSendElemsMock } = vi.hoisted(() => ({
buildSendElemsMock: vi.fn(async (_elements: unknown[], _ctx?: Record<string, unknown>) => []),
}));
vi.mock('@snowluma/bridge/element-builder', () => ({
vi.mock('@snowluma/protocol/element-builder', () => ({
buildSendElems: buildSendElemsMock,
}));
@@ -0,0 +1,181 @@
// Wire-byte alignment regression for nested forward upload — verifies
// that the OUTER LongMsgResult's `actions[]` carries:
// - `{actionCommand: 'MultiMsg', actionData.msgBody: <outer nodes>}`
// - `{actionCommand: <inner.uuid>, actionData.msgBody: <inner nodes>}`
// AND that the same uuid appears as `meta.detail.uniseq` inside the
// LightApp `com.tencent.multimsg` JSON of the outer's preview element
// pointing at the inner res_id.
//
// Without this alignment the QQ-NT recipient has no way to walk the
// piggyback — they see the inner preview's resid, look for a matching
// uniseq among the actions, find none, and either fall back to a fresh
// server fetch (extra latency) or render an empty bubble.
//
// Reference impls cross-checked:
// dev/NapCatQQ/.../SendMsg.ts:208-347
// dev/Lagrange.Core/.../Message/Entity/MultiMsgEntity.cs:43-115
// dev/NapCatQQ/.../helper/forward-msg-builder.ts:52-122
import { describe, it, expect, vi } from 'vitest';
import { gunzipSync, inflateSync } from 'zlib';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { SendLongMsgReq, SendLongMsgResp, LongMsgResult } from '@snowluma/proto-defs/longmsg';
import type { PushMsgBody } from '@snowluma/proto-defs/message';
import type { Elem } from '@snowluma/proto-defs/element';
// Don't mock element-builder — we WANT the real forward preview
// element to land in the encoded wire bytes so we can verify the
// `uniseq` round-trip against the piggyback's `actionCommand`.
// Mock highway uploads only — they're irrelevant for text-only nodes
// but the import would otherwise pull in the native ffmpeg addon.
vi.mock('@snowluma/protocol/highway/image-upload', () => ({
uploadImageMsgInfo: vi.fn(async () => new Uint8Array()),
}));
vi.mock('@snowluma/protocol/highway/ptt-upload', () => ({
uploadPttMsgInfo: vi.fn(async () => new Uint8Array()),
}));
vi.mock('@snowluma/protocol/highway/video-upload', () => ({
uploadVideoMsgInfo: vi.fn(async () => new Uint8Array()),
}));
import { ForwardApi } from '../../src/bridge/apis/forward';
import { mockBridge } from './_helpers';
function uploadResponseWithResId(resId: string) {
return {
success: true,
gotResponse: true,
errorCode: 0,
errorMessage: '',
responseData: Buffer.from(protobuf_encode<SendLongMsgResp>({ result: { resId } })),
};
}
function decodeOuterLongMsg(rawBytes: Uint8Array): LongMsgResult {
const env = protobuf_decode<SendLongMsgReq>(rawBytes);
const payload = env.info?.payload;
if (!(payload instanceof Uint8Array)) throw new Error('payload missing on the SendLongMsgReq');
return protobuf_decode<LongMsgResult>(gunzipSync(Buffer.from(payload)));
}
function findLightAppJson(msgBody: PushMsgBody[]): { resid?: string; uniseq?: string; app?: string } | null {
for (const body of msgBody) {
const elems: Elem[] = body.body?.richText?.elems ?? [];
for (const elem of elems) {
if (elem.lightApp?.data && elem.lightApp.data.length > 1) {
const data = elem.lightApp.data;
if (data[0] !== 0x01) continue;
try {
const json = inflateSync(Buffer.from(data.subarray(1))).toString('utf8');
const parsed = JSON.parse(json);
if (parsed?.app === 'com.tencent.multimsg') {
return {
app: parsed.app,
resid: parsed.meta?.detail?.resid,
uniseq: parsed.meta?.detail?.uniseq,
};
}
} catch { /* ignore */ }
}
}
}
return null;
}
describe('forward / nested upload wire alignment', () => {
it('outer LongMsgResult contains both MultiMsg and the inner uuid piggyback action', async () => {
// Inner upload returns inner-res; outer upload returns outer-res.
const responses = ['inner-res', 'outer-res'];
const sendRawPacket = vi.fn(async () =>
uploadResponseWithResId(responses.shift()!)) as any;
const bridge = mockBridge({ sendRawPacket });
const resId = await new ForwardApi(bridge as any).upload([
{
userUin: 111, nickname: 'outer', elements: [],
innerForward: [
{ userUin: 222, nickname: 'inner', elements: [{ type: 'text', text: 'hi' }] },
],
},
]);
expect(resId).toBe('outer-res');
expect(sendRawPacket).toHaveBeenCalledTimes(2);
// Second call is the OUTER's upload (the inner went first).
const outerBytes = sendRawPacket.mock.calls[1]![1] as Uint8Array;
const outerLongMsg = decodeOuterLongMsg(outerBytes);
const actions = outerLongMsg.action ?? [];
expect(actions).toHaveLength(2);
expect(actions[0]!.actionCommand).toBe('MultiMsg');
// The second action carries the inner's msgBody under a uuid
// actionCommand (NOT 'MultiMsg').
const piggybackUuid = actions[1]!.actionCommand!;
expect(piggybackUuid).not.toBe('MultiMsg');
expect(piggybackUuid).toMatch(/^[0-9a-f-]{36}$/i);
expect(actions[1]!.actionData?.msgBody?.length ?? 0).toBeGreaterThan(0);
});
it('outer preview LightApp uniseq matches the piggyback actionCommand uuid', async () => {
// This is the alignment bug: without it the QQ-NT receiver
// can't link the inner preview to its piggyback in actions[].
const responses = ['inner-res-A', 'outer-res-A'];
const sendRawPacket = vi.fn(async () =>
uploadResponseWithResId(responses.shift()!)) as any;
const bridge = mockBridge({ sendRawPacket });
await new ForwardApi(bridge as any).upload([
{
userUin: 111, nickname: 'outer', elements: [],
innerForward: [
{ userUin: 222, nickname: 'inner', elements: [{ type: 'text', text: 'hi' }] },
],
},
]);
const outerBytes = sendRawPacket.mock.calls[1]![1] as Uint8Array;
const outerLongMsg = decodeOuterLongMsg(outerBytes);
const piggybackUuid = outerLongMsg.action![1]!.actionCommand!;
const outerMsgBody = outerLongMsg.action![0]!.actionData!.msgBody!;
const preview = findLightAppJson(outerMsgBody);
expect(preview).not.toBeNull();
expect(preview!.app).toBe('com.tencent.multimsg');
expect(preview!.resid).toBe('inner-res-A');
expect(preview!.uniseq).toBe(piggybackUuid);
});
it('three-deep nesting: outermost action[] carries 1+2 entries (MultiMsg + 2 piggybacks)', async () => {
// The middle level's upload produces 1 MultiMsg + 1 piggyback
// (for the deepest). The outermost level then concatenates its
// own MultiMsg + the middle's piggyback set, so action[].length = 3.
const responses = ['deepest', 'middle', 'outermost'];
const sendRawPacket = vi.fn(async () =>
uploadResponseWithResId(responses.shift()!)) as any;
const bridge = mockBridge({ sendRawPacket });
await new ForwardApi(bridge as any).upload([
{
userUin: 1, nickname: 'L1', elements: [],
innerForward: [{
userUin: 2, nickname: 'L2', elements: [],
innerForward: [
{ userUin: 3, nickname: 'L3', elements: [{ type: 'text', text: 'deep' }] },
],
}],
},
]);
expect(sendRawPacket).toHaveBeenCalledTimes(3);
const outermostBytes = sendRawPacket.mock.calls[2]![1] as Uint8Array;
const outermost = decodeOuterLongMsg(outermostBytes);
expect(outermost.action).toHaveLength(3);
expect(outermost.action![0]!.actionCommand).toBe('MultiMsg');
expect(outermost.action![1]!.actionCommand).not.toBe('MultiMsg');
expect(outermost.action![2]!.actionCommand).not.toBe('MultiMsg');
expect(outermost.action![1]!.actionCommand).not.toBe(outermost.action![2]!.actionCommand);
});
});
+2 -2
View File
@@ -1,6 +1,6 @@
import { describe, it, expect, vi } from 'vitest';
vi.mock('@snowluma/bridge/bridge-oidb', () => ({
vi.mock('@snowluma/protocol/bridge-oidb', () => ({
runOidb: vi.fn(async () => new Uint8Array()),
makeOidbEnvelope: vi.fn((_oidbCmd, _subCmd, body) => ({ body })),
encodeOidbEnv: vi.fn(() => new Uint8Array()),
@@ -10,7 +10,7 @@ vi.mock('@snowluma/bridge/bridge-oidb', () => ({
// element-builder reaches into protoEncode with element-specific schemas
// that we don't want to construct manually in tests; stub it to return
// a benign placeholder.
vi.mock('@snowluma/bridge/element-builder', () => ({
vi.mock('@snowluma/protocol/element-builder', () => ({
buildSendElems: vi.fn(async () => []),
}));
+25 -27
View File
@@ -1,54 +1,52 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { describe, it, expect, vi } from 'vitest';
import { protobuf_decode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
OidbDeleteFriend,
OidbFriendRequestAction,
OidbSetFriendRemark,
} from '@snowluma/proto-defs/oidb-actions/base';
vi.mock('@snowluma/bridge/bridge-oidb', () => ({
runOidb: vi.fn(async () => new Uint8Array()),
makeOidbEnvelope: vi.fn((_oidbCmd, _subCmd, body) => ({ body })),
encodeOidbEnv: vi.fn(() => new Uint8Array()),
decodeOidbEnv: vi.fn(() => ({ body: {} })),
}));
import * as oidb from '@snowluma/bridge/bridge-oidb';
// Post-namespace migration: FriendApi is a thin facade over the
// namespaces under @snowluma/protocol/oidb-services/friend. Tests assert
// against the bridge mock's sendRawPacket directly — no need for
// module-level bridge-oidb mocks anymore.
import { FriendApi } from '../../src/bridge/apis/friend';
import { mockBridge } from './_helpers';
describe('apis/friend', () => {
beforeEach(() => {
vi.mocked(oidb.runOidb).mockClear();
vi.mocked(oidb.makeOidbEnvelope).mockClear();
});
it('handleRequest: numeric input is treated as UIN and resolved', async () => {
const bridge = mockBridge();
await new FriendApi(bridge as any).handleRequest('10001', true);
expect(bridge.resolveUserUid).toHaveBeenCalledWith(10001);
const body = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2];
expect(body).toMatchObject({ accept: 3, targetUid: 'resolved-uid' });
const [cmd, bytes] = bridge.sendRawPacket.mock.calls[0]!;
expect(cmd).toBe('OidbSvcTrpcTcp.0xb5d_44');
const env = protobuf_decode<OidbBase<OidbFriendRequestAction>>(bytes);
expect(env.body).toMatchObject({ accept: 3, targetUid: 'resolved-uid' });
});
it('handleRequest: non-numeric flag is forwarded as-is', async () => {
const bridge = mockBridge();
await new FriendApi(bridge as any).handleRequest('flag-abc', false);
expect(bridge.resolveUserUid).not.toHaveBeenCalled();
const body = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2];
expect(body).toMatchObject({ accept: 5, targetUid: 'flag-abc' });
const [, bytes] = bridge.sendRawPacket.mock.calls[0]!;
const env = protobuf_decode<OidbBase<OidbFriendRequestAction>>(bytes);
expect(env.body).toMatchObject({ accept: 5, targetUid: 'flag-abc' });
});
it('delete resolves UID, calls 0x126b_0, and triggers a friend-list refresh', async () => {
const bridge = mockBridge();
await new FriendApi(bridge as any).delete(10001, true);
expect(bridge.resolveUserUid).toHaveBeenCalledWith(10001);
const [, cmd] = vi.mocked(oidb.runOidb).mock.calls[0]!;
const [cmd, bytes] = bridge.sendRawPacket.mock.calls[0]!;
expect(cmd).toBe('OidbSvcTrpcTcp.0x126b_0');
const body = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2];
expect((body as any).field1.block).toBe(true);
const env = protobuf_decode<OidbBase<OidbDeleteFriend>>(bytes);
expect(env.body?.field1?.block).toBe(true);
expect(bridge.apis.contacts.fetchFriendList).toHaveBeenCalled();
});
it('delete still succeeds when the friend-list refresh throws', async () => {
const bridge = mockBridge();
// `fetchFriendList` lives on `apis.contacts` post-#6 refactor;
// override the default no-op stub to make the friend-list refresh
// throw and verify delete swallows the error.
bridge.apis.contacts.fetchFriendList = vi.fn(async () => { throw new Error('cache miss'); });
await expect(new FriendApi(bridge as any).delete(10001))
.resolves.toBeUndefined();
@@ -57,9 +55,9 @@ describe('apis/friend', () => {
it('setRemark resolves UID and sends 0xb6e_2', async () => {
const bridge = mockBridge();
await new FriendApi(bridge as any).setRemark(10001, 'best-friend');
const [, cmd] = vi.mocked(oidb.runOidb).mock.calls[0]!;
const [cmd, bytes] = bridge.sendRawPacket.mock.calls[0]!;
expect(cmd).toBe('OidbSvcTrpcTcp.0xb6e_2');
const body = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2];
expect(body).toMatchObject({ targetUid: 'resolved-uid', remark: 'best-friend' });
const env = protobuf_decode<OidbBase<OidbSetFriendRemark>>(bytes);
expect(env.body).toMatchObject({ targetUid: 'resolved-uid', remark: 'best-friend' });
});
});
+106 -73
View File
@@ -1,72 +1,73 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { protobuf_encode } from '@snowluma/proton';
import { describe, it, expect, vi } from 'vitest';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { Oidb0x8a7Resp } from '@snowluma/proto-defs/oidb-actions/base';
import type {
Oidb0x8a0Req,
Oidb0x8a7Resp,
Oidb0x89a_0AddOption,
Oidb0x89a_0Search,
Oidb0xf16Req,
OidbGroupRequestAction,
OidbKickMember,
OidbLeaveGroup,
OidbMuteAll,
OidbMuteMember,
OidbRenameGroup,
OidbRenameMember,
OidbSetAdmin,
OidbSpecialTitle,
} from '@snowluma/proto-defs/oidb-actions/base';
// `encodeOidbEnv` / `decodeOidbEnv` are proton-bound pass-through wrappers
// that the plugin substitutes at the call site with the inlined codec, so
// mocking them on the module object is a no-op. The only mockable point
// is `runOidb` (non-generic, untouched by proton) returning real bytes
// that the production-side codec then decodes. `makeOidbEnvelope` is a
// pure TS helper, so its mock works for introspection.
vi.mock('@snowluma/bridge/bridge-oidb', async () => {
const actual = await vi.importActual<typeof import('@snowluma/bridge/bridge-oidb')>(
'@snowluma/bridge/bridge-oidb',
);
return {
...actual,
runOidb: vi.fn(async () => new Uint8Array()),
makeOidbEnvelope: vi.fn((_oidbCmd, _subCmd, body) => ({ body })),
};
});
import * as oidb from '@snowluma/bridge/bridge-oidb';
// Post-namespace migration: GroupAdminApi forwards through namespaces
// under @snowluma/protocol/oidb-services/group-admin. Tests assert
// against bridge.sendRawPacket directly — no module-level mocks.
import { GroupAdminApi } from '../../src/bridge/apis/group-admin';
import { mockBridge } from './_helpers';
describe('actions/group-admin', () => {
beforeEach(() => {
vi.mocked(oidb.runOidb).mockReset();
vi.mocked(oidb.runOidb).mockResolvedValue(new Uint8Array());
vi.mocked(oidb.makeOidbEnvelope).mockClear();
});
function packResponse(body: Uint8Array) {
return {
success: true, gotResponse: true, errorCode: 0, errorMessage: '',
responseData: Buffer.from(body),
};
}
it('muteGroupMember resolves UID and dispatches 0x1253_1', async () => {
describe('apis/group-admin', () => {
it('muteMember resolves UID and dispatches 0x1253_1', async () => {
const bridge = mockBridge();
await new GroupAdminApi(bridge as any).muteMember(12345, 67890, 600);
expect(bridge.resolveUserUid).toHaveBeenCalledWith(67890, 12345);
expect(oidb.runOidb).toHaveBeenCalledOnce();
const [, cmd] = vi.mocked(oidb.runOidb).mock.calls[0]!;
const [cmd, bytes] = bridge.sendRawPacket.mock.calls[0]!;
expect(cmd).toBe('OidbSvcTrpcTcp.0x1253_1');
const [oidbCmd, subCmd, body] = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]!;
expect(oidbCmd).toBe(0x1253);
expect(subCmd).toBe(1);
expect(body).toMatchObject({
const env = protobuf_decode<OidbBase<OidbMuteMember>>(bytes);
expect(env.command).toBe(0x1253);
expect(env.subCommand).toBe(1);
expect(env.body).toMatchObject({
groupUin: 12345,
type: 1,
body: { targetUid: 'resolved-uid', duration: 600 },
});
});
it('muteGroupAll flips the muteState flag based on enable', async () => {
it('muteAll flips the muteState flag based on enable', async () => {
const bridge = mockBridge();
await new GroupAdminApi(bridge as any).muteAll(12345, true);
expect(vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2]).toMatchObject({
groupUin: 12345,
muteState: { state: 0xFFFFFFFF },
});
const env1 = protobuf_decode<OidbBase<OidbMuteAll>>(bridge.sendRawPacket.mock.calls[0]![1]);
expect(env1.body).toMatchObject({ groupUin: 12345, muteState: { state: 0xFFFFFFFF } });
await new GroupAdminApi(bridge as any).muteAll(12345, false);
expect(vi.mocked(oidb.makeOidbEnvelope).mock.calls[1]![2]).toMatchObject({
muteState: { state: 0 },
});
const env2 = protobuf_decode<OidbBase<OidbMuteAll>>(bridge.sendRawPacket.mock.calls[1]![1]);
// proto3 default 0 fields are omitted on the wire — equivalent to "state=0".
expect(env2.body?.muteState?.state ?? 0).toBe(0);
});
it('kickGroupMember resolves UID per-group and forwards reject + reason', async () => {
it('kickMember resolves UID per-group and forwards reject + reason', async () => {
const bridge = mockBridge();
await new GroupAdminApi(bridge as any).kickMember(12345, 67890, true, 'bad behaviour');
expect(bridge.resolveUserUid).toHaveBeenCalledWith(67890, 12345);
expect(vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2]).toMatchObject({
const [cmd, bytes] = bridge.sendRawPacket.mock.calls[0]!;
expect(cmd).toBe('OidbSvcTrpcTcp.0x8a0_1');
const env = protobuf_decode<OidbBase<OidbKickMember>>(bytes);
expect(env.body).toMatchObject({
groupUin: 12345,
targetUid: 'resolved-uid',
rejectAddRequest: true,
@@ -74,7 +75,7 @@ describe('actions/group-admin', () => {
});
});
it('kickGroupMembers resolves each UID in parallel', async () => {
it('kickMembers resolves each UID in parallel', async () => {
const bridge = mockBridge();
vi.mocked(bridge.resolveUserUid)
.mockResolvedValueOnce('uid-a')
@@ -82,28 +83,30 @@ describe('actions/group-admin', () => {
await new GroupAdminApi(bridge as any).kickMembers(12345, [11, 22], false);
expect(bridge.resolveUserUid).toHaveBeenCalledTimes(2);
const payload: any = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2];
expect(payload.targetUids).toEqual(['uid-a', 'uid-b']);
expect(payload.rejectAddRequest).toBe(0);
const env = protobuf_decode<OidbBase<Oidb0x8a0Req>>(bridge.sendRawPacket.mock.calls[0]![1]);
expect(env.body?.targetUids).toEqual(['uid-a', 'uid-b']);
expect(env.body?.rejectAddRequest ?? 0).toBe(0);
});
it('leaveGroup sends 0x1097_1 with the groupUin', async () => {
it('leave sends 0x1097_1 with the groupUin', async () => {
const bridge = mockBridge();
await new GroupAdminApi(bridge as any).leave(12345);
const [, cmd] = vi.mocked(oidb.runOidb).mock.calls[0]!;
const [cmd, bytes] = bridge.sendRawPacket.mock.calls[0]!;
expect(cmd).toBe('OidbSvcTrpcTcp.0x1097_1');
expect(vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2]).toMatchObject({ groupUin: 12345 });
const env = protobuf_decode<OidbBase<OidbLeaveGroup>>(bytes);
expect(env.body).toMatchObject({ groupUin: 12345 });
});
it('setGroupAdmin resolves UID and sends 0x1096_1', async () => {
it('setAdmin resolves UID and sends 0x1096_1', async () => {
const bridge = mockBridge();
await new GroupAdminApi(bridge as any).setAdmin(12345, 67890, true);
expect(vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2]).toMatchObject({
groupUin: 12345, uid: 'resolved-uid', isAdmin: true,
});
const [cmd, bytes] = bridge.sendRawPacket.mock.calls[0]!;
expect(cmd).toBe('OidbSvcTrpcTcp.0x1096_1');
const env = protobuf_decode<OidbBase<OidbSetAdmin>>(bytes);
expect(env.body).toMatchObject({ groupUin: 12345, uid: 'resolved-uid', isAdmin: true });
});
it('setGroupCard / setGroupName / setGroupSpecialTitle / setGroupRemark / setGroupAddOption / setGroupSearch dispatch the right command', async () => {
it('setCard / setName / setSpecialTitle / setRemark / setAddOption / setSearch dispatch the right command', async () => {
const bridge = mockBridge();
await new GroupAdminApi(bridge as any).setCard(1, 2, 'newCard');
await new GroupAdminApi(bridge as any).setName(1, 'newName');
@@ -112,7 +115,7 @@ describe('actions/group-admin', () => {
await new GroupAdminApi(bridge as any).setAddOption(1, 2);
await new GroupAdminApi(bridge as any).setSearch(1);
const cmds = vi.mocked(oidb.runOidb).mock.calls.map(call => call[1]);
const cmds = bridge.sendRawPacket.mock.calls.map(call => call[0]);
expect(cmds).toEqual([
'OidbSvcTrpcTcp.0x8fc_3',
'OidbSvcTrpcTcp.0x89a_15',
@@ -121,34 +124,58 @@ describe('actions/group-admin', () => {
'OidbSvcTrpcTcp.0x89a_0',
'OidbSvcTrpcTcp.0x89a_0',
]);
const cardEnv = protobuf_decode<OidbBase<OidbRenameMember>>(bridge.sendRawPacket.mock.calls[0]![1]);
expect(cardEnv.body).toMatchObject({ groupUin: 1, body: { targetUid: 'resolved-uid', targetName: 'newCard' } });
const nameEnv = protobuf_decode<OidbBase<OidbRenameGroup>>(bridge.sendRawPacket.mock.calls[1]![1]);
expect(nameEnv.body).toMatchObject({ groupUin: 1, body: { targetName: 'newName' } });
const titleEnv = protobuf_decode<OidbBase<OidbSpecialTitle>>(bridge.sendRawPacket.mock.calls[2]![1]);
// expireTime is proto int_32 with -1 sentinel; after wire round-trip the
// proton decoder surfaces it as the unsigned reinterpretation (-1 ≡ 0xFFFFFFFF).
expect(titleEnv.body?.groupUin).toBe(1);
expect(titleEnv.body?.body?.targetUid).toBe('resolved-uid');
expect(titleEnv.body?.body?.specialTitle).toBe('newTitle');
expect(titleEnv.body?.body?.expireTime).toBe(0xFFFFFFFF);
const remarkEnv = protobuf_decode<OidbBase<Oidb0xf16Req>>(bridge.sendRawPacket.mock.calls[3]![1]);
expect(remarkEnv.body?.inner).toMatchObject({ groupId: 1n, remark: 'newRemark' });
const addOptEnv = protobuf_decode<OidbBase<Oidb0x89a_0AddOption>>(bridge.sendRawPacket.mock.calls[4]![1]);
expect(addOptEnv.body).toMatchObject({ groupUin: 1n, settings: { addType: 2 } });
const searchEnv = protobuf_decode<OidbBase<Oidb0x89a_0Search>>(bridge.sendRawPacket.mock.calls[5]![1]);
expect(searchEnv.body?.groupUin).toBe(1n);
});
it('setGroupAddRequest picks _1 / _2 based on filtered flag', async () => {
it('setAddRequest picks _1 / _2 based on filtered flag', async () => {
const bridge = mockBridge();
await new GroupAdminApi(bridge as any).setAddRequest(12345, 5, 1, true, 'ok', false);
await new GroupAdminApi(bridge as any).setAddRequest(12345, 5, 1, false, 'no', true);
const cmds = vi.mocked(oidb.runOidb).mock.calls.map(call => call[1]);
const cmds = bridge.sendRawPacket.mock.calls.map(call => call[0]);
expect(cmds).toEqual([
'OidbSvcTrpcTcp.0x10c8_1',
'OidbSvcTrpcTcp.0x10c8_2',
]);
const firstBody: any = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2];
expect(firstBody.accept).toBe(1);
expect(firstBody.body.message).toBe('ok');
const env1 = protobuf_decode<OidbBase<OidbGroupRequestAction>>(bridge.sendRawPacket.mock.calls[0]![1]);
expect(env1.reserved).toBe(1); // uinForm
expect(env1.body?.accept).toBe(1);
expect(env1.body?.body?.message).toBe('ok');
const secondBody: any = vi.mocked(oidb.makeOidbEnvelope).mock.calls[1]![2];
expect(secondBody.accept).toBe(2);
const env2 = protobuf_decode<OidbBase<OidbGroupRequestAction>>(bridge.sendRawPacket.mock.calls[1]![1]);
expect(env2.body?.accept).toBe(2);
});
it('getGroupAtAllRemain decodes the response and converts BigInts', async () => {
it('getAtAllRemain decodes the response and converts BigInts', async () => {
const bridge = mockBridge();
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
protobuf_encode<OidbBase<Oidb0x8a7Resp>>({
body: { canAtAll: true, groupRemain: 12, uinRemain: 5 } as any,
}),
);
));
const out = await new GroupAdminApi(bridge as any).getAtAllRemain(12345);
expect(out).toEqual({
can_at_all: true,
@@ -157,13 +184,19 @@ describe('actions/group-admin', () => {
});
});
it('getGroupAtAllRemain throws when the response is empty', async () => {
it('getAtAllRemain falls back to zero / false when the response is empty', async () => {
const bridge = mockBridge();
// An empty OidbBase envelope (no body) — production code sees `body`
// undefined and throws the "empty" error.
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
// Empty OidbBase envelope (no body) — invokeOidb substitutes `{}`
// for the deserialize argument; canAtAll/groupRemain/uinRemain
// become undefined and get coerced to false/0.
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
protobuf_encode<OidbBase<Oidb0x8a7Resp>>({}),
);
await expect(new GroupAdminApi(bridge as any).getAtAllRemain(12345)).rejects.toThrow(/empty/);
));
const out = await new GroupAdminApi(bridge as any).getAtAllRemain(12345);
expect(out).toEqual({
can_at_all: false,
remain_at_all_count_for_group: 0,
remain_at_all_count_for_uin: 0,
});
});
});
+94 -143
View File
@@ -1,39 +1,33 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { protobuf_encode } from '@snowluma/proton';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
OidbGroupFileCountViewResp,
OidbGroupFileReq,
OidbGroupFileResp,
OidbGroupFileViewResp,
OidbGroupFileFolderResp,
OidbGroupSendFileReq,
} from '@snowluma/proto-defs/oidb-actions/group-file';
import type {
OidbPrivateFileUploadResp,
NTV2RichMediaResp,
} from '@snowluma/proto-defs/oidb-actions/media';
// `encodeOidbEnv` / `decodeOidbEnv` are proton-bound pass-through wrappers
// (substituted at the call site with the inlined codec). Mocking them on
// the module object is a no-op — proton has already inlined the call.
// We mock `runOidb` (non-generic, proton leaves it alone) to return real
// proton-encoded bytes, which the production-side codec then decodes.
vi.mock('@snowluma/bridge/bridge-oidb', async () => {
const actual = await vi.importActual<typeof import('@snowluma/bridge/bridge-oidb')>(
'@snowluma/bridge/bridge-oidb',
);
return {
...actual,
runOidb: vi.fn(async () => new Uint8Array()),
makeOidbEnvelope: vi.fn((_oidbCmd, _subCmd, body) => ({ body })),
};
});
// Post-namespace migration: GroupFileApi forwards single-OIDB methods
// through namespaces under @snowluma/protocol/oidb-services/group-file.
// The multi-stage methods (`upload` / `uploadPrivate`) keep their
// orchestration on the facade; we assert against bridge.sendRawPacket
// directly. Highway calls (fetchHighwaySession / uploadHighwayHttp)
// and the file-source loader are still module-mocked because the
// facade owns those calls directly.
vi.mock('@snowluma/bridge/highway', () => ({
vi.mock('@snowluma/protocol/highway', () => ({
fetchHighwaySession: vi.fn(async () => ({})),
uploadHighwayHttp: vi.fn(async () => undefined),
}));
vi.mock('@snowluma/bridge/highway/utils', () => ({
vi.mock('@snowluma/protocol/highway/utils', () => ({
loadBinarySource: vi.fn(async (_src: string, fallback: string) => ({
bytes: new Uint8Array([1, 2, 3]),
fileName: `${fallback}.bin`,
@@ -43,55 +37,56 @@ vi.mock('@snowluma/bridge/highway/utils', () => ({
FILE_UPLOAD_MAX_BYTES: 4 * 1024 * 1024 * 1024,
}));
import * as oidb from '@snowluma/bridge/bridge-oidb';
import * as highwayClient from '@snowluma/bridge/highway';
import * as highwayClient from '@snowluma/protocol/highway';
import { GroupFileApi } from '../../src/bridge/apis/group-file';
import { mockBridge } from './_helpers';
describe('actions/group-file', () => {
function packResponse(body: Uint8Array) {
return {
success: true, gotResponse: true, errorCode: 0, errorMessage: '',
responseData: Buffer.from(body),
};
}
describe('apis/group-file', () => {
beforeEach(() => {
vi.mocked(oidb.runOidb).mockReset();
vi.mocked(oidb.runOidb).mockResolvedValue(new Uint8Array());
vi.mocked(oidb.makeOidbEnvelope).mockClear();
vi.mocked(highwayClient.fetchHighwaySession).mockClear();
vi.mocked(highwayClient.uploadHighwayHttp).mockClear();
});
it('getCount returns { fileCount, maxCount } from the OIDB response', async () => {
const bridge = mockBridge();
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
protobuf_encode<OidbBase<OidbGroupFileCountViewResp>>({
body: { count: { fileCount: 42, maxCount: 1000 } },
}),
);
));
const out = await new GroupFileApi(bridge as any).getCount(12345);
expect(out).toEqual({ fileCount: 42, maxCount: 1000 });
});
it('getCount falls back to defaults on partial response', async () => {
const bridge = mockBridge();
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
protobuf_encode<OidbBase<OidbGroupFileCountViewResp>>({ body: { count: {} } }),
);
));
const out = await new GroupFileApi(bridge as any).getCount(12345);
expect(out).toEqual({ fileCount: 0, maxCount: 10000 });
});
it('upload skips highway when boolFileExist is true', async () => {
const bridge = mockBridge();
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
protobuf_encode<OidbBase<OidbGroupFileResp>>({
body: {
upload: {
// retCode 0 omitted by proto3 — production only checks against nonzero
fileId: 'fid-xyz',
boolFileExist: true,
},
} as any,
}),
);
));
const api = new GroupFileApi(bridge as any);
// Suppress the auto-publish — that path is covered separately.
vi.spyOn(api, 'publish').mockResolvedValue();
const out = await api.upload(12345, '/path/file.bin');
expect(out).toEqual({ fileId: 'fid-xyz' });
@@ -101,13 +96,12 @@ describe('actions/group-file', () => {
it('upload runs highway PUT when boolFileExist is false', async () => {
const bridge = mockBridge();
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
protobuf_encode<OidbBase<OidbGroupFileResp>>({
body: {
upload: {
fileId: 'fid-xyz',
// boolFileExist is the proto3 default (false) — omit, production
// sees undefined which the helper treats as "must upload via highway".
// boolFileExist is the proto3 default (false) — omit.
uploadIp: '1.2.3.4',
uploadPort: 8080,
fileKey: new Uint8Array([9]),
@@ -115,7 +109,7 @@ describe('actions/group-file', () => {
},
} as any,
}),
);
));
const api = new GroupFileApi(bridge as any);
vi.spyOn(api, 'publish').mockResolvedValue();
await api.upload(12345, '/path/file.bin');
@@ -125,20 +119,20 @@ describe('actions/group-file', () => {
it('upload throws on missing upload response', async () => {
const bridge = mockBridge();
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
protobuf_encode<OidbBase<OidbGroupFileResp>>({ body: {} }),
);
));
await expect(new GroupFileApi(bridge as any).upload(12345, '/path/file.bin'))
.rejects.toThrow(/response missing/);
});
it('upload bubbles up OIDB retCode errors', async () => {
const bridge = mockBridge();
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
protobuf_encode<OidbBase<OidbGroupFileResp>>({
body: { upload: { retCode: 999, retMsg: 'quota exceeded' } as any },
}),
);
));
await expect(new GroupFileApi(bridge as any).upload(12345, '/path/file.bin'))
.rejects.toThrow(/code=999/);
});
@@ -146,17 +140,13 @@ describe('actions/group-file', () => {
it('upload publishes the file via OIDB 0x6d9_4 after upload (the "empty message" regression)', async () => {
// Reproduces the bug report: OIDB upload + highway PUT alone only
// stage the bytes on QQ's side; without the trailing 0x6d9_4 OIDB
// call the file never appears in the chat. Earlier attempts used
// PbSendMsg with a transElem(24) but the QQ-NT server rejects that
// with result=79 (transElem(24) is a receive-side decoding shape,
// not a send-side one). Asserts that `this.publish` is invoked
// with the uploaded fileId.
// call the file never appears in the chat.
const bridge = mockBridge();
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
protobuf_encode<OidbBase<OidbGroupFileResp>>({
body: { upload: { fileId: 'fid-pub', boolFileExist: true } as any },
}),
);
));
const api = new GroupFileApi(bridge as any);
const publishSpy = vi.spyOn(api, 'publish').mockResolvedValue();
await api.upload(12345, '/path/some-file.bin', 'mynote.txt');
@@ -164,18 +154,16 @@ describe('actions/group-file', () => {
const [groupId, fileId] = publishSpy.mock.calls[0]!;
expect(groupId).toBe(12345);
expect(fileId).toBe('fid-pub');
// sendGroup must NOT be touched — the previous wire shape
// (PbSendMsg w/ transElem(24)) is the bug we're guarding against.
expect(bridge.apis.message.sendGroup).not.toHaveBeenCalled();
});
it('upload skips the chat post when uploadFile=false', async () => {
const bridge = mockBridge();
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
protobuf_encode<OidbBase<OidbGroupFileResp>>({
body: { upload: { fileId: 'fid-skip', boolFileExist: true } as any },
}),
);
));
const api = new GroupFileApi(bridge as any);
const publishSpy = vi.spyOn(api, 'publish').mockResolvedValue();
await api.upload(12345, '/path/file.bin', '', '/', false);
@@ -184,11 +172,11 @@ describe('actions/group-file', () => {
it('upload returns success even when the chat post fails (file is still uploaded)', async () => {
const bridge = mockBridge();
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
protobuf_encode<OidbBase<OidbGroupFileResp>>({
body: { upload: { fileId: 'fid-tolerant', boolFileExist: true } as any },
}),
);
));
const api = new GroupFileApi(bridge as any);
const publishSpy = vi.spyOn(api, 'publish').mockRejectedValueOnce(new Error('message rejected'));
const out = await api.upload(12345, '/path/file.bin');
@@ -197,15 +185,12 @@ describe('actions/group-file', () => {
});
it('upload caches the upload metadata for later resend by file_id', async () => {
// After upload, a later `send_group_msg` carrying just the file_id
// needs to recover the name/size/md5 from somewhere. Production
// populates `ctx.rememberUploadedFile` with the full tuple.
const bridge = mockBridge();
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
protobuf_encode<OidbBase<OidbGroupFileResp>>({
body: { upload: { fileId: 'fid-cached', boolFileExist: true } as any },
}),
);
));
const api = new GroupFileApi(bridge as any);
vi.spyOn(api, 'publish').mockResolvedValue();
await api.upload(12345, '/path/x.bin', 'x.bin');
@@ -220,30 +205,23 @@ describe('actions/group-file', () => {
});
it('publish hits OIDB 0x6d9_4 with the right body', async () => {
// Direct cover of the new bridge method. The previous send-shape
// (PbSendMsg + transElem(24)) failed with result=79; this is the
// Lagrange-V2-mirrored fix.
const bridge = mockBridge();
vi.mocked(oidb.runOidb).mockResolvedValueOnce(new Uint8Array());
await new GroupFileApi(bridge as any).publish(12345, 'fid-publish');
expect(oidb.runOidb).toHaveBeenCalledOnce();
const [, cmd] = vi.mocked(oidb.runOidb).mock.calls[0]!;
expect(cmd).toBe('OidbSvcTrpcTcp.0x6d9_4');
// The envelope wraps a `{body: {groupUin, type=2, info: {busiType=102, fileId, ...}}}`.
expect(oidb.makeOidbEnvelope).toHaveBeenCalledWith(
0x6D9, 4,
expect.objectContaining({
body: expect.objectContaining({
groupUin: 12345,
type: 2,
info: expect.objectContaining({
busiType: 102,
fileId: 'fid-publish',
field5: true,
}),
}),
expect(bridge.sendRawPacket).toHaveBeenCalledOnce();
const [wire, bytes] = bridge.sendRawPacket.mock.calls[0]!;
expect(wire).toBe('OidbSvcTrpcTcp.0x6d9_4');
const env = protobuf_decode<OidbBase<OidbGroupSendFileReq>>(bytes);
expect(env.command).toBe(0x6D9);
expect(env.subCommand).toBe(4);
expect(env.body?.body).toMatchObject({
groupUin: 12345,
type: 2,
info: expect.objectContaining({
busiType: 102,
fileId: 'fid-publish',
field5: true,
}),
);
});
});
it('uploadPrivate resolves both target + self UID before OIDB call', async () => {
@@ -258,31 +236,26 @@ describe('actions/group-file', () => {
},
});
vi.mocked(bridge.resolveUserUid)
.mockResolvedValueOnce('target-uid') // target user
.mockResolvedValueOnce('self-uid-resolved'); // self fallback
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
.mockResolvedValueOnce('target-uid')
.mockResolvedValueOnce('self-uid-resolved');
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
protobuf_encode<OidbBase<OidbPrivateFileUploadResp>>({
body: { upload: { uuid: 'fid', fileAddon: 'hash', boolFileExist: true } as any },
}),
);
));
const out = await new GroupFileApi(bridge as any).uploadPrivate(67890, '/path/file');
expect(out).toEqual({ fileId: 'fid', fileHash: 'hash' });
expect(bridge.resolveUserUid).toHaveBeenCalledTimes(2);
});
it('uploadPrivate publishes the file via apis.message.sendC2cFile after upload', async () => {
// C2C files use `RichText.notOnlineFile` (not in the elems array),
// so `uploadPrivate` calls the dedicated `sendC2cFile` path on
// the bridge rather than `sendPrivate`. Same bug class as the
// group case — without this the recipient sees no message even
// though the bytes are on the server.
const bridge = mockBridge();
vi.mocked(bridge.resolveUserUid).mockResolvedValueOnce('target-uid');
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
protobuf_encode<OidbBase<OidbPrivateFileUploadResp>>({
body: { upload: { uuid: 'pfid', fileAddon: 'phash', boolFileExist: true } as any },
}),
);
));
await new GroupFileApi(bridge as any).uploadPrivate(67890, '/path/private-file.bin', 'doc.pdf');
expect(bridge.apis.message.sendC2cFile).toHaveBeenCalledOnce();
const [userUin, userUid, info] = bridge.apis.message.sendC2cFile.mock.calls[0]!;
@@ -293,18 +266,13 @@ describe('actions/group-file', () => {
});
it('uploadPrivate caches the upload metadata for later resend by file_id', async () => {
// C2C file resend (send_private_msg with just file_id) was the
// "sends a 0 B file" bug: the wire packet needs fileSize/fileMd5/
// fileName/fileHash, but the OneBot caller only knows the file_id.
// Caching the upload tuple lets the OneBot send-message path
// recover the rest via `ctx.recallUploadedFile(fileId)`.
const bridge = mockBridge();
vi.mocked(bridge.resolveUserUid).mockResolvedValueOnce('target-uid');
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
protobuf_encode<OidbBase<OidbPrivateFileUploadResp>>({
body: { upload: { uuid: 'pfid-cache', fileAddon: 'addon-hash', boolFileExist: true } as any },
}),
);
));
await new GroupFileApi(bridge as any).uploadPrivate(67890, '/path/cache-me.txt', 'cache-me.txt');
expect(bridge.rememberUploadedFile).toHaveBeenCalledOnce();
const [meta] = bridge.rememberUploadedFile.mock.calls[0]!;
@@ -320,32 +288,24 @@ describe('actions/group-file', () => {
it('uploadPrivate skips the chat post when uploadFile=false', async () => {
const bridge = mockBridge();
vi.mocked(bridge.resolveUserUid).mockResolvedValueOnce('target-uid');
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
protobuf_encode<OidbBase<OidbPrivateFileUploadResp>>({
body: { upload: { uuid: 'pfid', fileAddon: 'phash', boolFileExist: true } as any },
}),
);
));
await new GroupFileApi(bridge as any).uploadPrivate(67890, '/path/file', '', false);
expect(bridge.apis.message.sendC2cFile).not.toHaveBeenCalled();
});
it('uploadPrivate reads host from rtpMediaPlatformUploadAddress[0].inIP when populated', async () => {
// The 2026 QQ-NT server rollout moved the upload host out of the
// legacy `uploadIp` (field 60) string into the new
// `rtpMediaPlatformUploadAddress` (field 210, repeated IPv4 message).
// Mirrors acidify's `UploadPrivateFile.kt` consumer logic — read
// `inIP` (LAN, same DC as the OIDB endpoint) and pair with `inPort`.
// The int is little-endian-packed: 0x0101A8C0 → 192.168.1.1.
const bridge = mockBridge();
vi.mocked(bridge.resolveUserUid).mockResolvedValueOnce('target-uid');
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
protobuf_encode<OidbBase<OidbPrivateFileUploadResp>>({
body: {
upload: {
uuid: 'pfid',
fileAddon: 'phash',
// boolFileExist defaults to false — forces highway path
// 192.168.1.1 little-endian packed = (1 << 24) | (1 << 16) | (168 << 8) | 192 = 16885952
rtpMediaPlatformUploadAddress: [
{ outIP: 0, outPort: 0, inIP: 16885952, inPort: 8080, iPType: 1 },
],
@@ -353,59 +313,46 @@ describe('actions/group-file', () => {
} as any,
},
}),
);
));
await new GroupFileApi(bridge as any).uploadPrivate(67890, '/path/file.bin');
expect(highwayClient.uploadHighwayHttp).toHaveBeenCalledOnce();
});
it('uploadPrivate falls back to uploadDomain when uploadIp is empty', async () => {
// Regression: the server has been observed in the wild returning the
// highway host in `uploadDomain` (field 70) instead of `uploadIp`
// (field 60), causing "private file upload host is invalid". The
// helper should walk the parallel host fields rather than dying on
// a single missing slot. Cross-referenced against napcat's proto
// (`Oidb.0XE37_800.ts` ApplyUploadRespV3) — fields 60/70/130/150/160
// all carry plausible host values from the same server endpoint.
const bridge = mockBridge();
vi.mocked(bridge.resolveUserUid).mockResolvedValueOnce('target-uid');
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
protobuf_encode<OidbBase<OidbPrivateFileUploadResp>>({
body: {
upload: {
uuid: 'pfid',
fileAddon: 'phash',
// boolFileExist defaults to false (proto3) — forces the
// highway path where the host fields actually matter.
uploadDomain: 'upload.qpic.cn',
uploadPort: 8080,
mediaPlatformUploadKey: new Uint8Array([1, 2, 3]),
} as any,
},
}),
);
));
await new GroupFileApi(bridge as any).uploadPrivate(67890, '/path/file.bin');
expect(highwayClient.uploadHighwayHttp).toHaveBeenCalledOnce();
});
it('uploadPrivate throws "host is invalid" only when every host field is empty', async () => {
// The diagnostic warn-log lists every host slot to help users
// report which one the server actually populated; this test just
// asserts that the throw still fires when none of them carry a
// value (boolFileExist=false + no usable host).
const bridge = mockBridge();
vi.mocked(bridge.resolveUserUid).mockResolvedValueOnce('target-uid');
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
protobuf_encode<OidbBase<OidbPrivateFileUploadResp>>({
body: { upload: { uuid: 'pfid', fileAddon: 'phash', uploadPort: 8080 } as any },
}),
);
));
await expect(new GroupFileApi(bridge as any).uploadPrivate(67890, '/path/file.bin'))
.rejects.toThrow(/upload host is invalid/);
});
it('list paginates files + folders out of OIDB items', async () => {
const bridge = mockBridge();
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
protobuf_encode<OidbBase<OidbGroupFileViewResp>>({
body: {
list: {
@@ -417,7 +364,7 @@ describe('actions/group-file', () => {
} as any,
},
}),
);
));
const out = await new GroupFileApi(bridge as any).list(12345);
expect(out.files).toHaveLength(1);
expect(out.files[0]).toMatchObject({ fileId: 'f1', fileName: 'a.txt', uploader: 1, uploaderName: 'alice' });
@@ -427,7 +374,7 @@ describe('actions/group-file', () => {
it('getUrl builds the https URL from downloadDns + hex-encoded path', async () => {
const bridge = mockBridge();
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
protobuf_encode<OidbBase<OidbGroupFileResp>>({
body: {
download: {
@@ -436,49 +383,53 @@ describe('actions/group-file', () => {
} as any,
},
}),
);
));
const url = await new GroupFileApi(bridge as any).getUrl(12345, 'fid-xyz');
expect(url).toBe('https://cdn.example.com/ftn_handler/0102/?fname=fid-xyz');
});
it('getUrl throws when response is missing dns or url', async () => {
const bridge = mockBridge();
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
protobuf_encode<OidbBase<OidbGroupFileResp>>({
body: { download: {} as any },
}),
);
));
await expect(new GroupFileApi(bridge as any).getUrl(12345, 'fid-xyz'))
.rejects.toThrow(/invalid/);
});
it('delete / move dispatch the right sub-commands', async () => {
const bridge = mockBridge();
vi.mocked(oidb.runOidb)
.mockResolvedValueOnce(protobuf_encode<OidbBase<OidbGroupFileResp>>({ body: { delete: {} as any } }))
.mockResolvedValueOnce(protobuf_encode<OidbBase<OidbGroupFileResp>>({ body: { move: {} as any } }));
bridge.sendRawPacket
.mockResolvedValueOnce(packResponse(protobuf_encode<OidbBase<OidbGroupFileResp>>({ body: { delete: {} as any } })))
.mockResolvedValueOnce(packResponse(protobuf_encode<OidbBase<OidbGroupFileResp>>({ body: { move: {} as any } })));
const api = new GroupFileApi(bridge as any);
await api.delete(12345, 'fid');
await api.move(12345, 'fid', '/a', '/b');
expect(vi.mocked(oidb.makeOidbEnvelope).mock.calls.map(c => c[1])).toEqual([3, 5]);
const env1 = protobuf_decode<OidbBase<OidbGroupFileReq>>(bridge.sendRawPacket.mock.calls[0]![1]);
const env2 = protobuf_decode<OidbBase<OidbGroupFileReq>>(bridge.sendRawPacket.mock.calls[1]![1]);
expect(env1.subCommand).toBe(3);
expect(env2.subCommand).toBe(5);
});
it('createFolder / deleteFolder / renameFolder dispatch 0x6d7 family', async () => {
const bridge = mockBridge();
vi.mocked(oidb.runOidb)
.mockResolvedValueOnce(protobuf_encode<OidbBase<OidbGroupFileFolderResp>>({ body: { create: {} as any } }))
.mockResolvedValueOnce(protobuf_encode<OidbBase<OidbGroupFileFolderResp>>({ body: { delete: {} as any } }))
.mockResolvedValueOnce(protobuf_encode<OidbBase<OidbGroupFileFolderResp>>({ body: { rename: {} as any } }));
bridge.sendRawPacket
.mockResolvedValueOnce(packResponse(protobuf_encode<OidbBase<OidbGroupFileFolderResp>>({ body: { create: {} as any } })))
.mockResolvedValueOnce(packResponse(protobuf_encode<OidbBase<OidbGroupFileFolderResp>>({ body: { delete: {} as any } })))
.mockResolvedValueOnce(packResponse(protobuf_encode<OidbBase<OidbGroupFileFolderResp>>({ body: { rename: {} as any } })));
const api = new GroupFileApi(bridge as any);
await api.createFolder(1, 'folder');
await api.deleteFolder(1, 'fid');
await api.renameFolder(1, 'fid', 'newname');
expect(vi.mocked(oidb.makeOidbEnvelope).mock.calls.map(c => c[0])).toEqual([0x6D7, 0x6D7, 0x6D7]);
const cmds = bridge.sendRawPacket.mock.calls.map(c => c[0]);
expect(cmds).toEqual(['OidbSvcTrpcTcp.0x6d7_0', 'OidbSvcTrpcTcp.0x6d7_1', 'OidbSvcTrpcTcp.0x6d7_2']);
});
it('get*Url builds https://domain/path?rkey from the NTV2 response', async () => {
const bridge = mockBridge();
vi.mocked(oidb.runOidb).mockResolvedValue(
bridge.sendRawPacket.mockResolvedValue(packResponse(
protobuf_encode<OidbBase<NTV2RichMediaResp>>({
body: {
respHead: {},
@@ -488,7 +439,7 @@ describe('actions/group-file', () => {
} as any,
} as any,
}),
);
));
const url = await new GroupFileApi(bridge as any).getVideoUrl(12345, { fileUuid: 'uuid' });
expect(url).toBe('https://media.example.com/path/x?rkey=abc');
});
@@ -6,7 +6,7 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
vi.mock('@snowluma/bridge/bridge-oidb', () => ({
vi.mock('@snowluma/protocol/bridge-oidb', () => ({
runOidb: vi.fn(async () => new Uint8Array()),
makeOidbEnvelope: vi.fn((_oidbCmd, _subCmd, body) => ({ body })),
encodeOidbEnv: vi.fn(() => new Uint8Array()),
+24 -44
View File
@@ -1,66 +1,44 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { describe, it, expect } from 'vitest';
import { protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { Oidb0x9083Resp } from '@snowluma/proto-defs/oidb-actions/base';
// `encodeOidbEnv` / `decodeOidbEnv` are proton-bound pass-through wrappers
// that the plugin substitutes at the call site for the inlined codec.
// That means production calls to them NEVER hit the imported function —
// mocking them on the module object is a no-op. The only mockable point
// is `runOidb` (non-generic, untouched by proton) returning real bytes
// that the production-side codec actually decodes. `makeOidbEnvelope` is
// a pure TS helper, so its mock works for introspection.
vi.mock('@snowluma/bridge/bridge-oidb', async () => {
const actual = await vi.importActual<typeof import('@snowluma/bridge/bridge-oidb')>(
'@snowluma/bridge/bridge-oidb',
);
return {
...actual,
runOidb: vi.fn(async () => new Uint8Array()),
makeOidbEnvelope: vi.fn((_oidbCmd, _subCmd, body) => ({ body })),
};
});
import * as oidb from '@snowluma/bridge/bridge-oidb';
// Post-namespace-migration: InteractionApi is a thin facade and
// production code routes through the namespace path (sender →
// sendRawPacket). Tests now assert against the bridge mock's
// sendRawPacket directly — no need for module-level mocks on the
// bridge-oidb internals.
import { InteractionApi } from '../../src/bridge/apis/interaction';
import { mockBridge } from './_helpers';
describe('apis/interaction', () => {
beforeEach(() => {
vi.mocked(oidb.runOidb).mockReset();
vi.mocked(oidb.runOidb).mockResolvedValue(new Uint8Array());
vi.mocked(oidb.makeOidbEnvelope).mockClear();
});
it('sendPoke group: groupUin set, friendUin=0', async () => {
const bridge = mockBridge();
await new InteractionApi(bridge as any).sendPoke(true, 12345, 67890);
const body = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2];
expect(body).toMatchObject({ uin: 67890, groupUin: 12345, friendUin: 0 });
expect(bridge.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0xed3_1');
});
it('sendPoke friend: friendUin set, groupUin=0, targetUin defaults to peer', async () => {
const bridge = mockBridge();
await new InteractionApi(bridge as any).sendPoke(false, 67890);
const body = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2];
expect(body).toMatchObject({ uin: 67890, groupUin: 0, friendUin: 67890 });
expect(bridge.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0xed3_1');
});
it('sendLike forwards target + count to 0x7e5_104', async () => {
const bridge = mockBridge();
await new InteractionApi(bridge as any).sendLike(10001, 3);
const [, cmd] = vi.mocked(oidb.runOidb).mock.calls[0]!;
expect(cmd).toBe('OidbSvcTrpcTcp.0x7e5_104');
const body = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2];
expect(body).toMatchObject({ targetUin: 10001, count: 3 });
expect(bridge.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0x7e5_104');
});
it('setReaction picks _1 for set and _2 for unset', async () => {
// setReaction now forwards through the SetReaction namespace, which
// calls bridge.sendRawPacket directly (bypassing runOidb).
const bridge = mockBridge();
const api = new InteractionApi(bridge as any);
await api.setReaction(12345, 99, '128516', true);
await api.setReaction(12345, 99, '128516', false);
const cmds = vi.mocked(oidb.runOidb).mock.calls.map(c => c[1]);
const cmds = bridge.sendRawPacket.mock.calls.map((c: any[]) => c[0]);
expect(cmds).toEqual(['OidbSvcTrpcTcp.0x9082_1', 'OidbSvcTrpcTcp.0x9082_2']);
});
@@ -69,31 +47,33 @@ describe('apis/interaction', () => {
const api = new InteractionApi(bridge as any);
await api.setEssence(12345, 99, 0, true);
await api.setEssence(12345, 99, 0, false);
const cmds = vi.mocked(oidb.runOidb).mock.calls.map(c => c[1]);
const cmds = bridge.sendRawPacket.mock.calls.map((c: any[]) => c[0]);
expect(cmds).toEqual(['OidbSvcTrpcTcp.0xeac_1', 'OidbSvcTrpcTcp.0xeac_2']);
});
it('getEmojiLikes decodes user list, base64-encodes cookie, and reports isLast', async () => {
const bridge = mockBridge();
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
protobuf_encode<OidbBase<Oidb0x9083Resp>>({
bridge.sendRawPacket.mockResolvedValueOnce({
success: true, gotResponse: true, errorCode: 0, errorMessage: '',
responseData: Buffer.from(protobuf_encode<OidbBase<Oidb0x9083Resp>>({
body: {
inner: { userInfo: { uin: 10001n } },
inner: { userInfo: [{ uin: 10001n }, { uin: 20002n }] },
cookie: new Uint8Array([0xCA, 0xFE]),
} as any,
}),
);
})),
});
const out = await new InteractionApi(bridge as any).getEmojiLikes(12345, 99, '128516');
expect(out.users).toEqual([{ uin: 10001 }]);
expect(out.users).toEqual([{ uin: 10001 }, { uin: 20002 }]);
expect(out.cookie).toBe(Buffer.from([0xCA, 0xFE]).toString('base64'));
expect(out.isLast).toBe(false);
});
it('getEmojiLikes reports isLast=true when no cookie comes back', async () => {
const bridge = mockBridge();
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
protobuf_encode<OidbBase<Oidb0x9083Resp>>({ body: {} }),
);
bridge.sendRawPacket.mockResolvedValueOnce({
success: true, gotResponse: true, errorCode: 0, errorMessage: '',
responseData: Buffer.from(protobuf_encode<OidbBase<Oidb0x9083Resp>>({ body: {} })),
});
const out = await new InteractionApi(bridge as any).getEmojiLikes(12345, 99, '128516');
expect(out.users).toEqual([]);
expect(out.isLast).toBe(true);
+29 -43
View File
@@ -1,4 +1,4 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { describe, it, expect, vi } from 'vitest';
import { protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
@@ -6,64 +6,49 @@ import type {
Oidb0x112eResp,
} from '@snowluma/proto-defs/oidb-actions/base';
// `encodeOidbEnv` / `decodeOidbEnv` are proton-bound pass-through wrappers
// — the plugin substitutes them at the call site with the inlined codec,
// so mocking them on the module object is a no-op. We mock `runOidb`
// (non-generic, untouched by proton) to return real proton-encoded bytes
// that the production-side codec then actually decodes.
vi.mock('@snowluma/bridge/bridge-oidb', async () => {
const actual = await vi.importActual<typeof import('@snowluma/bridge/bridge-oidb')>(
'@snowluma/bridge/bridge-oidb',
);
return {
...actual,
runOidb: vi.fn(async () => new Uint8Array()),
makeOidbEnvelope: vi.fn((_oidbCmd, _subCmd, body) => ({ body })),
};
});
import * as oidb from '@snowluma/bridge/bridge-oidb';
// Post-namespace migration: MiscApi forwards 3 OIDB cmds through
// @snowluma/protocol/oidb-services/misc namespaces. The non-OIDB
// `getMiniAppArk` (LightAppSvc) stays inline on the facade. Tests
// hit bridge.sendRawPacket directly.
import { MiscApi } from '../../src/bridge/apis/misc';
import { mockBridge } from './_helpers';
describe('apis/misc', () => {
beforeEach(() => {
vi.mocked(oidb.runOidb).mockReset();
vi.mocked(oidb.runOidb).mockResolvedValue(new Uint8Array());
vi.mocked(oidb.makeOidbEnvelope).mockClear();
});
function packResponse(body: Uint8Array) {
return {
success: true, gotResponse: true, errorCode: 0, errorMessage: '',
responseData: Buffer.from(body),
};
}
describe('apis/misc', () => {
it('translateEn2Zh returns dstWords when present', async () => {
const bridge = mockBridge();
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
protobuf_encode<OidbBase<Oidb0x990Resp>>({
body: { translateResp: { dstWords: ['你好', '世界'] } } as any,
}),
);
const out = await new MiscApi(bridge as any).translateEn2Zh( ['hello', 'world']);
));
const out = await new MiscApi(bridge as any).translateEn2Zh(['hello', 'world']);
expect(out).toEqual(['你好', '世界']);
});
it('translateEn2Zh throws on empty response', async () => {
const bridge = mockBridge();
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
protobuf_encode<OidbBase<Oidb0x990Resp>>({ body: {} }),
);
await expect(new MiscApi(bridge as any).translateEn2Zh( ['hello']))
));
await expect(new MiscApi(bridge as any).translateEn2Zh(['hello']))
.rejects.toThrow(/empty/);
});
it('getMiniAppArk rejects unsupported types', async () => {
const bridge = mockBridge();
await expect(
new MiscApi(bridge as any).getMiniAppArk( 'youtube', 't', 'd', 'p', 'u'),
new MiscApi(bridge as any).getMiniAppArk('youtube', 't', 'd', 'p', 'u'),
).rejects.toThrow(/unsupported type/);
});
it('getMiniAppArk routes to LightAppSvc with the encoded body', async () => {
// sendRawPacket is what the action calls; we need a deterministic
// successful response with a decodable body. Easiest: stub the
// raw packet with the encoded response we expect to come back.
const bridge = mockBridge({
sendRawPacket: vi.fn(async () => ({
success: true,
@@ -73,9 +58,7 @@ describe('apis/misc', () => {
responseData: null,
})) as any,
});
// With null responseData, the action should throw on decode — that
// still proves the right serviceCmd was used.
await expect(new MiscApi(bridge as any).getMiniAppArk( 'bili', 't', 'd', 'p', 'u')).rejects.toThrow();
await expect(new MiscApi(bridge as any).getMiniAppArk('bili', 't', 'd', 'p', 'u')).rejects.toThrow();
expect(bridge.sendRawPacket).toHaveBeenCalledOnce();
expect(bridge.sendRawPacket.mock.calls[0]![0])
.toBe('LightAppSvc.mini_app_share.AdaptShareInfo');
@@ -83,19 +66,22 @@ describe('apis/misc', () => {
it('clickInlineKeyboardButton returns shaped result', async () => {
const bridge = mockBridge();
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
protobuf_encode<OidbBase<Oidb0x112eResp>>({
body: { result: 1, errMsg: 'ok', promptText: 'hi' } as any,
}),
);
const out = await new MiscApi(bridge as any).clickInlineKeyboardButton( 1, 2, 'btn', 'data', 100);
));
const out = await new MiscApi(bridge as any).clickInlineKeyboardButton(1, 2, 'btn', 'data', 100);
expect(out).toMatchObject({ result: 1, errMsg: 'ok', promptText: 'hi', status: 0 });
});
it('sendGroupSign dispatches to 0xEB7_1', async () => {
it('sendGroupSign dispatches to 0xEB7_1 (uppercase preserved)', async () => {
const bridge = mockBridge();
await new MiscApi(bridge as any).sendGroupSign( 12345);
const [, cmd] = vi.mocked(oidb.runOidb).mock.calls[0]!;
await new MiscApi(bridge as any).sendGroupSign(12345);
const [cmd] = bridge.sendRawPacket.mock.calls[0]!;
// **Important**: this cmd keeps the historic UPPERCASE EB7 wire
// name. Default scheme would emit lowercase; the namespace
// overrides `wireName` to preserve byte-equality with NTQQ wire.
expect(cmd).toBe('OidbSvcTrpcTcp.0xEB7_1');
});
});
+29 -28
View File
@@ -14,9 +14,9 @@ import type {
// the module object is a no-op — proton has already inlined the call.
// We mock `runOidb` (non-generic) to return real proton-encoded bytes
// that the production-side codec actually decodes.
vi.mock('@snowluma/bridge/bridge-oidb', async () => {
const actual = await vi.importActual<typeof import('@snowluma/bridge/bridge-oidb')>(
'@snowluma/bridge/bridge-oidb',
vi.mock('@snowluma/protocol/bridge-oidb', async () => {
const actual = await vi.importActual<typeof import('@snowluma/protocol/bridge-oidb')>(
'@snowluma/protocol/bridge-oidb',
);
return {
...actual,
@@ -25,19 +25,19 @@ vi.mock('@snowluma/bridge/bridge-oidb', async () => {
};
});
vi.mock('@snowluma/bridge/highway', () => ({
vi.mock('@snowluma/protocol/highway', () => ({
fetchHighwaySession: vi.fn(async () => ({})),
uploadHighwayHttp: vi.fn(async () => undefined),
}));
vi.mock('@snowluma/bridge/highway/utils', () => ({
vi.mock('@snowluma/protocol/highway/utils', () => ({
loadBinarySource: vi.fn(async () => ({ bytes: new Uint8Array([1, 2, 3]), fileName: 'avatar.bin' })),
computeHashes: vi.fn(() => ({ md5: new Uint8Array(16), sha1: new Uint8Array(20) })),
computeMd5: vi.fn(() => new Uint8Array(16)),
}));
import * as oidb from '@snowluma/bridge/bridge-oidb';
import * as highwayClient from '@snowluma/bridge/highway';
import * as oidb from '@snowluma/protocol/bridge-oidb';
import * as highwayClient from '@snowluma/protocol/highway';
import { ProfileApi } from '../../src/bridge/apis/profile';
import { mockBridge } from './_helpers';
@@ -104,30 +104,28 @@ describe('apis/profile', () => {
it('setProfile is a no-op when both arguments are undefined', async () => {
const bridge = mockBridge();
await new ProfileApi(bridge as any).setProfile();
expect(oidb.runOidb).not.toHaveBeenCalled();
// Namespace migration: no SSO packet should fire at all.
expect(bridge.sendRawPacket).not.toHaveBeenCalled();
});
it('setProfile only sends non-undefined fields', async () => {
const bridge = mockBridge();
await new ProfileApi(bridge as any).setProfile('New Nick');
expect(oidb.runOidb).toHaveBeenCalledOnce();
const body = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2];
expect((body as any).stringProfiles).toEqual([{ fieldId: 20002, value: 'New Nick' }]);
expect(bridge.sendRawPacket).toHaveBeenCalledOnce();
expect(bridge.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0x112a_2');
});
it('setSelfLongNick wraps the long nick in profile tag 102', async () => {
it('setSelfLongNick targets 0x112a_2 wire cmd', async () => {
const bridge = mockBridge();
await new ProfileApi(bridge as any).setSelfLongNick( 'hello world');
const body = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2];
expect((body as any).profile).toEqual({ tag: 102, value: 'hello world' });
expect(bridge.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0x112a_2');
});
it('setInputStatus resolves UID first and sends 0xcd4_1', async () => {
const bridge = mockBridge();
await new ProfileApi(bridge as any).setInputStatus( 10001, 1);
expect(bridge.resolveUserUid).toHaveBeenCalledWith(10001);
const [, cmd] = vi.mocked(oidb.runOidb).mock.calls[0]!;
expect(cmd).toBe('OidbSvcTrpcTcp.0xcd4_1');
expect(bridge.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0xcd4_1');
});
it('setAvatar loads bytes and pushes through the highway upload path (cmd 90)', async () => {
@@ -161,7 +159,7 @@ describe('apis/profile', () => {
it('setGroupAvatar rejects an empty file before hitting highway', async () => {
const bridge = mockBridge();
const { loadBinarySource } = await import('@snowluma/bridge/highway/utils');
const { loadBinarySource } = await import('@snowluma/protocol/highway/utils');
vi.mocked(loadBinarySource).mockResolvedValueOnce({
bytes: new Uint8Array(0), fileName: 'empty.png',
} as any);
@@ -171,8 +169,9 @@ describe('apis/profile', () => {
it('getProfileLike (self): resolves self UID, returns formatted favorite + vote info', async () => {
const bridge = mockBridge();
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
protobuf_encode<OidbBase<Oidb0x7edResp>>({
bridge.sendRawPacket.mockResolvedValueOnce({
success: true, gotResponse: true, errorCode: 0, errorMessage: '',
responseData: Buffer.from(protobuf_encode<OidbBase<Oidb0x7edResp>>({
body: {
userLikeInfos: [{
uid: 'u',
@@ -181,8 +180,8 @@ describe('apis/profile', () => {
voteInfo: { totalCount: 7, newCount: 2, lastTime: 2n },
}],
} as any,
}),
);
})),
});
const out = await new ProfileApi(bridge as any).getLike();
expect(out.favoriteInfo.total_count).toBe(5);
expect(out.voteInfo.total_count).toBe(7);
@@ -190,19 +189,21 @@ describe('apis/profile', () => {
it('getProfileLike throws on empty result', async () => {
const bridge = mockBridge();
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
protobuf_encode<OidbBase<Oidb0x7edResp>>({ body: { userLikeInfos: [] } as any }),
);
bridge.sendRawPacket.mockResolvedValueOnce({
success: true, gotResponse: true, errorCode: 0, errorMessage: '',
responseData: Buffer.from(protobuf_encode<OidbBase<Oidb0x7edResp>>({ body: { userLikeInfos: [] } as any })),
});
await expect(new ProfileApi(bridge as any).getLike()).rejects.toThrow(/empty/);
});
it('getUnidirectionalFriendList parses the embedded JSON body', async () => {
const bridge = mockBridge();
vi.mocked(oidb.runOidb).mockResolvedValueOnce(
protobuf_encode<OidbBase<Oidb0xe17Resp>>({
bridge.sendRawPacket.mockResolvedValueOnce({
success: true, gotResponse: true, errorCode: 0, errorMessage: '',
responseData: Buffer.from(protobuf_encode<OidbBase<Oidb0xe17Resp>>({
body: { jsonBody: JSON.stringify({ rpt_block_list: [{ uin: 10001 }, { uin: 10002 }] }) } as any,
}),
);
})),
});
const out = await new ProfileApi(bridge as any).getUnidirectionalFriendList();
expect(out).toEqual([{ uin: 10001 }, { uin: 10002 }]);
});
+2 -2
View File
@@ -1,6 +1,6 @@
import { describe, expect, it, vi } from 'vitest';
import { BridgeEventBus } from '@snowluma/bridge/event-bus';
import type { FriendMessage, GroupMessage } from '@snowluma/bridge/events';
import { BridgeEventBus } from '@snowluma/protocol/event-bus';
import type { FriendMessage, GroupMessage } from '@snowluma/protocol/events';
function makeFriendMessage(): FriendMessage {
return {
@@ -1,8 +1,8 @@
import { describe, expect, it } from 'vitest';
import { Bridge } from '../src/bridge/bridge';
import { IdentityService } from '@snowluma/bridge/identity-service';
import type { GroupMemberInfo, QQGroupInfo } from '@snowluma/bridge/qq-info';
import type { GroupMemberJoin, QQEventVariant } from '@snowluma/bridge/events';
import { IdentityService } from '@snowluma/protocol/identity-service';
import type { GroupMemberInfo, QQGroupInfo } from '@snowluma/protocol/qq-info';
import type { GroupMemberJoin, QQEventVariant } from '@snowluma/protocol/events';
import type { PacketInfo } from '@snowluma/common/protocol-types';
const SELF_UIN = '10001';
@@ -4,14 +4,14 @@ import type { SendPacketResult } from '@snowluma/common/packet-sender';
import type { SendMessageRequest, SendMessageResponse } from '@snowluma/proto-defs/action';
import type { FileExtra } from '@snowluma/proto-defs/message';
vi.mock('@snowluma/bridge/element-builder', () => ({
vi.mock('@snowluma/protocol/element-builder', () => ({
buildSendElems: vi.fn(async () => [{ text: { str: 'stub media elem' } }]),
}));
describe('Bridge private media routing', () => {
it('includes resolved uid in the final c2c send request for media messages', async () => {
const { Bridge } = await import('../src/bridge/bridge');
const { IdentityService } = await import('@snowluma/bridge/identity-service');
const { IdentityService } = await import('@snowluma/protocol/identity-service');
class TestBridge extends Bridge {
capturedBody: Uint8Array | null = null;
@@ -60,7 +60,7 @@ describe('Bridge private media routing', () => {
// implementation wrote c2c routing + richText.notOnlineFile +
// c2cCmd=11 — the QQ-NT server rejected every c2c file send.
const { Bridge } = await import('../src/bridge/bridge');
const { IdentityService } = await import('@snowluma/bridge/identity-service');
const { IdentityService } = await import('@snowluma/protocol/identity-service');
class TestBridge extends Bridge {
capturedBody: Uint8Array | null = null;
+92 -4
View File
@@ -15,18 +15,19 @@
// recognise and got rejected with result=79.
import { describe, expect, it, vi } from 'vitest';
import { inflateSync } from 'zlib';
vi.mock('@snowluma/bridge/highway/image-upload', () => ({
vi.mock('@snowluma/protocol/highway/image-upload', () => ({
uploadImageMsgInfo: vi.fn(async () => new Uint8Array([7, 8, 9])),
}));
vi.mock('@snowluma/bridge/highway/ptt-upload', () => ({
vi.mock('@snowluma/protocol/highway/ptt-upload', () => ({
uploadPttMsgInfo: vi.fn(async () => new Uint8Array([4, 5, 6])),
}));
vi.mock('@snowluma/bridge/highway/video-upload', () => ({
vi.mock('@snowluma/protocol/highway/video-upload', () => ({
uploadVideoMsgInfo: vi.fn(async () => new Uint8Array([1, 2, 3])),
}));
import { buildSendElems } from '@snowluma/bridge/element-builder';
import { buildSendElems } from '@snowluma/protocol/element-builder';
const fakeBridge = {} as any;
@@ -118,3 +119,90 @@ describe('element-builder / file element is no longer carried in elems[]', () =>
expect(result).toEqual([]);
});
});
describe('element-builder / forward preview (com.tencent.multimsg LightApp)', () => {
// The forward preview is the bubble the recipient renders in chat
// before tapping to expand. It MUST be the modern LightApp /
// `com.tencent.multimsg` JSON (not the older `richMsg serviceID=35`
// XML) because nested forwards rely on `meta.detail.uniseq` to link
// each inner preview to the matching `actionCommand` piggyback on
// the outer's LongMsgResult — without uniseq the QQ-NT client has
// no way to walk the tree and has to re-fetch each inner resId.
function decodeLightApp(elem: any): unknown {
const data: Uint8Array = elem.lightApp.data;
expect(data[0]).toBe(0x01); // deflate prefix
const inflated = inflateSync(Buffer.from(data.subarray(1))).toString('utf8');
return JSON.parse(inflated);
}
it('emits a lightApp.data blob with prefix=0x01 (deflated JSON, not XML/serviceID=35)', async () => {
const [elem] = await buildSendElems(
[{ type: 'forward', resId: 'res-XYZ' } as any],
{ bridge: fakeBridge, groupId: 12345 },
);
expect(elem.lightApp).toBeDefined();
expect((elem as any).richMsg).toBeUndefined();
expect(elem.lightApp!.data![0]).toBe(0x01);
});
it('places resid + uniseq inside meta.detail (and uniseq matches extra.filename)', async () => {
const [elem] = await buildSendElems(
[{ type: 'forward', resId: 'res-XYZ', forwardUuid: 'fixed-uuid-1234' } as any],
{ bridge: fakeBridge, groupId: 12345 },
);
const json = decodeLightApp(elem) as any;
expect(json.app).toBe('com.tencent.multimsg');
expect(json.meta.detail.resid).toBe('res-XYZ');
expect(json.meta.detail.uniseq).toBe('fixed-uuid-1234');
// `extra` is a JSON string holding {filename, tsum}; filename must
// round-trip the same uniseq so the QQ-NT client links them.
const extra = JSON.parse(json.extra);
expect(extra.filename).toBe('fixed-uuid-1234');
});
it('autogenerates a uniseq when the element omits forwardUuid (flat forward — cosmetic)', async () => {
const [elem] = await buildSendElems(
[{ type: 'forward', resId: 'res-flat' } as any],
{ bridge: fakeBridge, groupId: 12345 },
);
const json = decodeLightApp(elem) as any;
expect(json.meta.detail.resid).toBe('res-flat');
// Auto-generated UUID — non-empty, non-trivial.
expect(json.meta.detail.uniseq).toMatch(/^[0-9a-f-]{36}$/i);
const extra = JSON.parse(json.extra);
expect(extra.filename).toBe(json.meta.detail.uniseq);
});
it('threads forwardSource / forwardSummary / forwardPrompt / forwardNews / forwardTSum verbatim', async () => {
const [elem] = await buildSendElems(
[{
type: 'forward', resId: 'r1', forwardUuid: 'u1',
forwardSource: 'alice和bob的聊天记录',
forwardSummary: '查看3条转发消息',
forwardPrompt: '[聊天记录]',
forwardNews: [{ text: 'alice: hi' }, { text: 'bob: hey' }],
forwardTSum: 3,
} as any],
{ bridge: fakeBridge, groupId: 12345 },
);
const json = decodeLightApp(elem) as any;
expect(json.meta.detail.source).toBe('alice和bob的聊天记录');
expect(json.meta.detail.summary).toBe('查看3条转发消息');
expect(json.meta.detail.news).toEqual([{ text: 'alice: hi' }, { text: 'bob: hey' }]);
expect(json.desc).toBe('[聊天记录]');
expect(json.prompt).toBe('[聊天记录]');
expect(JSON.parse(json.extra).tsum).toBe(3);
});
it('drops the forward element when resId is missing (preview unrenderable, fail open)', async () => {
// The dispatcher's `case 'forward': if (elem.resId) ...` short-
// circuits when resId is empty so a malformed segment from the
// OneBot client doesn't blow up the whole send. Receiver sees
// no forward bubble — same outcome as omitting the segment.
const out = await buildSendElems(
[{ type: 'forward' } as any],
{ bridge: fakeBridge, groupId: 12345 },
);
expect(out).toEqual([]);
});
});
+2 -2
View File
@@ -12,8 +12,8 @@ import {
formatMessageSegments,
formatReply,
formatUser,
} from '@snowluma/bridge/format';
import type { QQEventVariant } from '@snowluma/bridge/events';
} from '@snowluma/protocol/format';
import type { QQEventVariant } from '@snowluma/protocol/events';
// ─── Test fakes (just the find* surface event-format uses) ───
+1 -1
View File
@@ -3,7 +3,7 @@ import os from 'os';
import path from 'path';
import { pathToFileURL } from 'url';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { loadBinarySource, resolveLocalFilePath } from '@snowluma/bridge/highway/utils';
import { loadBinarySource, resolveLocalFilePath } from '@snowluma/protocol/highway/utils';
describe('highway source paths', () => {
it('normalizes file URLs with an extra leading slash on POSIX', () => {
@@ -5,13 +5,13 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
vi.mock('@snowluma/bridge/highway/pipeline', () => ({
vi.mock('@snowluma/protocol/highway/pipeline', () => ({
runNtv2Upload: vi.fn(async () => ({ msgInfo: { msgInfoBody: [], extBizInfo: {} } })),
finalizeMediaMsgInfo: vi.fn(() => new Uint8Array([0xCA, 0xFE])),
hexToBytes: vi.fn((hex: string) => new Uint8Array(hex.length / 2)),
}));
vi.mock('@snowluma/bridge/highway/utils', () => ({
vi.mock('@snowluma/protocol/highway/utils', () => ({
loadBinarySource: vi.fn(async () => ({ bytes: new Uint8Array([1, 2, 3]), fileName: 'src.jpg' })),
computeHashes: vi.fn(() => ({
md5: new Uint8Array(16),
@@ -22,9 +22,9 @@ vi.mock('@snowluma/bridge/highway/utils', () => ({
detectImageFormat: vi.fn(() => ({ format: 1000, width: 800, height: 600 })),
}));
import * as pipeline from '@snowluma/bridge/highway/pipeline';
import { uploadImageMsgInfo } from '@snowluma/bridge/highway/image-upload';
import { GROUP_IMAGE_CMD_ID, PRIVATE_IMAGE_CMD_ID } from '@snowluma/bridge/highway';
import * as pipeline from '@snowluma/protocol/highway/pipeline';
import { uploadImageMsgInfo } from '@snowluma/protocol/highway/image-upload';
import { GROUP_IMAGE_CMD_ID, PRIVATE_IMAGE_CMD_ID } from '@snowluma/protocol/highway';
describe('image-upload', () => {
beforeEach(() => {
@@ -67,16 +67,18 @@ describe('image-upload', () => {
expect(fileInfo.original).toBe(1);
});
it('forwards subType into bizType and ${subType}-aware textSummary', async () => {
it('forwards subType=1 (sticker) into bizType + Chinese textSummary `[动画表情]`', async () => {
// QQ chat-list bubble preview text — must match the literal
// strings mobile QQ / Lagrange.Core / NapCat all emit.
await uploadImageMsgInfo({} as any, true, 12345, { url: 'http://x', subType: 1 } as any);
const args = vi.mocked(pipeline.runNtv2Upload).mock.calls[0]![0];
expect((args.extBizInfo as any).pic.bizType).toBe(1);
expect((args.extBizInfo as any).pic.textSummary).toBe('[sticker]');
expect((args.extBizInfo as any).pic.textSummary).toBe('[动画表情]');
});
it('fingerprint path (noByteFallback): zero bytes, fastOnly error message ready', async () => {
await uploadImageMsgInfo({} as any, true, 12345, {
noByteFallback: true, md5Hex: 'aa', sha1Hex: 'bb', summary: '[image]',
noByteFallback: true, md5Hex: 'aa', sha1Hex: 'bb', summary: '[图片]',
} as any);
const sub = vi.mocked(pipeline.runNtv2Upload).mock.calls[0]![0].uploads[0]!;
expect(sub.bytes.length).toBe(0);
@@ -89,10 +91,20 @@ describe('image-upload', () => {
} as any)).rejects.toThrow(/requires md5Hex/);
});
it('finalize is invoked with pic defaults for image', async () => {
it('finalize is invoked with pic defaults for image (Chinese `[图片]`)', async () => {
await uploadImageMsgInfo({} as any, true, 12345, { url: 'http://x', subType: 0 } as any);
expect(pipeline.finalizeMediaMsgInfo).toHaveBeenCalledOnce();
const [, defaultPic] = vi.mocked(pipeline.finalizeMediaMsgInfo).mock.calls[0]!;
expect(defaultPic).toEqual({ bizType: 0, textSummary: '[image]' });
expect(defaultPic).toEqual({ bizType: 0, textSummary: '[图片]' });
});
it('caller-supplied summary wins over the Chinese default', async () => {
// OneBot clients can pass `summary: '[心形图片]'` (or any custom
// text) — that overrides our default and goes through verbatim.
await uploadImageMsgInfo({} as any, true, 12345, {
url: 'http://x', subType: 0, summary: '[custom-bubble]',
} as any);
const [, defaultPic] = vi.mocked(pipeline.finalizeMediaMsgInfo).mock.calls[0]!;
expect(defaultPic).toEqual({ bizType: 0, textSummary: '[custom-bubble]' });
});
});
@@ -0,0 +1,241 @@
// Regression test for the "two images in one message" bug user report.
//
// User saw: 1st image fast-uploaded (server already had the bytes), 2nd
// image triggered an actual highway PUT and the highway server returned
// `error_code=921`.
//
// This test walks two `runNtv2Upload` calls back-to-back through the
// real pipeline + buildHighwayExtend code path with the highway TCP/HTTP
// transport stubbed, and verifies:
//
// - the two calls don't share state (each has its own session, its
// own OIDB request, its own extend bytes),
// - the second call's extend payload is well-formed (uKey + msgInfoBody
// + ipv4s come from the *second* call's response, not the first),
// - the highway PUT receives the second image's bytes + md5 + sha1
// verbatim (no aliasing / truncation across calls).
//
// If this test ever starts failing, it's a real bug in the pipeline
// (state sharing, async race, or wrong-buffer aliasing). If it
// continues to pass, the user's 921 is almost certainly server-side
// (rate limit, malformed image rejection, expired session) rather than
// a client-emit issue.
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
vi.mock('@snowluma/protocol/highway', async () => {
const real = await vi.importActual<typeof import('@snowluma/protocol/highway')>('@snowluma/protocol/highway');
return {
...real,
// Only the TCP/HTTP transport is mocked — we keep real
// `buildHighwayExtend` so we can inspect its output bytes.
fetchHighwaySession: vi.fn(async () => ({
sigSession: new Uint8Array([0xAA]),
sessionKey: new Uint8Array([0xBB]),
host: 'highway.example',
port: 80,
})),
uploadHighwayHttp: vi.fn(async () => undefined),
};
});
import * as highway from '@snowluma/protocol/highway';
import { runNtv2Upload, type MediaSubFileUpload } from '@snowluma/protocol/highway/pipeline';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
NTV2UploadRichMediaReq,
NTV2UploadRichMediaResp,
NTV2RichMediaHighwayExt,
} from '@snowluma/proto-defs/highway';
function encodeOidbResponse(body: any): Buffer {
return Buffer.from(protobuf_encode<OidbBase<NTV2UploadRichMediaResp>>({
command: 0x11C4, subCommand: 100, errorCode: 0,
body: body as Record<string, unknown>, errorMsg: '', reserved: 1,
}));
}
function makeBridge(responses: Buffer[]) {
const sendRawPacket = vi.fn();
for (const r of responses) {
sendRawPacket.mockResolvedValueOnce({
success: true, gotResponse: true, errorCode: 0, errorMessage: '',
responseData: r,
});
}
return { sendRawPacket, identity: { uin: '10001' } } as any;
}
const baseParams = (bridge: any) => ({
bridge, isGroup: true, targetIdOrUid: 894750076,
oidbCmd: 0x11C4, serviceCmd: 'OidbSvcTrpcTcp.0x11c4_100',
requestId: 1, businessType: 1,
compatQmsgSceneType: 2,
extBizInfo: { pic: { bizType: 0, textSummary: '[image]' } },
});
describe('runNtv2Upload — two images in one message (sequential)', () => {
beforeEach(() => {
vi.mocked(highway.fetchHighwaySession).mockClear();
vi.mocked(highway.uploadHighwayHttp).mockClear();
});
it('does not leak the first image\'s upload metadata into the second\'s extend', async () => {
// Image 1 server response: NO uKey (fast-upload hit). The pipeline
// must skip the highway PUT entirely for this call.
// Image 2 server response: uKey + ipv4s + msgInfoBody set → real PUT.
const image1Bytes = Buffer.from(new Uint8Array(238963));
const image1Md5 = new Uint8Array(16).fill(0xF4);
const image2Bytes = Buffer.from(new Uint8Array(58));
const image2Md5 = new Uint8Array(16).fill(0xDD);
const image2Sha1 = new Uint8Array(20).fill(0x11);
const bridge = makeBridge([
// First OIDB upload response: fast-path hit (no uKey).
encodeOidbResponse({
upload: {
msgInfo: {
msgInfoBody: [{ index: { fileUuid: 'uuid-1' } }],
extBizInfo: {},
},
},
}),
// Second OIDB upload response: needs highway PUT.
encodeOidbResponse({
upload: {
uKey: 'ukey-image-2',
ipv4s: [{ outIp: 0x04030201, outPort: 8080 }],
msgInfo: {
msgInfoBody: [{ index: { fileUuid: 'uuid-2', info: { fileHash: 'dd', fileSha1: '11' } } }],
extBizInfo: {},
},
},
}),
]);
const uploads1: MediaSubFileUpload[] = [{
source: 'top', cmdId: 1004,
bytes: image1Bytes, md5: image1Md5, sha1: new Uint8Array(20).fill(0xAB),
fastOnlyError: 'image fast-upload not available',
}];
const uploads2: MediaSubFileUpload[] = [{
source: 'top', cmdId: 1004,
bytes: image2Bytes, md5: image2Md5, sha1: image2Sha1,
fastOnlyError: 'image fast-upload not available',
}];
// Image 1 — fast path; must NOT touch the highway transport.
await runNtv2Upload({
...baseParams(bridge),
uploadInfo: [{
fileInfo: { fileName: 'a.jpg', fileSize: 238963 },
subFileType: 0,
}],
uploads: uploads1,
label: 'image',
});
expect(highway.fetchHighwaySession).not.toHaveBeenCalled();
expect(highway.uploadHighwayHttp).not.toHaveBeenCalled();
// Image 2 — must PUT through highway exactly once.
await runNtv2Upload({
...baseParams(bridge),
uploadInfo: [{
fileInfo: { fileName: 'b.jpg', fileSize: 58 },
subFileType: 0,
}],
uploads: uploads2,
label: 'image',
});
expect(highway.fetchHighwaySession).toHaveBeenCalledOnce();
expect(highway.uploadHighwayHttp).toHaveBeenCalledOnce();
// The PUT receives image-2's bytes, image-2's md5, and the
// image-2-derived extend (NOT image-1's data).
const [, , cmdId, putBytes, putMd5, putExtend] = vi.mocked(highway.uploadHighwayHttp).mock.calls[0]!;
expect(cmdId).toBe(1004);
expect(putBytes).toBe(image2Bytes);
expect(putMd5).toBe(image2Md5);
// Decode the extend bytes; uKey + fileUuid must come from image-2's
// response, ipv4s must come from image-2's response.
const extend = protobuf_decode<NTV2RichMediaHighwayExt>(putExtend);
expect(extend.uKey).toBe('ukey-image-2');
expect(extend.fileUuid).toBe('uuid-2');
expect(extend.msgInfoBody?.[0]?.index?.fileUuid).toBe('uuid-2');
expect(extend.network?.ipv4s?.length).toBeGreaterThan(0);
});
it('image 2 fetches its own fresh session (no leftover from a prior call)', async () => {
// Both images hit the highway PUT path. The pipeline must call
// fetchHighwaySession once PER runNtv2Upload (not share session
// across calls), matching NapCat's per-context lifetime semantics
// would actually be a future optimisation, but for now correctness
// = "session is non-null when PUT runs".
const ok = encodeOidbResponse({
upload: {
uKey: 'ukey', ipv4s: [{ outIp: 1, outPort: 80 }],
msgInfo: { msgInfoBody: [{ index: { fileUuid: 'u' } }], extBizInfo: {} },
},
});
const bridge = makeBridge([ok, ok]);
const uploads: MediaSubFileUpload[] = [{
source: 'top', cmdId: 1004,
bytes: Buffer.from([1, 2, 3]),
md5: new Uint8Array(16), sha1: new Uint8Array(20),
fastOnlyError: 'image fast-upload not available',
}];
await runNtv2Upload({
...baseParams(bridge),
uploadInfo: [{ fileInfo: { fileName: 'a.jpg' }, subFileType: 0 }],
uploads, label: 'image',
});
await runNtv2Upload({
...baseParams(bridge),
uploadInfo: [{ fileInfo: { fileName: 'b.jpg' }, subFileType: 0 }],
uploads, label: 'image',
});
expect(highway.fetchHighwaySession).toHaveBeenCalledTimes(2);
expect(highway.uploadHighwayHttp).toHaveBeenCalledTimes(2);
// The session object passed to the PUT must be non-null both times.
for (const call of vi.mocked(highway.uploadHighwayHttp).mock.calls) {
const session = call[1];
expect(session).toBeDefined();
expect((session as any).sigSession).toBeDefined();
}
});
it('image 2\'s OIDB request body carries image-2\'s fileInfo (not image-1\'s)', async () => {
// Catches a hypothetical bug where someone mutates a shared body
// object across calls. Today the pipeline always builds a fresh
// body, but the regression is cheap to guard.
const ok = encodeOidbResponse({
upload: { msgInfo: { msgInfoBody: [], extBizInfo: {} } },
});
const bridge = makeBridge([ok, ok]);
await runNtv2Upload({
...baseParams(bridge),
uploadInfo: [{ fileInfo: { fileName: 'first.jpg', fileSize: 100 }, subFileType: 0 }],
uploads: [], label: 'image',
});
await runNtv2Upload({
...baseParams(bridge),
uploadInfo: [{ fileInfo: { fileName: 'second.jpg', fileSize: 200 }, subFileType: 0 }],
uploads: [], label: 'image',
});
expect(bridge.sendRawPacket).toHaveBeenCalledTimes(2);
const body1 = protobuf_decode<OidbBase<NTV2UploadRichMediaReq>>(bridge.sendRawPacket.mock.calls[0]![1]);
const body2 = protobuf_decode<OidbBase<NTV2UploadRichMediaReq>>(bridge.sendRawPacket.mock.calls[1]![1]);
expect(body1.body?.upload?.uploadInfo?.[0]?.fileInfo?.fileName).toBe('first.jpg');
expect(body2.body?.upload?.uploadInfo?.[0]?.fileInfo?.fileName).toBe('second.jpg');
// And the clientRandomId is different per call (sanity).
expect(body1.body?.upload?.clientRandomId).not.toBe(body2.body?.upload?.clientRandomId);
});
});
+8 -8
View File
@@ -5,10 +5,10 @@
// The OIDB response is built with real protobuf encoding so we exercise
// the actual decode path inside the pipeline.
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import { beforeEach, describe, expect, it, vi } from 'vitest';
vi.mock('@snowluma/bridge/highway', () => ({
vi.mock('@snowluma/protocol/highway', () => ({
fetchHighwaySession: vi.fn(async () => ({ sessionId: 'fake-session' })),
uploadHighwayHttp: vi.fn(async () => undefined),
buildHighwayExtend: vi.fn(() => new Uint8Array([0xAA, 0xBB])),
@@ -16,16 +16,16 @@ vi.mock('@snowluma/bridge/highway', () => ({
GROUP_IMAGE_CMD_ID: 1004,
}));
import * as highway from '@snowluma/bridge/highway';
import type { EncodableMediaMsgInfo, NTV2UploadRichMediaReq, NTV2UploadRichMediaResp } from '@snowluma/proto-defs/highway';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import * as highway from '@snowluma/protocol/highway';
import {
finalizeMediaMsgInfo,
hexToBytes,
makeClientRandomId,
runNtv2Upload,
type MediaSubFileUpload,
} from '@snowluma/bridge/highway/pipeline';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { EncodableMediaMsgInfo, NTV2UploadRichMediaReq, NTV2UploadRichMediaResp } from '@snowluma/proto-defs/highway';
} from '@snowluma/protocol/highway/pipeline';
interface FakeUploadResponse {
upload?: {
@@ -151,7 +151,7 @@ describe('pipeline — runNtv2Upload', () => {
});
const upload = await runNtv2Upload(baseParams({ bridge }));
expect(upload.uKey).toBe('fake-ukey');
expect(upload.msgInfo.msgInfoBody).toHaveLength(1);
expect(upload.msgInfo?.msgInfoBody).toHaveLength(1);
});
it('throws on transport failure', async () => {
@@ -315,7 +315,7 @@ describe('pipeline — finalizeMediaMsgInfo', () => {
it('encodes msgInfoBody + extBizInfo from the server response', () => {
const out = finalizeMediaMsgInfo({
msgInfo: {
msgInfoBody: [{ index: { fileType: 1 }, fileExist: true }],
msgInfoBody: [{ index: { subType: 1 }, fileExist: true }],
extBizInfo: { busiType: 1 },
},
});
@@ -7,14 +7,14 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
vi.mock('@snowluma/bridge/highway/pipeline', () => ({
vi.mock('@snowluma/protocol/highway/pipeline', () => ({
runNtv2Upload: vi.fn(async () => ({ msgInfo: { msgInfoBody: [], extBizInfo: {} } })),
finalizeMediaMsgInfo: vi.fn(() => new Uint8Array([0xAA, 0xBB])),
hexToBytes: vi.fn((hex: string) => new Uint8Array(hex.length / 2)),
}));
import * as pipeline from '@snowluma/bridge/highway/pipeline';
import { uploadPttMsgInfo, GROUP_PTT_CMD_ID, PRIVATE_PTT_CMD_ID } from '@snowluma/bridge/highway/ptt-upload';
import * as pipeline from '@snowluma/protocol/highway/pipeline';
import { uploadPttMsgInfo, GROUP_PTT_CMD_ID, PRIVATE_PTT_CMD_ID } from '@snowluma/protocol/highway/ptt-upload';
const FINGERPRINT = {
noByteFallback: true,
@@ -11,20 +11,20 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
vi.mock('@snowluma/bridge/highway/pipeline', () => ({
vi.mock('@snowluma/protocol/highway/pipeline', () => ({
runNtv2Upload: vi.fn(async () => ({ msgInfo: { msgInfoBody: [], extBizInfo: {} } })),
finalizeMediaMsgInfo: vi.fn(() => new Uint8Array([0x12, 0x34])),
hexToBytes: vi.fn((hex: string) => new Uint8Array(hex.length / 2)),
}));
import * as pipeline from '@snowluma/bridge/highway/pipeline';
import * as pipeline from '@snowluma/protocol/highway/pipeline';
import {
uploadVideoMsgInfo,
GROUP_VIDEO_CMD_ID,
GROUP_VIDEO_THUMB_CMD_ID,
PRIVATE_VIDEO_CMD_ID,
PRIVATE_VIDEO_THUMB_CMD_ID,
} from '@snowluma/bridge/highway/video-upload';
} from '@snowluma/protocol/highway/video-upload';
const FINGERPRINT = {
noByteFallback: true,
+3 -3
View File
@@ -1,8 +1,8 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import fs from 'fs';
import path from 'path';
import { IdentityService } from '@snowluma/bridge/identity-service';
import type { GroupMemberInfo, QQGroupInfo, UserProfileInfo } from '@snowluma/bridge/qq-info';
import { IdentityService } from '@snowluma/protocol/identity-service';
import type { GroupMemberInfo, QQGroupInfo, UserProfileInfo } from '@snowluma/protocol/qq-info';
const SELF_UIN = '10001';
const GROUP_ID = 123456789;
@@ -188,7 +188,7 @@ describe('IdentityService', () => {
describe('IdentityService.resolveUid', () => {
function makeProfile(uin: number, uid: string): UserProfileInfo {
return { uin, uid, nickname: '', remark: '', qid: '', sex: 'unknown', age: 0, sign: '', avatar: '' };
return { uin, uid, nickname: '', remark: '', qid: '', sex: 'unknown', age: 0, sign: '', avatar: '', level: 0 };
}
it('returns the cached uid without invoking the fetcher', async () => {
+4 -4
View File
@@ -1,8 +1,8 @@
import { describe, expect, it } from 'vitest';
import { protobuf_encode } from '@snowluma/proton';
import { parseMsgPush, MSG_PUSH_CMD } from '@snowluma/bridge/msg-push';
import { IdentityService } from '@snowluma/bridge/identity-service';
import type { GroupMemberInfo, QQGroupInfo } from '@snowluma/bridge/qq-info';
import { parseMsgPush, MSG_PUSH_CMD } from '@snowluma/protocol/msg-push';
import { IdentityService } from '@snowluma/protocol/identity-service';
import type { GroupMemberInfo, QQGroupInfo } from '@snowluma/protocol/qq-info';
// Proton's call-site analyzer keys off the literal type identifier
// printed in `protobuf_encode<X>` — it walks imports by *original*
// name (not alias). If both `import { X } from 'proto/notify'` and
@@ -18,7 +18,7 @@ import type {
import type { PushMsg } from '@snowluma/proto-defs/message';
import type {
GroupMemberJoin, FriendAddEvent, QQEventVariant,
} from '@snowluma/bridge/events';
} from '@snowluma/protocol/events';
// Local alias for the event-side recall type — derived via Extract so
// we avoid an `import { FriendRecall as X }` that collides with the
@@ -13,7 +13,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { protobuf_encode } from '@snowluma/proton';
import { subscribeLogs, type LogEntry } from '@snowluma/common/logger';
vi.mock('@snowluma/bridge/highway', () => ({
vi.mock('@snowluma/protocol/highway', () => ({
fetchHighwaySession: vi.fn(async () => ({ sessionId: 'fake-session' })),
uploadHighwayHttp: vi.fn(async () => undefined),
buildHighwayExtend: vi.fn(() => new Uint8Array([0xAA, 0xBB])),
@@ -24,12 +24,12 @@ vi.mock('@snowluma/bridge/highway', () => ({
import {
runNtv2Upload,
type MediaSubFileUpload,
} from '@snowluma/bridge/highway/pipeline';
} from '@snowluma/protocol/highway/pipeline';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { NTV2UploadRichMediaResp } from '@snowluma/proto-defs/highway';
import { MsgPushRegistry } from '@snowluma/bridge/msg-push/registry';
import type { MsgPushContext } from '@snowluma/bridge/msg-push/context';
import { decodeEvent0x2DC } from '@snowluma/bridge/msg-push/decoders/event-0x2dc';
import { MsgPushRegistry } from '@snowluma/protocol/msg-push/registry';
import type { MsgPushContext } from '@snowluma/protocol/msg-push/context';
import { decodeEvent0x2DC } from '@snowluma/protocol/msg-push/decoders/event-0x2dc';
function encodeOidbResponse(body: unknown): Buffer {
return Buffer.from(protobuf_encode<OidbBase<NTV2UploadRichMediaResp>>({
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@snowluma/onebot",
"version": "1.9.1",
"version": "1.9.2",
"private": true,
"type": "module",
"description": "SnowLuma OneBot v11 adapter — the protocol translation layer that maps the public OneBot vocabulary (HTTP / WebSocket actions, message segments, post events) onto @snowluma/core's typed Api hub (`bridge.apis.<area>.method()`). Owns network adapters (HTTP server / HTTP client / WS server / WS client), the registered action handlers, the receive-side event→OneBot converter, message-id hashing, message store (SQLite-backed event history), media store, and the OneBot instance + manager that ties one OneBotConfig to one Bridge. Per-file subpath exports mirror the legacy `core/src/onebot/*` layout 1:1 so the previous `import { … } from '../onebot/<x>'` collapses to `import { … } from '@snowluma/onebot/<x>'`.",
@@ -86,11 +86,11 @@
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@snowluma/bridge": "workspace:*",
"@snowluma/common": "workspace:*",
"@snowluma/core": "workspace:*",
"@snowluma/proto-defs": "workspace:*",
"@snowluma/proton": "workspace:*",
"@snowluma/protocol": "workspace:*",
"@snowluma/sqlite": "workspace:*",
"@snowluma/websocket": "workspace:*"
},
+66 -129
View File
@@ -1,7 +1,7 @@
import type { ApiActionContext, ApiHandler } from '../api-handler';
import { asBoolean, asMessage, asNumber, asString } from '../api-handler';
import type { ForwardPreviewMeta } from '../modules/message-actions';
import { RETCODE, failedResponse, okResponse } from '../types';
import { JsonObject, RETCODE, failedResponse, okResponse } from '../types';
const DOWNLOAD_FILE_MAX_BYTES = 1024 * 1024 * 1024; // 1 GiB
const DOWNLOAD_FILE_TIMEOUT_MS = 60_000;
@@ -31,10 +31,7 @@ async function fetchDownloadFile(
}
return bytes;
}
// Stream so a server that omits / understates Content-Length can't make
// us buffer past maxBytes — abort the read as soon as the running total
// crosses the cap.
// 流式读取,防止服务器 Content-Length 导致内存占用过大 — 一旦累计字节数超过上限就中止读取。
const chunks: Uint8Array[] = [];
let total = 0;
try {
@@ -55,11 +52,7 @@ async function fetchDownloadFile(
return Buffer.concat(chunks, total);
}
/**
* Pull NapCat-compatible forward preview overrides off a send_*_forward_msg
* payload. All four fields are optional — when omitted, the module layer
* derives sensible defaults from the actual node list.
*/
// 从 send_*_forward_msg 的参数里提取 NapCat 兼容的转发预览元信息。四个字段都是可选的——如果没有提供,模块层会根据实际消息节点列表推断出合理的默认值。
function readForwardPreviewMeta(params: Record<string, unknown>): ForwardPreviewMeta | undefined {
const source = asString(params.source) || undefined;
const summary = asString(params.summary) || undefined;
@@ -82,8 +75,7 @@ function readForwardPreviewMeta(params: Record<string, unknown>): ForwardPreview
}
export function register(h: ApiHandler, ctx: ApiActionContext): void {
// --- Likes & Pokes ---
// 赞
h.registerAction('send_like', async (params) => {
const userId = asNumber(params.user_id);
const times = asNumber(params.times) || 1;
@@ -91,7 +83,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
await ctx.bridge.apis.interaction.sendLike(userId, times);
return okResponse();
});
// 拍一拍
h.registerAction('friend_poke', async (params) => {
const userId = asNumber(params.user_id);
const targetId = asNumber(params.target_id) || undefined;
@@ -120,8 +112,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
return okResponse();
});
// --- Essence ---
// 精华消息
h.registerAction('set_essence_msg', async (params) => {
const messageId = asNumber(params.message_id);
if (!Number.isInteger(messageId) || messageId === 0) {
@@ -148,7 +139,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
try {
const essenceDataAll = await ctx.bridge.apis.web.getEssenceAll(groupId);
const allMsgs = essenceDataAll.flatMap((res: any) => res.data?.msg_list || []);
const allMsgs = essenceDataAll.flatMap((res) => res.data?.msg_list || []);
return okResponse(allMsgs);
} catch (e) {
@@ -156,8 +147,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
}
});
// --- Reactions ---
// 群聊表情回应
h.registerAction('set_group_reaction', async (params) => {
const groupId = asNumber(params.group_id);
const messageId = asNumber(params.message_id);
@@ -181,8 +171,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
return okResponse();
});
// --- History ---
// 消息历史
h.registerAction('get_group_msg_history', async (params) => {
const groupId = asNumber(params.group_id);
const messageId = asNumber(params.message_id) || 0;
@@ -201,6 +190,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
return okResponse({ messages });
});
// 标记消息已读
h.registerAction('mark_group_msg_as_read', async (params) => {
const messageId = asNumber(params.message_id);
const groupId = asNumber(params.group_id);
@@ -264,8 +254,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
});
// --- RKey ---
// 下载密钥
const handleGetRkey = async () => {
if (ctx.getDownloadRKeys) {
return okResponse(await ctx.getDownloadRKeys());
@@ -273,11 +262,9 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
};
h.registerAction('get_rkey', handleGetRkey);
// napcat exposes the same payload under `nc_get_rkey`; mirror the alias
// so clients that follow napcat's docs work out-of-the-box.
h.registerAction('nc_get_rkey', handleGetRkey);
// --- OCR stubs ---
// OCR 兜底未实现。
h.registerAction('ocr_image', async () => {
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
@@ -287,8 +274,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
});
// --- Group notice stubs ---
// 群公告
h.registerAction('_send_group_notice', async (params) => {
const groupId = asNumber(params.group_id);
const content = asString(params.content);
@@ -348,17 +334,12 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
}
});
// --- Forward messages ---
// 转发消息。
h.registerAction('upload_forward_msg', async (params) => {
const messages = asMessage(params.messages ?? params.message);
const groupId = asNumber(params.group_id);
if (messages === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'message/messages is required');
// Group and private forwards live in different resId namespaces
// (see bridge/actions/forward.ts: type=3+groupUin vs type=1+selfUid).
// Passing groupId through is what makes the resulting resId usable
// when the caller later sends it into the same group.
// 群聊和私聊转发消息的 resId 是分开的(前者是 type=3+groupUin,后者是 type=1+selfUid),
const result = await ctx.sendForwardMsg(messages, groupId > 0 ? groupId : undefined);
const data: Record<string, unknown> = {
res_id: result.forwardId,
@@ -366,11 +347,9 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
message_id: 0,
};
if (groupId > 0) data.group_id = groupId;
return okResponse(data as any);
return okResponse(data as import('../types').JsonObject);
});
// Kept for backward compat with clients that follow the historical
// gocqhttp/NapCat docs misspelling; same semantics as upload_forward_msg.
h.registerAction('upload_foward_msg', async (params) => {
const messages = asMessage(params.messages ?? params.message);
const groupId = asNumber(params.group_id);
@@ -458,7 +437,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
return okResponse({ messages });
});
// --- Media ---
// 文件信息
h.registerAction('get_image', async (params) => {
const file = asString(params.file) || asString(params.file_id);
@@ -476,7 +455,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
return failedResponse(RETCODE.ACTION_FAILED, 'record not found in cache');
});
// --- Credentials ---
// Cookie、CSRF 令牌和账号信息
h.registerAction('get_cookies', async (params) => {
const domain = asString(params.domain) || 'qun.qq.com';
@@ -511,7 +490,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
return failedResponse(RETCODE.ACTION_FAILED, String(e));
}
});
// --- Utility ---
// 重启和清理缓存
h.registerAction('set_restart', async () => {
return failedResponse(RETCODE.ACTION_FAILED, 'not supported');
@@ -530,13 +509,10 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
return okResponse();
});
// --- NapCat-compatible extended APIs ---
// 以下接口在方便用户迁移和兼容现有的 OneBot/NapCat 客户端。
h.registerAction('set_friend_remark', async (params) => {
const userId = asNumber(params.user_id);
if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
// remark must be explicitly provided. Falling back to '' on a missing
// field would silently CLEAR the operator's existing remark.
if (params.remark === undefined) {
return failedResponse(RETCODE.BAD_REQUEST, 'remark is required (pass an empty string to clear)');
}
@@ -598,10 +574,9 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
const tempDir = pathMod.resolve('data', 'downloads');
if (!fs.existsSync(tempDir)) fs.mkdirSync(tempDir, { recursive: true });
// Sanitize file name: strip any path components, reject anything that
// resolves outside `tempDir`. Without this guard, `name = "../../config/onebot_x.json"`
// would let an authenticated OneBot client overwrite arbitrary files
// (config / dist / node_modules) under the working directory.
// 清理文件名:移除所有路径部分,并拒绝任何会解析到 tempDir 外部的路径。
// 如果没有这个保护,name = "../../config/onebot_x.json" 会让已认证的 OneBot 客户端覆盖工作目录下的任意文件。
// 例如 config、dist、node_modules 等目录中的文件。
const resolveSafePath = (preferredName: string, fallbackBuf: Buffer): string | null => {
const raw = preferredName || cryptoMod.createHash('md5').update(fallbackBuf).digest('hex');
const safeName = pathMod.basename(raw);
@@ -614,9 +589,8 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
let buf: Buffer;
if (base64) {
// Every 4 base64 chars decode to at most 3 bytes. Reject before
// `Buffer.from` allocates anything to avoid OOM on a giant payload
// that wouldn't pass the post-decode check anyway.
// 每 4 个 base64 字符最多解码成 3 个字节。
// 在 Buffer.from 分配内存前先拒绝过大的载荷,避免最终也无法通过解码后检查的大载荷导致内存溢出。
const upperBound = Math.floor((base64.length * 3) / 4);
if (upperBound > DOWNLOAD_FILE_MAX_BYTES) {
return failedResponse(RETCODE.BAD_REQUEST, `base64 payload too large: > ${DOWNLOAD_FILE_MAX_BYTES} bytes`);
@@ -640,8 +614,8 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
const safe = resolveSafePath(name, buf);
if (!safe) return failedResponse(RETCODE.BAD_REQUEST, 'invalid file name');
// Async write so we don't block the event loop on a GiB-class download
// (the prior `writeFileSync` stalled every other bot action while it ran).
// 使用异步写入,避免 GiB 级下载阻塞事件循环。
// 之前的 writeFileSync 会在运行期间卡住其他所有机器人动作。
await fs.promises.writeFile(safe, buf);
return okResponse({ file: safe });
});
@@ -661,7 +635,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
});
h.registerAction('set_online_status', async (params) => {
// 按 OneBot/NapCat 习惯提取参数,状态码默认为 11
const status = asNumber(params.status);
const extStatus = asNumber(params.ext_status) || 0;
const batteryStatus = asNumber(params.battery_status) || 100;
@@ -680,11 +653,9 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
}
});
// DIY status — same wire packet as set_online_status, only the
// customExt sub-message is populated and status/extStatus are forced
// to the QQ-defined "I have a custom status" values (10 / 2000).
// face_id / face_type accept either number or numeric string (napcat
// parity); wording is the human-readable text shown next to the icon.
// 自定义在线状态:与 set_online_status 使用相同的网络包。
// 这里只填充 customExt 子消息,并将 status/extStatus 强制设为 QQ 定义的“我有自定义状态”取值(10 / 2000)。
// face_id 和 face_type 可接受数字或数字字符串,以兼容 NapCat;wording 是图标旁展示的可读文本。
h.registerAction('set_diy_online_status', async (params) => {
const faceId = asNumber(params.face_id);
const faceType = asNumber(params.face_type) || 1;
@@ -698,10 +669,9 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
}
});
// Filtered (机器人/被忽略) group join requests. SnowLuma already
// implements the underlying oidb 0x10c8_2 fetch via fetchGroupRequests;
// these three actions just rename / project the same data for the
// OneBot dialects clients use in the wild.
// 已过滤(机器人/被忽略)的入群请求。
// SnowLuma 已通过 fetchGroupRequests 实现底层 oidb 0x10c8_2 拉取。
// 这几个动作只是为实际使用中的 OneBot 方言客户端重命名并投影相同数据。
const fetchFilteredGroupRequests = async () => {
try {
return await ctx.bridge.apis.contacts.fetchGroupRequests(true);
@@ -727,10 +697,9 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
})));
});
// napcat name for the subset of ignored notifies that are join requests
// (notify type==7). We map every entry that flowed through filtered
// 0x10c8_2 into napcat's shape — eventType already encodes the request
// category in our pipeline.
// NapCat 对“被忽略通知中属于入群请求的子集”的命名(notify type == 7)。
// 这里把经过过滤的 0x10c8_2 每一项映射成 NapCat 结构。
// eventType 已经在当前流水线中编码了请求类别。
h.registerAction('get_group_ignore_add_request', async () => {
const reqs = await fetchFilteredGroupRequests();
return okResponse(reqs.map((r) => ({
@@ -746,8 +715,8 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
})));
});
// get_group_shut_list lives behind an oidb we don't yet wrap; honour
// the napcat contract (empty list) so callers don't blow up.
// get_group_shut_list 依赖尚未封装的 oidb。
// 这里遵循 NapCat 约定返回空列表,避免调用方出错。
h.registerAction('get_group_shut_list', async () => {
return okResponse([]);
});
@@ -778,21 +747,11 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
}
});
// todo 我的建议是引入数据库api 纯协议我不知道这种api怎么实现,ntQQ在实现这个方法的时候只进行了数据库查询,完全没碰网络
h.registerAction('get_recent_contact', async () => {
return okResponse([]);
});
h.registerAction('get_profile_like', async (params) => {
const userId = asNumber(params.user_id);
const start = asNumber(params.start) || 0;
const count = asNumber(params.count) || 10;
try {
// getLike treats falsy userId as "self" (it does `isSelf = !userId`
// internally), so passing 0 or undefined is equivalent — matches the
// old `ctx.getProfileLike(userId, start, count)` wrapper exactly.
const data = await ctx.bridge.apis.profile.getLike(userId, start, count);
return okResponse(data);
} catch (e) {
@@ -815,10 +774,10 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
const emojiId = asString(params.emoji_id) || '';
if (!messageId || !emojiId) return failedResponse(RETCODE.BAD_REQUEST, 'message_id and emoji_id are required');
try {
const meta = ctx.getMessageMeta(messageId);
if (!meta?.isGroup || !meta?.sequence) return failedResponse(RETCODE.BAD_REQUEST, 'message not found or not a group message');
const result = await ctx.bridge.apis.interaction.getEmojiLikes(meta.targetId, meta.sequence, emojiId);
return okResponse({ emoji_like_list: result.users.map(u => ({ user_id: String(u.uin), nick_name: '' })) });
const result = await ctx.fetchEmojiLikeUsers(messageId, emojiId, 1000);
return okResponse({
emoji_like_list: result.users.map(u => ({ user_id: String(u.uin), nick_name: '' })),
});
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e));
}
@@ -827,21 +786,21 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
h.registerAction('fetch_emoji_like', async (params) => {
const messageId = asNumber(params.message_id);
const emojiId = asString(params.emojiId) || '';
const emojiType = asNumber(params.emojiType) || 1;
const count = asNumber(params.count) || 10;
const cookie = asString(params.cookie) || '';
if (!messageId || !emojiId) return failedResponse(RETCODE.BAD_REQUEST, 'message_id and emojiId are required');
try {
const meta = ctx.getMessageMeta(messageId);
if (!meta?.isGroup || !meta?.sequence) return failedResponse(RETCODE.BAD_REQUEST, 'message not found or not a group message');
const result = await ctx.bridge.apis.interaction.getEmojiLikes(meta.targetId, meta.sequence, emojiId, emojiType, count, cookie);
const offset = cookie ? Number.parseInt(cookie, 10) || 0 : 0;
const result = await ctx.fetchEmojiLikeUsers(messageId, emojiId, count, offset);
const nextOffset = offset + result.users.length;
const isLastPage = nextOffset >= result.cachedCount;
return okResponse({
result: 0,
errMsg: '',
emojiLikesList: result.users.map(u => ({ tinyId: String(u.uin), nickName: '', headUrl: '' })),
cookie: result.cookie,
isLastPage: result.isLast,
isFirstPage: !cookie,
cookie: isLastPage ? '' : String(nextOffset),
isLastPage,
isFirstPage: offset === 0,
});
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e));
@@ -855,9 +814,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
return okResponse([]);
});
// --- Additional NapCat-compatible stubs ---
///napcat 似乎也用不了??,暂时不管了
// NapCat 似乎也用不了,暂时不处理。
h.registerAction('get_online_clients', async () => {
return okResponse({ clients: [] });
});
@@ -880,8 +837,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
if (!groupId) {
return failedResponse(RETCODE.BAD_REQUEST, 'invalid group_id');
}
try {
const data = await ctx.bridge.apis.groupAdmin.getAtAllRemain(groupId);
return okResponse(data);
@@ -906,8 +861,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
if (typeof longNick !== 'string') {
return failedResponse(RETCODE.BAD_REQUEST, 'invalid longNick');
}
try {
await ctx.bridge.apis.profile.setSelfLongNick(longNick);
return okResponse({});
@@ -950,7 +903,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
return failedResponse(RETCODE.BAD_REQUEST, 'invalid event_type');
}
try {
await ctx.bridge.apis.profile.setInputStatus(userId, eventType);
return okResponse({});
@@ -1033,7 +985,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
}
});
const handleGroupSign = async (params: any) => {
const handleGroupSign = async (params: import('../types').JsonObject) => {
const groupId = asNumber(params.group_id);
if (!groupId) {
@@ -1084,12 +1036,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
});
// --- Raw packet escape hatch (napcat parity) ---
//
// napcat exposes both names; the dot-prefix variant is the original
// gocqhttp-era backdoor, the no-prefix one is the modern API. They do
// the same thing in SnowLuma: encode hex → Bridge.sendRawPacket → hex.
const handleSendPacket = async (params: import('../types').JsonObject) => {
const handleSendPacket = async (params: JsonObject) => {
const cmd = asString(params.cmd);
const dataHex = asString(params.data);
const rsp = asBoolean(params.rsp, true);
@@ -1113,24 +1060,19 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
h.registerAction('send_packet', handleSendPacket);
h.registerAction('.send_packet', handleSendPacket);
// --- Bot lifecycle (napcat parity) ---
// 机器人生命周期(兼容 NapCat)。
h.registerAction('bot_exit', async () => {
// Defer so the OK response actually flushes before the process dies.
setTimeout(() => process.exit(0), 50);
return okResponse();
});
// SnowLuma has no separate packet-backend process (napcat's packet
// service runs out-of-process and can fail independently). Always
// report healthy.
h.registerAction('nc_get_packet_status', async () => {
return okResponse(null);
});
// napcat exposes `delete_group_folder`; SnowLuma's existing
// `delete_group_file_folder` is the same operation. Alias so clients
// following napcat docs work without rewriting payloads.
// NapCat 暴露 delete_group_folder。
// SnowLuma 现有的 delete_group_file_folder 是相同操作。
// 添加别名以便遵循 NapCat 文档的客户端无需重写载荷。
h.registerAction('delete_group_folder', async (params) => {
const groupId = asNumber(params.group_id);
const folderId = asString(params.folder_id);
@@ -1141,12 +1083,10 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
return okResponse();
});
// --- Group todo (oidb 0xF90) ---
//
// The three subcommands share an identical payload (group + msgSeq);
// we extract once and dispatch by action name. msgSeq comes from the
// message metadata cache (set/complete/cancel always target a real
// message the bot has seen).
// 群待办(oidb 0xF90)。
// 三个子命令共享相同载荷(群号 + msgSeq)。
// 这里统一提取一次,并按动作名称分发。
// msgSeq 来自消息元数据缓存;设置、完成、取消总是指向机器人见过的真实消息。
type GroupTodoOp = (groupId: number, msgSeq: bigint | number | string) => Promise<void>;
const handleGroupTodo = (op: GroupTodoOp) => async (params: import('../types').JsonObject) => {
const groupId = asNumber(params.group_id);
@@ -1169,7 +1109,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
h.registerAction('complete_group_todo', handleGroupTodo((g, s) => ctx.bridge.apis.extras.completeGroupTodo(g, BigInt(s))));
h.registerAction('cancel_group_todo', handleGroupTodo((g, s) => ctx.bridge.apis.extras.cancelGroupTodo(g, BigInt(s))));
// --- User online/ext status (napcat: nc_get_user_status) ---
// 用户在线/扩展状态(NapCat:nc_get_user_status)。
h.registerAction('nc_get_user_status', async (params) => {
const userId = asNumber(params.user_id);
@@ -1179,7 +1119,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
return okResponse({ ...status });
});
// --- AI voice (oidb 0x929D / 0x929B) ---
// AI 语音(oidb 0x929D / 0x929B)。
h.registerAction('get_ai_characters', async (params) => {
const groupId = asNumber(params.group_id);
@@ -1217,9 +1157,9 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
}
});
// napcat's send_group_ai_record is a side-effect-only call: invoking
// fetchAiVoice publishes the voice into the group; the returned
// message_id is always 0 because the oidb call doesn't echo one back.
// NapCat 的 send_group_ai_record 是仅产生副作用的调用。
// 调用 fetchAiVoice 会把语音发布到群里。
// 返回的 message_id 始终为 0,因为 oidb 调用不会回显消息 ID。
h.registerAction('send_group_ai_record', async (params) => {
const groupId = asNumber(params.group_id);
const character = asString(params.character);
@@ -1240,7 +1180,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
function hexToBytes(hex: string): Uint8Array {
const out = new Uint8Array(hex.length / 2);
for (let i = 0; i < out.length; i++) {
out[i] = parseInt(hex.substr(i * 2, 2), 16);
out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
}
return out;
}
@@ -1250,9 +1190,6 @@ function bytesToHex(buf: Buffer | Uint8Array): string {
return arr.toString('hex');
}
/**
* Parse download_file headers parameter into a Record.
*/
function parseDownloadHeaders(headers: unknown): Record<string, string> {
const result: Record<string, string> = {};
if (!headers) return result;
+3 -7
View File
@@ -1,5 +1,5 @@
import type { ApiHandler, ApiActionContext } from '../api-handler';
import { asNumber, asString, asBoolean } from '../api-handler';
import type { ApiActionContext, ApiHandler } from '../api-handler';
import { asBoolean, asNumber, asString } from '../api-handler';
import { RETCODE, failedResponse, okResponse } from '../types';
export function register(h: ApiHandler, ctx: ApiActionContext): void {
@@ -103,10 +103,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
return okResponse();
});
// Highway upload with cmdId 3000 + GroupAvatarExtra (Lagrange protocol).
// `file` accepts everything bridge.setGroupAvatar's underlying
// loadBinarySource handles: local paths, file:// URLs, http(s) URLs,
// and base64:// data URIs — same surface as set_qq_avatar.
h.registerAction('set_group_portrait', async (params) => {
const groupId = asNumber(params.group_id);
const file = asString(params.file);
@@ -119,4 +115,4 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err));
}
});
}
}
+2 -9
View File
@@ -1,7 +1,7 @@
import type { ApiHandler, ApiActionContext } from '../api-handler';
import type { ApiActionContext, ApiHandler } from '../api-handler';
import { asNumber, asString } from '../api-handler';
import { RETCODE, failedResponse, okResponse } from '../types';
import type { JsonValue } from '../types';
import { RETCODE, failedResponse, okResponse } from '../types';
export function register(h: ApiHandler, ctx: ApiActionContext): void {
h.registerAction('get_group_album_list', async (params) => {
@@ -47,9 +47,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
try {
const mediaList = await ctx.bridge.apis.groupAlbum.getMediaList(groupId, albumId, attachInfo);
// GroupAlbumMediaResult is a concrete domain type; okResponse
// expects JsonValue. The shape is JSON-compatible — same as the
// old ctx wrapper returning `Promise<any>`.
return okResponse(mediaList as unknown as JsonValue);
} catch (error) {
const message = error instanceof Error ? error.message : 'failed to get group album media list';
@@ -70,10 +67,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
try {
const comment = await ctx.bridge.apis.groupAlbum.comment(groupId, albumId, lloc, content);
// GroupAlbumCommentResult is a concrete domain type; okResponse
// expects JsonValue. The shape is JSON-compatible (no functions
// / classes / bigints), so cast is safe — same as the old ctx
// wrapper returning `Promise<any>`.
return okResponse(comment as unknown as JsonValue);
} catch (error) {
const message = error instanceof Error ? error.message : 'failed to comment on album media';
+1 -1
View File
@@ -1,7 +1,7 @@
import type { ApiHandler, ApiActionContext } from '../api-handler';
import { asNumber, asBoolean, asString } from '../api-handler';
import { RETCODE, failedResponse, okResponse } from '../types';
import { WebHonorType } from '@snowluma/bridge/web/group-honor';
import { WebHonorType } from '@snowluma/protocol/web/group-honor';
export function register(h: ApiHandler, ctx: ApiActionContext): void {
h.registerAction('get_group_list', async (params) => {
+2 -3
View File
@@ -1,4 +1,4 @@
import type { ApiHandler, ApiActionContext } from '../api-handler';
import type { ApiActionContext, ApiHandler } from '../api-handler';
import { okResponse } from '../types';
export function register(h: ApiHandler, ctx: ApiActionContext): void {
@@ -12,8 +12,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
return okResponse({ online, good: online });
});
// __APP_VERSION__ is injected by Vite from the monorepo root package.json;
// it's undefined under vitest (no define plugin), so fall back to 'dev'.
// 后续考虑移动到一个统一的地方构建,避免版本信息分散在各个模块中。
const appVersion = typeof __APP_VERSION__ !== 'undefined' ? __APP_VERSION__ : 'dev';
h.registerAction('get_version_info', async () => {
return okResponse({
+26 -59
View File
@@ -1,24 +1,20 @@
import type { JsonObject, JsonValue, MessageMeta } from './types';
import type { ForwardPreviewMeta } from './modules/message-actions';
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
import { RETCODE, failedResponse } from './types';
import { createLogger, type Logger } from '@snowluma/common/logger';
import { summarizeParams } from '@snowluma/common/log-summary';
const moduleLog = createLogger('Bridge.Action');
import { createLogger, type Logger } from '@snowluma/common/logger';
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
import { register as registerExtended } from './actions/extended';
import { register as registerFriend } from './actions/friend';
import { register as registerGroupAdmin } from './actions/group-admin';
import { register as registerGroupAlbum } from './actions/group-album';
import { register as registerGroupFile } from './actions/group-file';
import { register as registerGroupInfo } from './actions/group-info';
import { register as registerInfo } from './actions/info';
import { register as registerMessage } from './actions/message';
import { register as registerFriend } from './actions/friend';
import { register as registerGroupInfo } from './actions/group-info';
import { register as registerGroupAdmin } from './actions/group-admin';
import { register as registerGroupFile } from './actions/group-file';
import { register as registerRequest } from './actions/request';
import { register as registerExtended } from './actions/extended';
import { register as registerGroupAlbum } from './actions/group-album';
import type { ForwardPreviewMeta } from './modules/message-actions';
import type { JsonObject, JsonValue, MessageMeta } from './types';
import { RETCODE, failedResponse } from './types';
const moduleLog = createLogger('Bridge.Action');
import { WebHonorType } from '@snowluma/bridge/web/group-honor';
import type { ClientKeyInfo } from '@snowluma/core/bridge';
export interface MessageSendResult {
messageId: number;
@@ -30,21 +26,14 @@ export interface GroupEssenceMsgRet {
retcode: number;
data: {
is_end: boolean;
msg_list: any[];
[key: string]: any;
msg_list: JsonObject[];
[key: string]: JsonValue;
};
[key: string]: any;
[key: string]: JsonValue;
}
export interface ApiActionContext {
/**
* Direct access to the BridgeInterface. Use for actions that are pure
* 1:1 calls to a Bridge method — no rename, no default args, no
* composition with messageStore / mediaStore. When translation IS
* needed, route through the named adapters declared below instead.
*/
bridge: BridgeInterface;
getLoginInfo: () => { userId: number; nickname: string };
isOnline: () => boolean;
getMessage: (messageId: number) => JsonObject | null;
@@ -54,37 +43,16 @@ export interface ApiActionContext {
deleteMessage: (messageId: number, meta: MessageMeta) => Promise<void>;
canSendImage: () => boolean;
canSendRecord: () => boolean;
// Info retrieval (async — triggers OIDB fetch)
getFriendList: () => Promise<JsonObject[]>;
getGroupList: (noCache?: boolean) => Promise<JsonObject[]>;
getGroupInfo: (groupId: number, noCache?: boolean) => Promise<JsonObject | null>;
getGroupMemberList: (groupId: number, noCache?: boolean) => Promise<JsonObject[]>;
getGroupMemberInfo: (groupId: number, userId: number, noCache?: boolean) => Promise<JsonObject | null>;
getStrangerInfo: (userId: number) => Promise<JsonObject | null>;
// Group admin (mute/kick/admin/card/name/title/leave/etc) — all
// accessed directly through `ctx.bridge.apis.groupAdmin.method()`
// after the #6 OneBot-side slim-down; no per-method passthrough
// here anymore.
// Group file passthroughs are gone — actions call
// `ctx.bridge.apis.groupFile.{upload,uploadPrivate,getUrl,
// createFolder,getPrivateUrl,getCount}` directly. `getGroupFiles`
// stays because it composes through the `getGroupFiles` module
// helper (identity-lookup enrichment of uploader names).
getGroupFiles: (groupId: number, folderId?: string) => Promise<JsonObject>;
// Friend requests: direct via `ctx.bridge.apis.friend.handleRequest`.
// Group requests: stay on ctx because `handleGroupAddRequest` is a
// module helper that does the flag-parsing + group-request lookup
// dance before routing to `bridge.apis.groupAdmin.setAddRequest`.
handleGroupRequest: (flag: string, subType: string, approve: boolean, reason: string) => Promise<void>;
// Pokes: direct via `ctx.bridge.apis.interaction.sendPoke(isGroup, …)`.
// Essence (adapter: bakes the set/unset boolean)
setEssenceMsg: (messageId: number) => Promise<void>;
deleteEssenceMsg: (messageId: number) => Promise<void>;
// Profile reads and group essence reads: direct via
// `ctx.bridge.apis.profile.getLike(...)` and
// `ctx.bridge.apis.web.getEssence(...)`.
// Friend deletion: direct via `ctx.bridge.apis.friend.delete(userId, block)`.
// Module wrappers / multi-dep compositions
getGroupMsgHistory: (groupId: number, messageId?: number, count?: number) => Promise<JsonObject[]>;
getFriendMsgHistory: (userId: number, messageId?: number, count?: number) => Promise<JsonObject[]>;
handleGetGroupSystemMsg: () => Promise<JsonObject[]>;
@@ -94,19 +62,18 @@ export interface ApiActionContext {
sendForwardMsg: (messages: JsonValue, groupId?: number) => Promise<{ forwardId: string }>;
getForwardMsg: (resId: string) => Promise<JsonObject[]>;
forwardSingleMsg: (messageId: number, target: { groupId?: number; userId?: number }) => Promise<{ messageId: number }>;
// setMsgEmojiLike: stays because it threads messageStore meta lookup.
setMsgEmojiLike: (messageId: number, emojiId: string, set: boolean) => Promise<void>;
// All other extended / NapCat-compatible / Web / Album actions are
// accessed directly through `ctx.bridge.apis.<area>.<method>()`:
// * profile area: setProfile / setOnlineStatus / fetchCustomFace /
// setGroupAvatar / getLike
// * friend area: setRemark / delete / handleRequest
// * web area: getHonorInfo / getEssence(All) / sendNotice /
// getNotice / deleteNotice / getCookiesStr /
// getCsrfToken / getCredentials / forceFetchClientKey
// * groupAlbum area: list / upload / getMediaList / comment /
// delete / like
// Media lookup (populated from previously dispatched message segments)
fetchEmojiLikeUsers: (
messageId: number,
emojiId: string,
count: number,
offset?: number,
) => Promise<{
users: Array<{ uin: number; uid: string; setAt: number }>;
cachedCount: number;
serverCount: number;
complete: boolean;
}>;
getImageInfo: (file: string) => Promise<JsonObject | null>;
getRecordInfo: (file: string) => Promise<JsonObject | null>;
}
+2 -27
View File
@@ -1,7 +1,7 @@
import { createLogger } from '@snowluma/common/logger';
import { randomBytes } from 'crypto';
import fs from 'fs';
import path from 'path';
import { randomBytes } from 'crypto';
import { createLogger } from '@snowluma/common/logger';
import type {
HttpClientNetwork,
HttpServerNetwork,
@@ -54,13 +54,6 @@ function generateAccessToken(): string {
}
export interface LoadOneBotConfigOptions {
/**
* Persist the normalized config to disk when the file is missing or was
* in legacy format. Default `false` so accidental call sites (read-only
* GETs in particular) don't generate fresh access tokens, race on
* concurrent writes, or surprise the operator with materialized files.
* Pass `true` from boot / explicit POST handlers.
*/
persistDefaults?: boolean;
}
@@ -70,9 +63,6 @@ export function loadOneBotConfig(uin: string, options: LoadOneBotConfigOptions =
const perUinPath = path.join(CONFIG_DIR, `onebot_${uin}.json`);
const globalRaw = tryLoadJson(DEFAULT_CONFIG_PATH);
const perUinRaw = tryLoadJson(perUinPath);
// Detect legacy on-disk format (top-level per-type arrays). We auto-migrate
// these entries into `networks.*` and rewrite the file on the next save.
const legacy = !!perUinRaw && hasLegacyTopLevel(perUinRaw);
const sources: JsonObject[] = [];
@@ -162,11 +152,6 @@ function wsClientToJson(n: WsClientNetwork): JsonObject {
}
function fromJson(sources: JsonObject[], freshInstall: boolean): OneBotConfig {
// Legacy top-level scalars are pulled DOWN into each adapter on the first
// load: the on-disk schema has no globals anymore, every adapter is
// self-describing. We compute the legacy fallbacks here so that adapters
// missing `messageFormat`/`reportSelfMessage` inherit them once and the
// file is rewritten in normalized form.
let legacyFormat: MessageFormat | undefined;
let legacyReport: boolean | undefined;
let musicSignUrl = '';
@@ -178,19 +163,11 @@ function fromJson(sources: JsonObject[], freshInstall: boolean): OneBotConfig {
}
const inheritedFormat: MessageFormat = legacyFormat ?? 'array';
const inheritedReport: boolean = legacyReport ?? false;
// Pluck per-type arrays from each source: prefer `networks.<kind>` over
// legacy top-level arrays, but accept both. Later sources override earlier
// ones at the network level (last write wins per `(kind, name)` pair).
const adapterDefaults = { messageFormat: inheritedFormat, reportSelfMessage: inheritedReport };
const httpServers = collectByName<HttpServerNetwork>(sources, 'httpServers', (raw) => parseHttpServer(raw, adapterDefaults));
const httpClients = collectByName<HttpClientNetwork>(sources, 'httpClients', (raw) => parseHttpClient(raw, adapterDefaults), 'httpPostEndpoints');
const wsServers = collectByName<WsServerNetwork>(sources, 'wsServers', (raw) => parseWsServer(raw, adapterDefaults));
const wsClients = collectByName<WsClientNetwork>(sources, 'wsClients', (raw) => parseWsClient(raw, adapterDefaults));
// Seed defaults ONLY for a brand-new install (no source files at all).
// If the operator deliberately emptied every adapter, respect that and
// do NOT silently revive default 0.0.0.0 listeners.
if (
freshInstall &&
httpServers.length === 0 &&
@@ -340,8 +317,6 @@ function clean<T extends Record<string, unknown>>(obj: T): T {
}
function asRole(value: unknown, fallback: WsRole): WsRole {
// Accept both uppercase (canonical) and lowercase (legacy on-disk) forms.
// Lowercase values are auto-migrated to uppercase on the next save.
const text = asString(value, fallback).toLowerCase();
if (text === 'api') return 'Api';
if (text === 'event') return 'Event';
-6
View File
@@ -1,8 +1,2 @@
// Globals injected by Vite at build time (see `packages/core/vite.config.ts`).
// `__APP_VERSION__` reads from the monorepo root `package.json::version`;
// `__BUILD_WEBUI__` flips on when `BUILD_WEBUI=true` is set so the runner
// stitches the SPA assets in. Both are typed as `unknown` outside vite
// (e.g. when running tests via vitest where the plugin isn't applied) —
// callers guard with `typeof __APP_VERSION__ !== 'undefined'`.
declare const __BUILD_WEBUI__: boolean;
declare const __APP_VERSION__: string;
+2 -30
View File
@@ -1,4 +1,4 @@
import type { MessageElement, QQEventVariant } from '@snowluma/bridge/events';
import type { MessageElement, QQEventVariant } from '@snowluma/protocol/events';
import type { JsonObject } from '../types';
import {
convertFriendMessage,
@@ -25,16 +25,10 @@ import {
} from './to-request';
import { elementsToJson } from './to-segment';
// ─────────────── resolver callback types ───────────────
export type ImageUrlResolver = (element: MessageElement, isGroup: boolean) => string;
export type MediaUrlResolver = (element: MessageElement, isGroup: boolean, sessionId: number) => Promise<string>;
export type MessageIdResolver = (isGroup: boolean, sessionId: number, sequence: number, eventName: string) => number;
/**
* Side-channel callback invoked every time an image / record / video
* segment is produced, so callers can keep a lookup index (e.g. for
* `get_image` / `get_record`) without re-scanning the message store.
*/
export type MediaSegmentSink = (
mediaType: 'image' | 'record' | 'video',
element: MessageElement,
@@ -45,15 +39,7 @@ export type MediaSegmentSink = (
// ─────────────── context ───────────────
/**
* Everything `convertEvent` needs that isn't on the bridge event itself.
* Built once per OneBotInstance and passed through unchanged. Resolvers
* are nullable because tests routinely omit them; when missing, the
* converter falls back to the bridge event's own fields (e.g. raw
* `element.url`, raw `event.msgSeq`).
*/
export interface ConverterContext {
/** Self uin parsed once into a Number for inclusion in `self_id`. */
selfId: number;
imageUrlResolver: ImageUrlResolver | null;
mediaUrlResolver: MediaUrlResolver | null;
@@ -63,11 +49,6 @@ export interface ConverterContext {
// ─────────────── dispatcher ───────────────
/**
* Convert a bridge `QQEventVariant` to the OneBot wire-shape JSON.
* Returns null for kinds we don't surface (so callers can skip them
* without an explicit allow-list).
*/
export async function convertEvent(
ctx: ConverterContext,
event: QQEventVariant,
@@ -101,15 +82,6 @@ export async function convertEvent(
}
}
// ─────────────── side-channel re-export ───────────────
/**
* Element-array -> OneBot segment-array helper. Used by
* `modules/message-actions.ts` for forward-message rebuilding (where
* we already know the elements but want the OneBot segment shape).
* The signature stays backwards-compatible: each resolver is an
* optional positional argument.
*/
export async function elementsToOneBotSegments(
elements: MessageElement[],
isGroup: boolean,
@@ -1,9 +1,10 @@
import type { QQEventVariant } from '@snowluma/bridge/events';
import type { QQEventVariant } from '@snowluma/protocol/events';
import { segmentsToRawMessage } from '../helper/cq';
import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT } from '../message-id';
import type { JsonObject } from '../types';
import type { ConverterContext } from './index';
import { elementsToJson } from './to-segment';
import { applyMessageIdResolver, segmentsToRawMessage } from './utils';
import { applyMessageIdResolver } from './utils';
type FriendMessage = Extract<QQEventVariant, { kind: 'friend_message' }>;
type GroupMessage = Extract<QQEventVariant, { kind: 'group_message' }>;
@@ -1,4 +1,4 @@
import type { QQEventVariant } from '@snowluma/bridge/events';
import type { QQEventVariant } from '@snowluma/protocol/events';
import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT } from '../message-id';
import type { JsonObject } from '../types';
import type { ConverterContext } from './index';
@@ -183,17 +183,7 @@ export function convertFriendAdd(ctx: ConverterContext, event: FriendAdd): JsonO
};
}
/**
* Group message emoji reaction notice. Matches the gocqhttp / NapCat
* extension shape (`notice_type: 'group_msg_emoji_like'`) since OneBot
* v11 standard has no slot for reactions and that's what every
* downstream framework keys off.
*/
export function convertGroupMsgEmojiLike(ctx: ConverterContext, event: GroupMsgEmojiLike): JsonObject {
// Reconstruct the OneBot message_id we originally minted for the
// reacted-to message. hashMessageIdInt32 is deterministic so the ID
// matches whatever the client received at receive-time, even when
// the message has fallen out of our store.
const messageId = applyMessageIdResolver(
ctx.messageIdResolver, true, event.groupId, event.msgSeq, GROUP_MESSAGE_EVENT,
);
@@ -1,4 +1,4 @@
import type { QQEventVariant } from '@snowluma/bridge/events';
import type { QQEventVariant } from '@snowluma/protocol/events';
import type { JsonObject } from '../types';
import type { ConverterContext } from './index';
@@ -1,4 +1,4 @@
import type { MessageElement } from '@snowluma/bridge/events';
import type { MessageElement } from '@snowluma/protocol/events';
import type { JsonArray, JsonObject } from '../types';
import type {
ImageUrlResolver,
@@ -142,8 +142,5 @@ async function elementToSegment(
data: { id: element.resId ?? '' },
};
}
// Unknown / unmapped element type — emit an empty segment to keep the
// outgoing message length consistent with the bridge event.
return { type: element.type, data: {} };
}
@@ -1,5 +1,4 @@
import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT } from '../message-id';
import type { JsonArray, JsonObject } from '../types';
import type { MessageIdResolver } from './index';
export function parseSelfId(instanceUin: string): number {
@@ -7,11 +6,6 @@ export function parseSelfId(instanceUin: string): number {
return Number.isNaN(parsed) ? 0 : parsed;
}
/**
* Two QQEvent actors are "the same" when their uins match, or their
* uids match when uins aren't available. Used by the group_member_join
* sub-type calculation (self-approve vs. invite).
*/
export function isSameActor(
leftUin: number,
leftUid: string | undefined,
@@ -22,10 +16,6 @@ export function isSameActor(
return Boolean(leftUid) && leftUid === rightUid;
}
/**
* Run the optional MessageId resolver, falling back to the raw
* sequence when no resolver is wired or it returns 0.
*/
export function applyMessageIdResolver(
resolver: MessageIdResolver | null,
isGroup: boolean,
@@ -58,48 +48,3 @@ export function resolveReplyId(
return seq;
}
// ─────────────── raw_message (CQ string) generation ───────────────
function cqEscape(text: string): string {
return text.replace(/&/g, '&amp;').replace(/\[/g, '&#91;').replace(/\]/g, '&#93;').replace(/,/g, '&#44;');
}
export function segmentsToRawMessage(segments: JsonArray): string {
return segments.map(seg => segmentToCQ(seg as JsonObject)).join('');
}
function segmentToCQ(seg: JsonObject): string {
const type = String(seg.type ?? '');
const data = (seg.data ?? {}) as Record<string, unknown>;
switch (type) {
case 'text':
return cqEscape(String(data.text ?? ''));
case 'face':
return `[CQ:face,id=${data.id ?? 0}]`;
case 'image':
return `[CQ:image,file=${cqEscape(String(data.file ?? ''))},url=${cqEscape(String(data.url ?? ''))}]`;
case 'at':
return `[CQ:at,qq=${data.qq ?? ''}]`;
case 'reply':
return `[CQ:reply,id=${data.id ?? 0}]`;
case 'record':
return `[CQ:record,file=${cqEscape(String(data.file ?? ''))},url=${cqEscape(String(data.url ?? ''))}]`;
case 'video':
return `[CQ:video,file=${cqEscape(String(data.file ?? ''))},url=${cqEscape(String(data.url ?? ''))}]`;
case 'json':
return `[CQ:json,data=${cqEscape(String(data.data ?? ''))}]`;
case 'xml':
return `[CQ:xml,data=${cqEscape(String(data.data ?? ''))}]`;
case 'forward':
return `[CQ:forward,id=${cqEscape(String(data.id ?? ''))}]`;
case 'mface':
return `[CQ:mface,name=${cqEscape(String(data.name ?? ''))}]`;
case 'poke':
return `[CQ:poke,type=${data.type ?? 0}]`;
case 'file':
return `[CQ:file,name=${cqEscape(String(data.name ?? ''))},size=${data.size ?? 0},id=${cqEscape(String(data.id ?? ''))},url=${cqEscape(String(data.url ?? ''))}]`;
default:
return `[CQ:${type}]`;
}
}
-40
View File
@@ -1,16 +1,9 @@
import type { JsonObject, JsonValue, MessageFormat } from './types';
export interface EventReportOptions {
/** Effective `messageFormat` for this adapter. */
messageFormat: MessageFormat;
/** Whether self-sent messages should be forwarded to this adapter. */
reportSelfMessage: boolean;
}
/**
* Extract the dispatch options from an adapter. Each adapter is fully
* self-describing — there is no global fallback. Defaults are applied here
* only as a safety net for partially-deserialized legacy configs.
*/
export function resolveReportOptions(
network: { messageFormat?: MessageFormat; reportSelfMessage?: boolean },
): EventReportOptions {
@@ -20,32 +13,12 @@ export function resolveReportOptions(
};
}
/**
* Pre-built payload covering every adapter variant of a single canonical event.
*
* The bridge produces one OneBot-shaped event per upstream packet. Because
* adapters only differ in (a) whether they receive `message_sent` self-events
* and (b) whether the `message` field is the segment array or its CQ-string
* form, we serialize the event at most twice up-front and let every adapter
* pick the slot it needs in O(1).
*/
export interface DispatchPayload {
/** True when the canonical event is a self-sent message (`post_type='message_sent'`). */
isSelfMessage: boolean;
/** JSON for adapters using `messageFormat: 'array'` (the canonical event). */
arrayJson: string;
/**
* JSON for adapters using `messageFormat: 'string'`. For non-message events
* this points at the same string as `arrayJson` (no transformation needed).
*/
stringJson: string;
}
/**
* Build the dispatch payload for one canonical OneBot event. Performs at most
* two `JSON.stringify` calls (one per format variant) regardless of how many
* adapters the payload will fan out to.
*/
export function buildDispatchPayload(event: JsonObject): DispatchPayload {
const isSelfMessage = event.post_type === 'message_sent';
const arrayJson = JSON.stringify(event);
@@ -60,11 +33,6 @@ export function buildDispatchPayload(event: JsonObject): DispatchPayload {
return { isSelfMessage, arrayJson, stringJson };
}
/**
* Pick the pre-serialized payload variant an adapter should send, or `null`
* when the adapter chose not to receive this event. Hot-path helper: one
* branch + one map lookup per connection, no allocation.
*/
export function pickDispatchJson(
payload: DispatchPayload,
options: EventReportOptions,
@@ -73,14 +41,6 @@ export function pickDispatchJson(
return options.messageFormat === 'string' ? payload.stringJson : payload.arrayJson;
}
/**
* One-shot variant of {@link buildDispatchPayload} + {@link pickDispatchJson}
* for ad-hoc events (e.g. WS connection bootstrap meta events) that aren't
* worth pre-building a full payload for.
*
* Returns `null` when the adapter shouldn't see this event. Otherwise returns
* the original event untouched, or a shallow clone with `message` rewritten.
*/
export function shapeEventForAdapter(
event: JsonObject,
options: EventReportOptions,
+29 -14
View File
@@ -1,20 +1,10 @@
import type { QQEventVariant } from '@snowluma/bridge/events';
import type { QQEventVariant } from '@snowluma/protocol/events';
import { convertEvent } from './event-converter';
import type { OneBotInstanceContext } from './instance-context';
import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT, hashMessageIdInt32 } from './message-id';
/**
* Subscribe every `OneBotInstanceContext`-aware handler onto the bridge
* event bus. Returns a disposer that removes every subscription registered
* here in one shot — useful for tests and for tearing down a session.
*/
export function registerEventPipeline(ctx: OneBotInstanceContext): () => void {
const disposers: Array<() => void> = [];
// Every kind that maps onto an OB11 message event also seeds the
// message-meta cache; we do that synchronously before async conversion so
// reply / quote lookups for that message id work even if the converter
// takes a beat to finish (e.g. while resolving image URLs).
disposers.push(
ctx.bridge.events.on('group_message', async (event) => {
cacheGroupMessageMeta(ctx, event);
@@ -33,12 +23,12 @@ export function registerEventPipeline(ctx: OneBotInstanceContext): () => void {
await convertAndDispatch(ctx, event);
}),
);
// Notice / request / non-message events: no meta caching needed, just
// convert and dispatch.
for (const kind of NOTICE_KINDS) {
disposers.push(
ctx.bridge.events.on(kind, async (event) => {
if (event.kind === 'group_msg_emoji_like') {
cacheReaction(ctx, event);
}
await convertAndDispatch(ctx, event);
}),
);
@@ -105,3 +95,28 @@ function cachePrivateMessageMeta(
timestamp,
});
}
function cacheReaction(
ctx: OneBotInstanceContext,
event: Extract<QQEventVariant, { kind: 'group_msg_emoji_like' }>,
): void {
if (!event.groupId || !event.msgSeq || !event.emojiId || !event.operatorUin) return;
if (event.isAdd) {
ctx.reactionStore.recordAdd(
event.groupId,
event.msgSeq,
event.emojiId,
1,
event.operatorUin,
event.operatorUid,
event.time,
);
} else {
ctx.reactionStore.recordRemove(
event.groupId,
event.msgSeq,
event.emojiId,
event.operatorUin,
);
}
}
+80
View File
@@ -0,0 +1,80 @@
import type { MessageElement } from '@snowluma/protocol/events';
import { CQ_REGEX, parseCQParams, ParseMessageOptions, segmentToElement } from '../message-parser';
import type { JsonArray, JsonObject } from '../types';
export function segmentToCQ(seg: JsonObject): string {
const type = String(seg.type ?? '');
const data = (seg.data ?? {}) as Record<string, unknown>;
switch (type) {
case 'text':
return cqEscape(String(data.text ?? ''));
case 'face':
return `[CQ:face,id=${data.id ?? 0}]`;
case 'image':
return `[CQ:image,file=${cqEscape(String(data.file ?? ''))},url=${cqEscape(String(data.url ?? ''))}]`;
case 'at':
return `[CQ:at,qq=${data.qq ?? ''}]`;
case 'reply':
return `[CQ:reply,id=${data.id ?? 0}]`;
case 'record':
return `[CQ:record,file=${cqEscape(String(data.file ?? ''))},url=${cqEscape(String(data.url ?? ''))}]`;
case 'video':
return `[CQ:video,file=${cqEscape(String(data.file ?? ''))},url=${cqEscape(String(data.url ?? ''))}]`;
case 'json':
return `[CQ:json,data=${cqEscape(String(data.data ?? ''))}]`;
case 'xml':
return `[CQ:xml,data=${cqEscape(String(data.data ?? ''))}]`;
case 'forward':
return `[CQ:forward,id=${cqEscape(String(data.id ?? ''))}]`;
case 'mface':
return `[CQ:mface,name=${cqEscape(String(data.name ?? ''))}]`;
case 'poke':
return `[CQ:poke,type=${data.type ?? 0}]`;
case 'file':
return `[CQ:file,name=${cqEscape(String(data.name ?? ''))},size=${data.size ?? 0},id=${cqEscape(String(data.id ?? ''))},url=${cqEscape(String(data.url ?? ''))}]`;
default:
return `[CQ:${type}]`;
}
} export function segmentsToRawMessage(segments: JsonArray): string {
return segments.map(seg => segmentToCQ(seg as JsonObject)).join('');
}
export function cqEscape(text: string): string {
return text.replace(/&/g, '&amp;').replace(/\[/g, '&#91;').replace(/\]/g, '&#93;').replace(/,/g, '&#44;');
}
export function cqUnescape(text: string): string {
// Order matters: `&amp;` MUST be last so that, e.g., `&amp;#91;` keeps
// the literal `&#91;` instead of decoding twice into `[`.
return text
.replace(/&#91;/g, '[')
.replace(/&#93;/g, ']')
.replace(/&#44;/g, ',')
.replace(/&amp;/g, '&');
}
export async function parseFromCQString(message: string, options?: ParseMessageOptions): Promise<MessageElement[]> {
const elements: MessageElement[] = [];
let lastIndex = 0;
for (const match of message.matchAll(CQ_REGEX)) {
// Text before this CQ code
if (match.index! > lastIndex) {
const text = cqUnescape(message.substring(lastIndex, match.index!));
if (text) elements.push({ type: 'text', text });
}
lastIndex = match.index! + match[0].length;
const cqType = match[1];
const params = parseCQParams(match[2] || '');
const elem = await segmentToElement(cqType, params, options);
if (elem) elements.push(elem);
}
// Trailing text
if (lastIndex < message.length) {
const text = cqUnescape(message.substring(lastIndex));
if (text) elements.push({ type: 'text', text });
}
return elements;
}
+33 -77
View File
@@ -1,10 +1,10 @@
import type { WebHonorType } from '@snowluma/bridge/web/group-honor';
import type { Bridge } from '@snowluma/core/bridge';
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
import type { WebHonorType } from '@snowluma/protocol/web/group-honor';
import type { ApiActionContext } from './api-handler';
import type { ConverterContext } from './event-converter';
import type { MediaStore } from './media-store';
import type { MessageStore } from './message-store';
import type { JsonObject, MessageMeta, OneBotConfig } from './types';
import {
getDownloadRKeys,
getFriendList,
@@ -17,6 +17,10 @@ import {
getLoginInfo,
getStrangerInfo,
} from './modules/contact-actions';
import {
getImageInfo as getCachedImageInfo,
getRecordInfo as getCachedRecordInfo,
} from './modules/media-actions';
import {
deleteMessage,
forwardSingleMessage,
@@ -30,63 +34,26 @@ import {
setEssenceMessage,
uploadForwardMessage,
} from './modules/message-actions';
import {
getImageInfo as getCachedImageInfo,
getRecordInfo as getCachedRecordInfo,
} from './modules/media-actions';
import { handleGroupAddRequest } from './modules/request-actions';
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
import type { ReactionStore } from './reaction-store';
import type { JsonObject, MessageMeta, OneBotConfig } from './types';
/**
* Single shared context bag that flows through every OneBot instance-internal
* subsystem: API builder and the per-kind event pipeline.
*
* Only fields that are actually read through this bag live here. The API
* handler and network manager are owned by `OneBotInstance` directly because
* nothing reads them via ctx, and including them here would force a
* chicken-and-egg late-bound field dance during construction.
*
* `dispatchEvent` is the indirection used by the event pipeline to hand a
* converted OneBot event back to the instance for caching + adapter fan-out;
* it lets the pipeline stay decoupled from the network manager.
*/
export interface OneBotInstanceContext {
/** Self UIN as string (matches what's on disk and on the wire). */
uin: string;
/** Self UIN parsed once, used in event payloads. */
selfId: number;
bridge: BridgeInterface;
messageStore: MessageStore;
mediaStore: MediaStore;
reactionStore: ReactionStore;
converterCtx: ConverterContext;
config: OneBotConfig;
musicSignUrl?: string;
/** Persist meta about a message id; safe to call any number of times. */
cacheMessageMeta(messageId: number, meta: MessageMeta): void;
/** Hand a fully-converted OneBot event to the network manager + caches. */
dispatchEvent(event: JsonObject): void;
}
/**
* Build the ApiActionContext that ApiHandler hands to each action file.
*
* Two flavours of entries live in here:
* - Adapters — rename a Bridge method (setGroupKick → kickGroupMember),
* compose with messageStore / mediaStore / ref, bake in a constant
* (setEssenceMsg passes true; deleteEssenceMsg passes false), bridge a
* bridge call into OneBot vocabulary (sendFriendPoke flattens the
* isGroup boolean), or extract a field from the bridge return shape.
* - Pass-throughs used to live here too but added zero value; OneBot
* actions now call `ctx.bridge.<name>` directly when no translation is
* happening (set_group_admin, set_online_status, set_avatar, …).
*/
export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
const { bridge, messageStore, mediaStore } = ref;
const { bridge, messageStore, mediaStore, reactionStore } = ref;
return {
bridge,
@@ -97,38 +64,19 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
getMessageMeta: (messageId) => messageStore.findMeta(messageId),
canSendImage: () => true,
canSendRecord: () => true,
// OneBot11 message actions.
sendPrivateMessage: (userId, message, autoEscape) => sendPrivateMessage(ref, userId, message, autoEscape),
sendGroupMessage: (groupId, message, autoEscape) => sendGroupMessage(ref, groupId, message, autoEscape),
deleteMessage: (_messageId, meta) => deleteMessage(bridge, meta),
// OneBot11 info actions (wrap modules that also touch identity).
getFriendList: () => getFriendList(bridge),
getGroupList: (noCache) => getGroupList(bridge, noCache),
getGroupInfo: (groupId, noCache) => getGroupInfo(bridge, groupId, noCache),
getGroupMemberList: (groupId, noCache) => getGroupMemberList(bridge, groupId, noCache),
getGroupMemberInfo: (groupId, userId, noCache) => getGroupMemberInfo(bridge, groupId, userId, noCache),
getStrangerInfo: (userId) => getStrangerInfo(bridge, userId),
// Group admin — actions now call `ctx.bridge.apis.groupAdmin.X(...)`
// directly; no per-method passthrough here anymore.
// Group file — `getGroupFiles` stays because the module helper
// enriches uploader/creator names from the identity cache; the
// rest of the area is called directly via `ctx.bridge.apis.groupFile.*`.
getGroupFiles: (groupId, folderId) => getGroupFiles(bridge, groupId, folderId),
// Group request handling stays here because `handleGroupAddRequest`
// is a module helper (flag parsing + group-request lookup). Friend
// request handling moved to direct `ctx.bridge.apis.friend.handleRequest`.
handleGroupRequest: (flag, _subType, approve, reason) => handleGroupAddRequest(bridge, flag, approve, reason),
// Message-store-backed history reads.
getGroupMsgHistory: (groupId, messageId, count) => getGroupMsgHistory(messageStore, groupId, messageId, count),
getFriendMsgHistory: (userId, messageId, count) => getFriendMsgHistory(messageStore, userId, messageId, count),
// Module wrappers / multi-dep compositions.
handleGetGroupSystemMsg: () => getGroupSystemMessages(bridge),
getDownloadRKeys: () => getDownloadRKeys(bridge),
sendGroupForwardMsg: (groupId, messages, meta) => sendGroupForwardMessage(ref, groupId, messages, meta),
@@ -136,32 +84,40 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
sendForwardMsg: (messages, groupId) => uploadForwardMessage(ref, messages, groupId),
getForwardMsg: (resId) => getForwardMessage(ref, resId),
forwardSingleMsg: (messageId, target) => forwardSingleMessage(ref, messageId, target),
// Essence — bakes the set/unset boolean (the only "compose with
// messageStore meta lookup" entry remaining outside of dedicated
// module helpers).
setEssenceMsg: (messageId) => setEssenceMessage(bridge, messageStore, messageId, true),
deleteEssenceMsg: (messageId) => setEssenceMessage(bridge, messageStore, messageId, false),
// Emoji-like — same shape: meta lookup → bridge call. Group-only
// (QQ doesn't expose emoji reactions on private chats).
setMsgEmojiLike: async (messageId, emojiId, set) => {
const meta = messageStore.findMeta(messageId);
if (!meta) throw new Error('message not found');
if (!meta.isGroup) throw new Error('emoji reactions are not supported on private messages');
await bridge.apis.interaction.setReaction(meta.targetId, meta.sequence, emojiId, set);
},
// Media lookup.
fetchEmojiLikeUsers: async (messageId, emojiId, count, offset = 0) => {
const meta = messageStore.findMeta(messageId);
if (!meta) throw new Error('message not found');
if (!meta.isGroup) throw new Error('emoji reactions are not supported on private messages');
const raw = reactionStore.listUsers(meta.targetId, meta.sequence, emojiId, count, offset);
const users = raw.map(r => ({ uin: r.operatorUin, uid: r.operatorUid, setAt: r.setAt }));
const cachedCount = reactionStore.countUsers(meta.targetId, meta.sequence, emojiId);
let serverCount = cachedCount;
try {
const summary = await bridge.apis.interaction.fetchReactionSummary(meta.targetId, meta.sequence);
const match = summary.find(s => s.emojiId === emojiId);
if (match) serverCount = match.count;
} catch {
/* keep serverCount = cachedCount */
}
return {
users,
cachedCount,
serverCount,
complete: cachedCount >= serverCount,
};
},
getImageInfo: (file) => getCachedImageInfo(mediaStore, file),
getRecordInfo: (file) => getCachedRecordInfo(bridge, mediaStore, file),
};
}
// Re-export Bridge type so consumers of OneBotInstanceContext that need it
// (legacy) keep the import surface stable.
export type { Bridge };
export type { Bridge, WebHonorType };
// Re-export WebHonorType so legacy spots that imported it via this module
// keep working.
export type { WebHonorType };
+4 -14
View File
@@ -1,7 +1,7 @@
import type { MessageElement } from '@snowluma/bridge/events';
import { createLogger } from '@snowluma/common/logger';
import type { DownloadRKeyInfo } from '@snowluma/core/bridge';
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
import { createLogger } from '@snowluma/common/logger';
import type { MessageElement } from '@snowluma/protocol/events';
const log = createLogger('OneBot');
@@ -50,11 +50,6 @@ export class RKeyCache {
const separator = url.includes('?') ? '&rkey=' : '?rkey=';
return url + separator + encodeURIComponent(cleanRKey);
}
/**
* Resolve a URL for video/record/file media elements.
* Appends the correct RKey type based on media kind and group/private context.
*/
resolveMediaUrl(bridge: BridgeInterface, element: MessageElement, isGroup: boolean): string {
const url = element.url ?? '';
if (!url || !urlNeedsRKey(url)) return url;
@@ -111,18 +106,13 @@ export class RKeyCache {
let result = tryFind(primaryType) ?? tryFind(FALLBACK_IMAGE_RKEY_TYPE);
if (result) return result;
// Refresh check cooldown
if (now - this.lastRefreshAttempt < RKEY_REFRESH_COOLDOWN) return null;
this.lastRefreshAttempt = now;
// Schedule async refresh
bridge.apis.contacts.fetchDownloadRKeys().then(
(rkeys) => this.updateCache(rkeys),
() => { /* ignore */ },
);
// Try again (won't be ready yet for this call, but future calls will benefit)
result = tryFind(primaryType) ?? tryFind(FALLBACK_IMAGE_RKEY_TYPE);
return result;
}
@@ -132,8 +122,8 @@ function urlNeedsRKey(url: string): boolean {
if (!url || url.includes('rkey=')) return false;
if (url.includes('gchat.qpic.cn')) return false;
return url.includes('multimedia.nt.qq.com.cn') ||
url.includes('.nt.qq.com.cn') ||
url.includes('/download');
url.includes('.nt.qq.com.cn') ||
url.includes('/download');
}
function stripRKeyPrefix(rkey: string): string {
+18 -36
View File
@@ -1,26 +1,27 @@
import path from 'path';
import { createLogger, type Logger } from '@snowluma/common/logger';
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
import { formatGroup, formatMessageSegments, formatReply, formatUser } from '@snowluma/protocol/format';
import path from 'path';
import { ApiHandler } from './api-handler';
import type { ConverterContext } from './event-converter';
import { registerEventPipeline } from './event-pipeline';
import { buildApiContext, type OneBotInstanceContext } from './instance-context';
import { RKeyCache } from './instance-rkey';
import { MediaIndexer } from './media-indexer';
import { MediaStore } from './media-store';
import { MediaUrlResolver } from './media-url-resolver';
import { MessageStore } from './message-store';
import { RKeyCache } from './instance-rkey';
import { buildApiContext, type OneBotInstanceContext } from './instance-context';
import { registerEventPipeline } from './event-pipeline';
import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT, hashMessageIdInt32 } from './message-id';
import type { JsonObject, JsonValue, MessageMeta, OneBotConfig, NetworkBase } from './types';
import { MessageStore } from './message-store';
import {
OneBotNetworkManager,
WsServerAdapter,
WsClientAdapter,
HttpServerAdapter,
HttpPostAdapter,
HttpServerAdapter,
OneBotNetworkManager,
WsClientAdapter,
WsServerAdapter,
type NetworkAdapterContext,
} from './network';
import { createLogger, type Logger } from '@snowluma/common/logger';
import { formatGroup, formatMessageSegments, formatReply, formatUser } from '@snowluma/bridge/format';
import { ReactionStore } from './reaction-store';
import type { JsonObject, JsonValue, MessageMeta, NetworkBase, OneBotConfig } from './types';
const moduleLog = createLogger('Event');
@@ -32,9 +33,9 @@ export class OneBotInstance {
private readonly converterCtx: ConverterContext;
private readonly messageStore: MessageStore;
private readonly mediaStore: MediaStore;
private readonly reactionStore: ReactionStore;
private readonly networkManager: OneBotNetworkManager;
private readonly rkeyCache: RKeyCache;
private readonly ctx: OneBotInstanceContext;
private disposeEventPipeline: (() => void) | null = null;
private readonly pids = new Set<number>();
@@ -56,10 +57,7 @@ export class OneBotInstance {
this.rkeyCache = new RKeyCache();
this.mediaStore = new MediaStore(path.join('data', this.uin, 'media.db'));
this.messageStore = new MessageStore(path.join('data', this.uin, 'messages.json'));
// The converter context's four callbacks delegate to small, focused
// modules so this constructor doesn't carry the bridge-URL fetch
// branching or the mediaStore field-mapping fanout inline.
this.reactionStore = new ReactionStore(path.join('data', this.uin, 'reactions.db'));
const mediaUrlResolver = new MediaUrlResolver(this.bridge, this.rkeyCache);
const mediaIndexer = new MediaIndexer(this.mediaStore);
this.converterCtx = {
@@ -73,23 +71,19 @@ export class OneBotInstance {
mediaSegmentSink: (mediaType, element, data, isGroup, sessionId) =>
mediaIndexer.remember(mediaType, element, data, isGroup, sessionId),
};
// Shared instance context. Only carries fields that are actually read
// through it — api handler and network manager stay as direct fields on
// the instance because nothing reads them via ctx.
const ctx: OneBotInstanceContext = {
uin: this.uin,
selfId: parseInt(this.uin, 10) || 0,
bridge: this.bridge,
messageStore: this.messageStore,
mediaStore: this.mediaStore,
reactionStore: this.reactionStore,
converterCtx: this.converterCtx,
config,
musicSignUrl: config.musicSignUrl,
cacheMessageMeta: (messageId, meta) => this.cacheMessageMeta(messageId, meta),
dispatchEvent: (event) => this.dispatchEvent(event),
};
this.ctx = ctx;
this.apiHandler = new ApiHandler(buildApiContext(ctx), uinNum > 0 ? uinNum : undefined);
this.networkManager = new OneBotNetworkManager();
@@ -100,9 +94,6 @@ export class OneBotInstance {
this.startHeartbeat();
this.rkeyCache.warmUp(this.bridge, this.uin);
// Per-kind subscription on the typed event bus. Each bridge event kind
// gets its own focused handler in `event-pipeline`; the firehose is gone.
this.disposeEventPipeline = registerEventPipeline(ctx);
}
@@ -122,6 +113,7 @@ export class OneBotInstance {
});
this.messageStore.close();
this.mediaStore.close();
this.reactionStore.close();
}
addPid(pid: number): void {
@@ -147,10 +139,6 @@ export class OneBotInstance {
private dispatchEvent(event: JsonObject): void {
this.cacheMessageEvent(event);
this.logReceivedMessage(event);
// NetworkManager builds the dispatch payload once and fans out to every
// active adapter in parallel via Promise.allSettled — per-adapter errors
// are already isolated, so the outer promise should never reject. The
// .catch is a belt-and-suspenders guard against future refactors.
void this.networkManager.emitEvent(event).catch((err) => {
this.log.warn('emitEvent failed: %s', err instanceof Error ? (err.stack ?? err.message) : String(err));
});
@@ -213,14 +201,11 @@ export class OneBotInstance {
await this.networkManager.closeOne(adapter.name);
}
}
// Reload existing adapters in place; spin up new ones the manager hasn't
// seen before.
for (const [name, net] of desired) {
const existing = this.networkManager.get(name);
if (existing) {
try {
await existing.reload(net as never);
await existing.reload(net);
} catch (err) {
this.log.warn('reload [%s] failed: %s', name, err instanceof Error ? err.message : String(err));
}
@@ -328,9 +313,6 @@ export class OneBotInstance {
},
};
}
// --- Heartbeat ---
private startHeartbeat(): void {
this.heartbeatTimer = setInterval(() => {
this.dispatchEvent(this.makeHeartbeatEvent());
+2 -7
View File
@@ -1,6 +1,6 @@
import { createLogger } from '@snowluma/common/logger';
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
import type { BridgeManager } from '@snowluma/core/manager';
import { createLogger } from '@snowluma/common/logger';
import { loadOneBotConfig } from './config';
import { OneBotInstance } from './instance';
@@ -55,15 +55,10 @@ export class OneBotManager {
if (activePid !== null) {
instance.addPid(activePid);
}
// Seed nickname with the UIN so the WebUI never renders blank while
// warmup is in flight or if warmup never resolves a real nickname.
if (!bridge.identity.nickname) bridge.identity.nickname = uin;
this.instances.set(uin, instance);
log.info('session started: UIN=%s', uin);
// Warm up bridge state asynchronously (mirrors C++ warm_up_bridge_state)
warmUpBridgeState(uin, bridge).catch((err) => {
log.warn('warmup error for UIN %s: %s', uin, err instanceof Error ? (err.stack ?? err.message) : String(err));
});
@@ -97,7 +92,7 @@ async function warmUpBridgeState(uin: string, bridge: BridgeInterface): Promise<
bridge.identity.setSelfProfile({
uin: f.uin, uid: f.uid,
nickname: f.nickname || uin,
remark: '', qid: '', sex: 'unknown', age: 0, sign: '', avatar: '',
remark: '', qid: '', sex: 'unknown', age: 0, sign: '', avatar: '', level: 0,
});
bridge.identity.nickname = f.nickname || uin;
log.debug('self info: UIN=%s uid=%s nickname=%s', uin, f.uid, f.nickname ?? '');
+1 -5
View File
@@ -1,8 +1,4 @@
// Side-channel observer that watches every image / record / video
// segment emitted by the event converter and writes a row into the
// MediaStore so later `get_image` / `get_record` OneBot actions can
import type { MessageElement } from '@snowluma/bridge/events';
import type { MessageElement } from '@snowluma/protocol/events';
import type { MediaStore } from './media-store';
import type { JsonObject } from './types';
+2 -20
View File
@@ -1,31 +1,18 @@
// Persistent media metadata store.
//
// The `get_image` / `get_record` actions need to map a `data.file` (or related
// identifier) we previously emitted in a message segment back to the URL,
// size, name, and any OIDB media-node info needed to re-resolve a stale URL.
import fs from 'fs';
import type { MessageElement } from '@snowluma/protocol/events';
import Database, { type Database as DatabaseType, type Statement } from '@snowluma/sqlite';
import fs from 'fs';
import path from 'path';
import type { MessageElement } from '@snowluma/bridge/events';
export interface CachedImage {
/** Primary `data.file` value as exposed in the OneBot segment. */
file: string;
/** Last known resolved URL (may be empty if resolution failed). */
url: string;
fileSize: number;
fileName: string;
subType: number;
summary: string;
/** Conversation the media originated from. */
isGroup: boolean;
sessionId: number;
/** Original imageUrl from the MessageElement, used for RKey re-appending. */
imageUrl: string;
/** Fingerprints used for md5/sha1 fast-upload on forward. Optional because
* legacy CustomFace / NotOnlineImage only carry md5. */
md5Hex?: string;
sha1Hex?: string;
width?: number;
@@ -34,19 +21,14 @@ export interface CachedImage {
}
export interface CachedRecord {
/** Primary `data.file` value as exposed in the OneBot segment. */
file: string;
/** Raw fileId from the MessageElement (typically the fileUuid). */
fileId: string;
/** Last known resolved URL (may be empty if resolution failed). */
url: string;
fileSize: number;
fileName: string;
duration: number;
fileHash: string;
/** OIDB media node used to re-fetch the URL via getPtt*UrlByNode. */
mediaNode?: MessageElement['mediaNode'];
/** Conversation the media originated from (group vs private path). */
isGroup: boolean;
sessionId: number;
/** Fingerprints used for md5/sha1 fast-upload on forward. */
+1 -5
View File
@@ -1,5 +1,5 @@
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
import type { MessageElement } from '@snowluma/bridge/events';
import type { MessageElement } from '@snowluma/protocol/events';
import type { RKeyCache } from './instance-rkey';
export class MediaUrlResolver {
@@ -19,10 +19,6 @@ export class MediaUrlResolver {
}
return this.rkeyCache.resolveMediaUrl(this.bridge, element, isGroup);
}
/** Branches by element.type + isGroup to pick the right Bridge API.
* Mutates `element.url` in-place so the caller sees the same URL
* the downstream rkey/media-store path will see. */
private async populateUrl(element: MessageElement, isGroup: boolean, sessionId: number): Promise<void> {
if (element.type === 'file' && element.fileId) {
if (isGroup) {
+5 -71
View File
@@ -1,5 +1,6 @@
import type { MessageElement } from '@snowluma/bridge/events';
import { createLogger } from '@snowluma/common/logger';
import type { MessageElement } from '@snowluma/protocol/events';
import { parseFromCQString } from './helper/cq';
import type { JsonValue } from './types';
const log = createLogger('MsgParser');
@@ -13,14 +14,8 @@ export interface ParseMessageOptions {
// --- CQ Code parsing ---
const CQ_REGEX = /\[CQ:([A-Za-z]+)(?:,([^\]]*))?\]/g;
export const CQ_REGEX = /\[CQ:([A-Za-z]+)(?:,([^\]]*))?\]/g;
/**
* Best-effort base-10 integer coercion. Falls back to `fallback` (default 0)
* when the input can't be parsed as a finite integer — `parseInt('abc')`
* is `NaN`, which silently turns into `0`/`null` further down the wire
* pipeline and produces undebuggable protocol-level failures.
*/
function intOr(value: unknown, fallback = 0): number {
if (value === undefined || value === null) return fallback;
if (typeof value === 'number') return Number.isFinite(value) ? Math.trunc(value) : fallback;
@@ -28,7 +23,7 @@ function intOr(value: unknown, fallback = 0): number {
return Number.isFinite(n) ? n : fallback;
}
function parseCQParams(raw: string): Record<string, string> {
export function parseCQParams(raw: string): Record<string, string> {
const params: Record<string, string> = {};
if (!raw) return params;
for (const pair of raw.split(',')) {
@@ -44,43 +39,6 @@ function parseCQParams(raw: string): Record<string, string> {
return params;
}
function cqUnescape(text: string): string {
// Order matters: `&amp;` MUST be last so that, e.g., `&amp;#91;` keeps
// the literal `&#91;` instead of decoding twice into `[`.
return text
.replace(/&#91;/g, '[')
.replace(/&#93;/g, ']')
.replace(/&#44;/g, ',')
.replace(/&amp;/g, '&');
}
async function parseFromCQString(message: string, options?: ParseMessageOptions): Promise<MessageElement[]> {
const elements: MessageElement[] = [];
let lastIndex = 0;
for (const match of message.matchAll(CQ_REGEX)) {
// Text before this CQ code
if (match.index! > lastIndex) {
const text = cqUnescape(message.substring(lastIndex, match.index!));
if (text) elements.push({ type: 'text', text });
}
lastIndex = match.index! + match[0].length;
const cqType = match[1];
const params = parseCQParams(match[2] || '');
const elem = await segmentToElement(cqType, params, options);
if (elem) elements.push(elem);
}
// Trailing text
if (lastIndex < message.length) {
const text = cqUnescape(message.substring(lastIndex));
if (text) elements.push({ type: 'text', text });
}
return elements;
}
// --- JSON segment parsing ---
interface MessageSegment {
@@ -95,7 +53,7 @@ function isSegmentArray(val: unknown): val is MessageSegment[] {
);
}
async function segmentToElement(type: string, data: Record<string, unknown>, options?: ParseMessageOptions): Promise<MessageElement | null> {
export async function segmentToElement(type: string, data: Record<string, unknown>, options?: ParseMessageOptions): Promise<MessageElement | null> {
const normalizedType = type.toLowerCase();
switch (normalizedType) {
case 'text': {
@@ -120,10 +78,6 @@ async function segmentToElement(type: string, data: Record<string, unknown>, opt
if (!uid && options?.resolveMentionUid) {
uid = (await options.resolveMentionUid(uin))?.trim() ?? '';
}
// Leave `text` undefined when the caller didn't supply a display
// name. The element-builder then resolves it from the group roster
// (so QQ renders `@昵称` instead of `@QQ号`).
const element: MessageElement = { type: 'at', targetUin: uin };
if (uid) element.uid = uid;
if (name) element.text = `@${name} `;
@@ -333,14 +287,6 @@ async function segmentToElement(type: string, data: Record<string, unknown>, opt
return null;
}
case 'file': {
// OneBot11 file segment referencing a previously-uploaded file
// (returned by `upload_group_file` / `upload_private_file`).
// We deliberately do NOT support `{file: '/path'}` here because
// the upload pipeline is async and lives behind the bridge —
// the element-builder runs synchronously over the parsed
// message. Callers that want upload-and-send should use the
// dedicated `upload_*` actions which now publish the file in
// chat atomically (`actions/group-file.ts`).
const fileId = String(data.file_id ?? data.fileId ?? '').trim();
if (!fileId) {
log.warn('[MsgParser] file segment without file_id is unsupported (upload first via upload_group_file / upload_private_file)');
@@ -350,10 +296,6 @@ async function segmentToElement(type: string, data: Record<string, unknown>, opt
const fileSize = intOr(data.size ?? data.fileSize, 0);
const md5Hex = String(data.md5 ?? data.md5Hex ?? '').trim();
const sha1Hex = String(data.sha1 ?? data.sha1Hex ?? '').trim();
// file_hash is the c2c-file server-issued addon string — needed
// on the wire when re-sending a previously-uploaded c2c file.
// get_private_file_url callers already pass it through, so honour
// the same field naming here.
const fileHash = String(data.file_hash ?? data.fileHash ?? '').trim();
const elem: MessageElement = { type: 'file', fileId };
if (fileName) elem.fileName = fileName;
@@ -381,14 +323,6 @@ function segmentPayload(seg: MessageSegment): Record<string, unknown> {
// --- Public API ---
/**
* Parse an OneBot11 message value into internal MessageElement array.
* Supports:
* - string (plain text or CQ code string)
* - array of { type, data } segments (JSON segment format)
*
* If autoEscape is true, the string is treated as plain text (no CQ parsing).
*/
export async function parseMessage(message: JsonValue, autoEscape: boolean, options?: ParseMessageOptions): Promise<MessageElement[]> {
if (typeof message === 'string') {
if (autoEscape) {
+1 -14
View File
@@ -1,21 +1,8 @@
import fs from 'fs';
import Database, { type Database as DatabaseType, type Statement } from '@snowluma/sqlite';
import fs from 'fs';
import path from 'path';
import type { JsonObject, MessageMeta } from './types';
// Prepared statements are cached as `readonly` fields so the SQL parser
// runs once at construction time. Previously each `db.prepare(sql)`
// inside a hot-path method re-parsed on every call — the textbook
// SQLite anti-pattern. RoadMap #5 bench numbers showed
// storeMeta ≈ 17μs/op and storeEvent ≈ 23μs/op before caching;
// caching + better-sqlite3 drops both to single-digit-μs (see the
// commit-message numbers).
//
// Also: `node:sqlite` is still an experimental Node API (the
// "ExperimentalWarning: SQLite is an experimental feature" line shows
// up on every test run) — better-sqlite3 is the stable, sync, widely-
// deployed wrapper that proposes the same prepared-statement model.
export class MessageStore {
private readonly db: DatabaseType;
private readonly stmtStoreEvent: Statement;
+61 -59
View File
@@ -1,5 +1,5 @@
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
import type { IdentityService } from '@snowluma/bridge/identity-service';
import type { IdentityService } from '@snowluma/protocol/identity-service';
import type { OneBotInstanceContext } from '../instance-context';
import type { JsonObject } from '../types';
@@ -9,13 +9,11 @@ export function getLoginInfo(ref: OneBotInstanceContext): { userId: number; nick
return { userId, nickname };
}
// Keep refreshes scoped. A broad "refresh all members in all groups" call can
// turn one OneBot request into N OIDB calls, which is risky for busy clients.
async function refreshSingleGroupMembers(bridge: BridgeInterface, groupId: number): Promise<void> {
try {
await bridge.apis.contacts.fetchGroupMemberList(groupId);
} catch {
// Use cached data.
// 需要打log以便排查问题,但不应当让调用者感知到这个失败。
}
}
@@ -23,15 +21,15 @@ export async function getFriendList(bridge: BridgeInterface): Promise<JsonObject
try {
const friends = await bridge.apis.contacts.fetchFriendList();
return friends.map(f => ({
user_id: f.uin as any,
nickname: f.nickname as any,
remark: f.remark as any,
user_id: f.uin,
nickname: f.nickname,
remark: f.remark,
}));
} catch {
return bridge.identity.friends.map(f => ({
user_id: f.uin as any,
nickname: f.nickname as any,
remark: f.remark as any,
user_id: f.uin,
nickname: f.nickname,
remark: f.remark,
}));
}
}
@@ -48,10 +46,10 @@ export async function getGroupList(
// Use cached data.
}
return bridge.identity.groups.map(g => ({
group_id: g.groupId as any,
group_name: g.groupName as any,
member_count: g.memberCount as any,
max_member_count: g.memberMax as any,
group_id: g.groupId,
group_name: g.groupName,
member_count: g.memberCount,
max_member_count: g.memberMax,
}));
}
@@ -70,10 +68,10 @@ export async function getGroupInfo(
const g = bridge.identity.findGroup(groupId);
if (!g) return null;
return {
group_id: g.groupId as any,
group_name: g.groupName as any,
member_count: g.memberCount as any,
max_member_count: g.memberMax as any,
group_id: g.groupId,
group_name: g.groupName,
member_count: g.memberCount,
max_member_count: g.memberMax,
};
}
@@ -117,27 +115,27 @@ export async function getGroupFiles(
const result = await bridge.apis.groupFile.list(groupId, folderId ?? '/');
return {
files: result.files.map((file) => ({
group_id: groupId as any,
file_id: file.fileId as any,
file_name: file.fileName as any,
busid: file.busId as any,
file_size: file.fileSize as any,
upload_time: file.uploadTime as any,
dead_time: file.deadTime as any,
modify_time: file.modifyTime as any,
download_times: file.downloadTimes as any,
uploader: file.uploader as any,
uploader_name: file.uploaderName as any,
} as JsonObject)) as any,
group_id: groupId,
file_id: file.fileId,
file_name: file.fileName,
busid: file.busId,
file_size: file.fileSize,
upload_time: file.uploadTime,
dead_time: file.deadTime,
modify_time: file.modifyTime,
download_times: file.downloadTimes,
uploader: file.uploader,
uploader_name: file.uploaderName,
} as JsonObject)),
folders: result.folders.map((folder) => ({
group_id: groupId as any,
folder_id: folder.folderId as any,
folder_name: folder.folderName as any,
create_time: folder.createTime as any,
creator: folder.creator as any,
create_name: folder.creatorName as any,
total_file_count: folder.totalFileCount as any,
} as JsonObject)) as any,
group_id: groupId,
folder_id: folder.folderId,
folder_name: folder.folderName,
create_time: folder.createTime,
creator: folder.creator,
create_name: folder.creatorName,
total_file_count: folder.totalFileCount,
} as JsonObject)),
};
}
@@ -148,19 +146,23 @@ export async function getStrangerInfo(
try {
const p = await bridge.apis.contacts.fetchUserProfile(userId);
return {
user_id: p.uin as any,
nickname: p.nickname as any,
sex: p.sex as any,
age: p.age as any,
user_id: p.uin,
nickname: p.nickname,
sex: p.sex,
age: p.age,
qq_level: p.level,
level: p.level,
};
} catch {
const p = bridge.identity.findUserProfile(userId);
if (!p) return null;
return {
user_id: p.uin as any,
nickname: p.nickname as any,
sex: p.sex as any,
age: p.age as any,
user_id: p.uin,
nickname: p.nickname,
sex: p.sex,
age: p.age,
qq_level: p.level,
level: p.level,
};
}
}
@@ -176,7 +178,7 @@ export async function getGroupSystemMessages(bridge: BridgeInterface): Promise<J
requester_nick: r.targetName,
message: r.comment,
flag: `${r.eventType}:${r.groupId}:${r.targetUid}`,
} as JsonObject));
}));
} catch {
return [];
}
@@ -190,7 +192,7 @@ export async function getDownloadRKeys(bridge: BridgeInterface): Promise<JsonObj
type: r.type,
ttl: r.ttlSeconds,
create_time: r.createTime,
} as JsonObject));
}));
} catch {
return [];
}
@@ -220,16 +222,16 @@ function formatGroupMember(
},
): JsonObject {
return {
group_id: groupId as any,
user_id: member.uin as any,
nickname: member.nickname as any,
card: member.card as any,
sex: 'unknown' as any,
age: 0 as any,
join_time: member.joinTime as any,
last_sent_time: member.lastSentTime as any,
level: String(member.level) as any,
role: member.role as any,
title: member.title as any,
group_id: groupId,
user_id: member.uin,
nickname: member.nickname,
card: member.card,
sex: 'unknown',
age: 0,
join_time: member.joinTime,
last_sent_time: member.lastSentTime,
level: String(member.level),
role: member.role,
title: member.title,
};
}
+1 -5
View File
@@ -1,5 +1,5 @@
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
import { createLogger } from '@snowluma/common/logger';
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
import type { MediaStore } from '../media-store';
import type { JsonObject } from '../types';
@@ -27,9 +27,6 @@ export async function getRecordInfo(
): Promise<JsonObject | null> {
const cached = mediaStore.findRecord(file);
if (!cached) return null;
// Re-resolve via OIDB if the cached URL is missing or empty.
// Mirrors NapCat's getPttUrl path: GetGroupPttUrl / GetPttUrl by fileUuid.
let url = cached.url;
if (!url && cached.mediaNode) {
try {
@@ -43,7 +40,6 @@ export async function getRecordInfo(
log.warn('get_record url refetch failed: %s', err instanceof Error ? err.message : String(err));
}
}
return {
file: url || cached.file,
url: url || '',
@@ -1,14 +1,14 @@
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
import type { ForwardNodePayload, MessageElement } from '@snowluma/bridge/events';
import { createLogger } from '@snowluma/common/logger';
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
import type { ForwardNodePayload, MessageElement } from '@snowluma/protocol/events';
import type { MessageSendResult } from '../api-handler';
import { elementsToOneBotSegments } from '../event-converter';
import { segmentsToRawMessage } from '../event-converter/utils';
import { segmentsToRawMessage } from '../helper/cq';
import type { OneBotInstanceContext } from '../instance-context';
import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT, hashMessageIdInt32 } from '../message-id';
import { parseMessage } from '../message-parser';
import type { MessageStore } from '../message-store';
import type { JsonArray, JsonObject, JsonValue, MessageMeta } from '../types';
import type { OneBotInstanceContext } from '../instance-context';
const log = createLogger('OneBot');
@@ -6,7 +6,7 @@ export async function handleGroupAddRequest(
approve: boolean,
reason: string,
): Promise<void> {
// flag format: "add:groupId:uid" or "invite:groupId:uid" (from event-converter)
// flag format: "add:groupId:uid" or "invite:groupId:uid"
const parts = flag.split(':');
if (parts.length < 3) throw new Error('invalid group request flag');
const requestType = parts[0];
@@ -26,7 +26,6 @@ export async function handleGroupAddRequest(
if (!matching) {
throw new Error('matching group request not found');
}
await bridge.apis.groupAdmin.setAddRequest(
groupId,
matching.sequence,
Loaded 100 of 297 files, more files were not shown because too many files have changed in this diff. Show more