Merge pull request #183 from SnowLuma/dev

chore: promote dev → main (72aedbc)
This commit is contained in:
snowluma-bot[bot]
2026-07-01 14:15:29 +00:00
committed by GitHub
101 changed files with 3239 additions and 2332 deletions
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "snowluma-monorepo",
"version": "1.11.0",
"version": "1.11.1",
"description": "SnowLuma monorepo workspace (pnpm)",
"private": true,
"type": "module",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/bridge",
"version": "1.11.0",
"version": "1.11.1",
"private": true,
"type": "module",
"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).",
+77 -7
View File
@@ -1,18 +1,29 @@
import { createLogger, type Logger } from '@snowluma/common/logger';
import type { PacketSink } from '@snowluma/common/protocol-types';
import { isRealUin } from '@snowluma/common/uin';
import { EventEmitter } from 'events';
import { HookPacketClient } from './hook-packet-client';
import type { HookInjectResult } from './injector';
import type { QqHookClient, QqHookLoginState, QqHookPacket } from './qq-hook-client';
import { probeQqLoginInfo, type QqPortLoginInfo } from './qq-port-probe';
import { statusFor } from './hook-status';
import type { HookProcessInfo, HookProcessStatus } from './types';
/** How often to actively re-probe QQ's login state while connected but not yet
* logged in — the safety net for a login the native hook never pushed (Docker
* auto-login races/bypasses the pushed loginState frame). */
const LOGIN_RECONCILE_INTERVAL_MS = 3000;
export type HookSessionDeps = {
injector: {
inject: (pid: number) => HookInjectResult;
unload: (pid: number, handle: HookInjectResult['handle']) => void;
};
makeClient: (pid: number) => QqHookClient;
/** Active, pipe-independent login probe (reads QQ's ptlogin/deeplink ports).
* Drives the login-reconcile safety net; injectable for tests. Defaults to
* `probeQqLoginInfo`. */
probeLogin?: (pid: number) => Promise<QqPortLoginInfo | null>;
/** Sync fast-path check used by load() to skip re-injection when a
* prior SnowLuma run left a working pipe behind. `tickNow` forces a
* fresh poll — used after unload to dodge the up-to-1500ms cache
@@ -50,6 +61,7 @@ export class HookSession extends EventEmitter {
private readonly injector: HookSessionDeps['injector'];
private readonly makeClient: HookSessionDeps['makeClient'];
private readonly probeLogin: (pid: number) => Promise<QqPortLoginInfo | null>;
private readonly pipeWatcher: HookSessionDeps['pipeWatcher'];
private readonly onPacket: PacketSink | null;
private readonly log: Logger;
@@ -70,12 +82,15 @@ export class HookSession extends EventEmitter {
private bound = false;
private opChain: Promise<unknown> = Promise.resolve();
private disposed = false;
private loginProbeTimer: ReturnType<typeof setInterval> | null = null;
private probing = false;
constructor(pid: number, deps: HookSessionDeps) {
super();
this.pid = pid;
this.injector = deps.injector;
this.makeClient = deps.makeClient;
this.probeLogin = deps.probeLogin ?? probeQqLoginInfo;
this.pipeWatcher = deps.pipeWatcher;
this.onPacket = deps.onPacket ?? null;
this.log = deps.log ?? createLogger('HookSession');
@@ -347,8 +362,15 @@ export class HookSession extends EventEmitter {
// handleLoginState owns the connected+loggedIn → 'online' (+ login
// emit) transition; defer to it so the status is set once. Otherwise
// we're connected-but-not-logged-in → 'loaded'.
if (loginState.loggedIn) this.handleLoginState(loginState);
else this.applyStatus();
if (loginState.loggedIn) {
this.handleLoginState(loginState);
} else {
this.applyStatus();
// The native hook only PUSHES a loginState frame on the login edge;
// if QQ logged in before/around connect (Docker auto-login) that edge
// is missed and we'd wait forever. Actively re-probe until logged in.
this.startLoginReconcile();
}
this.log.info('pipe connected: PID=%d', this.pid);
} catch (error) {
this._error = errMsg(error);
@@ -381,6 +403,7 @@ export class HookSession extends EventEmitter {
}
private tearDownClient(): void {
this.stopLoginReconcile();
const client = this.client;
if (client) {
client.removeAllListeners();
@@ -398,6 +421,9 @@ export class HookSession extends EventEmitter {
const previousUin = this._uin;
this._uin = state.uin || state.uinNumber.toString();
this.loggedIn = state.loggedIn && isRealUin(this._uin);
// However login was observed (pushed frame or the active probe), the
// safety net's job is done.
if (this.loggedIn) this.stopLoginReconcile();
// Only the connected/logged-in states are ours to set here; when fully
// down we leave the status the teardown path already settled.
@@ -416,6 +442,55 @@ export class HookSession extends EventEmitter {
this.log.success('login detected: PID=%d UIN=%s', this.pid, this._uin);
}
// ─────────────── login reconcile (Docker auto-login safety net) ───────────
// The hook's loginState frame is edge-triggered (pushed only when the native
// observes the login transition). When that edge is missed — QQ auto-logged
// in before connect, or a silent session-restore path the hook doesn't
// intercept — we'd sit at 'loaded'/'connecting' forever. So while connected
// but not logged in, actively re-probe QQ's own ports and synthesize the
// login once it reports a real uin. Idempotent with the pushed-frame path
// (handleLoginState's wasLoggedIn guard dedups the 'login' emit).
private startLoginReconcile(): void {
if (this.loginProbeTimer || this.disposed) return;
void this.probeLoginOnce(); // immediate — catch already-logged-in fast
this.loginProbeTimer = setInterval(() => void this.probeLoginOnce(), LOGIN_RECONCILE_INTERVAL_MS);
this.loginProbeTimer.unref?.();
}
private stopLoginReconcile(): void {
if (this.loginProbeTimer) {
clearInterval(this.loginProbeTimer);
this.loginProbeTimer = null;
}
}
private async probeLoginOnce(): Promise<void> {
// A port-scan probe can outlast the interval; skip overlapping ticks so a
// slow probe never stacks concurrent subprocess-spawning scans.
if (this.probing) return;
if (this.disposed || !this.connected || this.loggedIn) { this.stopLoginReconcile(); return; }
this.probing = true;
try {
let info: QqPortLoginInfo | null;
try {
info = await this.probeLogin(this.pid);
} catch {
return; // best-effort; the interval retries
}
// The await yielded — re-check we still want this before mutating state.
if (this.disposed || !this.connected || this.loggedIn) { this.stopLoginReconcile(); return; }
if (info?.loggedIn && isRealUin(info.uin)) {
this.log.info('login reconciled via active probe: PID=%d UIN=%s', this.pid, info.uin);
// isRealUin guarantees a pure non-empty digit string, so BigInt() here
// cannot throw (keep that contract if isRealUin's regex is ever changed).
this.handleLoginState({ loggedIn: true, uin: info.uin, uinNumber: BigInt(info.uin) });
}
} finally {
this.probing = false;
}
}
private handlePacket(packet: QqHookPacket): void {
if (!this.loggedIn) return;
const uin = packet.uin || this._uin;
@@ -444,11 +519,6 @@ export class HookSession extends EventEmitter {
}
}
function isRealUin(uin: string): boolean {
if (!uin || uin === '0') return false;
return /^\d+$/.test(uin) && uin.length >= 5;
}
function errMsg(value: unknown): string {
return value instanceof Error ? value.message : String(value);
}
+139
View File
@@ -3,6 +3,7 @@ import { EventEmitter } from 'events';
import { HookSession } from '../src/hook-session';
import type { ManualMapHandle } from '../src/injector';
import type { QqHookClient, QqHookPacket } from '../src/qq-hook-client';
import type { QqPortLoginInfo } from '../src/qq-port-probe';
import type { PacketSink } from '@snowluma/common/protocol-types';
const DUMMY_HANDLE: ManualMapHandle = { base: 0n, entry: 0n, exceptionTable: 0n, size: 0 };
@@ -42,6 +43,7 @@ function makeSession(opts: {
pipeLive?: boolean;
clientFailsConnect?: boolean;
onPacket?: PacketSink;
probeLogin?: (pid: number) => Promise<QqPortLoginInfo | null>;
} = {}) {
const pid = opts.pid ?? 1234;
let pipeLive = opts.pipeLive ?? false;
@@ -50,6 +52,9 @@ function makeSession(opts: {
inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })),
unload: vi.fn(),
};
// Default probe reports "not logged in" so the reconcile safety net is inert
// unless a test opts into a logged-in probe (never hits the real port scan).
const probeLogin = opts.probeLogin ?? (async () => ({ port: 0, uin: '', loggedIn: false }));
const session = new HookSession(pid, {
injector,
@@ -60,6 +65,7 @@ function makeSession(opts: {
// Cast: FakeClient mirrors only the surface HookSession touches.
return c as unknown as QqHookClient;
},
probeLogin,
pipeWatcher: { isPipeLive: () => pipeLive },
onPacket: opts.onPacket,
});
@@ -533,3 +539,136 @@ describe('HookSession — packet forwarding', () => {
});
});
});
describe('HookSession — login reconcile (Docker auto-login safety net)', () => {
it('reconciles login via the active probe when the pushed frame is missed', async () => {
// Probe reports logged-in; the FakeClient never fires a loginState frame
// (the missed-edge Docker case). The immediate reconcile probe must detect
// it and emit "login".
const ctx = makeSession({
pipeLive: true,
probeLogin: async () => ({ port: 4301, uin: '10001', loggedIn: true }),
});
const loginSpy = vi.fn();
ctx.session.on('login', loginSpy);
await ctx.session.load();
ctx.session.onPipeUp();
await flush(); // connect (not logged in via frame) → starts reconcile
await flush(); // immediate probe resolves → handleLoginState
expect(loginSpy).toHaveBeenCalledOnce();
expect(loginSpy.mock.calls[0]![0]).toBe('10001');
expect(ctx.session.status).toBe('online');
expect(ctx.session.uin).toBe('10001');
});
it('does not log in when the probe reports not-logged-in', async () => {
const ctx = makeSession({
pipeLive: true,
probeLogin: async () => ({ port: 0, uin: '', loggedIn: false }),
});
const loginSpy = vi.fn();
ctx.session.on('login', loginSpy);
await ctx.session.load();
ctx.session.onPipeUp();
await flush(); await flush();
expect(loginSpy).not.toHaveBeenCalled();
expect(ctx.session.status).toBe('loaded');
});
it('ignores a probe with a non-real uin (0)', async () => {
const ctx = makeSession({
pipeLive: true,
probeLogin: async () => ({ port: 4301, uin: '0', loggedIn: true }),
});
const loginSpy = vi.fn();
ctx.session.on('login', loginSpy);
await ctx.session.load();
ctx.session.onPipeUp();
await flush(); await flush();
expect(loginSpy).not.toHaveBeenCalled();
});
it('tolerates a throwing probe (best-effort, no crash/login)', async () => {
const ctx = makeSession({
pipeLive: true,
probeLogin: async () => { throw new Error('port scan failed'); },
});
const loginSpy = vi.fn();
ctx.session.on('login', loginSpy);
await ctx.session.load();
ctx.session.onPipeUp();
await flush(); await flush();
expect(loginSpy).not.toHaveBeenCalled();
expect(ctx.session.status).toBe('loaded');
});
it('detects a login that lands on a LATER interval probe', async () => {
vi.useFakeTimers();
try {
let loggedIn = false;
const ctx = makeSession({
pipeLive: true,
probeLogin: async () => ({ port: 4301, uin: '10001', loggedIn }),
});
const loginSpy = vi.fn();
ctx.session.on('login', loginSpy);
await ctx.session.load();
ctx.session.onPipeUp();
await vi.advanceTimersByTimeAsync(0); // connect + immediate probe (not logged in yet)
expect(loginSpy).not.toHaveBeenCalled();
loggedIn = true; // QQ finishes auto-login
await vi.advanceTimersByTimeAsync(3000); // next interval probe picks it up
expect(loginSpy).toHaveBeenCalledOnce();
expect(ctx.session.status).toBe('online');
} finally {
vi.useRealTimers();
}
});
it('does not double-emit when the pushed frame logs in first', async () => {
// Pushed-frame login wins; a subsequent probe with the same uin must not
// re-emit (handleLoginState dedups), and the reconcile timer is stopped.
const probeLogin = vi.fn(async () => ({ port: 4301, uin: '10001', loggedIn: true }));
const ctx = makeSession({ pipeLive: true, probeLogin });
const loginSpy = vi.fn();
ctx.session.on('login', loginSpy);
await ctx.session.load();
ctx.session.onPipeUp();
await flush();
ctx.currentClient().fireLogin('10001'); // pushed-frame login first
await flush();
expect(loginSpy).toHaveBeenCalledOnce();
expect(ctx.session.status).toBe('online');
});
});
describe('HookSession — login reconcile does not stack concurrent probes', () => {
it('skips overlapping ticks while a slow probe is in flight', async () => {
vi.useFakeTimers();
try {
// A probe that never resolves — simulates a slow port scan spanning
// multiple intervals. The in-flight guard must call it only once.
const probeLogin = vi.fn(() => new Promise<never>(() => { /* pending */ }));
const ctx = makeSession({ pipeLive: true, probeLogin });
await ctx.session.load();
ctx.session.onPipeUp();
await vi.advanceTimersByTimeAsync(0); // connect + immediate probe (starts, stays pending)
await vi.advanceTimersByTimeAsync(9000); // 3 more interval ticks
expect(probeLogin).toHaveBeenCalledTimes(1); // not stacked
} finally {
vi.useRealTimers();
}
});
});
+13 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/common",
"version": "1.11.0",
"version": "1.11.1",
"private": true,
"type": "module",
"description": "SnowLuma shared infrastructure — leaf-package utilities with zero business dependencies. Logger / hex codec / log file transport / log line summariser / packet sender wire-protocol types / runtime config loader. Consumed by @snowluma/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).",
@@ -20,6 +20,14 @@
"types": "./src/coerce.ts",
"default": "./src/coerce.ts"
},
"./single-flight-cache": {
"types": "./src/single-flight-cache.ts",
"default": "./src/single-flight-cache.ts"
},
"./concurrency": {
"types": "./src/concurrency.ts",
"default": "./src/concurrency.ts"
},
"./hex": {
"types": "./src/hex.ts",
"default": "./src/hex.ts"
@@ -47,6 +55,10 @@
"./runtime": {
"types": "./src/runtime.ts",
"default": "./src/runtime.ts"
},
"./uin": {
"types": "./src/uin.ts",
"default": "./src/uin.ts"
}
},
"scripts": {
+27
View File
@@ -0,0 +1,27 @@
/**
* Map `items` through `fn` in sequential batches of at most `concurrency`
* items, awaiting each batch (`Promise.all`) before starting the next.
* Results come back in input order.
*
* Batched, not a rolling pool: every item in a batch must settle before the
* next batch starts. This caps peak parallelism — used to keep rate-limited
* fan-out (e.g. the per-uin OIDB profile fetches during forward-node
* enrichment) from bursting past a safe width and tripping Tencent
* risk-control. Pair it with a cap on `items` (slice) and per-item error
* handling inside `fn` for a fully bounded, best-effort enrichment — the
* shape that was previously hand-rolled at each such call site.
*/
export async function mapWithConcurrency<T, R>(
items: readonly T[],
concurrency: number,
fn: (item: T, index: number) => Promise<R>,
): Promise<R[]> {
const limit = Math.max(1, Math.trunc(concurrency));
const results = new Array<R>(items.length);
for (let i = 0; i < items.length; i += limit) {
const batch = items.slice(i, i + limit);
const settled = await Promise.all(batch.map((item, j) => fn(item, i + j)));
for (let j = 0; j < settled.length; j++) results[i + j] = settled[j]!;
}
return results;
}
+1 -1
View File
@@ -175,7 +175,7 @@ function render(level: LogLevel, options: LogOptions, args: unknown[], reqId?: n
// Pad first, then color only the visible tag so escape codes don't eat
// into the alignment width.
const cUin = uinTag
? ansi(COLOR_DIM, uinTag) + ' '.repeat(UIN_SLOT_WIDTH - uinTag.length)
? ansi(COLOR_DIM, uinTag) + ' '.repeat(Math.max(0, UIN_SLOT_WIDTH - uinTag.length))
: ' '.repeat(UIN_SLOT_WIDTH);
const cScope = ansi(COLOR_SCOPE, `[${options.scope}]`);
const cReq = reqTag ? `${ansi(COLOR_DIM, reqTag)} ` : '';
@@ -0,0 +1,93 @@
/**
* Single-flight + TTL memoization.
*
* Concentrates the "don't refetch what's fresh, and don't stampede the same
* key with concurrent loads" pattern that was hand-rolled (slightly
* differently each time) across the codebase — e.g. `ContactsApi`'s group
* member-list cache and the WebUI update-check. Each copy re-implemented the
* same fiddly trio: a TTL freshness check, an in-flight promise map to
* de-dupe concurrent callers, and `finally`-cleanup of that map. Getting any
* of the three subtly wrong (forgetting the `finally`, caching an error,
* racing the timestamp) is a real hazard — so it lives in one place.
*
* The underlying concern is Tencent risk-control: a busy OneBot client can
* fan out one uncached OIDB fetch per inbound message, and sustained bursts
* trip a ban. TTL + single-flight collapse that fan-out.
*/
export interface SingleFlightCacheOptions<K, V> {
/** Freshness window in ms. A cached entry older than this is reloaded. */
ttlMs: number;
/** Load the value for a key. Rejections propagate and are never cached. */
load: (key: K) => Promise<V>;
/**
* Decide whether a resolved value should be cached. Default: always.
* Return `false` to leave an entry uncached (e.g. an error-shaped result the
* next call should retry) while still de-duping concurrent in-flight callers.
*/
shouldCache?: (value: V) => boolean;
/** Clock, injectable for tests. Defaults to `Date.now`. */
now?: () => number;
}
export class SingleFlightCache<K, V> {
private readonly ttlMs: number;
private readonly load: (key: K) => Promise<V>;
private readonly shouldCache: (value: V) => boolean;
private readonly now: () => number;
private readonly fresh = new Map<K, { at: number; value: V }>();
private readonly inflight = new Map<K, Promise<V>>();
constructor(opts: SingleFlightCacheOptions<K, V>) {
this.ttlMs = opts.ttlMs;
this.load = opts.load;
this.shouldCache = opts.shouldCache ?? (() => true);
this.now = opts.now ?? Date.now;
}
/**
* Get the value for `key`.
*
* - Returns a fresh cached value when the last load was within `ttlMs`.
* - Otherwise de-dupes concurrent callers onto a single `load()` and caches
* the result (subject to `shouldCache`). A rejected `load` propagates to
* every joined caller, clears the in-flight slot, and is not cached.
* - `force` bypasses the freshness check but still joins an in-flight load
* rather than starting a second one.
*/
get(key: K, opts: { force?: boolean } = {}): Promise<V> {
if (!opts.force) {
const hit = this.fresh.get(key);
if (hit && this.now() - hit.at < this.ttlMs) return Promise.resolve(hit.value);
}
const existing = this.inflight.get(key);
if (existing) return existing;
const task = (async () => {
try {
const value = await this.load(key);
if (this.shouldCache(value)) this.fresh.set(key, { at: this.now(), value });
return value;
} finally {
this.inflight.delete(key);
}
})();
this.inflight.set(key, task);
return task;
}
/** Drop a cached entry. Does not abort an in-flight load. */
invalidate(key: K): void {
this.fresh.delete(key);
}
/** Drop all cached entries. Does not abort in-flight loads. */
clear(): void {
this.fresh.clear();
}
}
export function createSingleFlightCache<K, V>(
opts: SingleFlightCacheOptions<K, V>,
): SingleFlightCache<K, V> {
return new SingleFlightCache(opts);
}
+11
View File
@@ -0,0 +1,11 @@
// Shared QQ UIN validity check. A "real" UIN is a live QQ account number, not
// a garbage value the native hook can emit during the probe→inject race — e.g.
// a 13-digit millisecond timestamp read from not-yet-populated QQ memory
// (issue #162). No real QQ UIN exceeds 10 digits (they fit in uint32, max
// 4294967295), so a pure digit string of 5..10 chars is the accept window.
//
// Callers rely on a `true` result guaranteeing a BigInt()-safe pure-digit
// string. Keep that contract if the pattern ever changes.
export function isRealUin(uin: string): boolean {
return /^\d{5,10}$/.test(uin);
}
+68
View File
@@ -0,0 +1,68 @@
import { describe, it, expect } from 'vitest';
import { mapWithConcurrency } from '../src/concurrency';
const tick = () => new Promise<void>((r) => setTimeout(r, 0));
describe('mapWithConcurrency', () => {
it('returns results in input order', async () => {
const out = await mapWithConcurrency([1, 2, 3, 4, 5], 2, async (n) => n * 10);
expect(out).toEqual([10, 20, 30, 40, 50]);
});
it('passes the absolute index (across batch boundaries)', async () => {
const seen: Array<[number, number]> = [];
await mapWithConcurrency(['a', 'b', 'c', 'd', 'e'], 2, async (item, i) => {
seen.push([i, item.charCodeAt(0)]);
return i;
});
expect(seen.map(([i]) => i).sort((x, y) => x - y)).toEqual([0, 1, 2, 3, 4]);
});
it('never runs more than `concurrency` at once (batched), and serializes across batches', async () => {
let inFlight = 0;
let peak = 0;
const order: number[] = [];
await mapWithConcurrency([0, 1, 2, 3, 4, 5, 6], 3, async (n) => {
inFlight++;
peak = Math.max(peak, inFlight);
await tick();
order.push(n);
inFlight--;
return n;
});
expect(peak).toBeLessThanOrEqual(3);
// batched: first 3 (0,1,2) settle before the next batch (3,4,5) starts.
expect(order.slice(0, 3).sort((a, b) => a - b)).toEqual([0, 1, 2]);
expect(order.slice(3, 6).sort((a, b) => a - b)).toEqual([3, 4, 5]);
expect(order[6]).toBe(6);
});
it('handles a length not divisible by concurrency (short final batch)', async () => {
const out = await mapWithConcurrency([1, 2, 3, 4, 5], 3, async (n) => n);
expect(out).toEqual([1, 2, 3, 4, 5]);
});
it('runs everything in one batch when concurrency >= length', async () => {
let peak = 0, inFlight = 0;
const out = await mapWithConcurrency([1, 2, 3], 10, async (n) => {
inFlight++; peak = Math.max(peak, inFlight); await tick(); inFlight--; return n;
});
expect(out).toEqual([1, 2, 3]);
expect(peak).toBe(3);
});
it('returns [] for an empty input without calling fn', async () => {
let called = 0;
const out = await mapWithConcurrency([], 4, async (n) => { called++; return n; });
expect(out).toEqual([]);
expect(called).toBe(0);
});
it('treats concurrency < 1 as 1 (fully serial)', async () => {
let peak = 0, inFlight = 0;
await mapWithConcurrency([1, 2, 3], 0, async (n) => {
inFlight++; peak = Math.max(peak, inFlight); await tick(); inFlight--; return n;
});
expect(peak).toBe(1);
});
});
+45
View File
@@ -0,0 +1,45 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
// The file transport writes to disk; stub it so the test has no side effects.
vi.mock('../src/log-file-transport', () => ({
getFileTransport: () => ({ write: () => {} }),
}));
import { createLogger } from '../src/logger';
// Regression for issue #162: a hook-reported garbage UIN (13-digit, timestamp
// shaped) produced a `[…]` tag wider than the fixed UIN slot, and the colored
// render path did `' '.repeat(slot - tagLen)` → RangeError: Invalid count value
// → uncaughtException. The padding must clamp at zero.
describe('logger UIN slot padding', () => {
let prevTTY: boolean | undefined;
let prevNoColor: string | undefined;
beforeEach(() => {
prevTTY = process.stdout.isTTY;
prevNoColor = process.env.NO_COLOR;
// Force the colored render path (the only one that used .repeat()).
(process.stdout as unknown as { isTTY: boolean }).isTTY = true;
delete process.env.NO_COLOR;
vi.spyOn(process.stdout, 'write').mockReturnValue(true);
vi.spyOn(process.stderr, 'write').mockReturnValue(true);
});
afterEach(() => {
(process.stdout as unknown as { isTTY: boolean | undefined }).isTTY = prevTTY;
if (prevNoColor === undefined) delete process.env.NO_COLOR;
else process.env.NO_COLOR = prevNoColor;
vi.restoreAllMocks();
});
it('does not throw when the UIN tag exceeds the slot width', () => {
const log = createLogger('Test').child({ uin: '1701414379536' }); // 13-digit → [..] = 15 chars
expect(() => log.info('phantom account line')).not.toThrow();
expect(() => log.error('phantom error line')).not.toThrow();
});
it('still renders a normal-width UIN and a no-UIN logger', () => {
expect(() => createLogger('Test').child({ uin: '10001' }).info('ok')).not.toThrow();
expect(() => createLogger('Test').info('no uin')).not.toThrow();
});
});
@@ -0,0 +1,131 @@
import { describe, it, expect, vi } from 'vitest';
import { createSingleFlightCache } from '../src/single-flight-cache';
/** A promise whose resolve/reject is exposed, for driving single-flight races. */
function deferred<T>() {
let resolve!: (v: T) => void;
let reject!: (e: unknown) => void;
const promise = new Promise<T>((res, rej) => { resolve = res; reject = rej; });
return { promise, resolve, reject };
}
describe('SingleFlightCache', () => {
it('caches within the TTL and reloads once expired', async () => {
let clock = 1000;
const load = vi.fn(async (k: string) => `${k}@${clock}`);
const cache = createSingleFlightCache<string, string>({ ttlMs: 100, load, now: () => clock });
expect(await cache.get('a')).toBe('a@1000');
clock = 1050; // still fresh (< 100)
expect(await cache.get('a')).toBe('a@1000');
expect(load).toHaveBeenCalledTimes(1);
clock = 1101; // 101ms since store → expired
expect(await cache.get('a')).toBe('a@1101');
expect(load).toHaveBeenCalledTimes(2);
});
it('de-dupes concurrent callers onto a single load (single-flight)', async () => {
const d = deferred<string>();
const load = vi.fn(() => d.promise);
const cache = createSingleFlightCache<string, string>({ ttlMs: 1000, load });
const p1 = cache.get('k');
const p2 = cache.get('k');
const p3 = cache.get('k');
expect(load).toHaveBeenCalledTimes(1); // only one load in flight
d.resolve('v');
expect(await Promise.all([p1, p2, p3])).toEqual(['v', 'v', 'v']);
expect(load).toHaveBeenCalledTimes(1);
});
it('keys independently — different keys load separately', async () => {
const load = vi.fn(async (k: number) => k * 2);
const cache = createSingleFlightCache<number, number>({ ttlMs: 1000, load });
expect(await cache.get(1)).toBe(2);
expect(await cache.get(2)).toBe(4);
expect(load).toHaveBeenCalledTimes(2);
});
it('force bypasses the freshness check but still joins an in-flight load', async () => {
let clock = 0;
const load = vi.fn(async (k: string) => `${k}@${clock}`);
const cache = createSingleFlightCache<string, string>({ ttlMs: 10_000, load, now: () => clock });
expect(await cache.get('a')).toBe('a@0'); // 1 load, cached fresh
clock = 5; // still fresh
expect(await cache.get('a', { force: true })).toBe('a@5'); // force → reload despite fresh
expect(load).toHaveBeenCalledTimes(2);
// force still single-flights: two concurrent forced gets share one load.
const d = deferred<string>();
load.mockImplementationOnce(() => d.promise);
const p1 = cache.get('a', { force: true });
const p2 = cache.get('a', { force: true });
expect(load).toHaveBeenCalledTimes(3); // not 4
d.resolve('shared');
expect(await Promise.all([p1, p2])).toEqual(['shared', 'shared']);
});
it('shouldCache=false leaves the entry uncached (next call reloads) but still de-dupes in-flight', async () => {
let n = 0;
const load = vi.fn(async () => ({ error: true as boolean, n: ++n }));
const cache = createSingleFlightCache({ ttlMs: 10_000, load, shouldCache: (v) => !v.error });
// concurrent callers still share one load...
const [a, b] = await Promise.all([cache.get('k'), cache.get('k')]);
expect(a).toEqual({ error: true, n: 1 });
expect(b).toEqual({ error: true, n: 1 });
expect(load).toHaveBeenCalledTimes(1);
// ...but nothing was cached, so the next call reloads.
expect(await cache.get('k')).toEqual({ error: true, n: 2 });
expect(load).toHaveBeenCalledTimes(2);
// a good result IS cached.
load.mockImplementationOnce(async () => ({ error: false, n: ++n }));
const good = await cache.get('k');
expect(good).toEqual({ error: false, n: 3 });
expect(await cache.get('k')).toEqual({ error: false, n: 3 }); // served from cache
expect(load).toHaveBeenCalledTimes(3);
});
it('a rejected load propagates to all joined callers, is not cached, and clears in-flight', async () => {
let attempt = 0;
const load = vi.fn(async () => {
attempt++;
if (attempt === 1) throw new Error('boom');
return 'ok';
});
const cache = createSingleFlightCache<string, string>({ ttlMs: 10_000, load });
const p1 = cache.get('k');
const p2 = cache.get('k');
await expect(p1).rejects.toThrow('boom');
await expect(p2).rejects.toThrow('boom'); // same in-flight, same rejection
expect(load).toHaveBeenCalledTimes(1);
// in-flight cleared + not cached → next call retries and succeeds.
expect(await cache.get('k')).toBe('ok');
expect(load).toHaveBeenCalledTimes(2);
});
it('invalidate drops a cached entry; clear drops all', async () => {
const load = vi.fn(async (k: string) => k.toUpperCase());
const cache = createSingleFlightCache<string, string>({ ttlMs: 10_000, load });
await cache.get('a');
await cache.get('b');
expect(load).toHaveBeenCalledTimes(2);
cache.invalidate('a');
await cache.get('a'); // reloads
await cache.get('b'); // still cached
expect(load).toHaveBeenCalledTimes(3);
cache.clear();
await cache.get('a');
await cache.get('b');
expect(load).toHaveBeenCalledTimes(5);
});
});
+40
View File
@@ -0,0 +1,40 @@
import { describe, expect, it } from 'vitest';
import { isRealUin } from '../src/uin';
describe('isRealUin', () => {
it('accepts real QQ UINs (5..10 digits)', () => {
expect(isRealUin('10001')).toBe(true); // 5-digit floor
expect(isRealUin('123456789')).toBe(true);
expect(isRealUin('4294967295')).toBe(true); // uint32 max, 10 digits
});
it('rejects the empty string and "0"', () => {
expect(isRealUin('')).toBe(false);
expect(isRealUin('0')).toBe(false);
});
it('rejects too-short UINs (< 5 digits)', () => {
expect(isRealUin('1')).toBe(false);
expect(isRealUin('1234')).toBe(false);
});
it('rejects the garbage timestamp-shaped UINs from issue #162 (11+ digits)', () => {
expect(isRealUin('1701414379536')).toBe(false); // 13-digit ms timestamp
expect(isRealUin('1614019567632')).toBe(false);
expect(isRealUin('2014024115056')).toBe(false);
expect(isRealUin('12345678901')).toBe(false); // 11 digits — first rejected width
});
it('rejects non-digit strings (path traversal / injection guards)', () => {
expect(isRealUin('12345a')).toBe(false);
expect(isRealUin('12 345')).toBe(false);
expect(isRealUin('../etc')).toBe(false);
expect(isRealUin('123456\n')).toBe(false);
});
it('guarantees a BigInt-safe pure-digit string on accept', () => {
const uin = '123456789';
expect(isRealUin(uin)).toBe(true);
expect(() => BigInt(uin)).not.toThrow();
});
});
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/core",
"version": "1.11.0",
"version": "1.11.1",
"description": "SnowLuma core - NTQQ packet sniffer with Node.js native addon",
"private": true,
"type": "module",
+10 -23
View File
@@ -8,6 +8,7 @@ import { FetchUserProfile } from '@snowluma/protocol/oidb-services/contacts/fetc
import { FetchUserProfileByUid } from '@snowluma/protocol/oidb-services/contacts/fetch-user-profile-by-uid';
import { GetBuddyRecommendArk } from '@snowluma/protocol/oidb-services/contacts/get-buddy-recommend-ark';
import { GetGroupRecommendArk } from '@snowluma/protocol/oidb-services/contacts/get-group-recommend-ark';
import { createSingleFlightCache, type SingleFlightCache } from '@snowluma/common/single-flight-cache';
import type {
FriendInfo,
GroupMemberInfo,
@@ -55,16 +56,19 @@ 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.
* Per-group TTL + single-flight cache for `fetchGroupMemberList`, keyed by
* groupId, living 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[] }>();
private readonly memberListCache: SingleFlightCache<number, GroupMemberInfo[]> =
createSingleFlightCache({
ttlMs: MEMBER_LIST_TTL_MS,
load: (groupId) => this.fetchGroupMemberListUncached(groupId),
});
constructor(private readonly ctx: BridgeContext) { }
@@ -139,28 +143,11 @@ export class ContactsApi {
};
}
async fetchGroupMemberList(
fetchGroupMemberList(
groupId: number,
options: { force?: boolean } = {},
): Promise<GroupMemberInfo[]> {
const now = Date.now();
const last = this.memberListLastFetch.get(groupId);
if (!options.force && last && now - last.at < MEMBER_LIST_TTL_MS) {
return last.data;
}
const inflight = this.memberListInflight.get(groupId);
if (inflight) return inflight;
const task = (async () => {
try {
const data = await this.fetchGroupMemberListUncached(groupId);
this.memberListLastFetch.set(groupId, { at: Date.now(), data });
return data;
} finally {
this.memberListInflight.delete(groupId);
}
})();
this.memberListInflight.set(groupId, task);
return task;
return this.memberListCache.get(groupId, { force: options.force });
}
private async fetchGroupMemberListUncached(groupId: number): Promise<GroupMemberInfo[]> {
@@ -2,6 +2,7 @@
// 复用 OIDB 基础设施(invokeOidb),协议层在 @snowluma/protocol/oidb-services/flash-transfer/。
import type { BridgeContext } from '../bridge-context';
import { resolveSelfUid } from './shared';
import type { FlashFileEntry } from '@snowluma/proto-defs/oidb-actions/flash-transfer';
import { GetFilesetDetail } from '@snowluma/protocol/oidb-services/flash-transfer/get-fileset-detail';
import { ListFilesets } from '@snowluma/protocol/oidb-services/flash-transfer/list-filesets';
@@ -276,7 +277,9 @@ export class FlashTransferApi {
const uploader = {
uin: this.ctx.identity.uin,
nickname: this.ctx.identity.nickname,
uid: this.ctx.identity.selfUid ?? '',
// Resolve our own uid rather than ship an empty one — a blank uploader
// uid drops the fileset if this runs before warmup populated selfUid.
uid: await resolveSelfUid(this.ctx),
};
// 读取所有文件,每个分配 fileUuid + 序号 + formatCode
const items: { bytes: Uint8Array; fileName: string; fileUuid: string; fileIndex: number; formatCode: number }[] = [];
+8 -7
View File
@@ -1,4 +1,5 @@
import type { PacketInfo } from '@snowluma/common/protocol-types';
import { mapWithConcurrency } from '@snowluma/common/concurrency';
import type {
LongMsgResult,
RecvLongMsgReq,
@@ -150,7 +151,9 @@ async function buildForwardPushBody(
return {
responseHead: {
fromUin,
toUid: bridge.identity.selfUid ?? '',
// Resolve our own uid rather than ship an empty one — a blank toUid is a
// broken packet if this runs before warmup populated selfUid.
toUid: await resolveSelfUid(bridge),
forward: {
friendName: nickname,
},
@@ -676,14 +679,12 @@ export class ForwardApi {
.slice(0, FORWARD_PROFILE_MAX);
if (uins.length > 0) {
const byUin = new Map<number, string>();
for (let i = 0; i < uins.length; i += FORWARD_PROFILE_CONCURRENCY) {
const batch = uins.slice(i, i + FORWARD_PROFILE_CONCURRENCY);
const results = await Promise.all(batch.map(async (uin): Promise<readonly [number, string]> => {
const results = await mapWithConcurrency(uins, FORWARD_PROFILE_CONCURRENCY,
async (uin): Promise<readonly [number, string]> => {
try { return [uin, (await this.ctx.apis.contacts.fetchUserProfile(uin)).nickname] as const; }
catch { return [uin, ''] as const; }
}));
for (const [uin, nick] of results) byUin.set(uin, nick);
}
});
for (const [uin, nick] of results) byUin.set(uin, nick);
for (const n of residue) {
if (!this.needsName(n)) continue;
const nick = byUin.get(n.userUin);
+7 -8
View File
@@ -23,6 +23,7 @@ import { MoveGroupFile } from '@snowluma/protocol/oidb-services/group-file/move-
import { PublishGroupFile } from '@snowluma/protocol/oidb-services/group-file/publish-group-file';
import { RenameGroupFile } from '@snowluma/protocol/oidb-services/group-file/rename-group-file';
import { RenameGroupFolder } from '@snowluma/protocol/oidb-services/group-file/rename-group-folder';
import { TransGroupFile, type TransGroupFileResult } from '@snowluma/protocol/oidb-services/group-file/trans-group-file';
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';
@@ -238,6 +239,11 @@ export class GroupFileApi {
return PublishGroupFile.invoke(this.ctx, { groupId, fileId });
}
trans(groupId: number, fileId: string): Promise<TransGroupFileResult> {
if (!fileId) throw new Error('trans requires fileId');
return TransGroupFile.invoke(this.ctx, { groupId, fileId });
}
// ─────────────── count ───────────────
getCount(groupId: number): Promise<{ fileCount: number; maxCount: number }> {
@@ -360,14 +366,7 @@ export class GroupFileApi {
if (!loaded.bytes.length) throw new Error('private file is empty');
const targetUid = await this.ctx.resolveUserUid(userId);
let selfUid = this.ctx.identity.selfUid;
if (!selfUid) {
const selfUin = toInt(this.ctx.identity.uin);
if (selfUin > 0) {
selfUid = await this.ctx.resolveUserUid(selfUin);
}
}
if (!selfUid) throw new Error('self uid is unavailable');
const selfUid = await resolveSelfUid(this.ctx);
const senderUin = toInt(this.ctx.identity.uin);
if (senderUin <= 0) throw new Error('invalid self uin for private file upload');
+2 -6
View File
@@ -15,6 +15,7 @@ import { fetchC2cMessageRange, fetchGroupMessageRange } from '@snowluma/protocol
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import { createLogger } from '@snowluma/common/logger';
import type { BridgeContext } from '../bridge-context';
import { resolveSelfUid } from './shared';
// `Bridge` is imported as a type only so we can narrow `ctx` back to
// the concrete Bridge instance when passing it to `buildSendElems`
// (which still takes `Bridge` because the highway upload helpers it
@@ -259,12 +260,7 @@ export class MessageApi {
// Resolve our own uid — needed both for the 0xE37_800 finalize and the
// `field6` download-routing the receiver reads.
let selfUid = this.ctx.identity.selfUid;
if (!selfUid) {
const selfUin = Number.parseInt(this.ctx.identity.uin ?? '', 10);
if (Number.isFinite(selfUin) && selfUin > 0) selfUid = await this.ctx.resolveUserUid(selfUin);
}
if (!selfUid) throw new Error('self uid unavailable for c2c file send');
const selfUid = await resolveSelfUid(this.ctx);
// The file is already downloadable from the `NotOnlineFile` reference
// alone — verified on a live account: a plain c2c file send (no field6)
+9 -2
View File
@@ -55,10 +55,17 @@ export class QzoneApi {
* 发表说说,返回新说说的 tid。始终发到机器人自己的空间。
* `richType` / `richval`: 带图说说时传 richType=1 和 richval 字符串
* (多图用 `\t` 连接多个 richval)。纯文字说说省略这两个参数。
* `ugcRight` / `targetUins`: 查看权限及其作用名单(ugcRight=16/128 时必填)。
*/
async publish(content: string, richType?: number, richval?: string): Promise<QzonePublishResult> {
async publish(
content: string,
richType?: number,
richval?: string,
ugcRight = 1,
targetUins?: string,
): Promise<QzonePublishResult> {
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
return publishQzoneMsg(cookieObject, this.ctx.identity.uin, content, richType, richval);
return publishQzoneMsg(cookieObject, this.ctx.identity.uin, content, richType, richval, ugcRight, targetUins);
}
/** 删除机器人自己空间的一条说说(按 tid)。 */
+4 -18
View File
@@ -1,5 +1,3 @@
import type { Bridge } from '../bridge';
export function toInt(value: unknown): number {
if (typeof value === 'number' && Number.isFinite(value)) return Math.trunc(value);
if (typeof value === 'bigint') {
@@ -26,22 +24,10 @@ export function ensureRetCodeZero(operation: string, code: unknown, msg: unknown
throw new Error(`${operation} failed: code=${retCode} msg=${text}`);
}
/**
* Look up the bot's own UID. Cached on Identity once warmup populates
* `selfProfile`; forward/profile actions need this fast path before
* warmup completes.
*/
export async function resolveSelfUid(bridge: Bridge): Promise<string> {
let selfUid = bridge.identity.selfUid;
if (selfUid) return selfUid;
const selfUin = toInt(bridge.identity.uin);
if (selfUin <= 0) {
throw new Error('self uid is unavailable');
}
selfUid = await bridge.resolveUserUid(selfUin);
return selfUid;
}
// The bot's-own-UID resolver is the single source of truth in @snowluma/protocol
// (a Bridge satisfies its BridgeContext slice). Re-exported here so the existing
// `resolveSelfUid(bridge)` call sites in this package keep importing from shared.
export { resolveSelfUid } from '@snowluma/protocol/self-uid';
/**
* Index describing a server-side rich-media object (image / video /
+3 -7
View File
@@ -1,6 +1,7 @@
import { createLogger } from '@snowluma/common/logger';
import type { PacketSender } from '@snowluma/common/packet-sender';
import type { PacketInfo } from '@snowluma/common/protocol-types';
import { isRealUin } from '@snowluma/common/uin';
import { IdentityService } from '@snowluma/protocol/identity-service';
import { Bridge } from './bridge';
@@ -72,13 +73,8 @@ export class BridgeManager {
}
}
private static isRealUin(uin: string): boolean {
if (!uin || uin === '0') return false;
return /^\d+$/.test(uin) && uin.length >= 5;
}
onHookLogin(pid: number, uin: string, packetClient: PacketSender): void {
if (!BridgeManager.isRealUin(uin)) return;
if (!isRealUin(uin)) return;
this.pidPacketClients_.set(pid, packetClient);
@@ -94,7 +90,7 @@ export class BridgeManager {
}
onPacket(pkt: PacketInfo): void {
if (!pkt.uin || !BridgeManager.isRealUin(pkt.uin)) return;
if (!pkt.uin || !isRealUin(pkt.uin)) return;
const uin = pkt.uin;
// Ensure session exists
+5
View File
@@ -3,6 +3,7 @@ import { closeLogger, createLogger } from '@snowluma/common/logger';
import { loadRuntimeConfig } from '@snowluma/common/runtime';
import { OneBotManager } from '@snowluma/onebot/manager';
import { migrateGlobalSettings } from '@snowluma/onebot/global-config';
import { cleanupInvalidPerUinConfigs } from '@snowluma/onebot/config';
import { BridgeManager } from './bridge/manager';
import { createNotificationManager } from './notifications/manager';
import { createStateWiring } from './webui/state-wiring';
@@ -33,6 +34,10 @@ async function main() {
// any session (and thus any per-UIN config rewrite) can drop it.
migrateGlobalSettings();
// One-shot: purge any persisted phantom accounts (onebot_<garbage>.json) the
// native hook may have created with a timestamp-shaped UIN (issue #162).
cleanupInvalidPerUinConfigs();
const bridgeManager = new BridgeManager();
const oneBotManager = new OneBotManager();
const autoLoadOnDiscovery = resolveAutoLoad(runtimeConfig.hookAutoLoad);
+52 -133
View File
@@ -23,6 +23,7 @@ import { buildBackup, planRestore, validateBackup } from './backup';
import { collectActionDocs, collectCategories } from '@snowluma/onebot/action-docs';
import { createFramePusher } from './debug-stream';
import { buildStreamInvokeResponse, streamUploadToDisk } from './debug-tools';
import { sseResponse } from './sse-response';
import { bindStateStream } from './state-stream';
import type { StateBus, StateResource } from './state-bus';
import { startConnectionDiffLoop } from './connection-diff-loop';
@@ -100,9 +101,12 @@ export const SSE_TOKEN_QUERY_PATHS: ReadonlySet<string> = new Set([
]);
const TOKEN_QUERY_ALLOWLIST = SSE_TOKEN_QUERY_PATHS;
// uin = QQ number; 5–12 digits. Used to construct config file paths,
// so we MUST refuse anything else (path traversal, NUL bytes, etc.).
const UIN_REGEX = /^\d{5,12}$/;
// uin = QQ number; 5–10 digits (real QQ UINs fit in uint32, max 4294967295).
// Used to construct config file paths, so we MUST refuse anything else (path
// traversal, NUL bytes, etc.) — and the 10-digit cap also rejects the garbage
// timestamp-shaped UINs the native hook can emit (issue #162). Mirrors
// isRealUin in @snowluma/common/uin.
const UIN_REGEX = /^\d{5,10}$/;
const avatarCache = new Map<string, { body: Uint8Array; contentType: string; expiresAt: number }>();
@@ -969,45 +973,21 @@ export async function initWebUI(
// Live merged SSE of OneBot events + action calls across all accounts. Taps
// are attached only while a client is connected (on-demand). A slow client is
// dropped (not back-pressured onto the bot) with a periodic drop marker.
app.get('/api/debug/stream', (c) => {
const stream = new ReadableStream({
start(controller) {
const encoder = new TextEncoder();
let closed = false;
const offs: Array<() => void> = [];
let heartbeat: NodeJS.Timeout | undefined;
const teardown = () => {
if (closed) return;
closed = true;
if (heartbeat) clearInterval(heartbeat);
for (const off of offs) { try { off(); } catch { /* ignore */ } }
try { controller.close(); } catch { /* ignore */ }
};
const raw = (chunk: Uint8Array) => {
if (closed) return;
try { controller.enqueue(chunk); } catch { teardown(); }
};
// Drop-under-backpressure framing (unit-tested in debug-stream.ts).
const pushFrame = createFramePusher({
desiredSize: () => controller.desiredSize,
enqueue: raw,
encode: (s) => encoder.encode(s),
});
const send = (payload: unknown) => { if (!closed) pushFrame(payload); };
send({ kind: 'ready' });
for (const inst of oneBotManager.getInstances()) {
const uin = inst.uin;
offs.push(inst.subscribeDebugEvents((event) => send({ kind: 'event', uin, event })));
offs.push(inst.observeActions((rec) => send({ kind: 'action', uin, ...rec })));
}
heartbeat = setInterval(() => raw(encoder.encode(': heartbeat\n\n')), 15000);
c.req.raw.signal.addEventListener('abort', teardown);
},
app.get('/api/debug/stream', (c) => sseResponse(c, (ch) => {
// Drop-under-backpressure framing (unit-tested in debug-stream.ts).
const pushFrame = createFramePusher({
desiredSize: ch.desiredSize,
enqueue: ch.raw,
encode: ch.encode,
});
return new Response(stream, {
headers: { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', Connection: 'keep-alive' },
});
});
const send = (payload: unknown) => { if (!ch.isClosed()) pushFrame(payload); };
send({ kind: 'ready' });
for (const inst of oneBotManager.getInstances()) {
const uin = inst.uin;
ch.onClose(inst.subscribeDebugEvents((event) => send({ kind: 'event', uin, event })));
ch.onClose(inst.observeActions((rec) => send({ kind: 'action', uin, ...rec })));
}
}));
app.get('/api/qq-list', (c) => {
const instances = oneBotManager.getInstances();
@@ -1039,56 +1019,34 @@ export async function initWebUI(
return c.text('state stream not configured', 503);
}
const liveBus = stateBus;
const stream = new ReadableStream({
start(controller) {
const encoder = new TextEncoder();
let closed = false;
let binding: { dispose(): void } | undefined;
let heartbeat: NodeJS.Timeout | undefined;
const teardown = () => {
if (closed) return;
closed = true;
if (heartbeat) clearInterval(heartbeat);
binding?.dispose();
try { controller.close(); } catch { /* ignore */ }
};
const raw = (chunk: Uint8Array) => {
if (closed) return;
try { controller.enqueue(chunk); } catch { teardown(); }
};
const pushFrame = createFramePusher({
desiredSize: () => controller.desiredSize,
enqueue: raw,
encode: (s) => encoder.encode(s),
});
const send = (payload: unknown) => { if (!closed) pushFrame(payload); };
send({ kind: 'ready' });
return sseResponse(c, (ch) => {
const pushFrame = createFramePusher({
desiredSize: ch.desiredSize,
enqueue: ch.raw,
encode: ch.encode,
});
const send = (payload: unknown) => { if (!ch.isClosed()) pushFrame(payload); };
send({ kind: 'ready' });
const handle = bindStateStream({
bus: liveBus,
snapshot: async (resource: StateResource): Promise<unknown> => {
if (resource === 'processes') {
if (!hookManager) return [];
return hookManager.listProcesses();
}
if (resource === 'qq-list') {
return oneBotManager.getInstances().map((inst) => ({ uin: inst.uin, nickname: inst.nickname }));
}
return oneBotManager.getConnectionStatuses();
},
send: (frame) => send(frame),
debounceMs: 50,
});
binding = handle;
// Prime with the initial snapshot; if the client never sees the
// bus publish (idle system) it still has the current state.
void handle.sendAllInitial();
heartbeat = setInterval(() => raw(encoder.encode(': heartbeat\n\n')), 15000);
c.req.raw.signal.addEventListener('abort', teardown);
},
});
return new Response(stream, {
headers: { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', Connection: 'keep-alive' },
const handle = bindStateStream({
bus: liveBus,
snapshot: async (resource: StateResource): Promise<unknown> => {
if (resource === 'processes') {
if (!hookManager) return [];
return hookManager.listProcesses();
}
if (resource === 'qq-list') {
return oneBotManager.getInstances().map((inst) => ({ uin: inst.uin, nickname: inst.nickname }));
}
return oneBotManager.getConnectionStatuses();
},
send: (frame) => send(frame),
debounceMs: 50,
});
ch.onClose(() => handle.dispose());
// Prime with the initial snapshot; if the client never sees the
// bus publish (idle system) it still has the current state.
void handle.sendAllInitial();
});
});
@@ -1111,49 +1069,10 @@ export async function initWebUI(
return c.json({ level: getLogLevel(), levels: [...LOG_LEVELS] });
});
app.get('/api/logs/stream', (c) => {
const stream = new ReadableStream({
start(controller) {
const encoder = new TextEncoder();
let closed = false;
let unsubscribe: (() => void) | undefined;
let heartbeat: NodeJS.Timeout | undefined;
const teardown = () => {
if (closed) return;
closed = true;
if (heartbeat) clearInterval(heartbeat);
unsubscribe?.();
try { controller.close(); } catch { /* ignore */ }
};
const safeEnqueue = (chunk: Uint8Array) => {
if (closed) return;
try {
controller.enqueue(chunk);
} catch {
// The peer dropped between abort and the next enqueue —
// treat as end-of-stream so we don't leak listeners.
teardown();
}
};
const send = (event: unknown) => {
safeEnqueue(encoder.encode(`data: ${JSON.stringify(event)}\n\n`));
};
send({ type: 'ready' });
unsubscribe = subscribeLogs((entry) => send(entry));
heartbeat = setInterval(() => {
safeEnqueue(encoder.encode(': heartbeat\n\n'));
}, 15000);
c.req.raw.signal.addEventListener('abort', teardown);
},
});
return new Response(stream, {
headers: {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
Connection: 'keep-alive',
},
});
});
app.get('/api/logs/stream', (c) => sseResponse(c, (ch) => {
ch.send({ type: 'ready' });
ch.onClose(subscribeLogs((entry) => ch.send(entry)));
}));
app.get('/api/processes', async (c) => {
if (!hookManager) return c.json({ list: [] });
+69
View File
@@ -0,0 +1,69 @@
import { type Context } from 'hono';
/**
* The per-connection channel handed to an SSE endpoint's `start` callback.
* Everything the endpoint needs to talk to the client, without owning the
* transport lifecycle (heartbeat / teardown / abort / headers).
*/
export interface SseChannel {
/** Enqueue a raw chunk. Tears the stream down if the peer is already gone. */
raw(chunk: Uint8Array): void;
/** Encode a string to bytes (shared TextEncoder). */
encode(s: string): Uint8Array;
/** Convenience: enqueue one `data: <json>\n\n` frame. */
send(payload: unknown): void;
/** Register a cleanup to run once on teardown (unsubscribe / dispose). */
onClose(fn: () => void): void;
/** True after teardown — guard sends from late subscription callbacks. */
isClosed(): boolean;
/** Underlying controller backpressure signal, for `createFramePusher`. */
desiredSize(): number | null;
}
/**
* The SSE HTTP transport shell shared by the WebUI's live endpoints. Owns the
* TextEncoder, a `closed` guard, a 15s `: heartbeat` keep-alive, teardown
* (clear heartbeat → run registered cleanups → close the controller), safe
* enqueue (a throw means the peer dropped → teardown), the abort listener, and
* the `text/event-stream` headers. `start` wires up the endpoint-specific
* subscription + initial sends via the channel.
*
* Each of `/api/debug/stream`, `/api/state/stream`, `/api/logs/stream`
* previously hand-copied this ~40-line skeleton; a heartbeat-interval /
* teardown-order / header change had to be kept in sync across all three.
*/
export function sseResponse(c: Context, start: (ch: SseChannel) => void): Response {
const stream = new ReadableStream<Uint8Array>({
start(controller) {
const encoder = new TextEncoder();
let closed = false;
let heartbeat: ReturnType<typeof setInterval> | undefined;
const cleanups: Array<() => void> = [];
const teardown = () => {
if (closed) return;
closed = true;
if (heartbeat) clearInterval(heartbeat);
for (const fn of cleanups) { try { fn(); } catch { /* ignore */ } }
try { controller.close(); } catch { /* ignore */ }
};
const raw = (chunk: Uint8Array) => {
if (closed) return;
try { controller.enqueue(chunk); } catch { teardown(); }
};
const ch: SseChannel = {
raw,
encode: (s) => encoder.encode(s),
send: (payload) => raw(encoder.encode(`data: ${JSON.stringify(payload)}\n\n`)),
onClose: (fn) => { cleanups.push(fn); },
isClosed: () => closed,
desiredSize: () => controller.desiredSize,
};
start(ch);
heartbeat = setInterval(() => raw(encoder.encode(': heartbeat\n\n')), 15000);
c.req.raw.signal.addEventListener('abort', teardown);
},
});
return new Response(stream, {
headers: { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', Connection: 'keep-alive' },
});
}
+18 -17
View File
@@ -11,6 +11,7 @@
// "无法检查更新" rather than nagging).
import { createLogger } from '@snowluma/common/logger';
import { createSingleFlightCache } from '@snowluma/common/single-flight-cache';
const log = createLogger('Update');
@@ -79,8 +80,22 @@ export function compareVersions(a: string, b: string): number {
return pa.pre < pb.pre ? -1 : 1;
}
let cache: UpdateCheckResult | null = null;
let inflight: Promise<UpdateCheckResult> | null = null;
// TTL + single-flight: cache good results for CACHE_TTL_MS (well under GitHub's
// 60 req/hr limit) and collapse concurrent checks onto one fetch. Error results
// are intentionally not cached (shouldCache) so the next check retries.
const updateCache = createSingleFlightCache<string, UpdateCheckResult>({
ttlMs: CACHE_TTL_MS,
shouldCache: (r) => !r.error,
load: async (current) => {
const result = await fetchLatest(current);
if (result.error) {
log.debug('update check failed: %s', result.error);
} else if (result.hasUpdate) {
log.info('a newer release is available: v%s (running v%s)', result.latest, current);
}
return result;
},
});
async function fetchLatest(current: string): Promise<UpdateCheckResult> {
const base: UpdateCheckResult = {
@@ -133,21 +148,7 @@ export async function getUpdateInfo(force = false): Promise<UpdateCheckResult> {
if (!isEnabled()) {
return { ...emptyResult(current), error: 'disabled' };
}
if (!force && cache && Date.now() - cache.checkedAt < CACHE_TTL_MS) return cache;
if (inflight) return inflight;
inflight = (async () => {
const result = await fetchLatest(current);
if (result.error) {
log.debug('update check failed: %s', result.error);
} else {
cache = result; // only cache good results so transient errors retry
if (result.hasUpdate) log.info('a newer release is available: v%s (running v%s)', result.latest, current);
}
return result;
})().finally(() => {
inflight = null;
});
return inflight;
return updateCache.get(current, { force });
}
function emptyResult(current: string): UpdateCheckResult {
+2
View File
@@ -65,6 +65,7 @@ export interface MockGroupFileApi {
upload: ReturnType<typeof vi.fn>;
uploadPrivate: ReturnType<typeof vi.fn>;
publish: ReturnType<typeof vi.fn>;
trans: ReturnType<typeof vi.fn>;
getCount: ReturnType<typeof vi.fn>;
list: ReturnType<typeof vi.fn>;
getUrl: ReturnType<typeof vi.fn>;
@@ -85,6 +86,7 @@ export function mockGroupFileApi(): MockGroupFileApi {
upload: vi.fn(async () => ({ fileId: 'stub-fid' })),
uploadPrivate: vi.fn(async () => ({ fileId: 'stub-pfid', fileHash: 'stub-hash' })),
publish: vi.fn(async () => undefined),
trans: vi.fn(async () => ({ saveBusId: 102, saveFilePath: '/stub-path' })),
getCount: vi.fn(async () => ({ fileCount: 0, maxCount: 10000 })),
list: vi.fn(async () => ({ files: [], folders: [] })),
getUrl: vi.fn(async () => 'stub://url'),
@@ -8,6 +8,7 @@ import type {
OidbGroupFileViewResp,
OidbGroupFileFolderResp,
OidbGroupSendFileReq,
OidbGroupSendFileResp,
} from '@snowluma/proto-defs/oidb-actions/group-file';
import type {
OidbPrivateFileUploadResp,
@@ -246,6 +247,26 @@ describe('apis/group-file', () => {
});
});
it('trans hits OIDB 0x6d9_0 and returns the saved path metadata', async () => {
const bridge = mockBridge();
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
protobuf_encode<OidbBase<OidbGroupSendFileResp>>({
body: { transFile: { saveBusId: 102, saveFilePath: '/saved/path' } },
}),
));
const out = await new GroupFileApi(bridge as any).trans(12345, 'fid-trans');
expect(out).toEqual({ saveBusId: 102, saveFilePath: '/saved/path' });
const [wire, bytes] = bridge.sendRawPacket.mock.calls[0]!;
expect(wire).toBe('OidbSvcTrpcTcp.0x6d9_0');
const env = protobuf_decode<OidbBase<OidbGroupSendFileReq>>(bytes);
expect(env.body?.transFile).toMatchObject({
groupUin: 12345n,
appId: 7,
busId: 102,
fileId: 'fid-trans',
});
});
it('uploadPrivate resolves both target + self UID before OIDB call', async () => {
const bridge = mockBridge({
identity: {
+11 -3
View File
@@ -74,7 +74,7 @@ describe('apis/qzone', () => {
const pubSpy = vi.spyOn(qzoneWeb, 'publishQzoneMsg').mockResolvedValue({ tid: 'T', time: 1 });
const out = await new QzoneApi(bridge as never).publish('hello');
expect(getCookies).toHaveBeenCalledWith('qzone.qq.com');
expect(pubSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', 'hello', undefined, undefined);
expect(pubSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', 'hello', undefined, undefined, 1, undefined);
expect(out).toEqual({ tid: 'T', time: 1 });
});
@@ -85,7 +85,7 @@ describe('apis/qzone', () => {
const richval = ',12345,abc,abc,22,800,600,,800,600';
const out = await new QzoneApi(bridge as never).publish('look at this', 1, richval);
expect(getCookies).toHaveBeenCalledWith('qzone.qq.com');
expect(pubSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', 'look at this', 1, richval);
expect(pubSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', 'look at this', 1, richval, 1, undefined);
expect(out).toEqual({ tid: 'T2', time: 2 });
});
@@ -96,10 +96,18 @@ describe('apis/qzone', () => {
const richval = ',12345,a,a,22,800,600,,800,600\t,12346,b,b,22,1024,768,,1024,768';
const out = await new QzoneApi(bridge as never).publish('two images', 1, richval);
expect(getCookies).toHaveBeenCalledWith('qzone.qq.com');
expect(pubSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', 'two images', 1, richval);
expect(pubSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', 'two images', 1, richval, 1, undefined);
expect(out).toEqual({ tid: 'T3', time: 3 });
});
it('publish threads qzone visibility params', async () => {
const getCookies = vi.fn(async () => ({ p_skey: 'PSK' }));
const bridge = mockBridge({ apis: { ...mockApiHub(), web: { getCookies } } as never });
const pubSpy = vi.spyOn(qzoneWeb, 'publishQzoneMsg').mockResolvedValue({ tid: 'T', time: 1 });
await new QzoneApi(bridge as never).publish('hello', undefined, undefined, 16, '10002|10003');
expect(pubSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', 'hello', undefined, undefined, 16, '10002|10003');
});
it('delete removes a feed by tid from the bot\'s own space', async () => {
const getCookies = vi.fn(async () => ({ p_skey: 'PSK' }));
const bridge = mockBridge({ apis: { ...mockApiHub(), web: { getCookies } } as never });
@@ -10,10 +10,15 @@ vi.mock('@snowluma/protocol/element-builder', () => ({
buildSendElems: vi.fn(async () => [{ text: { str: 'stub media elem' } }]),
}));
// Imported statically (not via `await import` inside each `it`) so the heavy
// Bridge dependency-tree load happens once at file collection — not against a
// single test's 5s timeout, which tipped over on slower CI runners. vi.mock is
// hoisted above these by vitest, so element-builder is still mocked.
import { Bridge } from '../src/bridge/bridge';
import { IdentityService } from '@snowluma/protocol/identity-service';
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/protocol/identity-service');
class TestBridge extends Bridge {
capturedBody: Uint8Array | null = null;
@@ -61,8 +66,6 @@ describe('Bridge private media routing', () => {
// BuildPacketBase` + `FileEntity.PackMessageContent`. Previous
// 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/protocol/identity-service');
class TestBridge extends Bridge {
capturedBody: Uint8Array | null = null;
@@ -160,8 +163,6 @@ describe('Bridge private media routing', () => {
});
it('c2c file send survives a failing 0xE37_800 finalize — sends without field6 (#157 best-effort)', async () => {
const { Bridge } = await import('../src/bridge/bridge');
const { IdentityService } = await import('@snowluma/protocol/identity-service');
class TestBridge extends Bridge {
capturedBody: Uint8Array | null = null;
+62
View File
@@ -0,0 +1,62 @@
import { describe, it, expect, vi } from 'vitest';
import { sseResponse } from '../src/webui/sse-response';
// A minimal hono-Context stand-in: sseResponse only reads c.req.raw.signal.
function fakeCtx(signal: AbortSignal): Parameters<typeof sseResponse>[0] {
return { req: { raw: { signal } } } as unknown as Parameters<typeof sseResponse>[0];
}
describe('sseResponse', () => {
it('returns an event-stream Response with the SSE headers', () => {
const ac = new AbortController();
const res = sseResponse(fakeCtx(ac.signal), () => { /* no-op */ });
expect(res.headers.get('Content-Type')).toBe('text/event-stream');
expect(res.headers.get('Cache-Control')).toBe('no-cache');
expect(res.headers.get('Connection')).toBe('keep-alive');
ac.abort(); // clear the heartbeat timer
});
it('ch.send frames JSON as `data: …` and ch.raw enqueues verbatim', async () => {
const ac = new AbortController();
const res = sseResponse(fakeCtx(ac.signal), (ch) => {
ch.send({ type: 'ready' });
ch.raw(ch.encode(': heartbeat\n\n'));
});
const reader = res.body!.getReader();
const dec = new TextDecoder();
expect(dec.decode((await reader.read()).value)).toBe('data: {"type":"ready"}\n\n');
expect(dec.decode((await reader.read()).value)).toBe(': heartbeat\n\n');
ac.abort();
await reader.cancel();
});
it('abort runs registered cleanups exactly once, flips isClosed, and closes the stream', async () => {
const ac = new AbortController();
const cleanupA = vi.fn();
const cleanupB = vi.fn();
let channel!: Parameters<Parameters<typeof sseResponse>[1]>[0];
const res = sseResponse(fakeCtx(ac.signal), (ch) => {
channel = ch;
ch.onClose(cleanupA);
ch.onClose(cleanupB);
});
expect(channel.isClosed()).toBe(false);
ac.abort();
expect(cleanupA).toHaveBeenCalledTimes(1);
expect(cleanupB).toHaveBeenCalledTimes(1);
expect(channel.isClosed()).toBe(true);
const r = await res.body!.getReader().read();
expect(r.done).toBe(true);
});
it('send after teardown is a silent no-op', () => {
const ac = new AbortController();
let channel!: Parameters<Parameters<typeof sseResponse>[1]>[0];
sseResponse(fakeCtx(ac.signal), (ch) => { channel = ch; });
ac.abort();
expect(() => channel.send({ x: 1 })).not.toThrow();
expect(channel.isClosed()).toBe(true);
});
});
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/mcp",
"version": "1.11.0",
"version": "1.11.1",
"description": "MCP server exposing the SnowLuma OneBot action catalog (docs + JSON Schemas) and optional execution to LLM clients.",
"repository": {
"type": "git",
+83 -5
View File
@@ -7183,7 +7183,7 @@
{
"name": "send_qzone_msg",
"aliases": [],
"summary": "发表说说(QQ 空间,支持纯文字或带图;传 images 自动上传)",
"summary": "发表说说(QQ 空间,支持纯文字或带图;传 images 自动上传;可设置查看权限)",
"readOnly": false,
"params": [
{
@@ -7208,9 +7208,36 @@
}
},
"desc": "图片数组(可选),支持 file:// http:// base64://;自动上传"
},
{
"name": "ugc_right",
"type": "int",
"required": false,
"schema": {
"type": "integer",
"minimum": 1
},
"desc": "查看权限:1=所有人可见,4=好友可见,16=部分好友可见,64=仅自己可见,128=部分好友不可见",
"default": 1
},
{
"name": "target_uins",
"type": "uint[]",
"required": false,
"schema": {
"type": "array",
"items": {
"type": "integer",
"minimum": 1
}
},
"desc": "权限作用 QQ 号数组;ugc_right=16 时表示可见名单,128 时表示不可见名单"
}
],
"invariants": [],
"invariants": [
"ugc_right must be one of 1, 4, 16, 64, 128",
"target_uins is required when ugc_right is 16 or 128"
],
"inputSchema": {
"type": "object",
"properties": {
@@ -7226,6 +7253,20 @@
"minLength": 1
},
"description": "图片数组(可选),支持 file:// http:// base64://;自动上传"
},
"ugc_right": {
"type": "integer",
"minimum": 1,
"description": "查看权限:1=所有人可见,4=好友可见,16=部分好友可见,64=仅自己可见,128=部分好友不可见",
"default": 1
},
"target_uins": {
"type": "array",
"items": {
"type": "integer",
"minimum": 1
},
"description": "权限作用 QQ 号数组;ugc_right=16 时表示可见名单,128 时表示不可见名单"
}
},
"required": [
@@ -9053,13 +9094,50 @@
{
"name": "trans_group_file",
"aliases": [],
"summary": "转存群文件(未实现)",
"summary": "转存群文件",
"returns": "{ ok: true }",
"readOnly": false,
"params": [],
"params": [
{
"name": "group_id",
"type": "uint",
"required": true,
"role": "group_id",
"schema": {
"type": "integer",
"minimum": 1
}
},
{
"name": "file_id",
"type": "string",
"required": true,
"role": "file_id",
"schema": {
"type": "string",
"minLength": 1
}
}
],
"invariants": [],
"inputSchema": {
"type": "object",
"properties": {},
"properties": {
"group_id": {
"type": "integer",
"minimum": 1,
"x-role": "group_id"
},
"file_id": {
"type": "string",
"minLength": 1,
"x-role": "file_id"
}
},
"required": [
"group_id",
"file_id"
],
"additionalProperties": true
},
"category": "扩展"
+83 -5
View File
@@ -7186,7 +7186,7 @@ export const ACTIONS: CatalogAction[] = [
{
"name": "send_qzone_msg",
"aliases": [],
"summary": "发表说说(QQ 空间,支持纯文字或带图;传 images 自动上传)",
"summary": "发表说说(QQ 空间,支持纯文字或带图;传 images 自动上传;可设置查看权限)",
"readOnly": false,
"params": [
{
@@ -7211,9 +7211,36 @@ export const ACTIONS: CatalogAction[] = [
}
},
"desc": "图片数组(可选),支持 file:// http:// base64://;自动上传"
},
{
"name": "ugc_right",
"type": "int",
"required": false,
"schema": {
"type": "integer",
"minimum": 1
},
"desc": "查看权限:1=所有人可见,4=好友可见,16=部分好友可见,64=仅自己可见,128=部分好友不可见",
"default": 1
},
{
"name": "target_uins",
"type": "uint[]",
"required": false,
"schema": {
"type": "array",
"items": {
"type": "integer",
"minimum": 1
}
},
"desc": "权限作用 QQ 号数组;ugc_right=16 时表示可见名单,128 时表示不可见名单"
}
],
"invariants": [],
"invariants": [
"ugc_right must be one of 1, 4, 16, 64, 128",
"target_uins is required when ugc_right is 16 or 128"
],
"inputSchema": {
"type": "object",
"properties": {
@@ -7229,6 +7256,20 @@ export const ACTIONS: CatalogAction[] = [
"minLength": 1
},
"description": "图片数组(可选),支持 file:// http:// base64://;自动上传"
},
"ugc_right": {
"type": "integer",
"minimum": 1,
"description": "查看权限:1=所有人可见,4=好友可见,16=部分好友可见,64=仅自己可见,128=部分好友不可见",
"default": 1
},
"target_uins": {
"type": "array",
"items": {
"type": "integer",
"minimum": 1
},
"description": "权限作用 QQ 号数组;ugc_right=16 时表示可见名单,128 时表示不可见名单"
}
},
"required": [
@@ -9056,13 +9097,50 @@ export const ACTIONS: CatalogAction[] = [
{
"name": "trans_group_file",
"aliases": [],
"summary": "转存群文件(未实现)",
"summary": "转存群文件",
"returns": "{ ok: true }",
"readOnly": false,
"params": [],
"params": [
{
"name": "group_id",
"type": "uint",
"required": true,
"role": "group_id",
"schema": {
"type": "integer",
"minimum": 1
}
},
{
"name": "file_id",
"type": "string",
"required": true,
"role": "file_id",
"schema": {
"type": "string",
"minLength": 1
}
}
],
"invariants": [],
"inputSchema": {
"type": "object",
"properties": {},
"properties": {
"group_id": {
"type": "integer",
"minimum": 1,
"x-role": "group_id"
},
"file_id": {
"type": "string",
"minLength": 1,
"x-role": "file_id"
}
},
"required": [
"group_id",
"file_id"
],
"additionalProperties": true
},
"category": "扩展"
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/onebot",
"version": "1.11.0",
"version": "1.11.1",
"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>'`.",
+4 -35
View File
@@ -13,49 +13,18 @@
// Markdown default. Point any renderer at `collectActionDocs()`.
import type { ActionDoc } from './action-kit';
import { actions as infoActions } from './actions/info';
import { actions as messageActions } from './actions/message';
import { actions as friendActions } from './actions/friend';
import { actions as groupInfoActions } from './actions/group-info';
import { actions as groupAdminActions } from './actions/group-admin';
import { actions as groupFileActions } from './actions/group-file';
import { actions as requestActions } from './actions/request';
import { actions as extendedActions } from './actions/extended';
import { actions as groupAlbumActions } from './actions/group-album';
import { actions as qzoneActions } from './actions/qzone';
import { actions as streamFileActions } from './actions/stream-file';
import { actions as streamDownloadActions } from './actions/stream-download';
// The doc collector only ever calls `describe()`, so any spec carrying it
// qualifies — this admits both `defineAction` (ActionSpec) and
// `defineStreamAction` (StreamActionSpec) results without coupling to either.
type AnySpec = { describe(): ActionDoc };
// Source file = domain category. Each doc is tagged so the MCP / UI can group.
const GROUPS: ReadonlyArray<{ category: string; specs: readonly AnySpec[] }> = [
{ category: '信息', specs: infoActions },
{ category: '消息', specs: messageActions },
{ category: '好友', specs: friendActions },
{ category: '群信息', specs: groupInfoActions },
{ category: '群管理', specs: groupAdminActions },
{ category: '群文件', specs: groupFileActions },
{ category: '请求', specs: requestActions },
{ category: '扩展', specs: extendedActions },
{ category: '群相册', specs: groupAlbumActions },
{ category: '空间', specs: qzoneActions },
{ category: '流式接口', specs: [...streamFileActions, ...streamDownloadActions] },
];
import { ACTION_GROUPS } from './actions';
/** Every declarative action's doc (with category), sorted by name. */
export function collectActionDocs(): ActionDoc[] {
return GROUPS
.flatMap(({ category, specs }) => specs.map((s) => ({ ...s.describe(), category })))
return ACTION_GROUPS
.flatMap(({ category, actions }) => actions.map((s) => ({ ...s.describe(), category })))
.sort((a, b) => a.name.localeCompare(b.name));
}
/** Distinct categories with action counts. */
export function collectCategories(): Array<{ category: string; count: number }> {
return GROUPS.map(({ category, specs }) => ({ category, count: specs.length }));
return ACTION_GROUPS.map(({ category, actions }) => ({ category, count: actions.length }));
}
function paramRow(p: ActionDoc['params'][number]): string {
+14 -8
View File
@@ -440,16 +440,24 @@ export interface ActionDoc {
type Handler = (params: JsonObject) => Promise<ApiResponse>;
export interface ActionSpec<S extends Spec> {
/**
* The narrow shape both `ActionSpec` and `StreamActionSpec` share — enough to
* register a spec onto an `ApiHandler` and to collect its docs. The action
* registry barrel (`actions/index.ts`) is typed against this so it can hold
* both kinds in one flat list without coupling to either concrete generic.
*/
export interface RegisteredActionSpec {
describe(): ActionDoc;
register(h: ApiHandler, ctx: ApiActionContext): void;
}
export interface ActionSpec<S extends Spec> extends RegisteredActionSpec {
readonly names: string[];
readonly params: S;
/** Pure: coerce + validate + cross-field, no ctx, no I/O. The test surface. */
parse(raw: JsonObject): CoerceResult<InferParams<S>>;
/** Bind ctx and produce the `(params) => ApiResponse` for `registerAction`. */
toHandler(ctx: ApiActionContext): Handler;
/** Doc metadata (D4); a renderer walks this. */
describe(): ActionDoc;
register(h: ApiHandler, ctx: ApiActionContext): void;
}
interface ActionDef<S extends Spec> {
@@ -558,12 +566,10 @@ interface StreamActionDef<S extends Spec> {
run: (p: InferParams<S>, ctx: ApiActionContext, raw: JsonObject, sink: StreamSink) => Promise<ApiResponse> | ApiResponse;
}
export interface StreamActionSpec<S extends Spec> {
export interface StreamActionSpec<S extends Spec> extends RegisteredActionSpec {
readonly names: string[];
readonly params: S;
parse(raw: JsonObject): CoerceResult<InferParams<S>>;
describe(): ActionDoc;
register(h: ApiHandler, ctx: ApiActionContext): void;
}
export function defineStreamAction<S extends Spec>(def: StreamActionDef<S>): StreamActionSpec<S> {
@@ -639,6 +645,6 @@ export function groupUserAction<S extends Spec>(
/** Register many specs onto an ApiHandler. Coexists with legacy
* `h.registerAction(name, fn)` in the same `register(h, ctx)`. */
export function registerActions(h: ApiHandler, ctx: ApiActionContext, specs: ReadonlyArray<ActionSpec<Spec>>): void {
export function registerActions(h: ApiHandler, ctx: ApiActionContext, specs: ReadonlyArray<RegisteredActionSpec>): void {
for (const spec of specs) spec.register(h, ctx);
}
+190 -419
View File
@@ -1,9 +1,9 @@
import { readFile } from 'node:fs/promises';
import type { ApiActionContext, ApiHandler } from '../api-handler';
import type { ApiActionContext } from '../api-handler';
import { asNumber, asString } from '../api-handler';
import type { ForwardPreviewMeta } from '../modules/message-actions';
import { JsonObject, RETCODE, failedResponse, okResponse } from '../types';
import { defineAction, groupAction, groupUserAction, registerActions, f } from '../action-kit';
import { defineAction, groupAction, groupUserAction, f } from '../action-kit';
const DOWNLOAD_FILE_MAX_BYTES = 1024 * 1024 * 1024; // 1 GiB
const DOWNLOAD_FILE_TIMEOUT_MS = 60_000;
@@ -110,12 +110,8 @@ async function groupTodoRun(
if (!meta.isGroup || meta.targetId !== p.group_id) {
return failedResponse(RETCODE.ACTION_FAILED, 'message does not belong to this group');
}
try {
await op(p.group_id, BigInt(meta.sequence));
return okResponse();
} catch (err) {
return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err));
}
await op(p.group_id, BigInt(meta.sequence));
return okResponse();
}
/** FlashTransferApi 返回的 FlashFileInfo → OneBot JSON 响应(plain object,JsonObject 兼容)。
@@ -259,12 +255,8 @@ export const actions = [
summary: '删除收藏表情',
params: { emoji_id: f.string({ allowEmpty: false }) },
run: async (p, ctx) => {
try {
await ctx.bridge.apis.profile.deleteCustomFace(p.emoji_id);
return okResponse();
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e));
}
await ctx.bridge.apis.profile.deleteCustomFace(p.emoji_id);
return okResponse();
},
}),
@@ -274,12 +266,8 @@ export const actions = [
summary: '添加收藏表情',
params: { file: f.image() },
run: async (p, ctx) => {
try {
const emojiId = await ctx.bridge.apis.profile.addCustomFace(p.file);
return okResponse({ emoji_id: emojiId });
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e));
}
const emojiId = await ctx.bridge.apis.profile.addCustomFace(p.file);
return okResponse({ emoji_id: emojiId });
},
}),
@@ -292,12 +280,8 @@ export const actions = [
desc: f.string().default(''),
},
run: async (p, ctx) => {
try {
await ctx.bridge.apis.profile.modifyCustomFace(p.emoji_id, p.desc);
return okResponse();
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e));
}
await ctx.bridge.apis.profile.modifyCustomFace(p.emoji_id, p.desc);
return okResponse();
},
}),
@@ -311,12 +295,8 @@ export const actions = [
summary: '收藏表情移到最前',
params: { emoji_id: f.string({ allowEmpty: false }) },
run: async (p, ctx) => {
try {
await ctx.bridge.apis.profile.moveCustomFaceToFront(p.emoji_id);
return okResponse();
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e));
}
await ctx.bridge.apis.profile.moveCustomFaceToFront(p.emoji_id);
return okResponse();
},
}),
@@ -453,19 +433,15 @@ export const actions = [
confirm_required: f.raw(),
},
run: async (p, ctx) => {
try {
const options = {
image: p.image || undefined,
pinned: p.pinned !== undefined ? Number(p.pinned) : 0,
type: p.type !== undefined ? Number(p.type) : 1,
confirm_required: p.confirm_required !== undefined ? Number(p.confirm_required) : 1,
};
const options = {
image: p.image || undefined,
pinned: p.pinned !== undefined ? Number(p.pinned) : 0,
type: p.type !== undefined ? Number(p.type) : 1,
confirm_required: p.confirm_required !== undefined ? Number(p.confirm_required) : 1,
};
await ctx.bridge.apis.web.sendNotice(p.group_id, p.content, options);
return okResponse();
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e));
}
await ctx.bridge.apis.web.sendNotice(p.group_id, p.content, options);
return okResponse();
},
}),
@@ -474,12 +450,8 @@ export const actions = [
summary: '获取群公告',
readOnly: true,
run: async (p, ctx) => {
try {
const notices = await ctx.bridge.apis.web.getNotice(p.group_id);
return okResponse(notices);
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e));
}
const notices = await ctx.bridge.apis.web.getNotice(p.group_id);
return okResponse(notices);
},
}),
@@ -594,11 +566,7 @@ export const actions = [
run: async (_p, ctx, raw) => {
const messageId = asNumber(raw.message_id);
if (!messageId) return failedResponse(RETCODE.BAD_REQUEST, 'message_id is required');
try {
return okResponse(await ctx.fetchPttText(messageId));
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, e instanceof Error ? e.message : '获取语音转文字结果失败');
}
return okResponse(await ctx.fetchPttText(messageId));
},
}),
@@ -617,12 +585,8 @@ export const actions = [
},
params: { domain: f.string().default('qun.qq.com') },
run: async (p, ctx) => {
try {
const cookies = await ctx.bridge.apis.web.getCookiesStr(p.domain || 'qun.qq.com');
return okResponse({ cookies });
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e));
}
const cookies = await ctx.bridge.apis.web.getCookiesStr(p.domain || 'qun.qq.com');
return okResponse({ cookies });
},
}),
@@ -640,12 +604,8 @@ export const actions = [
},
params: {},
run: async (_p, ctx) => {
try {
const token = await ctx.bridge.apis.web.getCsrfToken();
return okResponse({ token });
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e));
}
const token = await ctx.bridge.apis.web.getCsrfToken();
return okResponse({ token });
},
}),
@@ -665,12 +625,8 @@ export const actions = [
},
params: { domain: f.string().default('qun.qq.com') },
run: async (p, ctx) => {
try {
const creds = await ctx.bridge.apis.web.getCredentials(p.domain || 'qun.qq.com');
return okResponse(creds);
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e));
}
const creds = await ctx.bridge.apis.web.getCredentials(p.domain || 'qun.qq.com');
return okResponse(creds);
},
}),
@@ -801,12 +757,8 @@ export const actions = [
const nickname = p.nickname;
const personalNote = p.personal_note;
try {
await ctx.bridge.apis.profile.setProfile(nickname, personalNote);
return okResponse();
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e));
}
await ctx.bridge.apis.profile.setProfile(nickname, personalNote);
return okResponse();
},
}),
@@ -820,12 +772,8 @@ export const actions = [
battery_status: f.int({ min: 0 }).default(100),
},
run: async (p, ctx) => {
try {
await ctx.bridge.apis.profile.setOnlineStatus(p.status, p.ext_status, p.battery_status);
return okResponse();
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e));
}
await ctx.bridge.apis.profile.setOnlineStatus(p.status, p.ext_status, p.battery_status);
return okResponse();
},
}),
@@ -842,12 +790,8 @@ export const actions = [
wording: f.string().default(''),
},
run: async (p, ctx) => {
try {
await ctx.bridge.apis.profile.setDiyOnlineStatus(p.face_id, p.wording, p.face_type);
return okResponse();
} catch (err) {
return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err));
}
await ctx.bridge.apis.profile.setDiyOnlineStatus(p.face_id, p.wording, p.face_type);
return okResponse();
},
}),
@@ -979,12 +923,8 @@ export const actions = [
summary: '获取群今日打卡列表',
readOnly: true,
run: async (p, ctx) => {
try {
const list = await ctx.bridge.apis.web.getSignedList(p.group_id);
return okResponse(list);
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, e instanceof Error ? e.message : String(e));
}
const list = await ctx.bridge.apis.web.getSignedList(p.group_id);
return okResponse(list);
},
}),
@@ -996,12 +936,8 @@ export const actions = [
user_id: f.userId(),
},
run: async (p, ctx) => {
try {
const result = await ctx.forwardSingleMsg(p.message_id, { userId: p.user_id });
return okResponse({ message_id: result.messageId });
} catch (err) {
return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err));
}
const result = await ctx.forwardSingleMsg(p.message_id, { userId: p.user_id });
return okResponse({ message_id: result.messageId });
},
}),
@@ -1013,12 +949,8 @@ export const actions = [
group_id: f.groupId(),
},
run: async (p, ctx) => {
try {
const result = await ctx.forwardSingleMsg(p.message_id, { groupId: p.group_id });
return okResponse({ message_id: result.messageId });
} catch (err) {
return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err));
}
const result = await ctx.forwardSingleMsg(p.message_id, { groupId: p.group_id });
return okResponse({ message_id: result.messageId });
},
}),
@@ -1063,12 +995,8 @@ export const actions = [
count: f.int({ min: 0 }).default(10),
},
run: async (p, ctx) => {
try {
const data = await ctx.bridge.apis.profile.getLike(p.user_id, p.start, p.count);
return okResponse(data);
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e));
}
const data = await ctx.bridge.apis.profile.getLike(p.user_id, p.start, p.count);
return okResponse(data);
},
}),
@@ -1088,19 +1016,15 @@ export const actions = [
return_type: f.string().default('url'),
},
run: async (p, ctx) => {
try {
const urls = await ctx.bridge.apis.profile.fetchCustomFace(p.count);
if (p.return_type === 'id') {
const emojiIds = urls.map((url) => {
const m = /\/qq_expression\/[^/]+\/([^/]+)\//.exec(url);
return m ? m[1] : '';
}).filter(Boolean);
return okResponse(emojiIds);
}
return okResponse(urls);
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e));
const urls = await ctx.bridge.apis.profile.fetchCustomFace(p.count);
if (p.return_type === 'id') {
const emojiIds = urls.map((url) => {
const m = /\/qq_expression\/[^/]+\/([^/]+)\//.exec(url);
return m ? m[1] : '';
}).filter(Boolean);
return okResponse(emojiIds);
}
return okResponse(urls);
},
}),
@@ -1132,14 +1056,10 @@ export const actions = [
emoji_id: f.string({ allowEmpty: false }),
},
run: async (p, ctx) => {
try {
const result = await ctx.fetchEmojiLikeUsers(p.message_id, p.emoji_id, 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));
}
const result = await ctx.fetchEmojiLikeUsers(p.message_id, p.emoji_id, 1000);
return okResponse({
emoji_like_list: result.users.map(u => ({ user_id: String(u.uin), nick_name: '' })),
});
},
}),
@@ -1179,22 +1099,18 @@ export const actions = [
cookie: f.string().default(''),
},
run: async (p, ctx) => {
try {
const offset = p.cookie ? Number.parseInt(p.cookie, 10) || 0 : 0;
const result = await ctx.fetchEmojiLikeUsers(p.message_id, p.emojiId, p.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: isLastPage ? '' : String(nextOffset),
isLastPage,
isFirstPage: offset === 0,
});
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e));
}
const offset = p.cookie ? Number.parseInt(p.cookie, 10) || 0 : 0;
const result = await ctx.fetchEmojiLikeUsers(p.message_id, p.emojiId, p.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: isLastPage ? '' : String(nextOffset),
isLastPage,
isFirstPage: offset === 0,
});
},
}),
@@ -1312,12 +1228,8 @@ export const actions = [
required: ['can_at_all', 'remain_at_all_count_for_group', 'remain_at_all_count_for_uin'],
},
run: async (p, ctx) => {
try {
const data = await ctx.bridge.apis.groupAdmin.getAtAllRemain(p.group_id);
return okResponse(data);
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e));
}
const data = await ctx.bridge.apis.groupAdmin.getAtAllRemain(p.group_id);
return okResponse(data);
},
}),
@@ -1327,12 +1239,8 @@ export const actions = [
readOnly: true,
params: {},
run: async (_p, ctx) => {
try {
const data = await ctx.bridge.apis.profile.getUnidirectionalFriendList();
return okResponse(data);
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e));
}
const data = await ctx.bridge.apis.profile.getUnidirectionalFriendList();
return okResponse(data);
},
}),
@@ -1386,17 +1294,13 @@ export const actions = [
phone_number: f.string().default(''),
},
run: async (p, ctx) => {
try {
if (p.group_id) {
return okResponse({ arkMsg: await ctx.bridge.apis.contacts.getGroupRecommendArk(p.group_id) });
}
if (p.user_id) {
return okResponse({ arkMsg: await ctx.bridge.apis.contacts.getBuddyRecommendArk(p.user_id, p.phone_number) });
}
return failedResponse(RETCODE.BAD_REQUEST, 'user_id or group_id is required');
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, e instanceof Error ? e.message : String(e));
if (p.group_id) {
return okResponse({ arkMsg: await ctx.bridge.apis.contacts.getGroupRecommendArk(p.group_id) });
}
if (p.user_id) {
return okResponse({ arkMsg: await ctx.bridge.apis.contacts.getBuddyRecommendArk(p.user_id, p.phone_number) });
}
return failedResponse(RETCODE.BAD_REQUEST, 'user_id or group_id is required');
},
}),
defineAction({
@@ -1417,17 +1321,13 @@ export const actions = [
phone_number: f.string().default(''),
},
run: async (p, ctx) => {
try {
if (p.group_id) {
return okResponse({ arkMsg: await ctx.bridge.apis.contacts.getGroupRecommendArk(p.group_id) });
}
if (p.user_id) {
return okResponse({ arkMsg: await ctx.bridge.apis.contacts.getBuddyRecommendArk(p.user_id, p.phone_number) });
}
return failedResponse(RETCODE.BAD_REQUEST, 'user_id or group_id is required');
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, e instanceof Error ? e.message : String(e));
if (p.group_id) {
return okResponse({ arkMsg: await ctx.bridge.apis.contacts.getGroupRecommendArk(p.group_id) });
}
if (p.user_id) {
return okResponse({ arkMsg: await ctx.bridge.apis.contacts.getBuddyRecommendArk(p.user_id, p.phone_number) });
}
return failedResponse(RETCODE.BAD_REQUEST, 'user_id or group_id is required');
},
}),
@@ -1443,11 +1343,7 @@ export const actions = [
returnsSchema: { type: 'string', description: '群 Ark 卡片 JSON 字符串' },
params: { group_id: f.groupId() },
run: async (p, ctx) => {
try {
return okResponse(await ctx.bridge.apis.contacts.getGroupRecommendArk(p.group_id));
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, e instanceof Error ? e.message : String(e));
}
return okResponse(await ctx.bridge.apis.contacts.getGroupRecommendArk(p.group_id));
},
}),
defineAction({
@@ -1458,11 +1354,7 @@ export const actions = [
returnsSchema: { type: 'string', description: '群 Ark 卡片 JSON 字符串' },
params: { group_id: f.groupId() },
run: async (p, ctx) => {
try {
return okResponse(await ctx.bridge.apis.contacts.getGroupRecommendArk(p.group_id));
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, e instanceof Error ? e.message : String(e));
}
return okResponse(await ctx.bridge.apis.contacts.getGroupRecommendArk(p.group_id));
},
}),
@@ -1489,12 +1381,8 @@ export const actions = [
},
params: { count: f.int({ min: 0 }).default(50) },
run: async (p, ctx) => {
try {
const list = await ctx.bridge.apis.friend.getDoubtRequests(p.count);
return okResponse(list);
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, e instanceof Error ? e.message : String(e));
}
const list = await ctx.bridge.apis.friend.getDoubtRequests(p.count);
return okResponse(list);
},
}),
// set_doubt_friends_add_request — handle a 可疑好友申请 (0xd69_0). `flag` is
@@ -1511,16 +1399,12 @@ export const actions = [
run: async (p, ctx) => {
// approve → approvalDoubtBuddyReq (0xd69_0); reject → delDoubtBuddyReq
// (also 0xd69_0, distinct body) — both RE'd from the binary.
try {
if (p.approve) {
await ctx.bridge.apis.friend.approveDoubtRequest(p.flag);
} else {
await ctx.bridge.apis.friend.rejectDoubtRequest(p.flag);
}
return okResponse();
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, e instanceof Error ? e.message : String(e));
if (p.approve) {
await ctx.bridge.apis.friend.approveDoubtRequest(p.flag);
} else {
await ctx.bridge.apis.friend.rejectDoubtRequest(p.flag);
}
return okResponse();
},
}),
@@ -1530,14 +1414,10 @@ export const actions = [
name: 'set_group_robot_add_option',
summary: '设置群机器人加群选项',
run: async (p, ctx) => {
try {
await ctx.bridge.apis.groupAdmin.setRobotAddOption(
p.group_id, p.robot_member_switch, p.robot_member_examine,
);
return okResponse();
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, e instanceof Error ? e.message : String(e));
}
await ctx.bridge.apis.groupAdmin.setRobotAddOption(
p.group_id, p.robot_member_switch, p.robot_member_examine,
);
return okResponse();
},
params: {
robot_member_switch: f.int({ min: 0 }).optional(),
@@ -1581,12 +1461,8 @@ export const actions = [
summary: '设置 QQ 头像',
params: { file: f.image() },
run: async (p, ctx) => {
try {
await ctx.bridge.apis.profile.setAvatar(p.file);
return okResponse();
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e));
}
await ctx.bridge.apis.profile.setAvatar(p.file);
return okResponse();
},
}),
@@ -1599,12 +1475,8 @@ export const actions = [
event_type: f.int().default(0),
},
run: async (p, ctx) => {
try {
await ctx.bridge.apis.profile.setInputStatus(p.user_id, p.event_type);
return okResponse({});
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e));
}
await ctx.bridge.apis.profile.setInputStatus(p.user_id, p.event_type);
return okResponse({});
},
}),
@@ -1636,10 +1508,15 @@ export const actions = [
defineAction({
name: 'trans_group_file',
summary: '转存群文件(未实现)',
params: {},
run: async () => {
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
summary: '转存群文件',
returns: '{ ok: true }',
params: {
group_id: f.groupId(),
file_id: f.fileId(),
},
run: async (p, ctx) => {
await ctx.bridge.apis.groupFile.trans(p.group_id, p.file_id);
return okResponse({ ok: true });
},
}),
@@ -1765,19 +1642,15 @@ export const actions = [
},
params: { chat_type: f.int({ min: 0 }).default(1) },
run: async (p, ctx) => {
try {
const list = await ctx.bridge.apis.extras.fetchAiVoiceList(p.group_id, p.chat_type);
return okResponse(list.map((cat) => ({
type: cat.category,
characters: cat.voices.map((v) => ({
character_id: v.voiceId,
character_name: v.voiceDisplayName,
preview_url: v.voiceExampleUrl,
})),
})));
} catch (err) {
return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err));
}
const list = await ctx.bridge.apis.extras.fetchAiVoiceList(p.group_id, p.chat_type);
return okResponse(list.map((cat) => ({
type: cat.category,
characters: cat.voices.map((v) => ({
character_id: v.voiceId,
character_name: v.voiceDisplayName,
preview_url: v.voiceExampleUrl,
})),
})));
},
}),
@@ -1790,13 +1663,9 @@ export const actions = [
chat_type: f.int({ min: 0 }).default(1),
},
run: async (p, ctx) => {
try {
const node = await ctx.bridge.apis.extras.fetchAiVoice(p.group_id, p.character, p.text, p.chat_type);
const url = await ctx.bridge.apis.groupFile.getPttUrl(p.group_id, node);
return okResponse(url);
} catch (err) {
return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err));
}
const node = await ctx.bridge.apis.extras.fetchAiVoice(p.group_id, p.character, p.text, p.chat_type);
const url = await ctx.bridge.apis.groupFile.getPttUrl(p.group_id, node);
return okResponse(url);
},
}),
@@ -1812,12 +1681,8 @@ export const actions = [
chat_type: f.int({ min: 0 }).default(1),
},
run: async (p, ctx) => {
try {
await ctx.bridge.apis.extras.fetchAiVoice(p.group_id, p.character, p.text, p.chat_type);
return okResponse({ message_id: 0 });
} catch (err) {
return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err));
}
await ctx.bridge.apis.extras.fetchAiVoice(p.group_id, p.character, p.text, p.chat_type);
return okResponse({ message_id: 0 });
},
}),
@@ -1826,27 +1691,23 @@ export const actions = [
summary: '请求数据库解密密钥',
params: { db_path: f.string({ allowEmpty: false }) },
run: async (p, ctx) => {
try {
const buffer = Buffer.alloc(128);
const fileHandle = await readFile(p.db_path);
const buffer = Buffer.alloc(128);
const fileHandle = await readFile(p.db_path);
if (fileHandle.length < 0xaf) {
return failedResponse(RETCODE.ACTION_FAILED, 'Database file too short');
}
fileHandle.copy(buffer, 0, 0x2f, 0xaf);
const dbSalt = buffer.toString('utf8');
if (!/^[0-9a-fA-F]{128}$/.test(dbSalt)) {
return failedResponse(RETCODE.ACTION_FAILED, 'Invalid db_salt: not a valid 128-character hex string');
}
const dbKey = await ctx.bridge.apis.misc.getDecryptKey(dbSalt.toLowerCase());
return okResponse({ db_key: dbKey });
} catch (err) {
return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err));
if (fileHandle.length < 0xaf) {
return failedResponse(RETCODE.ACTION_FAILED, 'Database file too short');
}
fileHandle.copy(buffer, 0, 0x2f, 0xaf);
const dbSalt = buffer.toString('utf8');
if (!/^[0-9a-fA-F]{128}$/.test(dbSalt)) {
return failedResponse(RETCODE.ACTION_FAILED, 'Invalid db_salt: not a valid 128-character hex string');
}
const dbKey = await ctx.bridge.apis.misc.getDecryptKey(dbSalt.toLowerCase());
return okResponse({ db_key: dbKey });
},
}),
@@ -1980,12 +1841,8 @@ export const actions = [
run: async (p, ctx) => {
const fid = p.fid || p.notice_id;
if (!fid) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and fid/notice_id are required');
try {
const success = await ctx.bridge.apis.web.deleteNotice(p.group_id, fid);
return success ? okResponse() : failedResponse(RETCODE.ACTION_FAILED, 'delete failed');
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e));
}
const success = await ctx.bridge.apis.web.deleteNotice(p.group_id, fid);
return success ? okResponse() : failedResponse(RETCODE.ACTION_FAILED, 'delete failed');
},
}),
@@ -2102,11 +1959,7 @@ export const actions = [
buf = Buffer.from(base64, 'base64');
if (buf.length > DOWNLOAD_FILE_MAX_BYTES) return failedResponse(RETCODE.BAD_REQUEST, `base64 payload too large: ${buf.length} > ${DOWNLOAD_FILE_MAX_BYTES} bytes`);
} else {
try {
buf = await fetchDownloadFile(url, parseDownloadHeaders(raw.headers), DOWNLOAD_FILE_MAX_BYTES, DOWNLOAD_FILE_TIMEOUT_MS);
} catch (err) {
return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err));
}
buf = await fetchDownloadFile(url, parseDownloadHeaders(raw.headers), DOWNLOAD_FILE_MAX_BYTES, DOWNLOAD_FILE_TIMEOUT_MS);
}
try {
const safe = await saveDownloadBuffer(buf, name);
@@ -2134,12 +1987,8 @@ export const actions = [
const rawWords = p.words;
if (!Array.isArray(rawWords)) return failedResponse(RETCODE.BAD_REQUEST, 'invalid words array');
const words = rawWords.map((w) => String(w));
try {
const translated = await ctx.bridge.apis.misc.translateEn2Zh(words);
return okResponse({ words: translated });
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e));
}
const translated = await ctx.bridge.apis.misc.translateEn2Zh(words);
return okResponse({ words: translated });
},
}),
@@ -2150,12 +1999,8 @@ export const actions = [
run: async (p, ctx) => {
const longNick = p.longNick || p.long_nick;
if (typeof longNick !== 'string') return failedResponse(RETCODE.BAD_REQUEST, 'invalid longNick');
try {
await ctx.bridge.apis.profile.setSelfLongNick(longNick);
return okResponse({});
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e));
}
await ctx.bridge.apis.profile.setSelfLongNick(longNick);
return okResponse({});
},
}),
@@ -2170,12 +2015,8 @@ export const actions = [
const desc = raw.desc || '';
const picUrl = raw.picUrl || raw.pic_url || '';
const jumpUrl = raw.jumpUrl || raw.jump_url || '';
try {
const data = await ctx.bridge.apis.misc.getMiniAppArk(String(type), String(title), String(desc), String(picUrl), String(jumpUrl));
return okResponse(data);
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e));
}
const data = await ctx.bridge.apis.misc.getMiniAppArk(String(type), String(title), String(desc), String(picUrl), String(jumpUrl));
return okResponse(data);
},
}),
@@ -2187,12 +2028,8 @@ export const actions = [
const buttonId = raw.button_id;
const callbackData = raw.callback_data || '';
if (!buttonId) return failedResponse(RETCODE.BAD_REQUEST, 'missing required parameters');
try {
const data = await ctx.bridge.apis.misc.clickInlineKeyboardButton(p.group_id, p.bot_appid, String(buttonId), String(callbackData), p.msg_seq);
return okResponse(data);
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e));
}
const data = await ctx.bridge.apis.misc.clickInlineKeyboardButton(p.group_id, p.bot_appid, String(buttonId), String(callbackData), p.msg_seq);
return okResponse(data);
},
}),
@@ -2200,12 +2037,8 @@ export const actions = [
name: ['set_group_sign', 'send_group_sign'],
summary: '群签到',
run: async (p, ctx) => {
try {
await ctx.bridge.apis.misc.sendGroupSign(p.group_id);
return okResponse({});
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e));
}
await ctx.bridge.apis.misc.sendGroupSign(p.group_id);
return okResponse({});
},
}),
@@ -2217,16 +2050,12 @@ export const actions = [
if (!/^[0-9a-fA-F]*$/.test(p.data) || p.data.length % 2 !== 0) {
return failedResponse(RETCODE.BAD_REQUEST, 'data must be a hex string of even length');
}
try {
const body = hexToBytes(p.data);
const result = await ctx.bridge.sendRawPacket(p.cmd, body);
if (!result.success) return failedResponse(RETCODE.ACTION_FAILED, result.errorMessage || 'send failed');
if (!p.rsp) return okResponse(null);
const respHex = result.responseData ? bytesToHex(result.responseData) : '';
return okResponse(respHex);
} catch (err) {
return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err));
}
const body = hexToBytes(p.data);
const result = await ctx.bridge.sendRawPacket(p.cmd, body);
if (!result.success) return failedResponse(RETCODE.ACTION_FAILED, result.errorMessage || 'send failed');
if (!p.rsp) return okResponse(null);
const respHex = result.responseData ? bytesToHex(result.responseData) : '';
return okResponse(respHex);
},
}),
@@ -2275,12 +2104,8 @@ export const actions = [
} else {
return failedResponse(RETCODE.BAD_REQUEST, 'files must be a string or string array');
}
try {
const result = await ctx.bridge.apis.flashTransfer.createFlashTask(fileList, p.name, p.thumb_path);
return okResponse({ fileset_id: result.filesetId, task_id: result.filesetId });
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e));
}
const result = await ctx.bridge.apis.flashTransfer.createFlashTask(fileList, p.name, p.thumb_path);
return okResponse({ fileset_id: result.filesetId, task_id: result.filesetId });
},
}),
@@ -2289,12 +2114,8 @@ export const actions = [
summary: '获取文件集信息',
params: { fileset_id: f.string({ allowEmpty: false }) },
run: async (p, ctx) => {
try {
const list = await ctx.bridge.apis.flashTransfer.getFilesetInfo(p.fileset_id);
return okResponse({ fileset_id: p.fileset_id, file_list: list.map(flashFileInfoToJson) });
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e));
}
const list = await ctx.bridge.apis.flashTransfer.getFilesetInfo(p.fileset_id);
return okResponse({ fileset_id: p.fileset_id, file_list: list.map(flashFileInfoToJson) });
},
}),
@@ -2303,12 +2124,8 @@ export const actions = [
summary: '获取闪传文件列表',
params: { fileset_id: f.string({ allowEmpty: false }) },
run: async (p, ctx) => {
try {
const list = await ctx.bridge.apis.flashTransfer.getFlashFileList(p.fileset_id);
return okResponse(list.map(flashFileInfoToJson));
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e));
}
const list = await ctx.bridge.apis.flashTransfer.getFlashFileList(p.fileset_id);
return okResponse(list.map(flashFileInfoToJson));
},
}),
@@ -2317,12 +2134,8 @@ export const actions = [
summary: '列出当前账号的所有闪传文件集',
params: {},
run: async (_p, ctx) => {
try {
const list = await ctx.bridge.apis.flashTransfer.listFilesets();
return okResponse(list.map(flashFileInfoToJson));
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e));
}
const list = await ctx.bridge.apis.flashTransfer.listFilesets();
return okResponse(list.map(flashFileInfoToJson));
},
}),
@@ -2335,12 +2148,8 @@ export const actions = [
file_index: f.number().optional(),
},
run: async (p, ctx) => {
try {
const url = await ctx.bridge.apis.flashTransfer.getFlashFileUrl(p.fileset_id, p.file_index);
return okResponse({ url });
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e));
}
const url = await ctx.bridge.apis.flashTransfer.getFlashFileUrl(p.fileset_id, p.file_index);
return okResponse({ url });
},
}),
@@ -2349,12 +2158,8 @@ export const actions = [
summary: '获取文件分享链接',
params: { fileset_id: f.string({ allowEmpty: false }) },
run: async (p, ctx) => {
try {
const url = await ctx.bridge.apis.flashTransfer.getShareLink(p.fileset_id);
return okResponse(url);
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e));
}
const url = await ctx.bridge.apis.flashTransfer.getShareLink(p.fileset_id);
return okResponse(url);
},
}),
@@ -2363,12 +2168,8 @@ export const actions = [
summary: '删除闪传文件',
params: { fileset_id: f.string({ allowEmpty: false }) },
run: async (p, ctx) => {
try {
await ctx.bridge.apis.flashTransfer.deleteFlashFile(p.fileset_id);
return okResponse();
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e));
}
await ctx.bridge.apis.flashTransfer.deleteFlashFile(p.fileset_id);
return okResponse();
},
}),
@@ -2380,12 +2181,8 @@ export const actions = [
new_name: f.string({ allowEmpty: false }),
},
run: async (p, ctx) => {
try {
await ctx.bridge.apis.flashTransfer.renameFlashFile(p.fileset_id, p.new_name);
return okResponse();
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e));
}
await ctx.bridge.apis.flashTransfer.renameFlashFile(p.fileset_id, p.new_name);
return okResponse();
},
}),
@@ -2399,19 +2196,15 @@ export const actions = [
file_index: f.number().optional(),
},
run: async (p, ctx) => {
try {
const target = await ctx.bridge.apis.flashTransfer.downloadFileset(p.fileset_id, {
fileName: p.file_name,
fileIndex: p.file_index,
});
return okResponse({
url: target.url,
file_name: target.fileName,
file_size: target.fileSize,
});
} catch (err) {
return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err));
}
const target = await ctx.bridge.apis.flashTransfer.downloadFileset(p.fileset_id, {
fileName: p.file_name,
fileIndex: p.file_index,
});
return okResponse({
url: target.url,
file_name: target.fileName,
file_size: target.fileSize,
});
},
}),
@@ -2428,16 +2221,12 @@ export const actions = [
if (!p.user_id && !p.group_id) {
return failedResponse(RETCODE.BAD_REQUEST, 'user_id or group_id is required');
}
try {
await ctx.bridge.apis.flashTransfer.sendFlashMsg(p.fileset_id, {
userId: p.user_id,
groupId: p.group_id,
});
// 0x93d7 响应无 message_id(分享 fileset,非传统消息),返回 0 兼容 OneBot 形状。
return okResponse({ message_id: 0 });
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, e instanceof Error ? e.message : String(e));
}
await ctx.bridge.apis.flashTransfer.sendFlashMsg(p.fileset_id, {
userId: p.user_id,
groupId: p.group_id,
});
// 0x93d7 响应无 message_id(分享 fileset,非传统消息),返回 0 兼容 OneBot 形状。
return okResponse({ message_id: 0 });
},
}),
@@ -2455,12 +2244,8 @@ export const actions = [
},
params: { share_code: f.string({ allowEmpty: false }) },
run: async (p, ctx) => {
try {
const filesetId = await ctx.bridge.apis.flashTransfer.getFilesetIdByCode(p.share_code);
return okResponse({ fileset_id: filesetId });
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, e instanceof Error ? e.message : String(e));
}
const filesetId = await ctx.bridge.apis.flashTransfer.getFilesetIdByCode(p.share_code);
return okResponse({ fileset_id: filesetId });
},
}),
];
@@ -2476,20 +2261,6 @@ async function fetchFilteredGroupRequests(ctx: ApiActionContext) {
}
}
export function register(h: ApiHandler, ctx: ApiActionContext): void {
registerActions(h, ctx, actions);
// .handle_quick_operation 仍保留 legacy:它需要把 ApiHandler 本身 (h) 交给
// executeQuickOperation 去回灌动作,而 action-kit 的 run 只提供 (p, ctx, raw)、不含 h。
h.registerAction('.handle_quick_operation', async (params) => {
const context = params.context as JsonObject | undefined;
const operation = params.operation as Record<string, unknown> | undefined;
if (!context || !operation) return failedResponse(RETCODE.BAD_REQUEST, 'context and operation are required');
const { executeQuickOperation } = await import('../network/quick-operation');
await executeQuickOperation(context, operation, h);
return okResponse();
});
}
function hexToBytes(hex: string): Uint8Array {
const out = new Uint8Array(hex.length / 2);
+1 -5
View File
@@ -1,5 +1,4 @@
import { defineAction, registerActions, f } from '../action-kit';
import type { ApiActionContext, ApiHandler } from '../api-handler';
import { defineAction, f } from '../action-kit';
import { okResponse } from '../types';
export const actions = [
@@ -68,6 +67,3 @@ export const actions = [
}),
];
export function register(h: ApiHandler, ctx: ApiActionContext): void {
registerActions(h, ctx, actions);
}
+4 -12
View File
@@ -1,6 +1,5 @@
import { defineAction, groupAction, groupUserAction, registerActions, f } from '../action-kit';
import type { ApiActionContext, ApiHandler } from '../api-handler';
import { RETCODE, failedResponse, okResponse } from '../types';
import { defineAction, groupAction, groupUserAction, f } from '../action-kit';
import { okResponse } from '../types';
export const actions = [
groupUserAction({
@@ -120,16 +119,9 @@ export const actions = [
summary: '设置群头像',
params: { file: f.image() },
run: async (p, ctx) => {
try {
await ctx.bridge.apis.profile.setGroupAvatar(p.group_id, p.file);
return okResponse();
} catch (err) {
return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err));
}
await ctx.bridge.apis.profile.setGroupAvatar(p.group_id, p.file);
return okResponse();
},
}),
];
export function register(h: ApiHandler, ctx: ApiActionContext): void {
registerActions(h, ctx, actions);
}
+27 -71
View File
@@ -1,7 +1,6 @@
import { groupAction, registerActions, f } from '../action-kit';
import type { ApiActionContext, ApiHandler } from '../api-handler';
import { groupAction, f } from '../action-kit';
import type { JsonValue } from '../types';
import { RETCODE, failedResponse, okResponse } from '../types';
import { okResponse } from '../types';
export const actions = [
groupAction({
@@ -23,13 +22,8 @@ export const actions = [
},
},
run: async (p, ctx) => {
try {
const albumList = await ctx.bridge.apis.groupAlbum.list(p.group_id);
return okResponse(albumList);
} catch (error) {
const message = error instanceof Error ? error.message : 'failed to get group album list';
return failedResponse(RETCODE.INTERNAL_ERROR, message);
}
const albumList = await ctx.bridge.apis.groupAlbum.list(p.group_id);
return okResponse(albumList);
},
}),
@@ -67,22 +61,17 @@ export const actions = [
required: ['album_list', 'attach_info', 'has_more'],
},
run: async (p, ctx) => {
try {
const albumList = await ctx.bridge.apis.groupAlbum.list(p.group_id);
return okResponse({
album_list: albumList.map((a) => ({
album_id: a.id,
album_name: a.name,
create_time: a.createTime,
pic_num: a.picNum,
})),
attach_info: '',
has_more: false,
});
} catch (error) {
const message = error instanceof Error ? error.message : 'failed to get qun album list';
return failedResponse(RETCODE.INTERNAL_ERROR, message);
}
const albumList = await ctx.bridge.apis.groupAlbum.list(p.group_id);
return okResponse({
album_list: albumList.map((a) => ({
album_id: a.id,
album_name: a.name,
create_time: a.createTime,
pic_num: a.picNum,
})),
attach_info: '',
has_more: false,
});
},
}),
@@ -94,13 +83,8 @@ export const actions = [
file: f.image(),
},
run: async (p, ctx) => {
try {
await ctx.bridge.apis.groupAlbum.upload(p.group_id, p.album_id, p.album_name, p.file);
return okResponse(null);
} catch (error) {
const message = error instanceof Error ? error.message : 'failed to upload image to group album';
return failedResponse(RETCODE.INTERNAL_ERROR, message);
}
await ctx.bridge.apis.groupAlbum.upload(p.group_id, p.album_id, p.album_name, p.file);
return okResponse(null);
},
}),
@@ -125,13 +109,8 @@ export const actions = [
attach_info: f.string().default(''),
},
run: async (p, ctx) => {
try {
const mediaList = await ctx.bridge.apis.groupAlbum.getMediaList(p.group_id, p.album_id, p.attach_info);
return okResponse(mediaList as unknown as JsonValue);
} catch (error) {
const message = error instanceof Error ? error.message : 'failed to get group album media list';
return failedResponse(RETCODE.INTERNAL_ERROR, message);
}
const mediaList = await ctx.bridge.apis.groupAlbum.getMediaList(p.group_id, p.album_id, p.attach_info);
return okResponse(mediaList as unknown as JsonValue);
},
}),
@@ -143,13 +122,8 @@ export const actions = [
content: f.string({ allowEmpty: false }),
},
run: async (p, ctx) => {
try {
const comment = await ctx.bridge.apis.groupAlbum.comment(p.group_id, p.album_id, p.lloc, p.content);
return okResponse(comment as unknown as JsonValue);
} catch (error) {
const message = error instanceof Error ? error.message : 'failed to comment on album media';
return failedResponse(RETCODE.INTERNAL_ERROR, message);
}
const comment = await ctx.bridge.apis.groupAlbum.comment(p.group_id, p.album_id, p.lloc, p.content);
return okResponse(comment as unknown as JsonValue);
},
}),
@@ -161,13 +135,8 @@ export const actions = [
lloc: f.string().optional(), // 可选参数(空串按未传处理)
},
run: async (p, ctx) => {
try {
const res = await ctx.bridge.apis.groupAlbum.like(p.group_id, p.album_id, p.batch_id, p.lloc || undefined, true);
return okResponse(res);
} catch (error) {
const message = error instanceof Error ? error.message : 'failed to set like on album media';
return failedResponse(RETCODE.INTERNAL_ERROR, message);
}
const res = await ctx.bridge.apis.groupAlbum.like(p.group_id, p.album_id, p.batch_id, p.lloc || undefined, true);
return okResponse(res);
},
}),
@@ -180,13 +149,8 @@ export const actions = [
lloc: f.string().optional(), // 可选参数(空串按未传处理)
},
run: async (p, ctx) => {
try {
const res = await ctx.bridge.apis.groupAlbum.like(p.group_id, p.album_id, p.batch_id, p.lloc || undefined, false);
return okResponse(res);
} catch (error) {
const message = error instanceof Error ? error.message : 'failed to cancel like on album media';
return failedResponse(RETCODE.INTERNAL_ERROR, message);
}
const res = await ctx.bridge.apis.groupAlbum.like(p.group_id, p.album_id, p.batch_id, p.lloc || undefined, false);
return okResponse(res);
},
}),
@@ -197,17 +161,9 @@ export const actions = [
lloc: f.string({ allowEmpty: false }),
},
run: async (p, ctx) => {
try {
const res = await ctx.bridge.apis.groupAlbum.delete(p.group_id, p.album_id, p.lloc);
return okResponse(res);
} catch (error) {
const message = error instanceof Error ? error.message : 'failed to delete album media';
return failedResponse(RETCODE.INTERNAL_ERROR, message);
}
const res = await ctx.bridge.apis.groupAlbum.delete(p.group_id, p.album_id, p.lloc);
return okResponse(res);
},
}),
];
export function register(h: ApiHandler, ctx: ApiActionContext): void {
registerActions(h, ctx, actions);
}
+1 -5
View File
@@ -1,5 +1,4 @@
import { defineAction, groupAction, registerActions, f } from '../action-kit';
import type { ApiHandler, ApiActionContext } from '../api-handler';
import { defineAction, groupAction, f } from '../action-kit';
import { RETCODE, failedResponse, okResponse } from '../types';
// NapCat/LLOneBot omit `busid` from their `get_group_file_url` schema entirely,
@@ -286,6 +285,3 @@ export const actions = [
}),
];
export function register(h: ApiHandler, ctx: ApiActionContext): void {
registerActions(h, ctx, actions);
}
+1 -5
View File
@@ -1,5 +1,4 @@
import { defineAction, groupAction, groupUserAction, registerActions, f } from '../action-kit';
import type { ApiHandler, ApiActionContext } from '../api-handler';
import { defineAction, groupAction, groupUserAction, f } from '../action-kit';
import { asString } from '../api-handler';
import { RETCODE, failedResponse, okResponse } from '../types';
import { WebHonorType } from '@snowluma/protocol/web/group-honor';
@@ -179,6 +178,3 @@ export const actions = [
}),
];
export function register(h: ApiHandler, ctx: ApiActionContext): void {
registerActions(h, ctx, actions);
}
+48
View File
@@ -0,0 +1,48 @@
// Action registry barrel — the single source of "which files contribute which
// actions", replacing three hand-synced lists that had to stay in lock-step:
// 1. ApiHandler's 12 `register as registerX` imports + 12 constructor calls,
// 2. each file's `export function register(h, ctx)` footer,
// 3. action-docs' own 13 imports + GROUPS array.
// Adding an action file now means editing exactly one place: ACTION_GROUPS.
//
// "Source file = domain category" is the existing convention (see action-docs),
// so the category label lives here too, making ACTION_GROUPS serve both runtime
// registration (via ALL_ACTIONS) and the doc collector (via the groups).
import type { RegisteredActionSpec } from '../action-kit';
import { actions as infoActions } from './info';
import { actions as messageActions } from './message';
import { actions as friendActions } from './friend';
import { actions as groupInfoActions } from './group-info';
import { actions as groupAdminActions } from './group-admin';
import { actions as groupFileActions } from './group-file';
import { actions as requestActions } from './request';
import { actions as extendedActions } from './extended';
import { actions as groupAlbumActions } from './group-album';
import { actions as qzoneActions } from './qzone';
import { actions as streamFileActions } from './stream-file';
import { actions as streamDownloadActions } from './stream-download';
export interface ActionGroup {
/** Domain category (= source file), surfaced to the MCP / UI for grouping. */
readonly category: string;
readonly actions: readonly RegisteredActionSpec[];
}
/** Every action, grouped by domain category. The single source of truth. */
export const ACTION_GROUPS: readonly ActionGroup[] = [
{ category: '信息', actions: infoActions },
{ category: '消息', actions: messageActions },
{ category: '好友', actions: friendActions },
{ category: '群信息', actions: groupInfoActions },
{ category: '群管理', actions: groupAdminActions },
{ category: '群文件', actions: groupFileActions },
{ category: '请求', actions: requestActions },
{ category: '扩展', actions: extendedActions },
{ category: '群相册', actions: groupAlbumActions },
{ category: '空间', actions: qzoneActions },
{ category: '流式接口', actions: [...streamFileActions, ...streamDownloadActions] },
];
/** Flat list of every action spec, for one-shot registration onto an ApiHandler. */
export const ALL_ACTIONS: readonly RegisteredActionSpec[] = ACTION_GROUPS.flatMap((g) => g.actions);
+1 -5
View File
@@ -1,5 +1,4 @@
import { defineAction, registerActions } from '../action-kit';
import type { ApiActionContext, ApiHandler } from '../api-handler';
import { defineAction } from '../action-kit';
import { okResponse } from '../types';
// 后续考虑移动到一个统一的地方构建,避免版本信息分散在各个模块中。
@@ -98,6 +97,3 @@ export const actions = [
}),
];
export function register(h: ApiHandler, ctx: ApiActionContext): void {
registerActions(h, ctx, actions);
}
+2 -5
View File
@@ -1,7 +1,7 @@
import { createLogger } from '@snowluma/common/logger';
import type { JsonObject, JsonValue } from '../types';
import type { ApiHandler, ApiActionContext } from '../api-handler';
import { defineAction, groupAction, registerActions, f } from '../action-kit';
import type { ApiActionContext } from '../api-handler';
import { defineAction, groupAction, f } from '../action-kit';
import { RETCODE, failedResponse, okResponse } from '../types';
const log = createLogger('OneBot');
@@ -119,6 +119,3 @@ export const actions = [
}),
];
export function register(h: ApiHandler, ctx: ApiActionContext): void {
registerActions(h, ctx, actions);
}
+32 -62
View File
@@ -1,7 +1,7 @@
import { defineAction, registerActions, f } from '../action-kit';
import type { ApiActionContext, ApiHandler } from '../api-handler';
import { defineAction, f } from '../action-kit';
import type { ApiActionContext } from '../api-handler';
import type { JsonValue } from '../types';
import { RETCODE, failedResponse, okResponse } from '../types';
import { okResponse } from '../types';
async function uploadQzoneImages(
ctx: ApiActionContext,
@@ -21,6 +21,8 @@ async function uploadQzoneImages(
return parts.join('\t');
}
const QZONE_UGC_RIGHTS = new Set<number>([1, 4, 16, 64, 128]);
export const actions = [
// get_qzone_msg_list — 获取 QQ 空间说说列表。无 go-cqhttp 标准,自定义命名。
// 默认取机器人自己的空间;传 target_uin 可查看指定账号(需有权限)。
@@ -59,13 +61,8 @@ export const actions = [
num: f.int({ min: 1, max: 100 }).describe('本页数量').default(20),
},
run: async (p, ctx) => {
try {
const res = await ctx.bridge.apis.qzone.getMsgList(p.target_uin, p.pos, p.num);
return okResponse(res as unknown as JsonValue);
} catch (error) {
const message = error instanceof Error ? error.message : 'failed to get qzone msg list';
return failedResponse(RETCODE.INTERNAL_ERROR, message);
}
const res = await ctx.bridge.apis.qzone.getMsgList(p.target_uin, p.pos, p.num);
return okResponse(res as unknown as JsonValue);
},
}),
@@ -104,13 +101,8 @@ export const actions = [
count: f.int({ min: 1, max: 50 }).describe('本页数量').default(10),
},
run: async (p, ctx) => {
try {
const res = await ctx.bridge.apis.qzone.getFeeds(p.page_num, p.count);
return okResponse(res as unknown as JsonValue);
} catch (error) {
const message = error instanceof Error ? error.message : 'failed to get qzone feeds';
return failedResponse(RETCODE.INTERNAL_ERROR, message);
}
const res = await ctx.bridge.apis.qzone.getFeeds(p.page_num, p.count);
return okResponse(res as unknown as JsonValue);
},
}),
@@ -120,24 +112,25 @@ export const actions = [
// 注意:发说说为主动行为,高频会被 Qzone 风控,调用方需自行限流。
defineAction({
name: 'send_qzone_msg',
summary: '发表说说(QQ 空间,支持纯文字或带图;传 images 自动上传)',
summary: '发表说说(QQ 空间,支持纯文字或带图;传 images 自动上传;可设置查看权限)',
params: {
content: f.string({ allowEmpty: false }).describe('说说正文'),
images: f.array(f.string({ allowEmpty: false })).describe('图片数组(可选),支持 file:// http:// base64://;自动上传').optional(),
ugc_right: f.int({ min: 1 }).describe('查看权限:1=所有人可见,4=好友可见,16=部分好友可见,64=仅自己可见,128=部分好友不可见').default(1),
target_uins: f.array(f.uint()).describe('权限作用 QQ 号数组;ugc_right=16 时表示可见名单,128 时表示不可见名单').optional(),
},
rules: (r) => [
r.rule('ugc_right must be one of 1, 4, 16, 64, 128', (p) => QZONE_UGC_RIGHTS.has(p.ugc_right)),
r.rule('target_uins is required when ugc_right is 16 or 128', (p) => (p.ugc_right !== 16 && p.ugc_right !== 128) || !!p.target_uins?.length),
],
run: async (p, ctx) => {
try {
if (p.images && p.images.length > 0) {
const richval = await uploadQzoneImages(ctx, p.images, (upload) => upload.richval);
const res = await ctx.bridge.apis.qzone.publish(p.content, 1, richval);
return okResponse(res as unknown as JsonValue);
}
const res = await ctx.bridge.apis.qzone.publish(p.content);
if (p.images && p.images.length > 0) {
const richval = await uploadQzoneImages(ctx, p.images, (upload) => upload.richval);
const res = await ctx.bridge.apis.qzone.publish(p.content, 1, richval, p.ugc_right, p.target_uins?.join('|'));
return okResponse(res as unknown as JsonValue);
} catch (error) {
const message = error instanceof Error ? error.message : 'failed to publish qzone msg';
return failedResponse(RETCODE.INTERNAL_ERROR, message);
}
const res = await ctx.bridge.apis.qzone.publish(p.content, undefined, undefined, p.ugc_right, p.target_uins?.join('|'));
return okResponse(res as unknown as JsonValue);
},
}),
@@ -149,13 +142,8 @@ export const actions = [
tid: f.string({ allowEmpty: false }).describe('说说 tid(来自 get_qzone_msg_list / send_qzone_msg)'),
},
run: async (p, ctx) => {
try {
await ctx.bridge.apis.qzone.delete(p.tid);
return okResponse(null);
} catch (error) {
const message = error instanceof Error ? error.message : 'failed to delete qzone msg';
return failedResponse(RETCODE.INTERNAL_ERROR, message);
}
await ctx.bridge.apis.qzone.delete(p.tid);
return okResponse(null);
},
}),
@@ -171,13 +159,8 @@ export const actions = [
abstime: f.int({ min: 0 }).describe('说说发表时间(unix 秒),传真实值更可靠').default(0).role('timestamp'),
},
run: async (p, ctx) => {
try {
await ctx.bridge.apis.qzone.like(p.tid, p.target_uin, true, p.abstime);
return okResponse(null);
} catch (error) {
const message = error instanceof Error ? error.message : 'failed to like qzone msg';
return failedResponse(RETCODE.INTERNAL_ERROR, message);
}
await ctx.bridge.apis.qzone.like(p.tid, p.target_uin, true, p.abstime);
return okResponse(null);
},
}),
@@ -192,13 +175,8 @@ export const actions = [
abstime: f.int({ min: 0 }).describe('说说发表时间(unix 秒),传真实值更可靠').default(0).role('timestamp'),
},
run: async (p, ctx) => {
try {
await ctx.bridge.apis.qzone.like(p.tid, p.target_uin, false, p.abstime);
return okResponse(null);
} catch (error) {
const message = error instanceof Error ? error.message : 'failed to unlike qzone msg';
return failedResponse(RETCODE.INTERNAL_ERROR, message);
}
await ctx.bridge.apis.qzone.like(p.tid, p.target_uin, false, p.abstime);
return okResponse(null);
},
}),
@@ -215,22 +193,14 @@ export const actions = [
images: f.array(f.string({ allowEmpty: false })).describe('图片数组(可选),支持 file:// http:// base64://;自动上传').optional(),
},
run: async (p, ctx) => {
try {
if (p.images && p.images.length > 0) {
const richval = await uploadQzoneImages(ctx, p.images, (upload) => upload.url);
const res = await ctx.bridge.apis.qzone.comment(p.tid, p.content, p.target_uin, 1, richval);
return okResponse(res as unknown as JsonValue);
}
const res = await ctx.bridge.apis.qzone.comment(p.tid, p.content, p.target_uin);
if (p.images && p.images.length > 0) {
const richval = await uploadQzoneImages(ctx, p.images, (upload) => upload.url);
const res = await ctx.bridge.apis.qzone.comment(p.tid, p.content, p.target_uin, 1, richval);
return okResponse(res as unknown as JsonValue);
} catch (error) {
const message = error instanceof Error ? error.message : 'failed to comment qzone msg';
return failedResponse(RETCODE.INTERNAL_ERROR, message);
}
const res = await ctx.bridge.apis.qzone.comment(p.tid, p.content, p.target_uin);
return okResponse(res as unknown as JsonValue);
},
}),
];
export function register(h: ApiHandler, ctx: ApiActionContext): void {
registerActions(h, ctx, actions);
}
+1 -5
View File
@@ -1,5 +1,4 @@
import { defineAction, registerActions, f } from '../action-kit';
import type { ApiActionContext, ApiHandler } from '../api-handler';
import { defineAction, f } from '../action-kit';
import { asString } from '../api-handler';
import { okResponse } from '../types';
@@ -37,6 +36,3 @@ export const actions = [
}),
];
export function register(h: ApiHandler, ctx: ApiActionContext): void {
registerActions(h, ctx, actions);
}
@@ -23,7 +23,7 @@ import net from 'net';
import dns from 'dns/promises';
import { resolveLocalFilePath } from '@snowluma/protocol/highway/utils';
import { defineStreamAction, f } from '../action-kit';
import type { ApiActionContext, ApiHandler } from '../api-handler';
import type { ApiActionContext } from '../api-handler';
import { okResponse, type ApiResponse, type JsonObject, type JsonValue } from '../types';
import { type StreamSink, StreamStatus } from '../streaming';
import { STREAM_ROOT } from './stream-file';
@@ -370,9 +370,5 @@ const testDownloadStream = defineStreamAction({
export const actions = [downloadFileStream, downloadFileImageStream, downloadFileRecordStream, testDownloadStream];
export function register(h: ApiHandler, ctx: ApiActionContext): void {
for (const a of actions) a.register(h, ctx);
}
// Exposed for tests.
export const __test = { resolveDownload, isWithinStreamRoot, isPrivateIp, assertSafeUrl, streamChunks, runDownload };
+1 -5
View File
@@ -23,7 +23,7 @@ import fs from 'fs';
import { createHash } from 'crypto';
import { createLogger } from '@snowluma/common/logger';
import { defineAction, defineStreamAction, f } from '../action-kit';
import type { ApiActionContext, ApiHandler } from '../api-handler';
import type { ApiActionContext } from '../api-handler';
import { okResponse, type ApiResponse } from '../types';
import { StreamStatus } from '../streaming';
@@ -361,9 +361,5 @@ const cleanStreamTempFile = defineAction({
export const actions = [uploadFileStream, cleanStreamTempFile];
export function register(h: ApiHandler, ctx: ApiActionContext): void {
for (const a of actions) a.register(h, ctx);
}
// Exposed for tests.
export const __test = { uploads, handleUpload, cleanDir, validateStreamId, STREAM_UPLOAD_DIR, MAX_CONCURRENT_STREAMS, MAX_CHUNKS };
+30 -30
View File
@@ -1,21 +1,11 @@
import { renderParamsVerbose, summarizeParams } from '@snowluma/common/log-summary';
import { createLogger, getLogLevel, nextRequestId, runWithRequestId, 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 registerQzone } from './actions/qzone';
import { register as registerRequest } from './actions/request';
import { register as registerStreamFile } from './actions/stream-file';
import { register as registerStreamDownload } from './actions/stream-download';
import { ALL_ACTIONS } from './actions';
import { registerActions } from './action-kit';
import type { ForwardPreviewMeta } from './modules/message-actions';
import type { JsonObject, JsonValue, MessageMeta } from './types';
import { RETCODE, failedResponse } from './types';
import { RETCODE, failedResponse, okResponse } from './types';
import { type StreamSink, wrapStreamFrame, wrapStreamTerminal } from './streaming';
const moduleLog = createLogger('Bridge.Action');
@@ -112,18 +102,20 @@ export class ApiHandler {
constructor(context: ApiActionContext, uin?: number) {
this.log = typeof uin === 'number' && uin > 0 ? moduleLog.child({ uin }) : moduleLog;
registerInfo(this, context);
registerMessage(this, context);
registerFriend(this, context);
registerGroupInfo(this, context);
registerGroupAdmin(this, context);
registerGroupFile(this, context);
registerRequest(this, context);
registerExtended(this, context);
registerGroupAlbum(this, context);
registerQzone(this, context);
registerStreamFile(this, context);
registerStreamDownload(this, context);
registerActions(this, context, ALL_ACTIONS);
// The one non-ActionSpec handler: `.handle_quick_operation` needs the
// ApiHandler itself (to re-drive actions via executeQuickOperation), which
// ActionSpec.run's (params, ctx) signature can't supply — so it's the sole
// raw registration, kept here rather than in an action file's footer.
this.registerAction('.handle_quick_operation', async (params) => {
const opContext = params.context as JsonObject | undefined;
const operation = params.operation as Record<string, unknown> | undefined;
if (!opContext || !operation) return failedResponse(RETCODE.BAD_REQUEST, 'context and operation are required');
const { executeQuickOperation } = await import('./network/quick-operation');
await executeQuickOperation(opContext, operation, this);
return okResponse();
});
}
registerAction(action: string, handler: ActionHandler): void {
@@ -178,15 +170,23 @@ export class ApiHandler {
response = await handler(params, sink);
this.log.trace(() => [`${action} ⇒ ${response.status} (${Date.now() - startedAt}ms)`]);
} catch (error) {
// Action failures are almost always param-shape problems coming
// from the OneBot client; warn (not error) is the right level so
// the log file stays a useful signal of real internal faults.
// Single error seam: any throw from a handler (bridge/OIDB business
// failure or an unexpected internal fault) maps here to one policy —
// ACTION_FAILED (100) + the error's message. Action `run` bodies
// shouldn't need to hand-roll their own try/catch → failedResponse:
// doing so only produced inconsistent retcodes (100 vs 1200) for the same
// kind of failure. The remaining per-action catches (qzone / group-album,
// still returning 1200) are being removed in a follow-up phase — until
// then their failures never reach this seam. `OidbError.message` already
// carries the QQ server code, so no special-casing is needed. warn (not
// error) keeps the log file a useful signal without drowning it in
// expected client-side failures.
this.log.warn('%s failed: %s\n%s',
action,
error instanceof Error ? error.message : String(error),
error instanceof Error ? (error.stack ?? '') : '');
const message = error instanceof Error ? error.message : 'internal error';
response = failedResponse(RETCODE.INTERNAL_ERROR, message);
const message = error instanceof Error ? error.message : String(error);
response = failedResponse(RETCODE.ACTION_FAILED, message);
}
this.notifyObservers(action, params, response, Date.now() - startedAt);
return response;
+33
View File
@@ -1,4 +1,5 @@
import { createLogger } from '@snowluma/common/logger';
import { isRealUin } from '@snowluma/common/uin';
import { randomBytes } from 'crypto';
import fs from 'fs';
import path from 'path';
@@ -105,6 +106,38 @@ function ensureConfigDir(): void {
fs.mkdirSync(CONFIG_DIR, { recursive: true });
}
const PER_UIN_CONFIG = /^onebot_(\d+)\.json$/;
/**
* Remove per-UIN config files whose UIN is not a real QQ account — leftovers
* from the phantom-account bug where the native hook reported a garbage
* (timestamp-shaped) UIN and a `onebot_<garbage>.json` got persisted (issue
* #162). Only files matching `onebot_<digits>.json` are considered, and only
* those failing isRealUin (i.e. 11+ digits) are deleted — legitimate accounts
* are never touched. Returns the deleted file names. Safe to call at startup.
*/
export function cleanupInvalidPerUinConfigs(): string[] {
let entries: string[];
try {
entries = fs.readdirSync(CONFIG_DIR);
} catch {
return []; // config dir not created yet — nothing to clean
}
const removed: string[] = [];
for (const name of entries) {
const match = PER_UIN_CONFIG.exec(name);
if (!match || isRealUin(match[1])) continue;
try {
fs.unlinkSync(path.join(CONFIG_DIR, name));
removed.push(name);
log.warn('removed phantom per-UIN config (invalid UIN): %s', name);
} catch (err) {
log.warn('failed to remove phantom config %s: %s', name, err instanceof Error ? err.message : String(err));
}
}
return removed;
}
function toJsonObject(config: OneBotConfig): JsonObject {
const nets = config.networks;
return {
@@ -0,0 +1,409 @@
import { createLogger } from '@snowluma/common/logger';
import type { MessageElement } from '@snowluma/protocol/events';
import type { JsonObject } from '../types';
import type { ParseMessageOptions } from '../message-parser';
import type {
ImageUrlResolver,
MediaUrlResolver,
MessageIdResolver,
MediaSegmentSink,
} from './index';
import { resolveReplyId } from './utils';
// ─────────────────────────────────────────────────────────────────────────
// 消息元素 codec 表(onebot 侧)—— 把「同一种元素」的两个 onebot 方向并到一处:
// S 收·转 toSegment MessageElement → OneBot 段
// P 发·解 fromSegment OneBot 段 → MessageElement
// 历史上这两向分散在 to-segment.ts 与 message-parser.ts、各写各的,容易一起漂。
// 现在每种元素类型一条 { toSegment?, fromSegment? } 条目,谁少写一向一眼可见,
// 并由 element-manifest 对账测试(onebot 侧)拿本表的键去核对清单。
//
// 第 1 步(收·解,proto 字段分派、异构)与第 4 步(发·打包,protocol 包)不在本表,
// 见 element-manifest.ts 的说明。纯 OneBot 输入糖(骰子/分享/…)也不进表,留在
// message-parser 当前置 normalize。
//
// 行为对 to-segment / message-parser 的原实现 byte 级不变——仅把分支体平移到此。
// ─────────────────────────────────────────────────────────────────────────
const log = createLogger('MsgParser');
/** toSegment(S 收·转)所需的上下文:会话信息 + 各类 URL/媒体解析器。 */
export interface ToSegmentContext {
isGroup: boolean;
sessionId: number;
imageUrlResolver?: ImageUrlResolver | null;
mediaUrlResolver?: MediaUrlResolver | null;
messageIdResolver?: MessageIdResolver | null;
mediaSegmentSink?: MediaSegmentSink | null;
}
export interface ElementCodec {
/** S 收·转:MessageElement → OneBot 段。 */
toSegment?: (element: MessageElement, ctx: ToSegmentContext) => Promise<JsonObject>;
/** P 发·解:OneBot 段 data → MessageElement(null = 丢弃该段)。 */
fromSegment?: (data: Record<string, unknown>, options?: ParseMessageOptions) => Promise<MessageElement | null>;
}
// ── 共享低层工具(原在 message-parser,移来供本表与 message-parser 的输入糖共用)──
export 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;
const n = parseInt(String(value), 10);
return Number.isFinite(n) ? n : fallback;
}
/** Build a market-face (`mface`) element from an OneBot segment's data.
* Shared by the dedicated `mface` segment and the `image`-with-`emoji_id`
* round-trip path. `emojiId` is the hex GUID the wire builder converts back
* to `MarketFace.faceId`. */
export function marketFaceElement(emojiId: string, data: Record<string, unknown>): MessageElement {
return {
type: 'mface',
text: String(data.summary ?? data.name ?? ''),
emojiId,
emojiPackageId: intOr(data.emoji_package_id ?? data.tab_id, 0),
emojiKey: String(data.key ?? ''),
};
}
/**
* Pick the best loadable source from a media segment's `file` / `url` / `path`
* / `media` fields.
*
* `file` is normally the canonical OneBot field and wins, but it can also be a
* QQ-internal media id (e.g. `<md5>.png`) that this process cannot resolve to a
* local path. When a bot framework echoes a received image back (Yunzai et al.
* resend the original `file=<md5>.ext` together with the download `url`), using
* `file` makes the send path `statSync` the id as a bogus local path and throw
* `ENOENT`. So: keep `file` when it is a directly loadable source (inline
* bytes, a remote url, or a filesystem path with a separator); otherwise, if a
* real http(s) `url` accompanies it, prefer that. (issue #155)
*/
export function pickMediaSource(data: Record<string, unknown>): string {
const file = String(data.file ?? '').trim();
const url = String(data.url ?? '').trim();
const fallback = file || url || String(data.path ?? '').trim() || String(data.media ?? '').trim();
if (!file) return fallback;
// `file` is itself loadable: inline bytes, a remote url, or a path (anything
// carrying a `/` or `\` separator, incl. file:// and absolute/relative paths).
if (/^(base64:\/\/|data:|https?:\/\/|file:\/\/)/i.test(file) || /[\\/]/.test(file)) return file;
// `file` is a bare token (QQ-internal id) — fall back to a real url if present.
if (/^https?:\/\//i.test(url)) return url;
return fallback;
}
// ── codec 表:一种元素类型一条,键即 element.type(收·转)/ 段 type(发·解,二者同名)──
export const ELEMENT_CODECS: Record<string, ElementCodec> = {
text: {
async toSegment(element) {
return { type: 'text', data: { text: element.text ?? '' } };
},
async fromSegment(data) {
const text = String(data.text ?? '');
return text ? { type: 'text', text } : null;
},
},
face: {
async toSegment(element) {
return { type: 'face', data: { id: String(element.faceId ?? 0) } };
},
async fromSegment(data) {
const id = intOr(data.id, -1);
if (id < 0) return null;
return { type: 'face', faceId: id };
},
},
at: {
async toSegment(element) {
const qq = (element.uid === 'all' || element.targetUin === 0)
? 'all'
: String(element.targetUin ?? 0);
return { type: 'at', data: { qq } };
},
async fromSegment(data, options) {
const qq = String(data.qq ?? '').trim();
if (qq === 'all') {
return { type: 'at', targetUin: 0, uid: 'all', text: '@全体成员 ' };
}
const uin = intOr(qq, 0);
if (uin <= 0) return null;
const name = String(data.name ?? data.nickname ?? data.card ?? '').trim();
let uid = String(data.uid ?? '').trim();
if (!uid && options?.resolveMentionUid) {
uid = (await options.resolveMentionUid(uin))?.trim() ?? '';
}
const element: MessageElement = { type: 'at', targetUin: uin };
if (uid) element.uid = uid;
if (name) element.text = `@${name} `;
return element;
},
},
reply: {
async toSegment(element, ctx) {
const id = resolveReplyId(ctx.isGroup, ctx.sessionId, element.replySeq ?? 0, ctx.messageIdResolver);
return { type: 'reply', data: { id: String(id) } };
},
async fromSegment(data, options) {
const id = intOr(data.id, 0);
if (id === 0) return null;
if (options?.resolveReplySequence) {
const resolved = options.resolveReplySequence(id);
if (typeof resolved === 'number' && resolved > 0) {
const element: MessageElement = {
type: 'reply',
replySeq: resolved,
replyMessageId: id // Keep the original messageId for logging
};
// Try to get additional meta info for better reply display
if (options?.resolveReplyMeta) {
const meta = options.resolveReplyMeta(id);
if (meta) {
element.replySenderUin = meta.senderUin;
element.replyTime = meta.time;
element.replyRandom = meta.random;
}
}
return element;
}
}
// Backward-compatible path: allow direct seq reply IDs.
return id > 0 ? { type: 'reply', replySeq: id } : null;
},
},
image: {
async toSegment(element, ctx) {
const url = ctx.imageUrlResolver ? await ctx.imageUrlResolver(element, ctx.isGroup) : (element.imageUrl ?? '');
const data: JsonObject = {
url,
file: element.fileId ?? '',
sub_type: element.subType ?? 0,
summary: element.summary ?? '',
};
if (ctx.mediaSegmentSink) ctx.mediaSegmentSink('image', element, data, ctx.isGroup, ctx.sessionId);
return { type: 'image', data };
},
async fromSegment(data) {
// A market face that was surfaced as an `image` (see toSegment) can be
// echoed straight back: when `emoji_id` is present we rebuild the market
// face instead of re-uploading the gif as a plain picture.
const imgEmojiId = String(data.emoji_id ?? '').trim();
if (imgEmojiId) return marketFaceElement(imgEmojiId, data);
return {
type: 'image',
url: pickMediaSource(data),
flash: data.type === 'flash',
subType: intOr(data.subType, 0),
summary: data.summary ? String(data.summary) : undefined,
};
},
},
record: {
async toSegment(element, ctx) {
const url = ctx.mediaUrlResolver ? await ctx.mediaUrlResolver(element, ctx.isGroup, ctx.sessionId) : (element.url ?? '');
const data: JsonObject = {
file: element.fileName ?? element.fileId ?? '',
url,
};
if (ctx.mediaSegmentSink) ctx.mediaSegmentSink('record', element, data, ctx.isGroup, ctx.sessionId);
return { type: 'record', data };
},
async fromSegment(data) {
const source = pickMediaSource(data);
if (!source) return null;
return {
type: 'record',
url: source,
};
},
},
video: {
async toSegment(element, ctx) {
const url = ctx.mediaUrlResolver ? await ctx.mediaUrlResolver(element, ctx.isGroup, ctx.sessionId) : (element.url ?? '');
const data: JsonObject = {
file: element.fileName ?? element.fileId ?? '',
url,
};
if (ctx.mediaSegmentSink) ctx.mediaSegmentSink('video', element, data, ctx.isGroup, ctx.sessionId);
return { type: 'video', data };
},
async fromSegment(data) {
const source = pickMediaSource(data);
if (!source) return null;
return {
type: 'video',
url: source,
thumbUrl: data.thumb ? String(data.thumb) : undefined,
};
},
},
json: {
async toSegment(element) {
return { type: 'json', data: { data: element.text ?? '' } };
},
async fromSegment(data) {
return {
type: 'json',
text: String(data.data ?? ''),
};
},
},
xml: {
async toSegment(element) {
return {
type: 'xml',
data: {
data: element.text ?? '',
resid: element.subType ?? 35,
},
};
},
async fromSegment(data) {
return {
type: 'xml',
text: String(data.data ?? ''),
subType: intOr(data.id, 0),
};
},
},
file: {
async toSegment(element, ctx) {
const url = ctx.mediaUrlResolver ? await ctx.mediaUrlResolver(element, ctx.isGroup, ctx.sessionId) : (element.url ?? '');
const fileName = element.fileName ?? '';
const fileSize = element.fileSize ?? 0;
const fileId = element.fileId ?? '';
return {
type: 'file',
data: {
// NapCat/LLOneBot-style canonical fields — most downstream
// OneBot adapters read these (`file`/`file_id`/`file_size`).
file: fileName,
file_id: fileId,
file_size: fileSize,
// Legacy SnowLuma field names, kept for backward compat with
// any consumer that already reads name/size/id.
name: fileName,
size: fileSize,
id: fileId,
url,
file_hash: element.fileHash ?? '',
},
};
},
async fromSegment(data) {
const fileId = String(data.file_id ?? data.fileId ?? '').trim();
const source = String(data.file ?? data.url ?? data.path ?? '').trim();
if (!fileId && !source) {
log.warn('[MsgParser] file segment without file_id or file/url is unsupported');
return null;
}
const fileName = String(data.name ?? data.filename ?? data.fileName ?? '').trim();
const fileSize = intOr(data.size ?? data.fileSize, 0);
const md5Hex = String(data.md5 ?? data.md5Hex ?? '').trim();
const sha1Hex = String(data.sha1 ?? data.sha1Hex ?? '').trim();
const fileHash = String(data.file_hash ?? data.fileHash ?? '').trim();
const elem: MessageElement = fileId ? { type: 'file', fileId } : { type: 'file', url: source };
if (fileName) elem.fileName = fileName;
if (fileSize > 0) elem.fileSize = fileSize;
if (md5Hex) elem.md5Hex = md5Hex;
if (sha1Hex) elem.sha1Hex = sha1Hex;
if (fileHash) elem.fileHash = fileHash;
return elem;
},
},
mface: {
async toSegment(element) {
// Unify market faces (商城表情) to an `image` segment so OneBot clients
// that don't special-case `mface` still render the sticker, while the
// `emoji_id`/`emoji_package_id`/`key` markers let aware clients (and our
// own send path) reproduce it as a real market face. Mirrors NapCat's
// marketFaceElement → image conversion. The gxh URL is a self-contained
// external link (no rkey), so we set it directly and skip mediaSegmentSink.
const emojiId = element.emojiId ?? '';
const dir = emojiId.slice(0, 2);
const url = emojiId
? `https://gxh.vip.qq.com/club/item/parcel/item/${dir}/${emojiId}/raw300.gif`
: '';
return {
type: 'image',
data: {
file: emojiId ? `${dir}-${emojiId}.gif` : '',
url,
summary: element.text ?? '',
sub_type: 0,
emoji_id: emojiId,
emoji_package_id: element.emojiPackageId ?? 0,
key: element.emojiKey ?? '',
},
};
},
async fromSegment(data) {
// Market face (商城表情). emoji_id is the hex GUID; without it we can't
// construct the wire element, so drop the segment.
const emojiId = String(data.emoji_id ?? '').trim();
if (!emojiId) {
log.warn('[MsgParser] mface segment without emoji_id is unsupported');
return null;
}
return marketFaceElement(emojiId, data);
},
},
poke: {
async toSegment(element) {
return {
type: 'poke',
data: {
type: element.subType ?? 0,
},
};
},
async fromSegment(data) {
return {
type: 'poke',
faceId: intOr(data.type ?? data.id, 0),
};
},
},
forward: {
async toSegment(element) {
return {
type: 'forward',
data: { id: element.resId ?? '' },
};
},
async fromSegment(data) {
return {
type: 'forward',
resId: String(data.id ?? ''),
};
},
},
markdown: {
// 收侧(S)无对应,仅发·解存在。
async fromSegment(data) {
return {
type: 'markdown',
text: String(data.content ?? ''),
};
},
},
};
@@ -0,0 +1,27 @@
import type { JsonObject } from '../types';
import type { ConverterContext } from './index';
// The OneBot post header every converted event shares: `time` + `self_id` +
// `post_type`. Previously each of the ~17 converters hand-wrote it, so the
// shared shape could drift. These builders concentrate it — a converter just
// supplies its `post_type`-specific fields.
type Timed = { time: number };
/** notice envelope — `{ time, self_id, post_type: 'notice', ...fields }`. */
export function notice(ctx: ConverterContext, event: Timed, fields: JsonObject): JsonObject {
return { time: event.time, self_id: ctx.selfId, post_type: 'notice', ...fields };
}
/** request envelope — `{ time, self_id, post_type: 'request', ...fields }`. */
export function request(ctx: ConverterContext, event: Timed, fields: JsonObject): JsonObject {
return { time: event.time, self_id: ctx.selfId, post_type: 'request', ...fields };
}
/**
* message envelope — `{ time, self_id, post_type, ...fields }`. `postType` is
* 'message' or 'message_sent' (self-echo), decided per-message by the caller.
*/
export function message(ctx: ConverterContext, event: Timed, postType: string, fields: JsonObject): JsonObject {
return { time: event.time, self_id: ctx.selfId, post_type: postType, ...fields };
}
+43 -27
View File
@@ -49,37 +49,53 @@ export interface ConverterContext {
// ─────────────── dispatcher ───────────────
/** Converter for one event kind — receives the narrowed event for that kind. */
type ConverterFor<K extends QQEventVariant['kind']> =
(ctx: ConverterContext, event: Extract<QQEventVariant, { kind: K }>) => JsonObject | Promise<JsonObject>;
/**
* Every event kind → its converter (or `null` for kinds intentionally not
* surfaced to OneBot clients). The mapped type is TOTAL over the union, so a
* new `QQEventVariant` kind that forgets a converter is a compile error here —
* not a silent `null` at runtime.
*/
type ConverterRegistry = { [K in QQEventVariant['kind']]: ConverterFor<K> | null };
const CONVERTERS: ConverterRegistry = {
// Messages.
friend_message: convertFriendMessage,
group_message: convertGroupMessage,
temp_message: convertTempMessage,
// Notices.
group_member_join: convertGroupMemberJoin,
group_member_leave: convertGroupMemberLeave,
group_mute: convertGroupMute,
group_admin: convertGroupAdmin,
friend_recall: convertFriendRecall,
group_recall: convertGroupRecall,
friend_poke: convertFriendPoke,
group_poke: convertGroupPoke,
group_essence: convertGroupEssence,
group_file_upload: convertGroupFileUpload,
friend_add: convertFriendAdd,
group_msg_emoji_like: convertGroupMsgEmojiLike,
// Requests.
friend_request: convertFriendRequest,
group_invite: convertGroupInvite,
// Internal-only: async voice-to-text result, correlated by a pending
// fetch_ptt_text; never emitted as an OneBot event.
ptt_trans_result: null,
};
export async function convertEvent(
ctx: ConverterContext,
event: QQEventVariant,
): Promise<JsonObject | null> {
switch (event.kind) {
// Messages.
case 'friend_message': return convertFriendMessage(ctx, event);
case 'group_message': return convertGroupMessage(ctx, event);
case 'temp_message': return convertTempMessage(ctx, event);
// Notices.
case 'group_member_join': return convertGroupMemberJoin(ctx, event);
case 'group_member_leave': return convertGroupMemberLeave(ctx, event);
case 'group_mute': return convertGroupMute(ctx, event);
case 'group_admin': return convertGroupAdmin(ctx, event);
case 'friend_recall': return convertFriendRecall(ctx, event);
case 'group_recall': return convertGroupRecall(ctx, event);
case 'friend_poke': return convertFriendPoke(ctx, event);
case 'group_poke': return convertGroupPoke(ctx, event);
case 'group_essence': return convertGroupEssence(ctx, event);
case 'group_file_upload': return convertGroupFileUpload(ctx, event);
case 'friend_add': return convertFriendAdd(ctx, event);
case 'group_msg_emoji_like': return convertGroupMsgEmojiLike(ctx, event);
// Requests.
case 'friend_request': return convertFriendRequest(ctx, event);
case 'group_invite': return convertGroupInvite(ctx, event);
default:
return null;
}
const converter = CONVERTERS[event.kind];
if (!converter) return null;
// The registry ties each key to its own event kind, but indexing by a
// runtime `event.kind` loses that correlation — one localized cast restores it.
return (converter as (ctx: ConverterContext, event: QQEventVariant) => JsonObject | Promise<JsonObject>)(ctx, event);
}
export async function elementsToOneBotSegments(
@@ -1,31 +1,42 @@
import type { QQEventVariant } from '@snowluma/protocol/events';
import type { MessageElement, 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 } from './utils';
import { message } from './envelope';
type FriendMessage = Extract<QQEventVariant, { kind: 'friend_message' }>;
type GroupMessage = Extract<QQEventVariant, { kind: 'group_message' }>;
type TempMessage = Extract<QQEventVariant, { kind: 'temp_message' }>;
export async function convertFriendMessage(ctx: ConverterContext, event: FriendMessage): Promise<JsonObject> {
/** Fill the media/id resolvers from ctx — collapses the 7-arg elementsToJson splat. */
function toSegments(ctx: ConverterContext, elements: MessageElement[], isGroup: boolean, sessionId: number) {
return elementsToJson(
elements, isGroup, sessionId,
ctx.imageUrlResolver, ctx.mediaUrlResolver, ctx.messageIdResolver, ctx.mediaSegmentSink,
);
}
/**
* friend_message and temp_message differ only in `sub_type` ('friend' vs
* 'group') — both are private, keyed by senderUin, same sender shape.
*/
async function convertPrivateMessage(
ctx: ConverterContext,
event: FriendMessage | TempMessage,
subType: 'friend' | 'group',
): Promise<JsonObject> {
const isSelf = event.senderUin === ctx.selfId;
const postType = isSelf ? 'message_sent' : 'message';
const messageId = applyMessageIdResolver(
ctx.messageIdResolver, false, event.senderUin, event.msgSeq, PRIVATE_MESSAGE_EVENT,
);
const segments = await elementsToJson(
event.elements, false, event.senderUin,
ctx.imageUrlResolver, ctx.mediaUrlResolver, ctx.messageIdResolver, ctx.mediaSegmentSink,
);
return {
time: event.time,
self_id: ctx.selfId,
post_type: postType,
const segments = await toSegments(ctx, event.elements, false, event.senderUin);
return message(ctx, event, postType, {
message_type: 'private',
sub_type: 'friend',
sub_type: subType,
message_id: messageId,
message_seq: event.msgSeq,
user_id: event.senderUin,
@@ -38,7 +49,15 @@ export async function convertFriendMessage(ctx: ConverterContext, event: FriendM
sex: 'unknown',
age: 0,
},
};
});
}
export function convertFriendMessage(ctx: ConverterContext, event: FriendMessage): Promise<JsonObject> {
return convertPrivateMessage(ctx, event, 'friend');
}
export function convertTempMessage(ctx: ConverterContext, event: TempMessage): Promise<JsonObject> {
return convertPrivateMessage(ctx, event, 'group');
}
export async function convertGroupMessage(ctx: ConverterContext, event: GroupMessage): Promise<JsonObject> {
@@ -47,14 +66,8 @@ export async function convertGroupMessage(ctx: ConverterContext, event: GroupMes
const messageId = applyMessageIdResolver(
ctx.messageIdResolver, true, event.groupId, event.msgSeq, GROUP_MESSAGE_EVENT,
);
const segments = await elementsToJson(
event.elements, true, event.groupId,
ctx.imageUrlResolver, ctx.mediaUrlResolver, ctx.messageIdResolver, ctx.mediaSegmentSink,
);
return {
time: event.time,
self_id: ctx.selfId,
post_type: postType,
const segments = await toSegments(ctx, event.elements, true, event.groupId);
return message(ctx, event, postType, {
message_type: 'group',
sub_type: 'normal',
message_id: messageId,
@@ -73,36 +86,5 @@ export async function convertGroupMessage(ctx: ConverterContext, event: GroupMes
age: 0,
},
anonymous: null,
};
}
export async function convertTempMessage(ctx: ConverterContext, event: TempMessage): Promise<JsonObject> {
const isSelf = event.senderUin === ctx.selfId;
const postType = isSelf ? 'message_sent' : 'message';
const messageId = applyMessageIdResolver(
ctx.messageIdResolver, false, event.senderUin, event.msgSeq, PRIVATE_MESSAGE_EVENT,
);
const segments = await elementsToJson(
event.elements, false, event.senderUin,
ctx.imageUrlResolver, ctx.mediaUrlResolver, ctx.messageIdResolver, ctx.mediaSegmentSink,
);
return {
time: event.time,
self_id: ctx.selfId,
post_type: postType,
message_type: 'private',
sub_type: 'group',
message_id: messageId,
message_seq: event.msgSeq,
user_id: event.senderUin,
message: segments,
raw_message: segmentsToRawMessage(segments),
font: 0,
sender: {
user_id: event.senderUin,
nickname: event.senderNick,
sex: 'unknown',
age: 0,
},
};
});
}
@@ -3,6 +3,7 @@ import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT } from '../message-id';
import type { JsonObject } from '../types';
import type { ConverterContext } from './index';
import { applyMessageIdResolver, isSameActor } from './utils';
import { notice } from './envelope';
type GroupMemberJoin = Extract<QQEventVariant, { kind: 'group_member_join' }>;
type GroupMemberLeave = Extract<QQEventVariant, { kind: 'group_member_leave' }>;
@@ -18,16 +19,13 @@ type FriendAdd = Extract<QQEventVariant, { kind: 'friend_add' }>;
type GroupMsgEmojiLike = Extract<QQEventVariant, { kind: 'group_msg_emoji_like' }>;
export function convertGroupMemberJoin(ctx: ConverterContext, event: GroupMemberJoin): JsonObject {
return {
time: event.time,
self_id: ctx.selfId,
post_type: 'notice',
return notice(ctx, event, {
notice_type: 'group_increase',
sub_type: isSameActor(event.operatorUin, event.operatorUid, event.userUin, event.userUid) ? 'approve' : 'invite',
group_id: event.groupId,
operator_id: event.operatorUin,
user_id: event.userUin,
};
});
}
export function convertGroupMemberLeave(ctx: ConverterContext, event: GroupMemberLeave): JsonObject {
@@ -42,79 +40,61 @@ export function convertGroupMemberLeave(ctx: ConverterContext, event: GroupMembe
default:
subType = 'leave';
}
return {
time: event.time,
self_id: ctx.selfId,
post_type: 'notice',
return notice(ctx, event, {
notice_type: 'group_decrease',
sub_type: subType,
group_id: event.groupId,
operator_id: event.operatorUin,
user_id: event.userUin,
};
});
}
export function convertGroupMute(ctx: ConverterContext, event: GroupMute): JsonObject {
return {
time: event.time,
self_id: ctx.selfId,
post_type: 'notice',
return notice(ctx, event, {
notice_type: 'group_ban',
sub_type: event.duration > 0 ? 'ban' : 'lift_ban',
group_id: event.groupId,
operator_id: event.operatorUin,
user_id: event.userUin,
duration: event.duration,
};
});
}
export function convertGroupAdmin(ctx: ConverterContext, event: GroupAdmin): JsonObject {
return {
time: event.time,
self_id: ctx.selfId,
post_type: 'notice',
return notice(ctx, event, {
notice_type: 'group_admin',
sub_type: event.set ? 'set' : 'unset',
group_id: event.groupId,
user_id: event.userUin,
};
});
}
export function convertFriendRecall(ctx: ConverterContext, event: FriendRecall): JsonObject {
const messageId = applyMessageIdResolver(
ctx.messageIdResolver, false, event.userUin, event.msgSeq, PRIVATE_MESSAGE_EVENT,
);
return {
time: event.time,
self_id: ctx.selfId,
post_type: 'notice',
return notice(ctx, event, {
notice_type: 'friend_recall',
user_id: event.userUin,
message_id: messageId,
};
});
}
export function convertGroupRecall(ctx: ConverterContext, event: GroupRecall): JsonObject {
const messageId = applyMessageIdResolver(
ctx.messageIdResolver, true, event.groupId, event.msgSeq, GROUP_MESSAGE_EVENT,
);
return {
time: event.time,
self_id: ctx.selfId,
post_type: 'notice',
return notice(ctx, event, {
notice_type: 'group_recall',
group_id: event.groupId,
operator_id: event.operatorUin,
user_id: event.authorUin,
message_id: messageId,
};
});
}
export function convertFriendPoke(ctx: ConverterContext, event: FriendPoke): JsonObject {
return {
time: event.time,
self_id: ctx.selfId,
post_type: 'notice',
return notice(ctx, event, {
notice_type: 'notify',
sub_type: 'poke',
user_id: event.userUin,
@@ -122,14 +102,11 @@ export function convertFriendPoke(ctx: ConverterContext, event: FriendPoke): Jso
action: event.action,
suffix: event.suffix,
action_img_url: event.actionImgUrl,
};
});
}
export function convertGroupPoke(ctx: ConverterContext, event: GroupPoke): JsonObject {
return {
time: event.time,
self_id: ctx.selfId,
post_type: 'notice',
return notice(ctx, event, {
notice_type: 'notify',
sub_type: 'poke',
group_id: event.groupId,
@@ -138,17 +115,14 @@ export function convertGroupPoke(ctx: ConverterContext, event: GroupPoke): JsonO
action: event.action,
suffix: event.suffix,
action_img_url: event.actionImgUrl,
};
});
}
export function convertGroupEssence(ctx: ConverterContext, event: GroupEssence): JsonObject {
const messageId = applyMessageIdResolver(
ctx.messageIdResolver, true, event.groupId, event.msgSeq, GROUP_MESSAGE_EVENT,
);
return {
time: event.time,
self_id: ctx.selfId,
post_type: 'notice',
return notice(ctx, event, {
notice_type: 'essence',
sub_type: event.set ? 'add' : 'delete',
group_id: event.groupId,
@@ -158,14 +132,11 @@ export function convertGroupEssence(ctx: ConverterContext, event: GroupEssence):
message_id: messageId,
message_seq: event.msgSeq,
random: event.random,
};
});
}
export function convertGroupFileUpload(ctx: ConverterContext, event: GroupFileUpload): JsonObject {
return {
time: event.time,
self_id: ctx.selfId,
post_type: 'notice',
return notice(ctx, event, {
notice_type: 'group_upload',
group_id: event.groupId,
user_id: event.userUin,
@@ -175,27 +146,21 @@ export function convertGroupFileUpload(ctx: ConverterContext, event: GroupFileUp
size: event.fileSize,
busid: event.busId,
},
};
});
}
export function convertFriendAdd(ctx: ConverterContext, event: FriendAdd): JsonObject {
return {
time: event.time,
self_id: ctx.selfId,
post_type: 'notice',
return notice(ctx, event, {
notice_type: 'friend_add',
user_id: event.userUin,
};
});
}
export function convertGroupMsgEmojiLike(ctx: ConverterContext, event: GroupMsgEmojiLike): JsonObject {
const messageId = applyMessageIdResolver(
ctx.messageIdResolver, true, event.groupId, event.msgSeq, GROUP_MESSAGE_EVENT,
);
return {
time: event.time,
self_id: ctx.selfId,
post_type: 'notice',
return notice(ctx, event, {
notice_type: 'group_msg_emoji_like',
sub_type: event.isAdd ? 'add' : 'remove',
group_id: event.groupId,
@@ -204,5 +169,5 @@ export function convertGroupMsgEmojiLike(ctx: ConverterContext, event: GroupMsgE
message_id: messageId,
message_seq: event.msgSeq,
likes: [{ emoji_id: event.emojiId, count: event.count }],
};
});
}
@@ -1,32 +1,27 @@
import type { QQEventVariant } from '@snowluma/protocol/events';
import type { JsonObject } from '../types';
import type { ConverterContext } from './index';
import { request } from './envelope';
type FriendRequest = Extract<QQEventVariant, { kind: 'friend_request' }>;
type GroupInvite = Extract<QQEventVariant, { kind: 'group_invite' }>;
export function convertFriendRequest(ctx: ConverterContext, event: FriendRequest): JsonObject {
return {
time: event.time,
self_id: ctx.selfId,
post_type: 'request',
return request(ctx, event, {
request_type: 'friend',
user_id: event.fromUin,
comment: event.message,
flag: event.flag,
};
});
}
export function convertGroupInvite(ctx: ConverterContext, event: GroupInvite): JsonObject {
return {
time: event.time,
self_id: ctx.selfId,
post_type: 'request',
return request(ctx, event, {
request_type: 'group',
sub_type: event.subType || 'invite',
group_id: event.groupId,
user_id: event.fromUin,
comment: event.message,
flag: event.flag,
};
});
}
+12 -131
View File
@@ -6,7 +6,7 @@ import type {
MediaUrlResolver,
MessageIdResolver,
} from './index';
import { resolveReplyId } from './utils';
import { ELEMENT_CODECS } from './element-codecs';
import { createLogger } from '@snowluma/common/logger';
const log = createLogger('OneBot');
@@ -46,136 +46,17 @@ async function elementToSegment(
messageIdResolver?: MessageIdResolver | null,
mediaSegmentSink?: MediaSegmentSink | null,
): Promise<JsonObject> {
if (element.type === 'text') {
return { type: 'text', data: { text: element.text ?? '' } };
}
if (element.type === 'face') {
return { type: 'face', data: { id: String(element.faceId ?? 0) } };
}
if (element.type === 'image') {
const url = imageUrlResolver ? await imageUrlResolver(element, isGroup) : (element.imageUrl ?? '');
const data: JsonObject = {
url,
file: element.fileId ?? '',
sub_type: element.subType ?? 0,
summary: element.summary ?? '',
};
if (mediaSegmentSink) mediaSegmentSink('image', element, data, isGroup, sessionId);
return { type: 'image', data };
}
if (element.type === 'at') {
const qq = (element.uid === 'all' || element.targetUin === 0)
? 'all'
: String(element.targetUin ?? 0);
return { type: 'at', data: { qq } };
}
if (element.type === 'reply') {
const id = resolveReplyId(isGroup, sessionId, element.replySeq ?? 0, messageIdResolver);
return { type: 'reply', data: { id: String(id) } };
}
if (element.type === 'record') {
const url = mediaUrlResolver ? await mediaUrlResolver(element, isGroup, sessionId) : (element.url ?? '');
const data: JsonObject = {
file: element.fileName ?? element.fileId ?? '',
url,
};
if (mediaSegmentSink) mediaSegmentSink('record', element, data, isGroup, sessionId);
return { type: 'record', data };
}
if (element.type === 'video') {
const url = mediaUrlResolver ? await mediaUrlResolver(element, isGroup, sessionId) : (element.url ?? '');
const data: JsonObject = {
file: element.fileName ?? element.fileId ?? '',
url,
};
if (mediaSegmentSink) mediaSegmentSink('video', element, data, isGroup, sessionId);
return { type: 'video', data };
}
if (element.type === 'json') {
return { type: 'json', data: { data: element.text ?? '' } };
}
if (element.type === 'xml') {
return {
type: 'xml',
data: {
data: element.text ?? '',
resid: element.subType ?? 35,
},
};
}
if (element.type === 'file') {
const url = mediaUrlResolver ? await mediaUrlResolver(element, isGroup, sessionId) : (element.url ?? '');
const fileName = element.fileName ?? '';
const fileSize = element.fileSize ?? 0;
const fileId = element.fileId ?? '';
return {
type: 'file',
data: {
// NapCat/LLOneBot-style canonical fields — most downstream
// OneBot adapters read these (`file`/`file_id`/`file_size`).
file: fileName,
file_id: fileId,
file_size: fileSize,
// Legacy SnowLuma field names, kept for backward compat with
// any consumer that already reads name/size/id.
name: fileName,
size: fileSize,
id: fileId,
url,
file_hash: element.fileHash ?? '',
},
};
}
if (element.type === 'mface') {
// Unify market faces (商城表情) to an `image` segment so OneBot clients
// that don't special-case `mface` still render the sticker, while the
// `emoji_id`/`emoji_package_id`/`key` markers let aware clients (and our
// own send path) reproduce it as a real market face. Mirrors NapCat's
// marketFaceElement → image conversion. The gxh URL is a self-contained
// external link (no rkey), so we set it directly and skip mediaSegmentSink.
const emojiId = element.emojiId ?? '';
const dir = emojiId.slice(0, 2);
const url = emojiId
? `https://gxh.vip.qq.com/club/item/parcel/item/${dir}/${emojiId}/raw300.gif`
: '';
return {
type: 'image',
data: {
file: emojiId ? `${dir}-${emojiId}.gif` : '',
url,
summary: element.text ?? '',
sub_type: 0,
emoji_id: emojiId,
emoji_package_id: element.emojiPackageId ?? 0,
key: element.emojiKey ?? '',
},
};
}
if (element.type === 'poke') {
return {
type: 'poke',
data: {
type: element.subType ?? 0,
},
};
}
if (element.type === 'forward') {
return {
type: 'forward',
data: { id: element.resId ?? '' },
};
// S 收·转:按 element.type 查 codec 表;缺条目则走 default 透传(保持原兜底)。
const codec = ELEMENT_CODECS[element.type];
if (codec?.toSegment) {
return codec.toSegment(element, {
isGroup,
sessionId,
imageUrlResolver,
mediaUrlResolver,
messageIdResolver,
mediaSegmentSink,
});
}
return { type: element.type, data: {} };
}
+2 -8
View File
@@ -1,7 +1,6 @@
import type { MessageElement } from '@snowluma/protocol/events';
import fs from 'fs';
import { DatabaseSync, type StatementSync } from 'node:sqlite';
import path from 'path';
import { openSqliteDb } from './sqlite-open';
export interface CachedImage {
file: string;
@@ -77,12 +76,7 @@ export class MediaStore {
constructor(dbPath: string, maxEntriesPerType = DEFAULT_KEEP_ENTRIES) {
this.maxEntriesPerType = Math.max(64, maxEntriesPerType);
const dir = path.dirname(dbPath);
fs.mkdirSync(dir, { recursive: true });
this.db = new DatabaseSync(dbPath);
this.db.exec('PRAGMA journal_mode = WAL');
this.db.exec('PRAGMA synchronous = NORMAL');
this.db = openSqliteDb(dbPath);
this.initSchema();
this.upsertEntry = this.db.prepare(
+13 -199
View File
@@ -1,6 +1,7 @@
import { createLogger } from '@snowluma/common/logger';
import type { MessageElement } from '@snowluma/protocol/events';
import { parseFromCQString } from './helper/cq';
import { ELEMENT_CODECS, intOr } from './event-converter/element-codecs';
import type { JsonValue } from './types';
const log = createLogger('MsgParser');
@@ -17,27 +18,6 @@ export interface ParseMessageOptions {
export const CQ_REGEX = /\[CQ:([A-Za-z]+)(?:,([^\]]*))?\]/g;
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;
const n = parseInt(String(value), 10);
return Number.isFinite(n) ? n : fallback;
}
/** Build a market-face (`mface`) element from an OneBot segment's data.
* Shared by the dedicated `mface` segment and the `image`-with-`emoji_id`
* round-trip path. `emojiId` is the hex GUID the wire builder converts back
* to `MarketFace.faceId`. */
function marketFaceElement(emojiId: string, data: Record<string, unknown>): MessageElement {
return {
type: 'mface',
text: String(data.summary ?? data.name ?? ''),
emojiId,
emojiPackageId: intOr(data.emoji_package_id ?? data.tab_id, 0),
emojiKey: String(data.key ?? ''),
};
}
export function parseCQParams(raw: string): Record<string, string> {
const params: Record<string, string> = {};
if (!raw) return params;
@@ -54,32 +34,6 @@ export function parseCQParams(raw: string): Record<string, string> {
return params;
}
/**
* Pick the best loadable source from a media segment's `file` / `url` / `path`
* / `media` fields.
*
* `file` is normally the canonical OneBot field and wins, but it can also be a
* QQ-internal media id (e.g. `<md5>.png`) that this process cannot resolve to a
* local path. When a bot framework echoes a received image back (Yunzai et al.
* resend the original `file=<md5>.ext` together with the download `url`), using
* `file` makes the send path `statSync` the id as a bogus local path and throw
* `ENOENT`. So: keep `file` when it is a directly loadable source (inline
* bytes, a remote url, or a filesystem path with a separator); otherwise, if a
* real http(s) `url` accompanies it, prefer that. (issue #155)
*/
function pickMediaSource(data: Record<string, unknown>): string {
const file = String(data.file ?? '').trim();
const url = String(data.url ?? '').trim();
const fallback = file || url || String(data.path ?? '').trim() || String(data.media ?? '').trim();
if (!file) return fallback;
// `file` is itself loadable: inline bytes, a remote url, or a path (anything
// carrying a `/` or `\` separator, incl. file:// and absolute/relative paths).
if (/^(base64:\/\/|data:|https?:\/\/|file:\/\/)/i.test(file) || /[\\/]/.test(file)) return file;
// `file` is a bare token (QQ-internal id) — fall back to a real url if present.
if (/^https?:\/\//i.test(url)) return url;
return fallback;
}
// --- JSON segment parsing ---
interface MessageSegment {
@@ -96,130 +50,11 @@ function isSegmentArray(val: unknown): val is MessageSegment[] {
export async function segmentToElement(type: string, data: Record<string, unknown>, options?: ParseMessageOptions): Promise<MessageElement | null> {
const normalizedType = type.toLowerCase();
// 纯 OneBot 输入糖:不是某种真实消息元素,只是被塌缩成 json/face/poke 的输入
// 便利(或 forward 组装用的中间 node),无收侧对应、无专属 wire 形态,故不进
// codec 表 —— 在这里前置处理。真实元素(收发同名)走下方的 ELEMENT_CODECS。
switch (normalizedType) {
case 'text': {
const text = String(data.text ?? '');
return text ? { type: 'text', text } : null;
}
case 'face': {
const id = intOr(data.id, -1);
if (id < 0) return null;
return { type: 'face', faceId: id };
}
case 'at': {
const qq = String(data.qq ?? '').trim();
if (qq === 'all') {
return { type: 'at', targetUin: 0, uid: 'all', text: '@全体成员 ' };
}
const uin = intOr(qq, 0);
if (uin <= 0) return null;
const name = String(data.name ?? data.nickname ?? data.card ?? '').trim();
let uid = String(data.uid ?? '').trim();
if (!uid && options?.resolveMentionUid) {
uid = (await options.resolveMentionUid(uin))?.trim() ?? '';
}
const element: MessageElement = { type: 'at', targetUin: uin };
if (uid) element.uid = uid;
if (name) element.text = `@${name} `;
return element;
}
case 'reply': {
const id = intOr(data.id, 0);
if (id === 0) return null;
if (options?.resolveReplySequence) {
const resolved = options.resolveReplySequence(id);
if (typeof resolved === 'number' && resolved > 0) {
const element: MessageElement = {
type: 'reply',
replySeq: resolved,
replyMessageId: id // Keep the original messageId for logging
};
// Try to get additional meta info for better reply display
if (options?.resolveReplyMeta) {
const meta = options.resolveReplyMeta(id);
if (meta) {
element.replySenderUin = meta.senderUin;
element.replyTime = meta.time;
element.replyRandom = meta.random;
}
}
return element;
}
}
// Backward-compatible path: allow direct seq reply IDs.
return id > 0 ? { type: 'reply', replySeq: id } : null;
}
case 'image': {
// A market face that was surfaced as an `image` (see to-segment) can be
// echoed straight back: when `emoji_id` is present we rebuild the market
// face instead of re-uploading the gif as a plain picture.
const imgEmojiId = String(data.emoji_id ?? '').trim();
if (imgEmojiId) return marketFaceElement(imgEmojiId, data);
return {
type: 'image',
url: pickMediaSource(data),
flash: data.type === 'flash',
subType: intOr(data.subType, 0),
summary: data.summary ? String(data.summary) : undefined,
};
}
case 'mface': {
// Market face (商城表情). emoji_id is the hex GUID; without it we can't
// construct the wire element, so drop the segment.
const emojiId = String(data.emoji_id ?? '').trim();
if (!emojiId) {
log.warn('[MsgParser] mface segment without emoji_id is unsupported');
return null;
}
return marketFaceElement(emojiId, data);
}
case 'record': {
const source = pickMediaSource(data);
if (!source) return null;
return {
type: 'record',
url: source,
};
}
case 'video': {
const source = pickMediaSource(data);
if (!source) return null;
return {
type: 'video',
url: source,
thumbUrl: data.thumb ? String(data.thumb) : undefined,
};
}
case 'json': {
return {
type: 'json',
text: String(data.data ?? ''),
};
}
case 'xml': {
return {
type: 'xml',
text: String(data.data ?? ''),
subType: intOr(data.id, 0),
};
}
case 'poke': {
return {
type: 'poke',
faceId: intOr(data.type ?? data.id, 0),
};
}
case 'forward': {
return {
type: 'forward',
resId: String(data.id ?? ''),
};
}
case 'node': {
// Fake forward node segment — store the raw data for later processing
// The content field may be a segment array, a single segment, or a CQ string
@@ -232,12 +67,6 @@ export async function segmentToElement(type: string, data: Record<string, unknow
resId: JSON.stringify(data.content ?? ''),
};
}
case 'markdown': {
return {
type: 'markdown',
text: String(data.content ?? ''),
};
}
case 'share': {
// Link share — map to json card message
const url = String(data.url ?? '');
@@ -349,30 +178,15 @@ export async function segmentToElement(type: string, data: Record<string, unknow
// Anonymous flag — ignored during send, the protocol handles anonymity
return null;
}
case 'file': {
const fileId = String(data.file_id ?? data.fileId ?? '').trim();
const source = String(data.file ?? data.url ?? data.path ?? '').trim();
if (!fileId && !source) {
log.warn('[MsgParser] file segment without file_id or file/url is unsupported');
return null;
}
const fileName = String(data.name ?? data.filename ?? data.fileName ?? '').trim();
const fileSize = intOr(data.size ?? data.fileSize, 0);
const md5Hex = String(data.md5 ?? data.md5Hex ?? '').trim();
const sha1Hex = String(data.sha1 ?? data.sha1Hex ?? '').trim();
const fileHash = String(data.file_hash ?? data.fileHash ?? '').trim();
const elem: MessageElement = fileId ? { type: 'file', fileId } : { type: 'file', url: source };
if (fileName) elem.fileName = fileName;
if (fileSize > 0) elem.fileSize = fileSize;
if (md5Hex) elem.md5Hex = md5Hex;
if (sha1Hex) elem.sha1Hex = sha1Hex;
if (fileHash) elem.fileHash = fileHash;
return elem;
}
default:
console.warn(`[MsgParser] unsupported segment type: ${type}`);
return null;
}
// 真实元素(P 发·解,段 type 与 element.type 同名):查 codec 表。
// 见 event-converter/element-codecs.ts。
const codec = ELEMENT_CODECS[normalizedType];
if (codec?.fromSegment) return codec.fromSegment(data, options);
console.warn(`[MsgParser] unsupported segment type: ${type}`);
return null;
}
function segmentPayload(seg: MessageSegment): Record<string, unknown> {
+2 -8
View File
@@ -1,7 +1,6 @@
import fs from 'fs';
import { DatabaseSync, type StatementSync } from 'node:sqlite';
import path from 'path';
import type { JsonObject, MessageMeta } from './types';
import { openSqliteDb } from './sqlite-open';
export class MessageStore {
private readonly db: DatabaseSync;
@@ -15,14 +14,9 @@ export class MessageStore {
private readonly stmtListEventsLatest: StatementSync;
constructor(dbPath: string) {
const dir = path.dirname(dbPath);
fs.mkdirSync(dir, { recursive: true });
// Replace .json extension with .db if present
const finalPath = dbPath.replace(/\.json$/, '.db');
this.db = new DatabaseSync(finalPath);
this.db.exec('PRAGMA journal_mode = WAL');
this.db.exec('PRAGMA synchronous = NORMAL');
this.db = openSqliteDb(finalPath);
this.initSchema();
// Prepare once. Statements survive for the lifetime of the
+43 -110
View File
@@ -417,6 +417,43 @@ export async function setEssenceMessage(
* inspect it through `/get_msg` can distinguish their own outbound
* messages from incoming ones.
*/
/**
* The shared "record a self-sent message" tail: derive the OneBot message id
* from (sequence, target, event), then cache both the meta and the self-sent
* copy. Centralizes the `isGroup ↔ eventName ↔ hashMessageIdInt32 event
* constant` coupling that was hand-paired in six send/forward paths — a
* mismatch there silently produced a wrong message_id or wrong event
* attribution. Returns the derived message id.
*/
async function finalizeSend(
ref: OneBotInstanceContext,
isGroup: boolean,
targetId: number,
receipt: { sequence: number; clientSequence: number; random: number; timestamp: number },
elements: MessageElement[],
): Promise<number> {
const eventName = isGroup ? GROUP_MESSAGE_EVENT : PRIVATE_MESSAGE_EVENT;
const messageId = hashMessageIdInt32(receipt.sequence, targetId, eventName);
ref.cacheMessageMeta(messageId, {
isGroup,
targetId,
sequence: receipt.sequence,
eventName,
clientSequence: receipt.clientSequence,
random: receipt.random,
timestamp: receipt.timestamp,
});
await cacheSelfSentMessage(ref, {
isGroup,
sessionId: targetId,
messageId,
sequence: receipt.sequence,
timestamp: receipt.timestamp,
elements,
});
return messageId;
}
async function cacheSelfSentMessage(
ref: OneBotInstanceContext,
options: {
@@ -644,24 +681,7 @@ export async function sendPrivateMessage(
}
if (!lastReceipt) throw new Error('message is empty');
const messageId = hashMessageIdInt32(lastReceipt.sequence, userId, PRIVATE_MESSAGE_EVENT);
ref.cacheMessageMeta(messageId, {
isGroup: false,
targetId: userId,
sequence: lastReceipt.sequence,
eventName: PRIVATE_MESSAGE_EVENT,
clientSequence: lastReceipt.clientSequence,
random: lastReceipt.random,
timestamp: lastReceipt.timestamp,
});
await cacheSelfSentMessage(ref, {
isGroup: false,
sessionId: userId,
messageId,
sequence: lastReceipt.sequence,
timestamp: lastReceipt.timestamp,
elements,
});
const messageId = await finalizeSend(ref, false, userId, lastReceipt, elements);
return { messageId };
}
@@ -758,24 +778,7 @@ export async function sendGroupMessage(
}
if (!lastReceipt) throw new Error('message is empty');
const messageId = hashMessageIdInt32(lastReceipt.sequence, groupId, GROUP_MESSAGE_EVENT);
ref.cacheMessageMeta(messageId, {
isGroup: true,
targetId: groupId,
sequence: lastReceipt.sequence,
eventName: GROUP_MESSAGE_EVENT,
clientSequence: lastReceipt.clientSequence,
random: lastReceipt.random,
timestamp: lastReceipt.timestamp,
});
await cacheSelfSentMessage(ref, {
isGroup: true,
sessionId: groupId,
messageId,
sequence: lastReceipt.sequence,
timestamp: lastReceipt.timestamp,
elements,
});
const messageId = await finalizeSend(ref, true, groupId, lastReceipt, elements);
return { messageId };
}
@@ -801,25 +804,7 @@ export async function sendGroupForwardMessage(
const forwardId = await ref.bridge.apis.forward.upload(nodes, groupId);
const previewElement = buildForwardPreviewElement(forwardId, nodes, true, meta);
const receipt = await ref.bridge.apis.message.sendGroup(groupId, [previewElement]);
const messageId = hashMessageIdInt32(receipt.sequence, groupId, GROUP_MESSAGE_EVENT);
ref.cacheMessageMeta(messageId, {
isGroup: true,
targetId: groupId,
sequence: receipt.sequence,
eventName: GROUP_MESSAGE_EVENT,
clientSequence: receipt.clientSequence,
random: receipt.random,
timestamp: receipt.timestamp,
});
await cacheSelfSentMessage(ref, {
isGroup: true,
sessionId: groupId,
messageId,
sequence: receipt.sequence,
timestamp: receipt.timestamp,
elements: [previewElement],
});
const messageId = await finalizeSend(ref, true, groupId, receipt, [previewElement]);
return { messageId, forwardId };
}
@@ -837,25 +822,7 @@ export async function sendPrivateForwardMessage(
const forwardId = await ref.bridge.apis.forward.upload(nodes, undefined, userId);
const previewElement = buildForwardPreviewElement(forwardId, nodes, false, meta);
const receipt = await ref.bridge.apis.message.sendPrivate(userId, [previewElement]);
const messageId = hashMessageIdInt32(receipt.sequence, userId, PRIVATE_MESSAGE_EVENT);
ref.cacheMessageMeta(messageId, {
isGroup: false,
targetId: userId,
sequence: receipt.sequence,
eventName: PRIVATE_MESSAGE_EVENT,
clientSequence: receipt.clientSequence,
random: receipt.random,
timestamp: receipt.timestamp,
});
await cacheSelfSentMessage(ref, {
isGroup: false,
sessionId: userId,
messageId,
sequence: receipt.sequence,
timestamp: receipt.timestamp,
elements: [previewElement],
});
const messageId = await finalizeSend(ref, false, userId, receipt, [previewElement]);
return { messageId, forwardId };
}
@@ -904,44 +871,10 @@ export async function forwardSingleMessage(
let messageIdOut: number;
if (target.groupId) {
receipt = await ref.bridge.apis.message.sendGroup(target.groupId, elements);
messageIdOut = hashMessageIdInt32(receipt.sequence, target.groupId, GROUP_MESSAGE_EVENT);
ref.cacheMessageMeta(messageIdOut, {
isGroup: true,
targetId: target.groupId,
sequence: receipt.sequence,
eventName: GROUP_MESSAGE_EVENT,
clientSequence: receipt.clientSequence,
random: receipt.random,
timestamp: receipt.timestamp,
});
await cacheSelfSentMessage(ref, {
isGroup: true,
sessionId: target.groupId,
messageId: messageIdOut,
sequence: receipt.sequence,
timestamp: receipt.timestamp,
elements,
});
messageIdOut = await finalizeSend(ref, true, target.groupId, receipt, elements);
} else {
receipt = await ref.bridge.apis.message.sendPrivate(target.userId!, elements);
messageIdOut = hashMessageIdInt32(receipt.sequence, target.userId!, PRIVATE_MESSAGE_EVENT);
ref.cacheMessageMeta(messageIdOut, {
isGroup: false,
targetId: target.userId!,
sequence: receipt.sequence,
eventName: PRIVATE_MESSAGE_EVENT,
clientSequence: receipt.clientSequence,
random: receipt.random,
timestamp: receipt.timestamp,
});
await cacheSelfSentMessage(ref, {
isGroup: false,
sessionId: target.userId!,
messageId: messageIdOut,
sequence: receipt.sequence,
timestamp: receipt.timestamp,
elements,
});
messageIdOut = await finalizeSend(ref, false, target.userId!, receipt, elements);
}
return { messageId: messageIdOut };
+2 -7
View File
@@ -1,6 +1,5 @@
import fs from 'fs';
import { DatabaseSync, type StatementSync } from 'node:sqlite';
import path from 'path';
import { openSqliteDb } from './sqlite-open';
export class ReactionStore {
private readonly db: DatabaseSync;
@@ -11,11 +10,7 @@ export class ReactionStore {
private readonly stmtCountByEmoji: StatementSync;
constructor(dbPath: string) {
const dir = path.dirname(dbPath);
fs.mkdirSync(dir, { recursive: true });
this.db = new DatabaseSync(dbPath);
this.db.exec('PRAGMA journal_mode = WAL');
this.db.exec('PRAGMA synchronous = NORMAL');
this.db = openSqliteDb(dbPath);
this.initSchema();
this.stmtUpsert = this.db.prepare(
+21
View File
@@ -0,0 +1,21 @@
import fs from 'node:fs';
import path from 'node:path';
import { DatabaseSync } from 'node:sqlite';
/**
* Open a SQLite database with the store-wide defaults: ensure the parent
* directory exists, then open with WAL journaling + NORMAL synchronous — the
* durability/throughput balance the message / media / reaction stores all
* want. The caller owns schema init and any path munging.
*
* Concentrates the bootstrap each store previously hand-copied verbatim, so a
* PRAGMA / journal-mode / busy-timeout change lands in one place instead of
* three.
*/
export function openSqliteDb(dbPath: string): DatabaseSync {
fs.mkdirSync(path.dirname(dbPath), { recursive: true });
const db = new DatabaseSync(dbPath);
db.exec('PRAGMA journal_mode = WAL');
db.exec('PRAGMA synchronous = NORMAL');
return db;
}
@@ -6,6 +6,7 @@
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { ApiHandler } from '../src/api-handler';
import { OidbError } from '@snowluma/protocol/oidb-service';
import { subscribeLogs, type LogEntry } from '@snowluma/common/logger';
import { summarizeParams } from '@snowluma/common/log-summary';
@@ -108,6 +109,35 @@ describe('ApiHandler dispatch logging', () => {
expect(warn!.message).toMatch(/at\s+/);
});
// The single error seam (ADR-0006 narrow seam): any throw from a handler
// maps to ONE policy here — ACTION_FAILED (100) + the error message —
// instead of each action hand-rolling its own inconsistent try/catch.
it('maps any handler throw to ACTION_FAILED (100) with the error message', async () => {
const handler = new ApiHandler(emptyContext(), 12345);
handler.registerAction('kaboom', async () => { throw new Error('permission denied'); });
const result = await handler.handle('kaboom', {});
expect(result).toMatchObject({ status: 'failed', retcode: 100, wording: 'permission denied' });
});
it('surfaces the OidbError code + server message through error.message (no special-casing)', async () => {
const handler = new ApiHandler(emptyContext(), 12345);
handler.registerAction('oidb_boom', async () => { throw new OidbError(34, 'no permission', 0x11ec, 2); });
const result = await handler.handle('oidb_boom', {});
expect(result).toMatchObject({ status: 'failed', retcode: 100 });
expect((result as { wording: string }).wording).toContain('34');
expect((result as { wording: string }).wording).toContain('no permission');
});
it('renders a non-Error throw via String()', async () => {
const handler = new ApiHandler(emptyContext(), 12345);
handler.registerAction('weird', async () => { throw 'just a string'; });
const result = await handler.handle('weird', {});
expect(result).toMatchObject({ status: 'failed', retcode: 100, wording: 'just a string' });
});
it('logs unknown actions at debug level', async () => {
const handler = new ApiHandler(emptyContext(), 99);
await handler.handle('not_a_real_action', {});
@@ -0,0 +1,60 @@
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import fs from 'fs';
import os from 'os';
import path from 'path';
import { cleanupInvalidPerUinConfigs } from '../src/config';
// Issue #162: phantom accounts (garbage timestamp-shaped UIN) got persisted as
// config/onebot_<garbage>.json. Startup cleanup must delete exactly those and
// never touch legitimate per-UIN configs or the global onebot.json.
describe('cleanupInvalidPerUinConfigs', () => {
let tempDir: string;
let prevCwd: string;
beforeEach(() => {
tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-config-cleanup-'));
prevCwd = process.cwd();
process.chdir(tempDir);
fs.mkdirSync('config', { recursive: true });
});
afterEach(() => {
process.chdir(prevCwd);
fs.rmSync(tempDir, { recursive: true, force: true });
});
const write = (name: string) => fs.writeFileSync(path.join('config', name), '{}');
const exists = (name: string) => fs.existsSync(path.join('config', name));
it('deletes only per-UIN files whose UIN fails validation', () => {
write('onebot.json'); // global — must survive
write('onebot_123456789.json'); // legit 9-digit — must survive
write('onebot_4294967295.json'); // legit 10-digit — must survive
write('onebot_1701414379536.json'); // 13-digit phantom — must go
write('onebot_12345678901.json'); // 11-digit phantom — must go
write('snowluma.json'); // unrelated global — must survive
const removed = cleanupInvalidPerUinConfigs().sort();
expect(removed).toEqual(['onebot_12345678901.json', 'onebot_1701414379536.json']);
expect(exists('onebot.json')).toBe(true);
expect(exists('onebot_123456789.json')).toBe(true);
expect(exists('onebot_4294967295.json')).toBe(true);
expect(exists('snowluma.json')).toBe(true);
expect(exists('onebot_1701414379536.json')).toBe(false);
expect(exists('onebot_12345678901.json')).toBe(false);
});
it('is a no-op when there are no phantom files', () => {
write('onebot.json');
write('onebot_123456789.json');
expect(cleanupInvalidPerUinConfigs()).toEqual([]);
expect(exists('onebot_123456789.json')).toBe(true);
});
it('does not throw when the config dir is absent', () => {
fs.rmSync('config', { recursive: true, force: true });
expect(() => cleanupInvalidPerUinConfigs()).not.toThrow();
expect(cleanupInvalidPerUinConfigs()).toEqual([]);
});
});
@@ -0,0 +1,54 @@
import { describe, it, expect } from 'vitest';
import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import {
typesForDirection,
INPUT_SUGAR_SEGMENTS,
} from '@snowluma/protocol/element-manifest';
import { ELEMENT_CODECS } from '../src/event-converter/element-codecs';
// 对账测试(onebot 侧)—— 拿 element-manifest 核对「按 element.type 收敛」的两个
// onebot 方向。阶段 2 起这两向已合入 ELEMENT_CODECS 表,故直接用**表的键**核对,
// 比扫源码正则更硬:
// S 收·转 codec.toSegment MessageElement → OneBot 段
// P 发·解 codec.fromSegment OneBot 段 → MessageElement
// protocol 侧的 D/W 由 protocol/tests/element-manifest.test.ts 核对(包边界所限)。
//
// 架构护栏:谁在表里增删一个方向却没同步 element-manifest,测试当场报红。
function codecTypesWith(dir: 'toSegment' | 'fromSegment'): string[] {
return Object.entries(ELEMENT_CODECS)
.filter(([, codec]) => typeof codec[dir] === 'function')
.map(([type]) => type)
.sort();
}
const sorted = (s: Iterable<string>): string[] => [...s].sort();
describe('element-manifest 对账(onebot 侧:S 收·转 / P 发·解)', () => {
it('S:ELEMENT_CODECS 里有 toSegment 的类型 == 清单声明的 S=yes', () => {
expect(codecTypesWith('toSegment')).toEqual(sorted(typesForDirection('S')));
});
it('P:ELEMENT_CODECS 里有 fromSegment 的类型 == 清单声明的 P=yes', () => {
expect(codecTypesWith('fromSegment')).toEqual(sorted(typesForDirection('P')));
});
it('输入糖仍由 message-parser 前置处理,未被静默丢弃', () => {
// 输入糖(骰子/分享/…)不进 codec 表,留在 message-parser 当前置 normalize。
// 用源码扫描锁住它们确实存在,防止将来重构时被悄悄删掉。
const abs = fileURLToPath(new URL('../src/message-parser.ts', import.meta.url));
const src = readFileSync(abs, 'utf8')
.replace(/\/\*[\s\S]*?\*\//g, '')
.replace(/\/\/.*$/gm, '');
const cases = new Set<string>();
for (const m of src.matchAll(/case\s*'([A-Za-z0-9_]+)'\s*:/g)) cases.add(m[1]!);
const sugarPresent = [...cases].filter((t) => INPUT_SUGAR_SEGMENTS.has(t)).sort();
expect(sugarPresent).toEqual(sorted(INPUT_SUGAR_SEGMENTS));
// 且 message-parser 不再手写任何真实元素类型的 case(已全部下沉到 codec 表)。
const realLeftInParser = [...cases].filter((t) => !INPUT_SUGAR_SEGMENTS.has(t));
expect(realLeftInParser).toEqual([]);
});
});
+27 -2
View File
@@ -641,6 +641,31 @@ describe('extended-actions / get_group_shut_list', () => {
});
});
// ─── Wave 1: trans_group_file (0x6D9_0) ───
describe('extended-actions / trans_group_file', () => {
it('forwards group_id + file_id to apis.groupFile.trans and returns ok:true', async () => {
const trans = vi.fn(async () => ({ saveBusId: 102, saveFilePath: '/saved/path' }));
const bridge = fakeBridge({ apis: { groupFile: { trans } } });
const res = await makeHandler(fakeCtx(bridge)).handle('trans_group_file', {
group_id: 12345,
file_id: 'fid-trans',
});
expect(trans).toHaveBeenCalledWith(12345, 'fid-trans');
expect(res).toMatchObject({ status: 'ok', retcode: 0, data: { ok: true } });
});
it('rejects missing required params', async () => {
const trans = vi.fn();
const bridge = fakeBridge({ apis: { groupFile: { trans } } });
const r1 = await makeHandler(fakeCtx(bridge)).handle('trans_group_file', { file_id: 'fid' });
const r2 = await makeHandler(fakeCtx(bridge)).handle('trans_group_file', { group_id: 12345 });
expect(r1).toMatchObject({ status: 'failed', retcode: 1400 });
expect(r2).toMatchObject({ status: 'failed', retcode: 1400 });
expect(trans).not.toHaveBeenCalled();
});
});
// ─── Wave 1: get_file (compose image→record cache) ───
describe('extended-actions / get_file', () => {
@@ -705,13 +730,13 @@ describe('extended-actions / rename_group_file', () => {
expect(rename).not.toHaveBeenCalled();
});
it('surfaces oidb errors (handler maps a thrown error to INTERNAL_ERROR, as its sibling file ops do)', async () => {
it('surfaces oidb errors — a thrown error maps to the single seam (ACTION_FAILED 100 + message)', async () => {
const rename = vi.fn(async () => { throw new Error('rename rejected'); });
const bridge = fakeBridge({ apis: { groupFile: { rename } } });
const res = await makeHandler(fakeCtx(bridge)).handle('rename_group_file', {
group_id: 1, file_id: '/a', current_parent_directory: '/', new_name: 'x',
});
expect(res).toMatchObject({ status: 'failed', retcode: 1200, wording: 'rename rejected' });
expect(res).toMatchObject({ status: 'failed', retcode: 100, wording: 'rename rejected' });
});
});
+2 -2
View File
@@ -24,7 +24,7 @@ describe('qzone actions', () => {
expect(res).toMatchObject({ status: 'ok', retcode: 0, data: { tid: 'T1', time: 1 } });
expect(uploadImageFromSource).toHaveBeenNthCalledWith(1, 'file:///a.jpg');
expect(uploadImageFromSource).toHaveBeenNthCalledWith(2, 'file:///b.jpg');
expect(publish).toHaveBeenCalledWith('hello', 1, 'RV1\tRV2');
expect(publish).toHaveBeenCalledWith('hello', 1, 'RV1\tRV2', 1, undefined);
});
it('comment_qzone uploads images and comments direct urls joined with tab', async () => {
@@ -57,7 +57,7 @@ describe('qzone actions', () => {
images: ['file:///a.jpg', 'file:///b.jpg'],
});
expect(res).toMatchObject({ status: 'failed', retcode: 1200 });
expect(res).toMatchObject({ status: 'failed', retcode: 100 });
expect(res.wording).toContain('第 2 张图片上传失败: network down');
expect(publish).not.toHaveBeenCalled();
});
+4 -40
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/proto-defs",
"version": "1.11.0",
"version": "1.11.1",
"private": true,
"type": "module",
"description": "SnowLuma QQ/Lagrange wire-protobuf type definitions. Pure TypeScript interfaces with proton's `pb<N, T>` marker types — `@snowluma/proton`'s vite plugin compiles them into zero-runtime encoder/decoder functions at the call sites in `@snowluma/core` (and any downstream consumer). Exposed as per-file subpaths (`@snowluma/proto-defs/oidb`, `@snowluma/proto-defs/message`, …) so the import-site shape mirrors the legacy `bridge/proto/proton/*` layout and avoids name collisions across files (notably `highway.ts` and `oidb-actions/media.ts` share NTV2-prefixed names).",
@@ -56,45 +56,9 @@
"types": "./src/oidb-action.ts",
"default": "./src/oidb-action.ts"
},
"./oidb-actions/base": {
"types": "./src/oidb-actions/base.ts",
"default": "./src/oidb-actions/base.ts"
},
"./oidb-actions/contact-ark": {
"types": "./src/oidb-actions/contact-ark.ts",
"default": "./src/oidb-actions/contact-ark.ts"
},
"./oidb-actions/doubt-buddy": {
"types": "./src/oidb-actions/doubt-buddy.ts",
"default": "./src/oidb-actions/doubt-buddy.ts"
},
"./oidb-actions/group-ext": {
"types": "./src/oidb-actions/group-ext.ts",
"default": "./src/oidb-actions/group-ext.ts"
},
"./oidb-actions/group-album": {
"types": "./src/oidb-actions/group-album.ts",
"default": "./src/oidb-actions/group-album.ts"
},
"./oidb-actions/group-file": {
"types": "./src/oidb-actions/group-file.ts",
"default": "./src/oidb-actions/group-file.ts"
},
"./oidb-actions/flash-transfer": {
"types": "./src/oidb-actions/flash-transfer.ts",
"default": "./src/oidb-actions/flash-transfer.ts"
},
"./oidb-actions/media": {
"types": "./src/oidb-actions/media.ts",
"default": "./src/oidb-actions/media.ts"
},
"./oidb-actions/ocr": {
"types": "./src/oidb-actions/ocr.ts",
"default": "./src/oidb-actions/ocr.ts"
},
"./oidb-actions/sys-faces": {
"types": "./src/oidb-actions/sys-faces.ts",
"default": "./src/oidb-actions/sys-faces.ts"
"./oidb-actions/*": {
"types": "./src/oidb-actions/*.ts",
"default": "./src/oidb-actions/*.ts"
}
},
"scripts": {
@@ -132,6 +132,19 @@ export interface OidbGroupFileResp {
rename?: pb<5, OidbGroupFileRetResp>;
move?: pb<6, OidbGroupFileRetResp>;
}
export interface OidbGroupTransFileReq {
groupUin?: pb<1, uint_64>;
appId?: pb<2, uint_32>;
busId?: pb<3, uint_32>;
fileId?: pb<4, string>;
}
export interface OidbGroupTransFileResp {
retCode?: pb<1, int_32>;
retMsg?: pb<2, string>;
clientWording?: pb<3, string>;
saveBusId?: pb<4, uint_32>;
saveFilePath?: pb<5, string>;
}
export interface OidbGroupSendFileInfo {
busiType?: pb<1, uint_32>;
fileId?: pb<2, string>;
@@ -145,8 +158,12 @@ export interface OidbGroupSendFileBody {
info?: pb<3, OidbGroupSendFileInfo>;
}
export interface OidbGroupSendFileReq {
transFile?: pb<1, OidbGroupTransFileReq>;
body?: pb<5, OidbGroupSendFileBody>;
}
export interface OidbGroupSendFileResp {
transFile?: pb<1, OidbGroupTransFileResp>;
}
export interface OidbGroupFileCreateFolderReq {
groupUin?: pb<1, uint_32>;
rootDirectory?: pb<3, string>;
+21 -425
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/protocol",
"version": "1.11.0",
"version": "1.11.1",
"private": true,
"type": "module",
"description": "SnowLuma protocol — 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/protocol/<x>'`.",
@@ -32,6 +32,14 @@
"types": "./src/element-builder.ts",
"default": "./src/element-builder.ts"
},
"./element-manifest": {
"types": "./src/element-manifest.ts",
"default": "./src/element-manifest.ts"
},
"./self-uid": {
"types": "./src/self-uid.ts",
"default": "./src/self-uid.ts"
},
"./bridge-oidb": {
"types": "./src/bridge-oidb.ts",
"default": "./src/bridge-oidb.ts"
@@ -40,365 +48,9 @@
"types": "./src/oidb-service.ts",
"default": "./src/oidb-service.ts"
},
"./oidb-services/reaction/set-reaction": {
"types": "./src/oidb-services/reaction/set-reaction.ts",
"default": "./src/oidb-services/reaction/set-reaction.ts"
},
"./oidb-services/reaction/fetch-reaction-summary": {
"types": "./src/oidb-services/reaction/fetch-reaction-summary.ts",
"default": "./src/oidb-services/reaction/fetch-reaction-summary.ts"
},
"./oidb-services/reaction/get-emoji-likes": {
"types": "./src/oidb-services/reaction/get-emoji-likes.ts",
"default": "./src/oidb-services/reaction/get-emoji-likes.ts"
},
"./oidb-services/custom-face/delete-custom-face": {
"types": "./src/oidb-services/custom-face/delete-custom-face.ts",
"default": "./src/oidb-services/custom-face/delete-custom-face.ts"
},
"./oidb-services/custom-face/add-custom-face": {
"types": "./src/oidb-services/custom-face/add-custom-face.ts",
"default": "./src/oidb-services/custom-face/add-custom-face.ts"
},
"./oidb-services/custom-face/modify-custom-face": {
"types": "./src/oidb-services/custom-face/modify-custom-face.ts",
"default": "./src/oidb-services/custom-face/modify-custom-face.ts"
},
"./oidb-services/custom-face/move-custom-face": {
"types": "./src/oidb-services/custom-face/move-custom-face.ts",
"default": "./src/oidb-services/custom-face/move-custom-face.ts"
},
"./oidb-services/custom-face/order-custom-face": {
"types": "./src/oidb-services/custom-face/order-custom-face.ts",
"default": "./src/oidb-services/custom-face/order-custom-face.ts"
},
"./oidb-services/flash-transfer/get-fileset-detail": {
"types": "./src/oidb-services/flash-transfer/get-fileset-detail.ts",
"default": "./src/oidb-services/flash-transfer/get-fileset-detail.ts"
},
"./oidb-services/flash-transfer/list-filesets": {
"types": "./src/oidb-services/flash-transfer/list-filesets.ts",
"default": "./src/oidb-services/flash-transfer/list-filesets.ts"
},
"./oidb-services/flash-transfer/get-download-url": {
"types": "./src/oidb-services/flash-transfer/get-download-url.ts",
"default": "./src/oidb-services/flash-transfer/get-download-url.ts"
},
"./oidb-services/flash-transfer/delete-file": {
"types": "./src/oidb-services/flash-transfer/delete-file.ts",
"default": "./src/oidb-services/flash-transfer/delete-file.ts"
},
"./oidb-services/flash-transfer/rename-file": {
"types": "./src/oidb-services/flash-transfer/rename-file.ts",
"default": "./src/oidb-services/flash-transfer/rename-file.ts"
},
"./oidb-services/flash-transfer/apply-fileset": {
"types": "./src/oidb-services/flash-transfer/apply-fileset.ts",
"default": "./src/oidb-services/flash-transfer/apply-fileset.ts"
},
"./oidb-services/flash-transfer/commit-file": {
"types": "./src/oidb-services/flash-transfer/commit-file.ts",
"default": "./src/oidb-services/flash-transfer/commit-file.ts"
},
"./oidb-services/flash-transfer/complete-fileset": {
"types": "./src/oidb-services/flash-transfer/complete-fileset.ts",
"default": "./src/oidb-services/flash-transfer/complete-fileset.ts"
},
"./oidb-services/flash-transfer/set-status": {
"types": "./src/oidb-services/flash-transfer/set-status.ts",
"default": "./src/oidb-services/flash-transfer/set-status.ts"
},
"./oidb-services/flash-transfer/apply-upload": {
"types": "./src/oidb-services/flash-transfer/apply-upload.ts",
"default": "./src/oidb-services/flash-transfer/apply-upload.ts"
},
"./oidb-services/flash-transfer/prepare-upload": {
"types": "./src/oidb-services/flash-transfer/prepare-upload.ts",
"default": "./src/oidb-services/flash-transfer/prepare-upload.ts"
},
"./oidb-services/flash-transfer/send-flash": {
"types": "./src/oidb-services/flash-transfer/send-flash.ts",
"default": "./src/oidb-services/flash-transfer/send-flash.ts"
},
"./oidb-services/flash-transfer/get-flash-download": {
"types": "./src/oidb-services/flash-transfer/get-flash-download.ts",
"default": "./src/oidb-services/flash-transfer/get-flash-download.ts"
},
"./oidb-services/interaction/send-poke": {
"types": "./src/oidb-services/interaction/send-poke.ts",
"default": "./src/oidb-services/interaction/send-poke.ts"
},
"./oidb-services/interaction/send-like": {
"types": "./src/oidb-services/interaction/send-like.ts",
"default": "./src/oidb-services/interaction/send-like.ts"
},
"./oidb-services/interaction/set-essence": {
"types": "./src/oidb-services/interaction/set-essence.ts",
"default": "./src/oidb-services/interaction/set-essence.ts"
},
"./oidb-services/profile/set-profile": {
"types": "./src/oidb-services/profile/set-profile.ts",
"default": "./src/oidb-services/profile/set-profile.ts"
},
"./oidb-services/profile/set-self-long-nick": {
"types": "./src/oidb-services/profile/set-self-long-nick.ts",
"default": "./src/oidb-services/profile/set-self-long-nick.ts"
},
"./oidb-services/profile/set-input-status": {
"types": "./src/oidb-services/profile/set-input-status.ts",
"default": "./src/oidb-services/profile/set-input-status.ts"
},
"./oidb-services/profile/get-like": {
"types": "./src/oidb-services/profile/get-like.ts",
"default": "./src/oidb-services/profile/get-like.ts"
},
"./oidb-services/profile/get-unidirectional-friend-list": {
"types": "./src/oidb-services/profile/get-unidirectional-friend-list.ts",
"default": "./src/oidb-services/profile/get-unidirectional-friend-list.ts"
},
"./oidb-services/friend/handle-friend-request": {
"types": "./src/oidb-services/friend/handle-friend-request.ts",
"default": "./src/oidb-services/friend/handle-friend-request.ts"
},
"./oidb-services/friend/get-doubt-buddy-req": {
"types": "./src/oidb-services/friend/get-doubt-buddy-req.ts",
"default": "./src/oidb-services/friend/get-doubt-buddy-req.ts"
},
"./oidb-services/friend/approve-doubt-buddy-req": {
"types": "./src/oidb-services/friend/approve-doubt-buddy-req.ts",
"default": "./src/oidb-services/friend/approve-doubt-buddy-req.ts"
},
"./oidb-services/friend/reject-doubt-buddy-req": {
"types": "./src/oidb-services/friend/reject-doubt-buddy-req.ts",
"default": "./src/oidb-services/friend/reject-doubt-buddy-req.ts"
},
"./oidb-services/contacts/get-buddy-recommend-ark": {
"types": "./src/oidb-services/contacts/get-buddy-recommend-ark.ts",
"default": "./src/oidb-services/contacts/get-buddy-recommend-ark.ts"
},
"./oidb-services/contacts/get-group-recommend-ark": {
"types": "./src/oidb-services/contacts/get-group-recommend-ark.ts",
"default": "./src/oidb-services/contacts/get-group-recommend-ark.ts"
},
"./oidb-services/group-admin/modify-group-ext-info": {
"types": "./src/oidb-services/group-admin/modify-group-ext-info.ts",
"default": "./src/oidb-services/group-admin/modify-group-ext-info.ts"
},
"./oidb-services/friend/delete-friend": {
"types": "./src/oidb-services/friend/delete-friend.ts",
"default": "./src/oidb-services/friend/delete-friend.ts"
},
"./oidb-services/friend/set-friend-remark": {
"types": "./src/oidb-services/friend/set-friend-remark.ts",
"default": "./src/oidb-services/friend/set-friend-remark.ts"
},
"./oidb-services/misc/translate-en-to-zh": {
"types": "./src/oidb-services/misc/translate-en-to-zh.ts",
"default": "./src/oidb-services/misc/translate-en-to-zh.ts"
},
"./oidb-services/misc/image-ocr": {
"types": "./src/oidb-services/misc/image-ocr.ts",
"default": "./src/oidb-services/misc/image-ocr.ts"
},
"./oidb-services/misc/click-inline-keyboard-button": {
"types": "./src/oidb-services/misc/click-inline-keyboard-button.ts",
"default": "./src/oidb-services/misc/click-inline-keyboard-button.ts"
},
"./oidb-services/misc/send-group-sign": {
"types": "./src/oidb-services/misc/send-group-sign.ts",
"default": "./src/oidb-services/misc/send-group-sign.ts"
},
"./oidb-services/misc/request-decrypt-key": {
"types": "./src/oidb-services/misc/request-decrypt-key.ts",
"default": "./src/oidb-services/misc/request-decrypt-key.ts"
},
"./oidb-services/web/force-fetch-client-key": {
"types": "./src/oidb-services/web/force-fetch-client-key.ts",
"default": "./src/oidb-services/web/force-fetch-client-key.ts"
},
"./oidb-services/web/get-pskey": {
"types": "./src/oidb-services/web/get-pskey.ts",
"default": "./src/oidb-services/web/get-pskey.ts"
},
"./oidb-services/extras/group-todo": {
"types": "./src/oidb-services/extras/group-todo.ts",
"default": "./src/oidb-services/extras/group-todo.ts"
},
"./oidb-services/extras/get-stranger-status": {
"types": "./src/oidb-services/extras/get-stranger-status.ts",
"default": "./src/oidb-services/extras/get-stranger-status.ts"
},
"./oidb-services/extras/fetch-ai-voice-list": {
"types": "./src/oidb-services/extras/fetch-ai-voice-list.ts",
"default": "./src/oidb-services/extras/fetch-ai-voice-list.ts"
},
"./oidb-services/extras/fetch-ai-voice": {
"types": "./src/oidb-services/extras/fetch-ai-voice.ts",
"default": "./src/oidb-services/extras/fetch-ai-voice.ts"
},
"./oidb-services/contacts/fetch-friend-list-page": {
"types": "./src/oidb-services/contacts/fetch-friend-list-page.ts",
"default": "./src/oidb-services/contacts/fetch-friend-list-page.ts"
},
"./oidb-services/contacts/fetch-group-detail": {
"types": "./src/oidb-services/contacts/fetch-group-detail.ts",
"default": "./src/oidb-services/contacts/fetch-group-detail.ts"
},
"./oidb-services/contacts/fetch-group-list": {
"types": "./src/oidb-services/contacts/fetch-group-list.ts",
"default": "./src/oidb-services/contacts/fetch-group-list.ts"
},
"./oidb-services/contacts/fetch-group-member-list-page": {
"types": "./src/oidb-services/contacts/fetch-group-member-list-page.ts",
"default": "./src/oidb-services/contacts/fetch-group-member-list-page.ts"
},
"./oidb-services/contacts/fetch-user-profile": {
"types": "./src/oidb-services/contacts/fetch-user-profile.ts",
"default": "./src/oidb-services/contacts/fetch-user-profile.ts"
},
"./oidb-services/contacts/fetch-user-profile-by-uid": {
"types": "./src/oidb-services/contacts/fetch-user-profile-by-uid.ts",
"default": "./src/oidb-services/contacts/fetch-user-profile-by-uid.ts"
},
"./oidb-services/contacts/fetch-group-requests": {
"types": "./src/oidb-services/contacts/fetch-group-requests.ts",
"default": "./src/oidb-services/contacts/fetch-group-requests.ts"
},
"./oidb-services/contacts/fetch-download-rkeys": {
"types": "./src/oidb-services/contacts/fetch-download-rkeys.ts",
"default": "./src/oidb-services/contacts/fetch-download-rkeys.ts"
},
"./oidb-services/group-admin/mute-member": {
"types": "./src/oidb-services/group-admin/mute-member.ts",
"default": "./src/oidb-services/group-admin/mute-member.ts"
},
"./oidb-services/group-admin/mute-all": {
"types": "./src/oidb-services/group-admin/mute-all.ts",
"default": "./src/oidb-services/group-admin/mute-all.ts"
},
"./oidb-services/group-admin/set-add-option": {
"types": "./src/oidb-services/group-admin/set-add-option.ts",
"default": "./src/oidb-services/group-admin/set-add-option.ts"
},
"./oidb-services/group-admin/set-search": {
"types": "./src/oidb-services/group-admin/set-search.ts",
"default": "./src/oidb-services/group-admin/set-search.ts"
},
"./oidb-services/group-admin/set-add-request": {
"types": "./src/oidb-services/group-admin/set-add-request.ts",
"default": "./src/oidb-services/group-admin/set-add-request.ts"
},
"./oidb-services/group-admin/kick-member": {
"types": "./src/oidb-services/group-admin/kick-member.ts",
"default": "./src/oidb-services/group-admin/kick-member.ts"
},
"./oidb-services/group-admin/kick-members": {
"types": "./src/oidb-services/group-admin/kick-members.ts",
"default": "./src/oidb-services/group-admin/kick-members.ts"
},
"./oidb-services/group-admin/leave-group": {
"types": "./src/oidb-services/group-admin/leave-group.ts",
"default": "./src/oidb-services/group-admin/leave-group.ts"
},
"./oidb-services/group-admin/set-admin": {
"types": "./src/oidb-services/group-admin/set-admin.ts",
"default": "./src/oidb-services/group-admin/set-admin.ts"
},
"./oidb-services/group-admin/set-member-card": {
"types": "./src/oidb-services/group-admin/set-member-card.ts",
"default": "./src/oidb-services/group-admin/set-member-card.ts"
},
"./oidb-services/group-admin/set-group-name": {
"types": "./src/oidb-services/group-admin/set-group-name.ts",
"default": "./src/oidb-services/group-admin/set-group-name.ts"
},
"./oidb-services/group-admin/set-special-title": {
"types": "./src/oidb-services/group-admin/set-special-title.ts",
"default": "./src/oidb-services/group-admin/set-special-title.ts"
},
"./oidb-services/group-admin/set-group-remark": {
"types": "./src/oidb-services/group-admin/set-group-remark.ts",
"default": "./src/oidb-services/group-admin/set-group-remark.ts"
},
"./oidb-services/group-admin/get-at-all-remain": {
"types": "./src/oidb-services/group-admin/get-at-all-remain.ts",
"default": "./src/oidb-services/group-admin/get-at-all-remain.ts"
},
"./oidb-services/shared": {
"types": "./src/oidb-services/shared.ts",
"default": "./src/oidb-services/shared.ts"
},
"./oidb-services/group-file/publish-group-file": {
"types": "./src/oidb-services/group-file/publish-group-file.ts",
"default": "./src/oidb-services/group-file/publish-group-file.ts"
},
"./oidb-services/group-file/get-group-file-count": {
"types": "./src/oidb-services/group-file/get-group-file-count.ts",
"default": "./src/oidb-services/group-file/get-group-file-count.ts"
},
"./oidb-services/group-file/upload-group-file-request": {
"types": "./src/oidb-services/group-file/upload-group-file-request.ts",
"default": "./src/oidb-services/group-file/upload-group-file-request.ts"
},
"./oidb-services/group-file/upload-private-file-request": {
"types": "./src/oidb-services/group-file/upload-private-file-request.ts",
"default": "./src/oidb-services/group-file/upload-private-file-request.ts"
},
"./oidb-services/group-file/finalize-offline-file": {
"types": "./src/oidb-services/group-file/finalize-offline-file.ts",
"default": "./src/oidb-services/group-file/finalize-offline-file.ts"
},
"./oidb-services/group-file/list-group-files-page": {
"types": "./src/oidb-services/group-file/list-group-files-page.ts",
"default": "./src/oidb-services/group-file/list-group-files-page.ts"
},
"./oidb-services/group-file/get-group-file-url": {
"types": "./src/oidb-services/group-file/get-group-file-url.ts",
"default": "./src/oidb-services/group-file/get-group-file-url.ts"
},
"./oidb-services/group-file/get-private-file-url": {
"types": "./src/oidb-services/group-file/get-private-file-url.ts",
"default": "./src/oidb-services/group-file/get-private-file-url.ts"
},
"./oidb-services/group-file/delete-group-file": {
"types": "./src/oidb-services/group-file/delete-group-file.ts",
"default": "./src/oidb-services/group-file/delete-group-file.ts"
},
"./oidb-services/group-file/move-group-file": {
"types": "./src/oidb-services/group-file/move-group-file.ts",
"default": "./src/oidb-services/group-file/move-group-file.ts"
},
"./oidb-services/group-file/rename-group-file": {
"types": "./src/oidb-services/group-file/rename-group-file.ts",
"default": "./src/oidb-services/group-file/rename-group-file.ts"
},
"./oidb-services/group-file/create-group-folder": {
"types": "./src/oidb-services/group-file/create-group-folder.ts",
"default": "./src/oidb-services/group-file/create-group-folder.ts"
},
"./oidb-services/group-file/delete-group-folder": {
"types": "./src/oidb-services/group-file/delete-group-folder.ts",
"default": "./src/oidb-services/group-file/delete-group-folder.ts"
},
"./oidb-services/group-file/rename-group-folder": {
"types": "./src/oidb-services/group-file/rename-group-folder.ts",
"default": "./src/oidb-services/group-file/rename-group-folder.ts"
},
"./oidb-services/group-file/get-group-ptt-url": {
"types": "./src/oidb-services/group-file/get-group-ptt-url.ts",
"default": "./src/oidb-services/group-file/get-group-ptt-url.ts"
},
"./oidb-services/group-file/get-private-ptt-url": {
"types": "./src/oidb-services/group-file/get-private-ptt-url.ts",
"default": "./src/oidb-services/group-file/get-private-ptt-url.ts"
},
"./oidb-services/group-file/get-group-video-url": {
"types": "./src/oidb-services/group-file/get-group-video-url.ts",
"default": "./src/oidb-services/group-file/get-group-video-url.ts"
},
"./oidb-services/group-file/get-private-video-url": {
"types": "./src/oidb-services/group-file/get-private-video-url.ts",
"default": "./src/oidb-services/group-file/get-private-video-url.ts"
"./oidb-services/*": {
"types": "./src/oidb-services/*.ts",
"default": "./src/oidb-services/*.ts"
},
"./bridge-context": {
"types": "./src/bridge-context.ts",
@@ -416,77 +68,21 @@
"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"
"./msg-push/*": {
"types": "./src/msg-push/*.ts",
"default": "./src/msg-push/*.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/*": {
"types": "./src/highway/*.ts",
"default": "./src/highway/*.ts"
},
"./highway/sha1-stream": {
"types": "./src/highway/sha1-stream.ts",
"default": "./src/highway/sha1-stream.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/group-signin": {
"types": "./src/web/group-signin.ts",
"default": "./src/web/group-signin.ts"
},
"./web/qzone": {
"types": "./src/web/qzone.ts",
"default": "./src/web/qzone.ts"
},
"./web/request-util": {
"types": "./src/web/request-util.ts",
"default": "./src/web/request-util.ts"
"./web/*": {
"types": "./src/web/*.ts",
"default": "./src/web/*.ts"
}
},
"scripts": {
+137
View File
@@ -0,0 +1,137 @@
/**
* 消息元素「四向」对账清单 —— 单一权威。
*
* 一种消息元素(文字/图片/戳一戳/商城表情…)要在两个流向、共 4 处处理,散在
* 不同文件、不同包。历史上这 4 处各写各的、没人对账,导致字段名对不上、漏写
* 方向无人知(都走运行时兜底 `default`,悄悄失败)。
*
* 本清单声明「每种元素类型应支持哪几个方向」,配套的两道对账测试
* (`protocol/tests/element-manifest.test.ts` 与 `onebot/tests/element-manifest.test.ts`,
* 因包边界拆两处、共用本清单)拿它逐一核对那 4 处代码 —— 漏写或多写一个方向
* 立即报红,而不再是运行时静默。
*
* 四个方向:
* D 收·解 QQ 原始数据 → MessageElement `protocol/msg-push/rich-body-decoder.ts`
* S 收·转 MessageElement → OneBot 段 `onebot/event-converter/to-segment.ts`
* P 发·解 OneBot 段 → MessageElement `onebot/message-parser.ts`
* W 发·打包 MessageElement → QQ 原始数据 `protocol/element-builder.ts`
*
* 注:D(收·解)按 proto 字段分派、一字段可扇出多种元素、多字段可收敛为一种,
* 与另外三个「按 element.type 分派」的方向异构,故它保持独立开关、不进 onebot
* 侧的合并表;但它产出的元素类型集合仍受本清单核对。
*
* 取值语义:
* 'yes' 该方向有对应处理。
* 'no' 该方向暂无(记录在案的缺口,本次重构不补,另立任务再议)。
* 'by-design-no' 该方向按设计不支持(QQ 协议限制),缺席是正确的。
*/
export const ELEMENT_DIRECTIONS = ['D', 'S', 'P', 'W'] as const;
export type ElementDirection = (typeof ELEMENT_DIRECTIONS)[number];
export type DirectionSupport = 'yes' | 'no' | 'by-design-no';
export interface ElementSpec {
/** 每个方向的支持状态。 */
readonly directions: Readonly<Record<ElementDirection, DirectionSupport>>;
/**
* 该元素类型在 `MessageElement` 上「属于自己」的字段 —— 字段契约的文档基准,
* 供各方向读写时对齐(例如 poke 统一用 `subType`,不再收侧 `subType` / 发侧
* `faceId` 打架)。当前为文档性声明,字段级强制留待后续阶段。
*/
readonly fields: readonly string[];
/** 备注:媒体上传、三角映射、协议限制等需要跨方向知道的事。 */
readonly note?: string;
}
/**
* 全部规范元素类型 × 四向支持。此表须与那 4 处派发代码逐字一致,否则对账测试报红。
*/
export const ELEMENT_MANIFEST = {
text: {
directions: { D: 'yes', S: 'yes', P: 'yes', W: 'yes' },
fields: ['text'],
},
at: {
directions: { D: 'yes', S: 'yes', P: 'yes', W: 'yes' },
fields: ['targetUin', 'uid', 'text'],
},
face: {
directions: { D: 'yes', S: 'yes', P: 'yes', W: 'yes' },
fields: ['faceId'],
},
reply: {
directions: { D: 'yes', S: 'yes', P: 'yes', W: 'yes' },
fields: ['replySeq', 'replyMessageId', 'replySenderUin', 'replyTime', 'replyRandom', 'replyElements'],
},
json: {
directions: { D: 'yes', S: 'yes', P: 'yes', W: 'yes' },
fields: ['text'],
},
xml: {
directions: { D: 'yes', S: 'yes', P: 'yes', W: 'yes' },
fields: ['text', 'subType'],
},
forward: {
directions: { D: 'yes', S: 'yes', P: 'yes', W: 'yes' },
fields: ['resId', 'forwardSource', 'forwardSummary', 'forwardPrompt', 'forwardNews', 'forwardTSum', 'forwardUuid'],
},
image: {
directions: { D: 'yes', S: 'yes', P: 'yes', W: 'yes' },
fields: ['imageUrl', 'fileId', 'fileName', 'fileSize', 'url', 'subType', 'summary', 'width', 'height', 'flash', 'md5Hex', 'sha1Hex', 'picFormat', 'noByteFallback', 'mediaNode'],
note: 'media:W(打包)经 highway 上传、异步,需 SendContext',
},
record: {
directions: { D: 'yes', S: 'yes', P: 'yes', W: 'yes' },
fields: ['fileName', 'fileId', 'url', 'duration', 'fileSize', 'md5Hex', 'sha1Hex', 'voiceFormat', 'noByteFallback', 'mediaNode'],
note: 'media',
},
video: {
directions: { D: 'yes', S: 'yes', P: 'yes', W: 'yes' },
fields: ['fileName', 'fileId', 'url', 'thumbUrl', 'thumbFileId', 'duration', 'width', 'height', 'fileSize', 'md5Hex', 'sha1Hex', 'videoFormat', 'noByteFallback', 'mediaNode'],
note: 'media',
},
mface: {
directions: { D: 'yes', S: 'yes', P: 'yes', W: 'yes' },
fields: ['emojiId', 'emojiPackageId', 'emojiKey', 'text', 'summary'],
note: '商城表情三角:S(转 OneBot)输出 image 段并挂 emoji_id/emoji_package_id/key 标记,P(解)再从该 image 段认回',
},
file: {
directions: { D: 'yes', S: 'yes', P: 'yes', W: 'yes' },
fields: ['fileId', 'thumbFileId', 'fileName', 'fileSize', 'url', 'fileHash', 'md5Hex', 'sha1Hex', 'resId'],
note: 'W 特殊:live-send 在 OneBot 层被拆走走独立上传管线,仅 forwardFake 时落 transElem(24)',
},
poke: {
directions: { D: 'yes', S: 'yes', P: 'yes', W: 'by-design-no' },
fields: ['subType'],
note: 'QQ 不允许戳一戳当消息段发送,故 W(打包)按设计不支持;戳一戳作为独立动作走 OIDB send-poke,与本表无关。字段契约以收侧既有 subType 为准',
},
markdown: {
directions: { D: 'no', S: 'no', P: 'yes', W: 'yes' },
fields: ['text'],
note: '收侧(D/S)无对应,仅发送方向存在',
},
} as const satisfies Record<string, ElementSpec>;
export type ElementType = keyof typeof ELEMENT_MANIFEST;
/**
* 某方向应被处理的元素类型集合(`directions[dir] === 'yes'`)—— 对账测试的基准。
*/
export function typesForDirection(dir: ElementDirection): Set<string> {
const out = new Set<string>();
for (const [type, spec] of Object.entries(ELEMENT_MANIFEST)) {
if (spec.directions[dir] === 'yes') out.add(type);
}
return out;
}
/**
* 发·解(P)侧还接收一批「纯 OneBot 输入糖」:它们不是某种真实消息元素,只是被
* 塌缩成 json / face / poke 的输入便利(如骰子、猜拳、位置/音乐/名片分享、转发
* node、匿名标记),没有收侧对应,也没有专属的 wire 形态,故不进本清单。对账 P
* 时须先从代码里剔除这些类型。
*/
export const INPUT_SUGAR_SEGMENTS: ReadonlySet<string> = new Set([
'node', 'share', 'music', 'location', 'contact', 'rps', 'dice', 'shake', 'anonymous',
]);
+16 -131
View File
@@ -18,6 +18,7 @@ import {
loadBinarySource,
resolveLocalFilePath,
} from './utils';
import { Sha1Stream } from './sha1-stream';
const moduleLog = createLogger('Highway.Video');
@@ -35,6 +36,7 @@ export const GROUP_VIDEO_THUMB_CMD_ID = 1006;
export const MAX_VIDEO_SIZE = 100 * 1024 * 1024;
const MAX_VIDEO_SIZE_HARD = 1536 * 1024 * 1024;
const SHA1_STREAM_BLOCK_SIZE = 1024 * 1024;
const SHA1_BLOCK_SIZE = 64;
export function getVideoSourceSize(element: MessageElement): number | null {
if (element.fileSize && element.fileSize > 0) return element.fileSize;
@@ -123,143 +125,26 @@ interface ThumbPayload {
// ─────────────── 1MB-block sha1 (Highway main-video extend) ───────────────
// Highway expects sha1 computed over each 1 MB block of the file, plus
// the final overall sha1. This is a streaming implementation that doesn't
// reuse Node's crypto because Node only exposes the final digest.
class Sha1StreamState {
readonly blockSize = 64;
private readonly padding = Buffer.concat([Buffer.from([0x80]), Buffer.alloc(63)]);
private readonly state = new Uint32Array(5);
private readonly count = new Uint32Array(2);
private readonly buffer = Buffer.allocUnsafe(this.blockSize);
private readonly w = new Uint32Array(80);
constructor() {
this.reset();
}
private reset(): void {
this.state[0] = 0x67452301;
this.state[1] = 0xEFCDAB89;
this.state[2] = 0x98BADCFE;
this.state[3] = 0x10325476;
this.state[4] = 0xC3D2E1F0;
this.count[0] = 0;
this.count[1] = 0;
this.buffer.fill(0);
}
private rotateLeft(value: number, offset: number): number {
return ((value << offset) | (value >>> (32 - offset))) >>> 0;
}
private transform(chunk: Uint8Array, offset: number): void {
const view = new DataView(chunk.buffer, chunk.byteOffset + offset, this.blockSize);
for (let i = 0; i < 16; i++) {
this.w[i] = view.getUint32(i * 4, false);
}
for (let i = 16; i < 80; i++) {
this.w[i] = this.rotateLeft(this.w[i - 3] ^ this.w[i - 8] ^ this.w[i - 14] ^ this.w[i - 16], 1);
}
let a = this.state[0];
let b = this.state[1];
let c = this.state[2];
let d = this.state[3];
let e = this.state[4];
for (let i = 0; i < 80; i++) {
let temp: number;
if (i < 20) {
temp = ((b & c) | (~b & d)) + 0x5A827999;
} else if (i < 40) {
temp = (b ^ c ^ d) + 0x6ED9EBA1;
} else if (i < 60) {
temp = ((b & c) | (b & d) | (c & d)) + 0x8F1BBCDC;
} else {
temp = (b ^ c ^ d) + 0xCA62C1D6;
}
temp += (this.rotateLeft(a, 5) + e + this.w[i]) >>> 0;
e = d;
d = c;
c = this.rotateLeft(b, 30);
b = a;
a = temp >>> 0;
}
this.state[0] = (this.state[0] + a) >>> 0;
this.state[1] = (this.state[1] + b) >>> 0;
this.state[2] = (this.state[2] + c) >>> 0;
this.state[3] = (this.state[3] + d) >>> 0;
this.state[4] = (this.state[4] + e) >>> 0;
}
update(data: Uint8Array): void {
let index = (this.count[0] >>> 3) & 0x3F;
const dataLen = data.length;
this.count[0] = (this.count[0] + (dataLen << 3)) >>> 0;
if (this.count[0] < (dataLen << 3)) this.count[1] = (this.count[1] + 1) >>> 0;
this.count[1] = (this.count[1] + (dataLen >>> 29)) >>> 0;
const partLen = this.blockSize - index;
let i = 0;
if (dataLen >= partLen) {
this.buffer.set(data.subarray(0, partLen), index);
this.transform(this.buffer, 0);
for (i = partLen; i + this.blockSize <= dataLen; i += this.blockSize) {
this.transform(data, i);
}
index = 0;
}
if (i < dataLen) {
this.buffer.set(data.subarray(i, dataLen), index);
}
}
hash(bigEndian = true): Uint8Array {
const digest = Buffer.allocUnsafe(20);
for (let i = 0; i < 5; i++) {
if (bigEndian) digest.writeUInt32BE(this.state[i], i * 4);
else digest.writeUInt32LE(this.state[i], i * 4);
}
return new Uint8Array(digest);
}
final(): Uint8Array {
const bits = Buffer.allocUnsafe(8);
bits.writeUInt32BE(this.count[1], 0);
bits.writeUInt32BE(this.count[0], 4);
const index = (this.count[0] >>> 3) & 0x3F;
const padLen = index < 56 ? 56 - index : 120 - index;
this.update(this.padding.subarray(0, padLen));
this.update(bits);
return this.hash(true);
}
}
function computeVideoSha1Blocks(bytes: Uint8Array): Uint8Array[] {
const sha1 = new Sha1StreamState();
// Highway expects the sha1 of each 1 MB block (intermediate un-finalized state,
// little-endian) plus the overall sha1. Reuses the well-tested streaming
// Sha1Stream for the block states and Node crypto for the overall digest (same
// split as computeSha1StateV), replacing a ~110-line hand-rolled, untested
// SHA1 duplicate.
export function computeVideoSha1Blocks(bytes: Uint8Array): Uint8Array[] {
const sha1 = new Sha1Stream();
const blocks: Uint8Array[] = [];
let bytesRead = 0;
let offset = 0;
while (offset + sha1.blockSize <= bytes.length) {
const block = bytes.subarray(offset, offset + sha1.blockSize);
sha1.update(block);
offset += sha1.blockSize;
bytesRead += sha1.blockSize;
while (offset + SHA1_BLOCK_SIZE <= bytes.length) {
sha1.update(bytes.subarray(offset, offset + SHA1_BLOCK_SIZE));
offset += SHA1_BLOCK_SIZE;
bytesRead += SHA1_BLOCK_SIZE;
if (bytesRead % SHA1_STREAM_BLOCK_SIZE === 0) {
blocks.push(sha1.hash(false));
blocks.push(sha1.hash(true)); // little-endian intermediate state
}
}
if (offset < bytes.length) sha1.update(bytes.subarray(offset));
blocks.push(sha1.final());
// Overall SHA1 (finalized) via Node crypto — the reference impl.
blocks.push(new Uint8Array(crypto.createHash('sha1').update(Buffer.from(bytes)).digest()));
return blocks;
}
@@ -3,7 +3,9 @@ import { toHex, toHexUpper } from '@snowluma/common/hex';
import type { MessageElement } from '../events';
import type {
Elem,
FileInfo,
GroupFileExtra,
IndexNode,
MentionExtra,
MsgInfo,
NotOnlineImage,
@@ -17,6 +19,38 @@ type ElemDecoded = Elem;
type RichTextDecoded = RichText;
export type PushMsgBody = MessageBody;
/**
* Build the `mediaNode` re-upload descriptor from an NTV2 IndexNode + FileInfo.
* Record and video decode to the byte-identical `{ fileUuid, storeId,
* uploadTime, ttl, subType, info:{…} }` shape — share one builder so the two
* never drift (add a field to one and forget the other).
*/
function buildMediaNode(idx: IndexNode, fi: FileInfo): MessageElement['mediaNode'] {
return {
fileUuid: idx.fileUuid,
storeId: idx.storeId,
uploadTime: idx.uploadTime,
ttl: idx.ttl,
subType: idx.subType,
info: {
fileSize: fi.fileSize,
fileHash: fi.fileHash,
fileSha1: fi.fileSha1,
fileName: fi.fileName,
width: fi.width,
height: fi.height,
time: fi.time,
original: fi.original,
type: {
type: fi.type?.type,
picFormat: fi.type?.picFormat,
videoFormat: fi.type?.videoFormat,
voiceFormat: fi.type?.voiceFormat,
},
},
};
}
export function decodeRichBody(body: PushMsgBody | undefined, isGroup: boolean): MessageElement[] {
const elements: MessageElement[] = [];
if (body?.richText) {
@@ -418,29 +452,7 @@ function convertElements(elems: ElemDecoded[]): MessageElement[] {
md5Hex: fi.fileHash ?? '',
sha1Hex: fi.fileSha1 ?? '',
voiceFormat: fi.type?.voiceFormat ?? 0,
mediaNode: {
fileUuid: idx.fileUuid,
storeId: idx.storeId,
uploadTime: idx.uploadTime,
ttl: idx.ttl,
subType: idx.subType,
info: {
fileSize: fi.fileSize,
fileHash: fi.fileHash,
fileSha1: fi.fileSha1,
fileName: fi.fileName,
width: fi.width,
height: fi.height,
time: fi.time,
original: fi.original,
type: {
type: fi.type?.type,
picFormat: fi.type?.picFormat,
videoFormat: fi.type?.videoFormat,
voiceFormat: fi.type?.voiceFormat,
},
},
},
mediaNode: buildMediaNode(idx, fi),
});
} else if (bizType === 11 || bizType === 21) {
// Video
@@ -454,29 +466,7 @@ function convertElements(elems: ElemDecoded[]): MessageElement[] {
md5Hex: fi.fileHash ?? '',
sha1Hex: fi.fileSha1 ?? '',
videoFormat: fi.type?.videoFormat ?? 0,
mediaNode: {
fileUuid: idx.fileUuid,
storeId: idx.storeId,
uploadTime: idx.uploadTime,
ttl: idx.ttl,
subType: idx.subType,
info: {
fileSize: fi.fileSize,
fileHash: fi.fileHash,
fileSha1: fi.fileSha1,
fileName: fi.fileName,
width: fi.width,
height: fi.height,
time: fi.time,
original: fi.original,
type: {
type: fi.type?.type,
picFormat: fi.type?.picFormat,
videoFormat: fi.type?.videoFormat,
voiceFormat: fi.type?.voiceFormat,
},
},
},
mediaNode: buildMediaNode(idx, fi),
});
}
}
@@ -0,0 +1,52 @@
// 0x6D9_0 — transfer a temporary group file into permanent group storage.
// Mirrors LagrangeV2's TransFileReqBody shape under the 0x6D9 family.
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
OidbGroupSendFileReq,
OidbGroupSendFileResp,
} from '@snowluma/proto-defs/oidb-actions/group-file';
import { invokeOidb, type OidbSender } from '../../oidb-service';
import { ensureRetCodeZero, toInt } from '../shared';
export interface TransGroupFileResult {
saveBusId: number;
saveFilePath: string;
}
export namespace TransGroupFile {
export const command = 0x6D9;
export const subCommand = 0;
export interface Params { groupId: number; fileId: string; }
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, p: Params): OidbGroupSendFileReq => ({
transFile: {
groupUin: BigInt(p.groupId),
appId: 7,
busId: 102,
fileId: p.fileId,
},
});
export const deserialize = (_ctx: Deps, body: OidbGroupSendFileResp): TransGroupFileResult => {
const result = body.transFile;
if (!result) throw new Error('group file transfer response missing');
ensureRetCodeZero('group file transfer', result.retCode, result.retMsg, result.clientWording);
return {
saveBusId: toInt(result.saveBusId),
saveFilePath: typeof result.saveFilePath === 'string' ? result.saveFilePath : '',
};
};
export const encode = (env: OidbBase<OidbGroupSendFileReq>): Uint8Array =>
protobuf_encode<OidbBase<OidbGroupSendFileReq>>(env);
export const decode = (bytes: Uint8Array): OidbBase<OidbGroupSendFileResp> =>
protobuf_decode<OidbBase<OidbGroupSendFileResp>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<TransGroupFileResult> =>
invokeOidb(deps, TransGroupFile, params);
}
@@ -8,6 +8,7 @@ import type { Oidb0x7edReq, Oidb0x7edResp } from '@snowluma/proto-defs/oidb-acti
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { BridgeContext } from '../../bridge-context';
import { invokeOidb, type OidbSender } from '../../oidb-service';
import { resolveSelfUid } from '../../self-uid';
export interface LikeInfo {
[key: string]: import('@snowluma/common/json').JsonValue;
@@ -46,7 +47,7 @@ export namespace GetLike {
export const serialize = async (ctx: Deps, p: Params): Promise<Oidb0x7edReq> => {
const targetUid = p.userId
? await ctx.resolveUserUid(p.userId)
: await resolveSelf(ctx);
: await resolveSelfUid(ctx);
if (!targetUid) throw new Error('target uid not found');
return {
targetUid,
@@ -89,15 +90,3 @@ export namespace GetLike {
export const invoke = (deps: Deps, params: Params): Promise<LikeInfo> =>
invokeOidb(deps, GetLike, params);
}
async function resolveSelf(deps: Pick<BridgeContext, 'identity' | 'resolveUserUid'>): Promise<string> {
// Mirrors `apis/shared.ts::resolveSelfUid` — kept inline here so the
// namespace is self-contained against just the BridgeContext slice.
const cached = deps.identity.selfUid;
if (cached) return cached;
const selfUin = Number(deps.identity.uin);
if (!Number.isFinite(selfUin) || selfUin <= 0) {
throw new Error('self uid is unavailable');
}
return deps.resolveUserUid(selfUin);
}
+16 -9
View File
@@ -104,9 +104,7 @@ export class IncomingPacketPipeline {
err instanceof Error ? (err.stack ?? err.message) : String(err));
});
} else {
this.handleSideEffects(event);
printEvent(this.eventLog, this.deps.identity, event);
this.emit(event);
this.finishDispatch(event);
}
}
} catch (e) {
@@ -121,6 +119,19 @@ export class IncomingPacketPipeline {
void this.deps.events.emit(event);
}
/**
* Common dispatch tail shared by the sync path and the two async enrichment
* paths: run side effects, log the event, then emit it. `alreadyRefreshed` is
* threaded through to `handleSideEffects` (true only on the identity-refresh
* path, where the roster refresh was already done) — it defaults false, so
* `finishDispatch(event)` matches the old `handleSideEffects(event)` calls.
*/
private finishDispatch(event: QQEventVariant, alreadyRefreshed = false): void {
this.handleSideEffects(event, alreadyRefreshed);
printEvent(this.eventLog, this.deps.identity, event);
this.emit(event);
}
private needsPreDispatchIdentityRefresh(event: QQEventVariant): event is Extract<QQEventVariant, { kind: 'group_member_join' }> {
return event.kind === 'group_member_join' && event.groupId > 0 && event.userUin <= 0 && Boolean(event.userUid);
}
@@ -155,9 +166,7 @@ export class IncomingPacketPipeline {
event.groupId, event.userUid ?? '', e instanceof Error ? e.message : String(e));
}
this.handleSideEffects(event, refreshed);
printEvent(this.eventLog, this.deps.identity, event);
this.emit(event);
this.finishDispatch(event, refreshed);
}
private async dispatchGroupInvite(event: Extract<QQEventVariant, { kind: 'group_invite' }>): Promise<void> {
@@ -218,9 +227,7 @@ export class IncomingPacketPipeline {
}
}
this.handleSideEffects(event);
printEvent(this.eventLog, this.deps.identity, event);
this.emit(event);
this.finishDispatch(event);
}
private async prepareGroupMemberJoinIdentity(event: Extract<QQEventVariant, { kind: 'group_member_join' }>): Promise<boolean> {
+29
View File
@@ -0,0 +1,29 @@
import type { BridgeContext } from './bridge-context';
/**
* Resolve the bot's own UID — the single source of truth for "what is my uid".
*
* Fast path: once warmup populates `selfProfile`, `identity.selfUid` is set and
* returns immediately. Before that, resolve via `resolveUserUid(selfUin)`.
* Throws when there is no self identity at all (uin missing / <= 0).
*
* Callers that put the uid on an outbound packet must route here rather than
* fall back to an empty string: an empty uid ships a broken packet. This used
* to be re-inlined in ContactsApi shared helpers, group-file, message, and
* get-like — the copies had drifted into three error messages and two silent
* `?? ''` empty-uid bugs before being converged here.
*
* Takes just the `BridgeContext` slice it needs, so both a full `Bridge` and a
* bare context (e.g. an OIDB service's Deps) satisfy it.
*/
export async function resolveSelfUid(
ctx: Pick<BridgeContext, 'identity' | 'resolveUserUid'>,
): Promise<string> {
const cached = ctx.identity.selfUid;
if (cached) return cached;
const selfUin = Number(ctx.identity.uin);
if (!Number.isFinite(selfUin) || selfUin <= 0) {
throw new Error('self uid is unavailable');
}
return ctx.resolveUserUid(selfUin);
}
+176 -9
View File
@@ -80,6 +80,131 @@ export function parseQzoneJson<T>(text: string): T {
return JSON.parse(s.slice(start, end + 1)) as T;
}
/**
* Parse the JavaScript OBJECT-LITERAL payload of a Qzone JSONP feeds response
* WITHOUT executing it. feeds3_html_more returns `_preloadCallback({ … })` where
* the `data` value uses unquoted keys, single-quoted strings, `\xNN` escapes and
* literal `undefined`s — it is meant to be eval'd by the browser callback, so
* JSON.parse chokes on it. We ran the alternatives to ground: no param combo
* (outputhtmlfeed/format) makes the CGI emit real JSON, and feeds are pure
* remote H5 (absent from the native client), so there is no cleaner endpoint.
* Rather than eval remote-controlled content (a `vm` sandbox is not a security
* boundary — a tampered body escapes it to RCE), we recursively DESCEND the
* literal as data: it can only ever produce a value, never run code.
*
* Handles the subset the CGI emits: objects (unquoted or quoted keys), arrays
* (incl. `undefined`/elided holes), single/double-quoted strings with JS escapes
* (`\xNN`, `\uNNNN`, `\/`, …), numbers and `true|false|null|undefined`.
* `__proto__` keys are dropped (no prototype pollution).
*/
function parseJsLiteral(src: string): unknown {
let i = 0;
const n = src.length;
const isWs = (c: string): boolean => c === ' ' || c === '\t' || c === '\n' || c === '\r' || c === '\f' || c === '\v';
const skipWs = (): void => { while (i < n && isWs(src[i]!)) i++; };
function parseString(quote: string): string {
i++; // opening quote
let out = '';
while (i < n) {
const c = src[i]!;
if (c === '\\') {
const e = src[i + 1];
if (e === 'x') { out += String.fromCharCode(parseInt(src.slice(i + 2, i + 4), 16)); i += 4; continue; }
if (e === 'u') { out += String.fromCharCode(parseInt(src.slice(i + 2, i + 6), 16)); i += 6; continue; }
const simple: Record<string, string> = { n: '\n', t: '\t', r: '\r', b: '\b', f: '\f', v: '\v', '0': '\0' };
out += e !== undefined ? (simple[e] ?? e) : ''; // \/ → /, \' → ', unknown → the char
i += 2;
continue;
}
if (c === quote) { i++; return out; }
out += c;
i++;
}
throw new Error('unterminated string in qzone feeds payload');
}
function parseKey(): string {
skipWs();
const c = src[i];
if (c === '"' || c === "'") return parseString(c);
let s = '';
while (i < n && /[A-Za-z0-9_$]/.test(src[i]!)) { s += src[i]; i++; }
if (!s) throw new Error('expected object key in qzone feeds payload');
return s;
}
function parseObject(): Record<string, unknown> {
i++; // {
const obj: Record<string, unknown> = {};
skipWs();
if (src[i] === '}') { i++; return obj; }
for (;;) {
const key = parseKey();
skipWs();
if (src[i] !== ':') throw new Error('expected ":" in qzone feeds payload');
i++;
const value = parseValue();
if (key !== '__proto__') obj[key] = value;
skipWs();
const ch = src[i];
if (ch === ',') { i++; skipWs(); if (src[i] === '}') { i++; return obj; } continue; }
if (ch === '}') { i++; return obj; }
throw new Error('expected "," or "}" in qzone feeds payload');
}
}
function parseArray(): unknown[] {
i++; // [
const arr: unknown[] = [];
skipWs();
if (src[i] === ']') { i++; return arr; }
for (;;) {
arr.push(parseValue());
skipWs();
const ch = src[i];
if (ch === ',') { i++; skipWs(); if (src[i] === ']') { i++; return arr; } continue; }
if (ch === ']') { i++; return arr; }
throw new Error('expected "," or "]" in qzone feeds payload');
}
}
function parseValue(): unknown {
skipWs();
const c = src[i];
if (c === undefined) throw new Error('unexpected end of qzone feeds payload');
if (c === '{') return parseObject();
if (c === '[') return parseArray();
if (c === '"' || c === "'") return parseString(c);
let token = '';
while (i < n && !/[,}\]:\s]/.test(src[i]!)) { token += src[i]; i++; }
if (token === 'true') return true;
if (token === 'false') return false;
if (token === 'null') return null;
if (token === 'undefined') return undefined;
if (token !== '') { const num = Number(token); if (!Number.isNaN(num)) return num; }
throw new Error('unexpected token in qzone feeds payload: ' + token.slice(0, 20));
}
return parseValue();
}
/**
* Extract the object a Qzone feeds JSONP body hands to its callback, parsed as
* data (never executed — see {@link parseJsLiteral}). Slices from the first `{`
* (the callback argument) and parses one balanced value; trailing `);` is
* ignored. Throws if the payload is not an object.
*/
export function parseQzoneCallback<T>(text: string): T {
const start = text.indexOf('{');
if (start === -1) throw new Error('invalid feeds response from qzone api');
const value = parseJsLiteral(text.slice(start));
if (value === null || typeof value !== 'object') {
throw new Error('invalid feeds response from qzone api');
}
return value as T;
}
function assertRichParams(richType?: number, richval?: string): void {
const hasRichType = richType !== undefined;
const hasRichval = richval !== undefined && richval.trim() !== '';
@@ -194,6 +319,7 @@ export async function getQzoneMsgList(
const text = await RequestUtil.HttpGetText(url, 'GET', '', {
Cookie: cookieToString(cookieObject),
});
log.trace('getQzoneMsgList raw body (uin=%s): %s', targetUin, text);
const data = parseQzoneJson<RawMsgListResponse>(text);
if (typeof data.code === 'number' && data.code !== 0) {
@@ -201,8 +327,8 @@ export async function getQzoneMsgList(
throw new Error(`qzone msglist failed: code=${data.code} ${data.message ?? ''}`.trim());
}
if (!Array.isArray(data.msglist)) {
log.warn('getQzoneMsgList: no msglist in response (uin=%s) — likely auth/cookie failure', targetUin);
throw new Error('无法获取空间说说列表');
log.warn('getQzoneMsgList: no msglist in response (uin=%s) — likely auth/cookie failure or unverified response shape; body head=%s', targetUin, text.slice(0, 300));
throw new Error(`无法获取空间说说列表(响应结构异常): ${text.slice(0, 200)}`);
}
return mapMsgList(data);
@@ -262,7 +388,8 @@ export interface QzoneFeedsResult {
/** Pure transform from the raw feeds response into the OneBot list. */
export function mapFeeds(data: RawFeedsResponse): QzoneFeedsResult {
const list = data.data?.data ?? [];
// The CGI pads the array with trailing `undefined`/null holes — drop them.
const list = (data.data?.data ?? []).filter((f): f is RawFeedItem => !!f);
return {
feeds: list.map((f) => ({
uin: Number(f.uin ?? 0),
@@ -335,15 +462,18 @@ export async function getQzoneFeeds(
const text = await RequestUtil.HttpGetText(url, 'GET', '', {
Cookie: cookieToString(cookieObject),
});
const data = parseQzoneJson<RawFeedsResponse>(text);
log.trace('getQzoneFeeds raw body (uin=%s): %s', selfUin, text);
// feeds3_html_more's payload is a JS object literal, not JSON — parse it as
// inert data (see parseQzoneCallback; never executed) rather than JSON.parse.
const data = parseQzoneCallback<RawFeedsResponse>(text);
if (typeof data.code === 'number' && data.code !== 0) {
log.warn('getQzoneFeeds: non-zero code (uin=%s) code=%d msg=%s', selfUin, data.code, data.message);
throw new Error(`qzone feeds failed: code=${data.code} ${data.message ?? ''}`.trim());
}
if (!Array.isArray(data.data?.data)) {
log.warn('getQzoneFeeds: no data array in response (uin=%s) — likely auth/cookie failure', selfUin);
throw new Error('无法获取空间好友动态');
log.warn('getQzoneFeeds: no data array in response (uin=%s) — likely auth/cookie failure or unverified response shape; body head=%s', selfUin, text.slice(0, 300));
throw new Error(`无法获取空间好友动态(响应结构异常): ${text.slice(0, 200)}`);
}
return mapFeeds(data);
@@ -370,6 +500,8 @@ interface RawPublishResponse {
now?: number;
}
export type QzoneUgcRight = 1 | 4 | 16 | 64 | 128;
/** Result of publishing a 说说. */
export interface QzonePublishResult {
[key: string]: JsonValue;
@@ -379,6 +511,31 @@ export interface QzonePublishResult {
time: number;
}
const QZONE_UGC_RIGHTS = new Set<number>([1, 4, 16, 64, 128]);
function normalizeQzoneUgcRight(ugcRight: number): QzoneUgcRight {
if (!QZONE_UGC_RIGHTS.has(ugcRight)) {
throw new Error('ugc_right must be one of 1, 4, 16, 64, 128');
}
return ugcRight as QzoneUgcRight;
}
function normalizeTargetUins(targetUins?: string): string {
const raw = (targetUins ?? '').trim();
if (!raw) return '';
const seen = new Set<string>();
for (const part of raw.split('|')) {
const uin = part.trim();
if (!uin) continue;
if (!/^\d+$/.test(uin)) {
throw new Error('target_uins must contain QQ numbers separated by |');
}
seen.add(uin);
}
return [...seen].join('|');
}
/**
* Publish a 说说 via taotao.qzone.qq.com's emotion_cgi_publish_v6 CGI
* (proxied through h5.qzone.qq.com). POSTs a form-urlencoded body with
@@ -399,6 +556,8 @@ export async function publishQzoneMsg(
content: string,
richType?: number,
richval?: string,
ugcRight = 1,
targetUins?: string,
): Promise<QzonePublishResult> {
if (!cookieObject || typeof cookieObject !== 'object') {
throw new Error('cookieObject is required');
@@ -408,9 +567,15 @@ export async function publishQzoneMsg(
}
assertRichParams(richType, richval);
const right = normalizeQzoneUgcRight(ugcRight);
const effectiveTargetUins = right === 16 || right === 128 ? normalizeTargetUins(targetUins) : '';
if ((right === 16 || right === 128) && !effectiveTargetUins) {
throw new Error('target_uins is required when ugc_right is 16 or 128');
}
const bkn = getBknFromCookie(cookieObject);
const url = `https://h5.qzone.qq.com/proxy/domain/taotao.qzone.qq.com/cgi-bin/emotion_cgi_publish_v6?g_tk=${bkn}`;
const body = new URLSearchParams({
const bodyParams = new URLSearchParams({
syn_tweet_verson: '1',
paramstr: '1',
pic_template: '',
@@ -421,14 +586,16 @@ export async function publishQzoneMsg(
con: content,
feedversion: '1',
ver: '1',
ugc_right: '1',
ugc_right: String(right),
to_sign: '0',
who: '1',
hostuin: hostUin,
code_version: '1',
format: 'json',
qzreferrer: `https://user.qzone.qq.com/${hostUin}`,
}).toString();
});
if (effectiveTargetUins) bodyParams.set('allow_uins', effectiveTargetUins);
const body = bodyParams.toString();
const text = await RequestUtil.HttpGetText(url, 'POST', body, {
Cookie: cookieToString(cookieObject),
+29 -26
View File
@@ -4,41 +4,44 @@ import https from 'node:https';
type RequestBody = string | Buffer | Uint8Array | Record<string, unknown> | undefined;
export class RequestUtil {
static async HttpsGetCookies(url: string): Promise<{ [key: string]: string; }> {
// Collect Set-Cookie across the ptlogin2 jump's redirect chain. NEVER hangs:
// a per-request timeout + a redirect-depth cap guarantee termination, and any
// failed/slow hop resolves with the cookies gathered so far rather than
// throwing. This matters because the jump's final hop can target a host the
// deployment can't reach (e.g. a datacenter网络 that times out on
// qzone.qq.com) — without the ceiling that would hang every cookie-backed web
// action forever (the essential cookies are already set by the first hop).
static async HttpsGetCookies(url: string, depth = 0): Promise<{ [key: string]: string; }> {
const client = url.startsWith('https') ? https : http;
return new Promise((resolve, reject) => {
return new Promise((resolve) => {
const cookies: { [key: string]: string; } = {};
let settled = false;
const done = (extra?: { [key: string]: string; }) => {
if (settled) return;
settled = true;
resolve(extra ? { ...cookies, ...extra } : cookies);
};
const req = client.get(url, (res) => {
const cookies: { [key: string]: string; } = {};
res.on('data', () => { }); // 必须消耗流
res.on('end', () => {
this.handleRedirect(res, url, cookies)
.then(resolve)
.catch(reject);
});
if (res.headers['set-cookie']) {
this.extractCookies(res.headers['set-cookie'], cookies);
}
res.on('data', () => { }); // 必须消耗流
res.on('end', () => {
const location = res.headers.location;
if ((res.statusCode === 301 || res.statusCode === 302) && location && depth < 5) {
this.HttpsGetCookies(new URL(location, url).href, depth + 1)
.then((rc) => done(rc))
.catch(() => done());
} else {
done();
}
});
});
req.on('error', (error: Error) => {
reject(error);
});
req.setTimeout(8000, () => { req.destroy(); done(); });
req.on('error', () => done());
});
}
private static async handleRedirect(res: http.IncomingMessage, url: string, cookies: { [key: string]: string; }): Promise<{ [key: string]: string; }> {
if (res.statusCode === 301 || res.statusCode === 302) {
if (res.headers.location) {
const redirectUrl = new URL(res.headers.location, url);
const redirectCookies = await this.HttpsGetCookies(redirectUrl.href);
return { ...cookies, ...redirectCookies };
}
}
return cookies;
}
private static extractCookies(setCookieHeaders: string[], cookies: { [key: string]: string; }) {
setCookieHeaders.forEach((cookie) => {
const parts = cookie.split(';')[0]?.split('=');
@@ -0,0 +1,50 @@
import { describe, it, expect } from 'vitest';
import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { typesForDirection } from '../src/element-manifest';
// 对账测试(protocol 侧)—— 拿 element-manifest 核对「按 element.type 收敛」的
// 两个 protocol 方向:
// D 收·解 rich-body-decoder.ts 产出的 MessageElement 类型集合
// W 发·打包 element-builder.ts 的 switch 分支集合
// onebot 侧的 S/P 由 onebot/tests/element-manifest.test.ts 核对(包边界所限)。
//
// 这是一道架构护栏(fitness function):谁在这两处新增/删除一种元素方向,却没有
//同步更新 element-manifest,测试立即报红——把「漏写一个方向」从运行时兜底静默
// 变成 CI 当场可见。纯读源码、零运行时行为改动。
function readSrc(relFromTestDir: string): string {
const abs = fileURLToPath(new URL(relFromTestDir, import.meta.url));
const raw = readFileSync(abs, 'utf8');
// 剥掉块注释与行注释,避免注释里出现的类型字面量污染扫描结果。
return raw.replace(/\/\*[\s\S]*?\*\//g, '').replace(/\/\/.*$/gm, '');
}
/** 抽出所有匹配 `pattern` 第 1 捕获组的去重、排序类型名。 */
function extractTypes(src: string, pattern: RegExp): string[] {
const found = new Set<string>();
for (const m of src.matchAll(pattern)) found.add(m[1]!);
return [...found].sort();
}
const sorted = (s: Iterable<string>): string[] => [...s].sort();
describe('element-manifest 对账(protocol 侧:D 收·解 / W 发·打包)', () => {
it('D:rich-body-decoder 产出的元素类型 == 清单声明的 D=yes', () => {
const src = readSrc('../src/msg-push/rich-body-decoder.ts');
// 解码产出形如 `result.push({ type: 'image', ... })` / `{ type: 'reply', ... }`。
// 值域放宽到 `[A-Za-z0-9_]+`(而非仅小写):类型名当前虽全小写,但收紧到
// `[a-z]+` 会让未来的驼峰/下划线类型名被静默漏抓,护栏就形同虚设——正是本
// 重构要消灭的"漏一个方向、走 default 静默"失效模式,不能在护栏自身重演。
const handled = extractTypes(src, /(?<![A-Za-z])type:\s*'([A-Za-z0-9_]+)'/g);
expect(handled).toEqual(sorted(typesForDirection('D')));
});
it('W:element-builder 的 switch 分支 == 清单声明的 W=yes', () => {
const src = readSrc('../src/element-builder.ts');
const handled = extractTypes(src, /case\s*'([A-Za-z0-9_]+)'\s*:/g);
// poke 按设计不支持发送(QQ 限制),element-builder 必须没有 poke 分支。
expect(handled).not.toContain('poke');
expect(handled).toEqual(sorted(typesForDirection('W')));
});
});
@@ -0,0 +1,46 @@
import { describe, it, expect } from 'vitest';
import { createHash } from 'node:crypto';
import { computeVideoSha1Blocks } from '../../src/highway/video-upload';
// Deterministic input generator (matches the golden-capture script).
function det(len: number): Uint8Array {
const b = new Uint8Array(len);
for (let i = 0; i < len; i++) b[i] = (i * 31 + 7) & 0xFF;
return b;
}
const hex = (u: Uint8Array): string => Buffer.from(u).toString('hex');
const nodeSha1 = (b: Uint8Array): string => createHash('sha1').update(Buffer.from(b)).digest('hex');
describe('computeVideoSha1Blocks', () => {
// GOLDEN: captured from the previous hand-rolled Sha1StreamState implementation
// before the F3 rewrite (Sha1Stream + Node crypto), so this locks the rewrite
// byte-identical for the block states AND the overall digest.
it('reproduces the pre-refactor golden 1MB-block states + overall sha1', () => {
const input = det(2 * 1024 * 1024 + 12345); // 2 full 1MB blocks + a partial tail
expect(computeVideoSha1Blocks(input).map(hex)).toEqual([
'ab9a20fd6c98fc1f8f0c985cd552ff14c6feacfd', // intermediate un-finalized state @1MB (little-endian)
'2ccc5923b75f46ebd8ccb78e8c413c18025178b9', // intermediate un-finalized state @2MB
'dd9cfd4648ab460260afa820c98bfec1b17655d4', // overall (finalized)
]);
});
it('the final block equals the standard full-file SHA1', () => {
const input = det(2 * 1024 * 1024 + 12345);
const blocks = computeVideoSha1Blocks(input);
expect(hex(blocks[blocks.length - 1]!)).toBe(nodeSha1(input));
});
it('a file shorter than 1MB yields just the overall sha1', () => {
const input = det(1000);
const blocks = computeVideoSha1Blocks(input);
expect(blocks).toHaveLength(1);
expect(hex(blocks[0]!)).toBe(nodeSha1(input));
});
it('a file that is an exact 1MB multiple emits the boundary state then the overall', () => {
const input = det(1024 * 1024);
const blocks = computeVideoSha1Blocks(input);
expect(blocks).toHaveLength(2);
expect(hex(blocks[1]!)).toBe(nodeSha1(input)); // last is the finalized overall
});
});
@@ -0,0 +1,52 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
OidbGroupSendFileReq, OidbGroupSendFileResp,
} from '@snowluma/proto-defs/oidb-actions/group-file';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { TransGroupFile } from '../../../src/oidb-services/group-file/trans-group-file';
function makeDeps(body?: OidbGroupSendFileResp) {
const responseData = body !== undefined
? Buffer.from(protobuf_encode<OidbBase<OidbGroupSendFileResp>>({ body }))
: Buffer.alloc(0);
const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData };
return { sendRawPacket: vi.fn(async () => r) };
}
describe('TransGroupFile namespace', () => {
it('declares 0x6D9_0', () => {
expect(TransGroupFile.command).toBe(0x6D9);
expect(TransGroupFile.subCommand).toBe(0);
});
it('packages group + file id under the transFile slot', async () => {
const deps = makeDeps({ transFile: { saveBusId: 102, saveFilePath: '/abc' } });
const out = await TransGroupFile.invoke(deps, { groupId: 12345, fileId: 'fid' });
expect(out).toEqual({ saveBusId: 102, saveFilePath: '/abc' });
expect(deps.sendRawPacket).toHaveBeenCalledOnce();
const [wire, bytes] = deps.sendRawPacket.mock.calls[0]!;
expect(wire).toBe('OidbSvcTrpcTcp.0x6d9_0');
const env = protobuf_decode<OidbBase<OidbGroupSendFileReq>>(bytes);
expect(env.body?.transFile).toEqual({
groupUin: 12345n,
appId: 7,
busId: 102,
fileId: 'fid',
});
});
it('throws on missing transFile sub-message', async () => {
const deps = makeDeps({});
await expect(TransGroupFile.invoke(deps, { groupId: 1, fileId: 'f' }))
.rejects.toThrow(/transfer response missing/);
});
it('throws on non-zero retCode', async () => {
const deps = makeDeps({ transFile: { retCode: 7, retMsg: 'denied' } });
await expect(TransGroupFile.invoke(deps, { groupId: 1, fileId: 'f' }))
.rejects.toThrow(/code=7/);
});
});
File diff suppressed because one or more lines are too long
@@ -0,0 +1,75 @@
import { describe, it, expect } from 'vitest';
import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { mapFeeds, parseQzoneCallback } from '@snowluma/protocol/web/qzone';
// Real feeds3_html_more response captured live (issue #182). Its `data` value
// is a JS object literal (unquoted keys, single-quoted strings, \xNN escapes,
// trailing `undefined`) — JSON.parse throws on it; parseQzoneCallback must not.
const SAMPLE = readFileSync(
fileURLToPath(new URL('./fixtures/qzone-feeds-sample.jsonp', import.meta.url)),
'utf8',
);
interface RawFeeds {
code?: number;
data?: { data?: unknown[]; hasmore?: number | string };
}
describe('qzone feeds JS-literal parsing (issue #182)', () => {
it('JSON.parse chokes on the real body (regression baseline)', () => {
const inner = SAMPLE.slice(SAMPLE.indexOf('{'), SAMPLE.lastIndexOf('}') + 1);
expect(() => JSON.parse(inner)).toThrow();
});
it('parseQzoneCallback evaluates the JS-literal payload', () => {
const data = parseQzoneCallback<RawFeeds>(SAMPLE);
expect(data.code).toBe(0);
expect(Array.isArray(data.data?.data)).toBe(true);
// The array carries a trailing `undefined` hole alongside the real feed.
expect(data.data!.data!.length).toBe(2);
expect(data.data!.data!.some((x) => x === undefined)).toBe(true);
});
it('mapFeeds drops the undefined hole and normalises the feed', () => {
const data = parseQzoneCallback(SAMPLE);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const result = mapFeeds(data as any);
expect(result.feeds).toHaveLength(1);
const f = result.feeds[0]!;
expect(f.uin).toBe(20050606);
expect(f.nickname).toBe('官方Qzone');
expect(f.appid).toBe(311);
expect(f.time).toBe(1780711209);
expect(f.key).toBe('aef23101297f236ae4f10600');
// \xNN escapes decoded by the JS eval, html passed through verbatim.
expect(f.html).toContain('<li class="f-single f-s-s"');
expect(f.html).toContain('官方Qzone');
});
it('parses as inert data — never resolves identifiers or executes code', () => {
// The parser has no notion of globals, member access, or calls: any such
// token is rejected, so a tampered body cannot reach `process`/`Function`
// etc. (the whole reason we do NOT eval this payload).
expect(() => parseQzoneCallback('_preloadCallback({x: process})')).toThrow();
expect(() => parseQzoneCallback('_preloadCallback({x: callback.constructor})')).toThrow();
expect(() => parseQzoneCallback('_preloadCallback({x: (function(){return 1})()})')).toThrow();
expect(() => parseQzoneCallback('_preloadCallback(eval("1+1"))')).toThrow();
});
it('does not pollute Object.prototype via a __proto__ key', () => {
parseQzoneCallback('_preloadCallback({"__proto__":{"polluted":1},"code":0})');
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect(({} as any).polluted).toBeUndefined();
});
it('decodes JS string escapes (\\xNN, \\/) literally, not as markup', () => {
const d = parseQzoneCallback<{ s?: string }>("_preloadCallback({s:'\\x3Cb\\x3E&\\/x'})");
expect(d.s).toBe('<b>&/x');
});
it('rejects a body that captures no object', () => {
expect(() => parseQzoneCallback('_preloadCallback(42)')).toThrow('invalid feeds response');
expect(() => parseQzoneCallback('void 0')).toThrow('invalid feeds response');
});
});
+44 -3
View File
@@ -175,17 +175,17 @@ describe('qzone / getQzoneFeeds (HTTP layer)', () => {
});
it('returns an empty list (not a throw) for a genuinely empty feed', async () => {
vi.spyOn(RequestUtil, 'HttpGetText').mockResolvedValue('{"code":0,"data":{"data":[],"hasmore":0}}');
vi.spyOn(RequestUtil, 'HttpGetText').mockResolvedValue('_preloadCallback({"code":0,"data":{"data":[],"hasmore":0}});');
await expect(getQzoneFeeds(cookies, '10000')).resolves.toEqual({ feeds: [], has_more: false });
});
it('throws on a non-zero qzone code', async () => {
vi.spyOn(RequestUtil, 'HttpGetText').mockResolvedValue('{"code":-3000,"message":"need login"}');
vi.spyOn(RequestUtil, 'HttpGetText').mockResolvedValue('_preloadCallback({"code":-3000,"message":"need login"});');
await expect(getQzoneFeeds(cookies, '10000')).rejects.toThrow('code=-3000');
});
it('throws when the data array is absent (cookie failure), not an empty list', async () => {
vi.spyOn(RequestUtil, 'HttpGetText').mockResolvedValue('{"code":0,"data":{}}');
vi.spyOn(RequestUtil, 'HttpGetText').mockResolvedValue('_preloadCallback({"code":0,"data":{}});');
await expect(getQzoneFeeds(cookies, '10000')).rejects.toThrow('无法获取空间好友动态');
});
});
@@ -218,6 +218,8 @@ describe('qzone / publishQzoneMsg (HTTP layer)', () => {
expect(form.get('con')).toBe('hello 世界 & friends');
expect(form.get('hostuin')).toBe('10000');
expect(form.get('who')).toBe('1');
expect(form.get('ugc_right')).toBe('1');
expect(form.has('allow_uins')).toBe(false);
expect(form.get('format')).toBe('json');
expect(form.get('qzreferrer')).toBe('https://user.qzone.qq.com/10000');
});
@@ -235,6 +237,39 @@ describe('qzone / publishQzoneMsg (HTTP layer)', () => {
expect(form.get('richval')).toBe(richval);
});
it('threads publish permission fields for restricted visibility', async () => {
const spy = vi.spyOn(RequestUtil, 'HttpGetText').mockResolvedValue(
'{"code":0,"t1_tid":"RIGHTTID","t1_time":"1700000000"}',
);
await expect(publishQzoneMsg(cookies, '10000', 'limited', undefined, undefined, 16, '10001 | 10002|10001')).resolves.toEqual({
tid: 'RIGHTTID',
time: 1700000000,
});
const [, , body] = spy.mock.calls[0]!;
const form = new URLSearchParams(body as string);
expect(form.get('ugc_right')).toBe('16');
expect(form.get('allow_uins')).toBe('10001|10002');
expect(form.get('who')).toBe('1');
});
it('ignores target_uins for non-restricted visibility', async () => {
const spy = vi.spyOn(RequestUtil, 'HttpGetText').mockResolvedValue(
'{"code":0,"t1_tid":"FRIENDTID","t1_time":"1700000000"}',
);
await expect(publishQzoneMsg(cookies, '10000', 'friends', undefined, undefined, 4, 'not-a-uin')).resolves.toEqual({
tid: 'FRIENDTID',
time: 1700000000,
});
const [, , body] = spy.mock.calls[0]!;
const form = new URLSearchParams(body as string);
expect(form.get('ugc_right')).toBe('4');
expect(form.has('allow_uins')).toBe(false);
});
it('falls back to tid/now for alternate client builds', async () => {
vi.spyOn(RequestUtil, 'HttpGetText').mockResolvedValue('{"code":0,"tid":"ALT","now":1700000001}');
await expect(publishQzoneMsg(cookies, '10000', 'hi')).resolves.toEqual({ tid: 'ALT', time: 1700000001 });
@@ -253,6 +288,12 @@ describe('qzone / publishQzoneMsg (HTTP layer)', () => {
expect(spy).not.toHaveBeenCalled();
});
it('rejects restricted visibility without target_uins before any request', async () => {
const spy = vi.spyOn(RequestUtil, 'HttpGetText');
await expect(publishQzoneMsg(cookies, '10000', 'hi', undefined, undefined, 128)).rejects.toThrow('target_uins is required');
expect(spy).not.toHaveBeenCalled();
});
it('throws on a non-zero qzone code (rejected/rate-limited)', async () => {
vi.spyOn(RequestUtil, 'HttpGetText').mockResolvedValue('{"code":-10000,"message":"too frequent"}');
await expect(publishQzoneMsg(cookies, '10000', 'hi')).rejects.toThrow('code=-10000');
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/proton",
"version": "1.11.0",
"version": "1.11.1",
"private": true,
"type": "module",
"description": "Compile-time protobuf encoder/decoder generator for SnowLuma. TypeScript interfaces → fully-inlined, zero-runtime protobuf codec functions. Vendored from SnowLuma/protobuf-dsl (reference copy under dev/protobuf-dsl/) with edge-case fixes applied.",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/runtime",
"version": "1.11.0",
"version": "1.11.1",
"private": true,
"type": "module",
"main": "index.mjs",
+1 -1
View File
@@ -4,7 +4,7 @@
"name": "MotricSeven",
"email": "motricseven@gmail.com"
},
"version": "1.11.0",
"version": "1.11.1",
"description": "TypeScript SDK for SnowLuma OneBot HTTP and WebSocket transports",
"keywords": [
"snowluma",
+1 -1
View File
@@ -4,7 +4,7 @@
"name": "MotricSeven",
"email": "motricseven@gmail.com"
},
"version": "1.11.0",
"version": "1.11.1",
"description": "Shared SnowLuma UI primitives — Tailwind 4 theme tokens + shadcn-style atomic components",
"keywords": [
"snowluma",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/websocket",
"version": "1.11.0",
"version": "1.11.1",
"private": true,
"type": "module",
"main": "./src/index.ts",
+1 -1
View File
@@ -2,7 +2,7 @@
"license": "SEE LICENSE IN LICENSE",
"name": "webui",
"private": true,
"version": "1.11.0",
"version": "1.11.1",
"type": "module",
"scripts": {
"dev": "vite",
@@ -8,7 +8,6 @@
import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
import { motion } from 'motion/react';
import { AlertTriangle, FlaskConical, History, Loader2, Play, RotateCcw, ShieldCheck, Trash2, Zap } from 'lucide-react';
import { Select } from '@/components/ui/select';
import { Textarea } from '@/components/ui/textarea';
import { Picker } from '@/components/ui/picker';
import { JsonTree } from '@/components/ui/json-tree';
@@ -27,6 +26,10 @@ const cardCls = 'rounded-2xl border border-border/60 bg-card/80 shadow-[0_1px_2p
// stakes (the amber banner already warns that any write is real).
const DESTRUCTIVE_RE = /(kick|ban|mute|recall|withdraw|delete|del_|dismiss|disband|leave|quit|remove|revoke)/i;
function qqAvatarUrl(uin: string) {
return `/avatar/${encodeURIComponent(uin)}`;
}
function coerceParam(type: string, raw: string): unknown {
if (raw === '') return undefined;
if (/int|uint|number|messageId/i.test(type)) {
@@ -82,6 +85,18 @@ export function ActionTester({ accounts, docs, presetAction }: { accounts: QQInf
const isStream = !!doc?.stream;
const isDestructive = DESTRUCTIVE_RE.test(actionName);
const accountOptions = useMemo(
() => accounts.length === 0
? [{ value: '', label: '(无在线账号)' }]
: accounts.map((a) => ({
value: a.uin,
label: a.nickname || a.uin,
sub: a.nickname ? a.uin : undefined,
avatar: qqAvatarUrl(a.uin),
})),
[accounts],
);
const actionOptions = useMemo(
() => docs.map((d) => ({ value: d.name, label: d.name, sub: d.summary })),
[docs],
@@ -201,10 +216,15 @@ export function ActionTester({ accounts, docs, presetAction }: { accounts: QQInf
<div className="grid gap-4 sm:grid-cols-2">
<Field label="账号">
<Select value={uin} onChange={(e) => setUin(e.target.value)}>
{accounts.length === 0 && <option value="">(无在线账号)</option>}
{accounts.map((a) => <option key={a.uin} value={a.uin}>{a.nickname || a.uin}</option>)}
</Select>
<Picker
ariaLabel="选择账号"
value={uin}
onChange={setUin}
options={accountOptions}
placeholder="选择账号…"
validateRaw={() => false}
disabled={accounts.length === 0}
/>
</Field>
<Field label="Action">
<Picker
@@ -11,6 +11,7 @@ import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { useApi } from '@/lib/api';
import { useFlashMessage } from '@/hooks/use-flash-message';
import { cn } from '@/lib/utils';
import type { GlobalSettings } from '@/types';
@@ -30,9 +31,8 @@ export function GlobalConfigPanel() {
const [config, setConfig] = useState<GlobalSettings | null>(null);
const [loading, setLoading] = useState(true);
const [loadFailed, setLoadFailed] = useState(false);
const [msg, setMsg] = useState<{ kind: 'ok' | 'err'; text: string } | null>(null);
const { msg, flash } = useFlashMessage();
const saveTimer = useRef<number | null>(null);
const msgTimer = useRef<number | null>(null);
const saveGen = useRef(0);
const load = useCallback(async () => {
@@ -54,17 +54,10 @@ export function GlobalConfigPanel() {
useEffect(
() => () => {
if (saveTimer.current) clearTimeout(saveTimer.current);
if (msgTimer.current) clearTimeout(msgTimer.current);
},
[],
);
const flash = (kind: 'ok' | 'err', text: string) => {
setMsg({ kind, text });
if (msgTimer.current) clearTimeout(msgTimer.current);
msgTimer.current = window.setTimeout(() => setMsg(null), 2400);
};
/** Apply locally + debounced auto-save. Deliberately does NOT reconcile the
* inputs from the server's normalized response (it would wipe a half-typed
* URL); a generation guard just confirms the latest save. */
@@ -11,6 +11,7 @@ import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { ToggleSwitch } from '@/components/ui/toggle-switch';
import { useApi } from '@/lib/api';
import { useFlashMessage } from '@/hooks/use-flash-message';
import { useTheme } from '@/contexts/ThemeContext';
import { cn } from '@/lib/utils';
import type { NotificationChannel, NotificationsConfig } from '@/types';
@@ -41,9 +42,8 @@ export function NotificationsPanel() {
const [loading, setLoading] = useState(true);
const [dialog, setDialog] = useState<DialogState>({ open: false, index: null, seed: blankChannel([]) });
const [testing, setTesting] = useState<string | null>(null);
const [msg, setMsg] = useState<{ kind: 'ok' | 'err'; text: string } | null>(null);
const { msg, flash, setMsg } = useFlashMessage();
const saveTimer = useRef<number | null>(null);
const msgTimer = useRef<number | null>(null);
const saveGen = useRef(0);
useEffect(() => {
@@ -66,17 +66,10 @@ export function NotificationsPanel() {
useEffect(
() => () => {
if (saveTimer.current) clearTimeout(saveTimer.current);
if (msgTimer.current) clearTimeout(msgTimer.current);
},
[],
);
const flash = (kind: 'ok' | 'err', text: string) => {
setMsg({ kind, text });
if (msgTimer.current) clearTimeout(msgTimer.current);
msgTimer.current = window.setTimeout(() => setMsg(null), 2400);
};
/** Apply locally + debounced auto-save. A generation guard reconciles with
* the server's normalized result only if no newer edit landed meanwhile. */
const commit = (next: NotificationsConfig) => {
@@ -16,6 +16,7 @@ import { Select } from '@/components/ui/select';
import { Textarea } from '@/components/ui/textarea';
import { ToggleSwitch } from '@/components/ui/toggle-switch';
import { useApi } from '@/lib/api';
import { useFlashMessage } from '@/hooks/use-flash-message';
import { cn } from '@/lib/utils';
import type { SystemSettingsResponse } from '@/types';
@@ -24,7 +25,7 @@ export function SystemPanel() {
const [data, setData] = useState<SystemSettingsResponse | null>(null);
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [msg, setMsg] = useState<{ kind: 'ok' | 'err'; text: string } | null>(null);
const { msg, flash, setMsg } = useFlashMessage(4000);
// editable form state
const [port, setPort] = useState('');
@@ -60,10 +61,6 @@ export function SystemPanel() {
useEffect(() => { void load(); }, []); // eslint-disable-line react-hooks/exhaustive-deps
const overridden = (field: string) => data?.envOverrides.includes(field) ?? false;
const flash = (kind: 'ok' | 'err', text: string) => {
setMsg({ kind, text });
window.setTimeout(() => setMsg(null), 4000);
};
const saveSettings = async () => {
const portNum = Number(port);
+13 -2
View File
@@ -50,6 +50,7 @@ export function Picker({
const rootRef = useRef<HTMLDivElement>(null);
const listRef = useRef<HTMLDivElement>(null);
const searchRef = useRef<HTMLInputElement>(null);
const suppressTriggerClick = useRef(false);
const selected = options.find((o) => o.value === value);
@@ -124,7 +125,13 @@ export function Picker({
aria-label={ariaLabel}
aria-haspopup="listbox"
aria-expanded={open}
onClick={() => !disabled && setOpen((v) => !v)}
onClick={() => {
if (suppressTriggerClick.current) {
suppressTriggerClick.current = false;
return;
}
if (!disabled) setOpen((v) => !v);
}}
className={cn(
'flex h-9 w-full items-center gap-2 rounded-md border border-border bg-transparent px-3 text-sm outline-none transition-colors',
'focus-visible:ring-[3px] focus-visible:ring-ring/40 focus-visible:border-ring disabled:opacity-50',
@@ -196,7 +203,11 @@ export function Picker({
role="option"
aria-selected={idx === active}
onMouseEnter={() => setActive(idx)}
onClick={() => choose(idx)}
onPointerDown={(e) => {
e.preventDefault();
suppressTriggerClick.current = true;
choose(idx);
}}
className={cn(
'absolute left-0 right-0 flex cursor-pointer items-center gap-2.5 px-3',
idx === active ? 'bg-accent text-accent-foreground' : 'hover:bg-accent/50',
@@ -0,0 +1,37 @@
import { useEffect, useRef, useState } from 'react';
export type FlashKind = 'ok' | 'err';
export interface FlashMessage {
kind: FlashKind;
text: string;
}
/**
* Transient status-banner state for a settings panel.
*
* - `flash(kind, text)` shows a message that auto-clears after `durationMs`,
* cancelling any prior auto-clear timer first.
* - `setMsg` sets/clears the message directly (a persistent one that stays
* until the next action — e.g. a load-failure banner).
* - The pending timer is cleared on unmount.
*
* Replaces the per-panel hand-rolled `msg` state + `msgTimer` ref + `flash` +
* unmount cleanup, which had drifted (one panel omitted the ref, the
* prior-timer cancel, and the unmount cleanup entirely — leaking a timer that
* could fire a stale `setMsg` after unmount).
*/
export function useFlashMessage(durationMs = 2400): {
msg: FlashMessage | null;
flash: (kind: FlashKind, text: string) => void;
setMsg: (msg: FlashMessage | null) => void;
} {
const [msg, setMsg] = useState<FlashMessage | null>(null);
const timer = useRef<number | null>(null);
useEffect(() => () => { if (timer.current) clearTimeout(timer.current); }, []);
const flash = (kind: FlashKind, text: string) => {
setMsg({ kind, text });
if (timer.current) clearTimeout(timer.current);
timer.current = window.setTimeout(() => setMsg(null), durationMs);
};
return { msg, flash, setMsg };
}

Some files were not shown because too many files have changed in this diff Show More