Compare commits

...

16 Commits

Author SHA1 Message Date
DrSmoothl
8fc68c0ec3 chore(release): v2.1.0 2026-10-21 20:28:15 +08:00
DrSmoothl
b4ece8671b fix: improve client self-message reporting
Update desktop support for client-sent private and group messages.

Refs #528
2026-10-21 17:42:56 +08:00
DrSmoothl
bde7f2805d fix: handle delayed client message availability
Keep self-sent private messages available when their history becomes visible shortly after sending. Preserve account isolation while completing the report.

Refs #528
2026-10-21 17:25:13 +08:00
DrSmoothl
491b531841 feat: support client private-message reporting
Handle confirmed private messages sent from the client and preserve account isolation when sessions change. Surface unavailable messages without reporting incomplete content.

Refs #528.
2026-10-21 16:59:26 +08:00
DrSmoothl
617e7581dd fix: avoid duplicate private self-message reports
Keep repeated confirmations of the same private message from producing duplicate events while preserving distinct messages and stored content.

Refs #528.
2026-10-21 16:59:19 +08:00
DrSmoothl
27120f884a fix: resolve issue #559
Fixes #559.
2026-10-21 15:17:43 +08:00
DrSmoothl
3a4c1eeea2 fix(onebot): deduplicate client group self-message reports
Prevent repeated reports for client-originated group messages while preserving distinct sends and existing private-message behavior.

Cover opt-in reporting, message formats, account isolation, and repeated delivery.

Refs #528
2026-10-21 14:43:37 +08:00
DrSmoothl
5cd4ae61dd feat(webui): add opt-in MaiBot appearance overlay 2026-10-21 13:07:44 +08:00
DrSmoothl
28f64113e7 test(core): resolve startup fixture paths through symlinks
Canonicalize temporary fixture directories before matching build inputs and locating staged updates. Compare the child working directory with its real path so startup tests also pass when the default temporary directory is a symlink.
2026-10-20 14:24:23 +08:00
DrSmoothl
c537311ed1 fix(core): bound forward caches with nested result retention
Keep at most 512 outer results per bridge and retain their bundled nested results as one cache group. Reads refresh the whole group, shared inner results survive while another containing group remains cached, and late sender enrichment cannot resurrect evicted entries.

Collect uploaded and downloaded nested results before publishing a complete cache group. Cover eviction, account isolation, nested retrieval, shared ownership and asynchronous enrichment through the forward API.

Refs #546, #555, #557.

Co-authored-by: wanqing-last <2917149421@qq.com>
2026-10-20 13:50:21 +08:00
DrSmoothl
9d8df59370 fix(protocol): decode XML forward identities from root attributes
Recognize forward cards with an omitted protocol service ID from the root msg attributes. Decode attribute references once so resource IDs and nested lookup keys survive XML escaping, while preserving ordinary XML when the root declaration is ambiguous.

Refs #547, #556, #558.

Co-authored-by: wanqing-last <2917149421@qq.com>
2026-10-20 13:49:53 +08:00
DrSmoothl
76846f40b1 fix(onebot): resolve voice transcription for signed message IDs
Allow voice transcription results to complete for messages with negative IDs while preserving existing message identities and account isolation.

Report unmatched transcription results accurately and document the signed message ID contract.

Fixes #554
2026-10-20 13:27:40 +08:00
DrSmoothl
79522d949f fix(protocol): recover highway uploads after missing responses
Try another available upload endpoint when a transfer stops responding,
while preserving confirmed progress and the current upload session.
Report unconfirmed transfers clearly and cover recovery and publication
boundaries with regression tests.

Fixes #552
2026-10-20 08:47:48 +08:00
手瓜一十雪
db142db9e6 chore(release): v2.0.3
Validated by the full CI workflow: https://github.com/SnowLuma/SnowLuma/actions/runs/39187830699
2026-10-19 10:02:42 +08:00
手瓜一十雪
e5cfec01bd refactor: replace polling with event-driven updates
Trigger account detection and group requests from observed changes. Remove native stage log forwarding and its lifecycle state, and simplify the README.
2026-10-19 09:56:20 +08:00
晚晴
1b74747251 fix(core): allow account reopening after a failed close (#545)
Allow an account to reconnect after a previous shutdown reports an error, while preserving error reporting.

Add regression tests for failed and pending shutdown tasks.
2026-10-18 23:31:26 +08:00
115 changed files with 5104 additions and 2394 deletions

View File

@@ -78,6 +78,8 @@ Use focused tests while iterating. Before handing off a code change, run the ful
`pnpm dev` starts Core and can attach to local QQ processes; use it only when runtime testing is intended. `pnpm dev:web` starts the frontend, which expects a WebUI backend. Follow the existing test fakes for isolated work rather than starting a live account unnecessarily.
WebUI deployment targets use a reversible presentation overlay. Read [the host appearance contract](packages/webui/INTEGRATIONS.md) before changing it. Keep target validation in `@snowluma/common/webui-target`, implementations in the frontend target registry, and saved preferences separate from effective appearance. Default deployments must not load target assets or host listeners; do not put target-name branches in business pages.
## Implementation rules
- **Fix the cause.** Reproduce failures at the owning layer and add a regression test for the observable behavior. Avoid account-, filename-, or example-specific patches.
@@ -86,6 +88,7 @@ Use focused tests while iterating. Before handing off a code change, run the ful
- **Keep parsing separate from effects.** QQ decoders and OneBot event converters translate data. Live state updates belong to their owning pipeline or service; reading history must not mutate live membership or pending requests.
- **Use the declared interfaces.** OneBot consumes the [Bridge interface](packages/core/src/bridge/bridge-interface.ts). Reuse package exports and existing dependency injection instead of reaching into another owner's state or building a second registry.
- **Validate at inputs.** Use the existing action field and cross-field validation helpers. Preserve accepted input forms, response fields and error behavior unless the change explicitly calls for new semantics. Do not silently discard invalid outbound message content.
- **Preserve signed message IDs.** OneBot `message_id` / `messageId` values generated by [message-id.ts](packages/onebot/src/message-id.ts) are non-zero signed 32-bit integers; negative values are valid. Use `f.messageId()` for action inputs and preserve the value through storage, replies, lookups and result matching. Protocol representations must be converted losslessly at their boundary; changing the sign or generation rule changes existing message identities.
- **Protect persisted data.** Message history and media metadata are durable records. Do not add automatic deletion or treat them as disposable caches. Migration changes need failure and restart coverage; keep failures visible.
- **Preserve transport policy.** Retain configured bind addresses and access checks. TLS startup failure must not silently downgrade to HTTP. Distinguish saved configuration from changes actually applied to a running adapter.
- **Keep types and ownership clear.** Follow the strict TypeScript configuration, existing import style and four-space TypeScript indentation. Validate unknown external data instead of hiding mismatches with casts or fallback values. Keep comments about reasons and non-obvious behavior.

View File

@@ -53,8 +53,7 @@ SnowLuma 是面向 QQ 客户端的 TypeScript 互操作运行时,将 QQ 原生
3. 打开 [`http://localhost:5099`](http://localhost:5099),使用启动日志中的初始密码登录 WebUI,按引导接入 QQ 进程并配置 OneBot 连接。
在「设置 → 关于 → 软件更新」下载新版本,再点「重启更新」。文件优先暂存于系统临时目录,不可用时使用安装目录的 `tmp/update`,下次启动时替换并清理,配置、日志与消息数据保留。更新沿用当前 Node.js;容器部署请更新镜像。
版本号遵循 [SemVer](https://semver.org/),在线更新仅安装正式版;构建元数据不影响版本排序。
账号识别由登录数据库的文件变化、进程和登录事件或手动操作触发,不做周期探测。未载入的 QQ 进程也不会持续调用 Windows Restart Manager;需要重查时可点击 WebUI 进程行的刷新/重连。
## 接入与文档

View File

@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "snowluma-monorepo",
"version": "2.0.2",
"version": "2.1.0",
"description": "SnowLuma monorepo workspace (pnpm)",
"private": true,
"type": "module",

View File

@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/bridge",
"version": "2.0.2",
"version": "2.1.0",
"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).",

View File

@@ -14,13 +14,15 @@ import {
import { PipeWatcher } from './pipe-watcher';
import { createProcessEnumerator, type ProcessEnumerator } from './process-enumerator';
import { QqHookClient } from './qq-hook-client';
import { detectAccountLoginsForPids, type AccountLoginState } from './qq-account';
import {
detectAccountLoginsForPids,
watchAccountChangesForPids,
type AccountLoginState,
} from './qq-account';
import type { HookProcessAccount, HookProcessInfo } from './types';
const AUTO_LOAD_MAX_ATTEMPTS = 3;
const DEFAULT_ACCOUNT_REPROBE_INTERVAL_MS = 5000;
type AutoLoadAttempt = {
attempts: number;
inFlight: boolean;
@@ -61,9 +63,8 @@ export type HookManagerDeps = {
* the HOME it actually runs under (a container can give every QQ instance
* its own). Defaults to reading QQ's own account data. */
detectAccounts?: (pids: readonly number[]) => Promise<AccountLoginState[]>;
/** How often the watcher re-probes the account label of each process, in
* milliseconds. Defaults to `DEFAULT_ACCOUNT_REPROBE_INTERVAL_MS`. */
accountReprobeIntervalMs?: number;
/** Subscribe to login database changes. Returns the subscription cleanup. */
watchAccounts?: (pids: readonly number[], onChange: () => void) => () => void;
/** When true, every newly-discovered QQ process is auto-injected (fires
* `loadProcess(pid)` from the watcher's 'process-discovered' handler).
* Failed loads are logged and leave the session in the 'error' state.
@@ -106,7 +107,7 @@ export class HookManager {
private readonly ownsPipeWatcher: boolean;
private readonly enumerator: ProcessEnumerator;
private readonly detectAccounts: (pids: readonly number[]) => Promise<AccountLoginState[]>;
private readonly accountReprobeIntervalMs: number;
private readonly watchAccounts: NonNullable<HookManagerDeps['watchAccounts']>;
private readonly autoLoadOnDiscovery: boolean;
private readonly onSessionsChangedRaw?: () => void;
private readonly log: Logger;
@@ -116,7 +117,8 @@ export class HookManager {
private accounts = new Map<number, HookProcessAccount>();
private accountProbe: Promise<void> | null = null;
private nextAccountProbeAt = 0;
private accountsDirty = true;
private stopWatchingAccounts?: () => void;
private lastAccountProbeFailure = '';
private disposed = false;
@@ -133,8 +135,9 @@ export class HookManager {
};
this.makeClient = deps.makeClient ?? ((pid: number) => new QqHookClient(pid));
this.detectAccounts = deps.detectAccounts ?? detectAccountLoginsForPids;
this.accountReprobeIntervalMs =
deps.accountReprobeIntervalMs ?? DEFAULT_ACCOUNT_REPROBE_INTERVAL_MS;
this.watchAccounts =
deps.watchAccounts ??
((pids, onChange) => watchAccountChangesForPids(pids, onChange, this.log));
this.autoLoadOnDiscovery = deps.autoLoadOnDiscovery ?? false;
this.enumerator = createProcessEnumerator({
@@ -186,6 +189,7 @@ export class HookManager {
await this.startPromise;
this.autoLoadAttempts.delete(pid);
const session = this.ensureSession(pid);
this.invalidateAccounts();
await session.load();
this.pipeWatcher.wake();
await this.refreshAccounts();
@@ -197,6 +201,7 @@ export class HookManager {
await this.startPromise;
this.autoLoadAttempts.delete(pid);
const session = this.ensureSession(pid);
this.invalidateAccounts();
await session.unload();
await this.refreshAccounts();
return this.processInfo(session);
@@ -206,6 +211,8 @@ export class HookManager {
this.assertValidPid(pid);
await this.startPromise;
const session = this.ensureSession(pid);
this.updateAccountWatcher();
this.invalidateAccounts();
await session.refresh();
await this.refreshAccounts();
return this.processInfo(session);
@@ -217,6 +224,7 @@ export class HookManager {
}
this.disposed = true;
this.stopWatchingAccounts?.();
for (const session of this.sessions.values()) {
session.dispose();
@@ -238,45 +246,52 @@ export class HookManager {
return { ...session.toInfo(), account: this.accounts.get(session.pid) ?? null };
}
private invalidateAccounts(): void {
this.accountsDirty = true;
}
private updateAccountWatcher(): void {
this.stopWatchingAccounts?.();
this.stopWatchingAccounts = this.watchAccounts([...this.sessions.keys()], () => {
this.invalidateAccounts();
void this.refreshAccounts();
});
}
/** REST, watcher ticks and login reconciliation share the same account snapshot. */
private async refreshAccounts(): Promise<void> {
if (this.disposed) {
if (this.disposed || this.sessions.size === 0) {
return;
}
if (this.accountProbe) {
await this.accountProbe;
// Process discovery invalidates the snapshot while a read is in flight.
if (this.nextAccountProbeAt === 0) {
await this.refreshAccounts();
}
return;
}
if (Date.now() < this.nextAccountProbeAt || this.sessions.size === 0) {
if (!this.accountsDirty) {
return;
}
this.nextAccountProbeAt = Date.now() + this.accountReprobeIntervalMs;
this.accountProbe = runWithTraceRequest(() => this.readAccounts()).finally(() => {
this.accountProbe = runWithTraceRequest(async () => {
// All callers await the replacement read too if a lifecycle change
// invalidates an in-flight result.
do {
this.accountsDirty = false;
await this.readAccounts();
} while (!this.disposed && this.sessions.size > 0 && this.accountsDirty);
}).finally(() => {
this.accountProbe = null;
});
await this.accountProbe;
}
private async readAccounts(): Promise<void> {
const sessions = new Map(this.sessions);
const accounts = new Map<number, HookProcessAccount>();
try {
for (const state of await this.detectAccounts([...sessions.keys()])) {
if (
state.pid !== null &&
sessions.has(state.pid) &&
this.sessions.get(state.pid) === sessions.get(state.pid)
) {
for (const state of await this.detectAccounts([...this.sessions.keys()])) {
if (state.pid !== null && this.sessions.has(state.pid)) {
accounts.set(state.pid, { uin: state.uin, nickname: state.nickname });
}
}
@@ -291,7 +306,7 @@ export class HookManager {
}
}
if (this.disposed) {
if (this.disposed || this.accountsDirty) {
return;
}
@@ -364,6 +379,7 @@ export class HookManager {
const session = this.sessions.get(pid);
if (session) {
this.invalidateAccounts();
session.onPipeUp();
}
});
@@ -375,6 +391,7 @@ export class HookManager {
const session = this.sessions.get(pid);
if (session) {
this.invalidateAccounts();
session.onPipeDown();
}
});
@@ -570,7 +587,10 @@ export class HookManager {
session.attachProcessInfo({ name: defaultProcessName() });
session.on('login', (uin: string, sender) => {
// Account switches can keep the same 'online' status.
this.invalidateAccounts();
this.bridgeManager.onHookLogin(pid, uin, sender);
this.notifySessionsChanged();
});
session.on('disconnected', (wasLoggedIn: boolean) => {
if (wasLoggedIn) {
@@ -580,20 +600,25 @@ export class HookManager {
session.on('receive-health-changed', (healthy: boolean) => {
this.bridgeManager.onPidReceiveHealthChanged(pid, healthy);
});
// status-changed fires on EVERY internal status mutation, including the
// ones reached via login / disconnected / refresh — subscribing here
// alone covers every transition the WebUI processes view cares about.
session.on('status-changed', () => {
let previousStatus = session.status;
session.on('status-changed', (status) => {
if (previousStatus === 'online' && status !== 'online') {
this.invalidateAccounts();
}
previousStatus = status;
this.notifySessionsChanged();
});
session.on('disposed', () => {
this.sessions.delete(pid);
this.accounts.delete(pid);
this.nextAccountProbeAt = 0;
this.updateAccountWatcher();
this.invalidateAccounts();
});
this.sessions.set(pid, session);
this.nextAccountProbeAt = 0;
this.updateAccountWatcher();
this.invalidateAccounts();
return session;
}

View File

@@ -957,6 +957,17 @@ export class HookSession extends EventEmitter {
return;
}
if (
packet.source === 'client-message' &&
(!isRealUin(packet.uin) || packet.uin !== this._uin)
) {
this.log.warn(
'Client message receipt belongs to an inactive account: PID=%d',
this.pid,
);
return;
}
const uin = packet.uin || this._uin;
// Routing requires a real UIN, but even a frame carrying UIN=0 proves the
// receive hook is alive. Attribute that evidence to the current epoch
@@ -986,6 +997,7 @@ export class HookSession extends EventEmitter {
seqId: packet.seq,
retCode: packet.error,
fromClient: false,
...(packet.source ? { source: packet.source } : {}),
body: Buffer.from(packet.body),
});
}

View File

@@ -12,6 +12,7 @@ export {
type LoginDbFailure,
} from './login-db';
export { accountDirName, loginDbPaths, ntMsgDbPath, qqDataRoots, qqDataRootsForPid } from './paths';
export { watchAccountChangesForPids } from './watch';
export {
decryptDatabase,
detectAlgorithm,

View File

@@ -0,0 +1,115 @@
import { errorMessage } from '@snowluma/common/errors';
import { createLogger, type Logger } from '@snowluma/common/logger';
import { watch, type FSWatcher } from 'node:fs';
import path from 'node:path';
import { loginDbPaths, qqDataRootsForPid } from './paths';
export function watchAccountChangesForPids(
pids: readonly number[],
onChange: () => void,
log: Logger = createLogger('QqAccount'),
): () => void {
const roots = new Set<string>();
for (const pid of pids) {
try {
for (const root of qqDataRootsForPid(pid)) {
roots.add(root);
}
} catch (error) {
log.warn('account watch root failed: PID=%d err=%s', pid, errorMessage(error));
}
}
return watchAccountFiles([...roots].flatMap(loginDbPaths), onChange, log);
}
/** Watch directories so replacing login.db or recreating its WAL keeps working. */
export function watchAccountFiles(
dbPaths: readonly string[],
onChange: () => void,
log: Logger = createLogger('QqAccount'),
): () => void {
const watchers = new Map<string, FSWatcher>();
let timer: NodeJS.Timeout | undefined;
const changed = () => {
clearTimeout(timer);
timer = setTimeout(() => {
timer = undefined;
onChange();
}, 250);
timer.unref();
};
const observe = (dbPath: string) => {
watchers.get(dbPath)?.close();
watchers.delete(dbPath);
const dbDirectory = path.dirname(dbPath);
let directory = dbDirectory;
for (;;) {
const target = path.relative(directory, dbPath).split(path.sep)[0]!;
try {
const watcher = watch(directory, { persistent: false }, (_event, filename) => {
if (
watchers.get(dbPath) !== watcher ||
(filename !== null &&
filename !== target &&
!(directory === dbDirectory && filename === `${target}-wal`))
) {
return;
}
// QQ may create its data directories after process discovery.
if (directory !== dbDirectory) {
observe(dbPath);
}
changed();
});
watcher.on('error', (error) => {
if (watchers.get(dbPath) !== watcher) {
return;
}
watcher.close();
watchers.delete(dbPath);
log.warn('account watch failed: path=%s err=%s', dbPath, errorMessage(error));
});
watchers.set(dbPath, watcher);
return;
} catch (error) {
const parent = path.dirname(directory);
if (
error instanceof Error &&
'code' in error &&
error.code === 'ENOENT' &&
parent !== directory
) {
directory = parent;
continue;
}
log.warn('account watch failed: path=%s err=%s', dbPath, errorMessage(error));
return;
}
}
};
for (const dbPath of new Set(dbPaths)) {
observe(dbPath);
}
return () => {
clearTimeout(timer);
for (const watcher of watchers.values()) {
watcher.close();
}
watchers.clear();
};
}

View File

@@ -7,6 +7,7 @@ import {
} from '@snowluma/common/logger';
import { renderParamsVerbose } from '@snowluma/common/log-summary';
import { isRealUin } from '@snowluma/common/uin';
import { CLIENT_MESSAGE_RECEIPT_CMD } from '@snowluma/common/protocol-types';
import { readdirSync, promises as fs } from 'fs';
import net from 'net';
import path from 'path';
@@ -38,6 +39,8 @@ export enum PipeOp {
recvPacket = 6,
loginState = 7,
loginIdentityHint = 17,
clientMessageReceipt = 21,
clientMessageState = 22,
}
const PipeFlagWantReply = 1 << 0;
@@ -55,6 +58,7 @@ export interface QqHookPacket {
cmd: string;
uin: string;
body: Buffer;
source?: 'client-message';
}
export interface QqHookHello {
@@ -1369,6 +1373,44 @@ export class QqHookClient extends EventEmitter {
return;
}
if (frame.op === PipeOp.clientMessageState) {
if (frame.status === 1) {
runtimeLog.debug('Client private-message reporting is available: PID=%d', this.pid);
} else {
runtimeLog.warn(
'Client private-message reporting is unavailable: PID=%d status=%d',
this.pid,
frame.status,
);
}
return;
}
if (frame.op === PipeOp.clientMessageReceipt) {
if (
frame.cmd !== '' ||
frame.requestId !== 0 ||
frame.flags !== 0 ||
frame.value0 <= 0n ||
frame.value0 > BigInt(Number.MAX_SAFE_INTEGER) ||
!isRealUin(frame.msg)
) {
runtimeLog.warn('Invalid client message receipt: PID=%d', this.pid);
return;
}
this.emit('packet', {
seq: Number(frame.value0),
error: frame.status,
cmd: CLIENT_MESSAGE_RECEIPT_CMD,
uin: frame.msg,
body: Buffer.from(frame.body),
source: 'client-message',
} satisfies QqHookPacket);
return;
}
if (frame.op !== PipeOp.recvPacket) {
return;
}

View File

@@ -24,6 +24,8 @@ interface Harness {
setLivePipes: (next: number[]) => void;
onSessionsChanged: ReturnType<typeof vi.fn>;
clientFactory: ReturnType<typeof vi.fn>;
notifyAccountChange: () => void;
watchAccounts: ReturnType<typeof vi.fn>;
}
function makeManager(
@@ -31,7 +33,6 @@ function makeManager(
processes?: number[];
livePipes?: number[];
detectAccounts?: (pids: readonly number[]) => Promise<AccountLoginState[]>;
accountReprobeIntervalMs?: number;
} = {},
): Harness {
let pids = opts.processes ?? [];
@@ -64,6 +65,13 @@ function makeManager(
onPidReceiveHealthChanged: vi.fn(),
} as unknown as BridgeManagerSink & { onPidReceiveHealthChanged: ReturnType<typeof vi.fn> };
const onSessionsChanged = vi.fn();
let accountChanged = () => {};
const watchAccounts = vi.fn((_pids: readonly number[], onChange: () => void) => {
accountChanged = onChange;
return vi.fn();
});
const manager = new HookManager({
bridgeManager,
pipeWatcher,
@@ -77,7 +85,7 @@ function makeManager(
makeClient: clientFactory,
listProcesses: async () => pids.map((pid) => ({ pid, name: 'qq', path: '' })),
detectAccounts: opts.detectAccounts ?? (async () => []),
accountReprobeIntervalMs: opts.accountReprobeIntervalMs,
watchAccounts,
onSessionsChanged,
});
return {
@@ -86,6 +94,8 @@ function makeManager(
bridgeManager,
onSessionsChanged,
clientFactory,
notifyAccountChange: () => accountChanged(),
watchAccounts,
setProcesses: (next) => {
pids = next;
},
@@ -198,6 +208,7 @@ describe('HookManager.onSessionsChanged', () => {
}),
listProcesses: async () => pids.map((pid) => ({ pid, name: 'qq', path: '' })),
detectAccounts: async () => [],
watchAccounts: () => () => {},
// onSessionsChanged deliberately omitted
});
await pipeWatcher.start();
@@ -210,7 +221,111 @@ describe('HookManager.onSessionsChanged', () => {
});
});
describe('HookManager periodic account re-probe', () => {
describe('HookManager account re-probe', () => {
it('reuses the account snapshot across ticks and REST reads while all sessions are online (#549)', async () => {
const detectAccounts = vi.fn(async (): Promise<AccountLoginState[]> => [
{ uin: '10001', uid: 'u_a', nickname: 'Alice', pid: 4242 },
{ uin: '10002', uid: 'u_b', nickname: 'Bob', pid: 5151 },
]);
const ctx = makeManager({
processes: [4242, 5151],
livePipes: [4242, 5151],
detectAccounts,
});
const now = vi.spyOn(Date, 'now');
try {
await ctx.pipeWatcher.start();
await flush();
for (const [index, uin] of ['10001', '10002'].entries()) {
const client = ctx.clientFactory.mock.results[index]!.value as EventEmitter;
client.emit('loginState', { loggedIn: true, uin, uinNumber: BigInt(uin) });
}
const initial = await ctx.manager.listProcesses();
expect(initial.map((info) => info.status)).toEqual(['online', 'online']);
const baseline = detectAccounts.mock.calls.length;
ctx.onSessionsChanged.mockClear();
const startedAt = Date.now();
for (let tick = 1; tick <= 10; tick++) {
now.mockReturnValue(startedAt + tick * 6000);
await ctx.pipeWatcher.tickNow();
expect(await ctx.manager.listProcesses()).toEqual(initial);
}
expect(detectAccounts).toHaveBeenCalledTimes(baseline);
expect(ctx.onSessionsChanged).not.toHaveBeenCalled();
} finally {
now.mockRestore();
ctx.manager.dispose();
ctx.pipeWatcher.dispose();
}
});
it.each(['loadProcess', 'unloadProcess', 'refreshProcess'] as const)(
'refreshes account labels on %s even within the probe interval',
async (operation) => {
let nickname = 'Alice';
const ctx = makeManager({
processes: [4242],
detectAccounts: async () => [{ uin: '10001', uid: 'u_a', nickname, pid: 4242 }],
});
try {
expect((await ctx.manager.listProcesses())[0]!.account?.nickname).toBe('Alice');
nickname = 'Updated';
expect((await ctx.manager[operation](4242)).account?.nickname).toBe('Updated');
} finally {
ctx.manager.dispose();
ctx.pipeWatcher.dispose();
}
},
);
it('discards an in-flight account result when an online process switches accounts', async () => {
const stale = Promise.withResolvers<AccountLoginState[]>();
const fresh = Promise.withResolvers<AccountLoginState[]>();
const detectAccounts = vi.fn(async (): Promise<AccountLoginState[]> => [
{ uin: '10001', uid: 'u_a', nickname: 'Alice', pid: 4242 },
]);
const ctx = makeManager({
processes: [4242],
livePipes: [4242],
detectAccounts,
});
try {
await ctx.pipeWatcher.start();
await flush();
const client = ctx.clientFactory.mock.results[0]!.value as EventEmitter;
client.emit('loginState', { loggedIn: true, uin: '10001', uinNumber: 10001n });
await ctx.manager.listProcesses();
detectAccounts.mockImplementationOnce(() => stale.promise);
detectAccounts.mockImplementationOnce(() => fresh.promise);
const refreshing = ctx.manager.refreshProcess(4242);
await flush();
const baseline = detectAccounts.mock.calls.length;
client.emit('loginState', { loggedIn: true, uin: '10002', uinNumber: 10002n });
const snapshot = ctx.manager.listProcesses();
await flush();
ctx.onSessionsChanged.mockClear();
stale.resolve([{ uin: '10003', uid: 'u_c', nickname: 'Stale', pid: 4242 }]);
await flush();
expect(ctx.onSessionsChanged).not.toHaveBeenCalled();
expect(detectAccounts).toHaveBeenCalledTimes(baseline + 1);
fresh.resolve([{ uin: '10002', uid: 'u_b', nickname: 'Bob', pid: 4242 }]);
expect((await snapshot)[0]!.account).toEqual({ uin: '10002', nickname: 'Bob' });
expect((await refreshing).account).toEqual({ uin: '10002', nickname: 'Bob' });
} finally {
stale.resolve([]);
fresh.resolve([]);
ctx.manager.dispose();
ctx.pipeWatcher.dispose();
}
});
it('shares one account probe between watcher ticks and concurrent snapshots', async () => {
const probe = Promise.withResolvers<AccountLoginState[]>();
const detectAccounts = vi.fn(() => probe.promise);
@@ -234,6 +349,86 @@ describe('HookManager periodic account re-probe', () => {
}
});
it.each(['pipe-down', 'client-close', 'logout'] as const)(
're-probes after %s and observes later login data changes',
async (event) => {
let accounts: AccountLoginState[] = [
{ uin: '10001', uid: 'u_a', nickname: 'Alice', pid: 4242 },
];
const detectAccounts = vi.fn(async () => accounts);
const ctx = makeManager({
processes: [4242],
livePipes: [4242],
detectAccounts,
});
const now = vi.spyOn(Date, 'now');
try {
await ctx.pipeWatcher.start();
await flush();
const client = ctx.clientFactory.mock.results[0]!.value as EventEmitter;
client.emit('loginState', { loggedIn: true, uin: '10001', uinNumber: 10001n });
await ctx.manager.listProcesses();
accounts = [];
if (event === 'pipe-down') {
ctx.setLivePipes([]);
await ctx.pipeWatcher.tickNow();
} else if (event === 'client-close') {
client.emit('close');
} else {
client.emit('loginState', { loggedIn: false, uin: '0', uinNumber: 0n });
}
await flush();
expect((await ctx.manager.listProcesses())[0]!.account).toBeNull();
accounts = [{ uin: '10002', uid: 'u_b', nickname: 'Bob', pid: 4242 }];
now.mockReturnValue(Date.now() + 6000);
ctx.notifyAccountChange();
await ctx.pipeWatcher.tickNow();
expect((await ctx.manager.listProcesses())[0]!.account?.uin).toBe('10002');
} finally {
now.mockRestore();
ctx.manager.dispose();
ctx.pipeWatcher.dispose();
}
},
);
it('re-probes when another process appears and when it exits', async () => {
let nickname = 'Alice';
const detectAccounts = vi.fn(async (): Promise<AccountLoginState[]> => [
{ uin: '10001', uid: 'u_a', nickname, pid: 4242 },
{ uin: '10002', uid: 'u_b', nickname: 'Bob', pid: 5151 },
]);
const ctx = makeManager({ processes: [4242], livePipes: [4242], detectAccounts });
try {
await ctx.pipeWatcher.start();
await flush();
const client = ctx.clientFactory.mock.results[0]!.value as EventEmitter;
client.emit('loginState', { loggedIn: true, uin: '10001', uinNumber: 10001n });
await ctx.manager.listProcesses();
nickname = 'Updated';
ctx.setProcesses([4242, 5151]);
await ctx.pipeWatcher.tickNow();
expect((await ctx.manager.listProcesses()).map((info) => info.account)).toEqual([
{ uin: '10001', nickname: 'Updated' },
{ uin: '10002', nickname: 'Bob' },
]);
nickname = 'Final';
ctx.setProcesses([4242]);
await ctx.pipeWatcher.tickNow();
await flush();
const list = await ctx.manager.listProcesses();
expect(list).toHaveLength(1);
expect(list[0]!.account?.nickname).toBe('Final');
} finally {
ctx.manager.dispose();
ctx.pipeWatcher.dispose();
}
});
it('keeps all process labels when an operation reads just one process', async () => {
const accounts: AccountLoginState[] = [
{ uin: '10001', uid: 'u_a', nickname: 'Alice', pid: 4242 },
@@ -246,8 +441,8 @@ describe('HookManager periodic account re-probe', () => {
try {
await ctx.manager.listProcesses();
const baseline = detectAccounts.mock.calls.length;
expect((await ctx.manager.refreshProcess(4242)).account?.uin).toBe('10001');
const baseline = detectAccounts.mock.calls.length;
ctx.onSessionsChanged.mockClear();
await ctx.pipeWatcher.tickNow();
await flush();
@@ -282,17 +477,13 @@ describe('HookManager periodic account re-probe', () => {
}
});
// A login can happen with no hook edge at all (QQ signs in after SnowLuma
// started, or before the hook was injected), so no session status changes
// and nothing pushes a fresh processes snapshot. These cover the watcher
// pass that re-reads the account labels and invalidates when they move.
// Login database changes can reveal login before the hook is loaded.
it('publishes when a process gains an account label', async () => {
let accounts: AccountLoginState[] = [{ uin: '1', uid: 'u1', nickname: 'A', pid: null }];
const ctx = makeManager({
processes: [4242],
detectAccounts: async () => accounts,
accountReprobeIntervalMs: 0,
});
await ctx.pipeWatcher.start();
await flush();
@@ -300,7 +491,7 @@ describe('HookManager periodic account re-probe', () => {
// QQ finished signing in: the account's nt_msg.db is now held by 4242.
accounts = [{ uin: '1', uid: 'u1', nickname: 'A', pid: 4242 }];
await ctx.pipeWatcher.tickNow();
ctx.notifyAccountChange();
await flush();
await flush();
@@ -317,14 +508,12 @@ describe('HookManager periodic account re-probe', () => {
const ctx = makeManager({
processes: [4242],
detectAccounts,
accountReprobeIntervalMs: 0,
});
await ctx.pipeWatcher.start();
await flush();
ctx.onSessionsChanged.mockClear();
await ctx.pipeWatcher.tickNow();
await ctx.pipeWatcher.tickNow();
ctx.notifyAccountChange();
await flush();
await flush();
@@ -340,7 +529,6 @@ describe('HookManager periodic account re-probe', () => {
const ctx = makeManager({
processes: [4242],
detectAccounts: async () => accounts,
accountReprobeIntervalMs: 0,
});
await ctx.pipeWatcher.start();
await flush();
@@ -352,7 +540,7 @@ describe('HookManager periodic account re-probe', () => {
{ uin: '1', uid: 'u1', nickname: 'A', pid: null },
{ uin: '2', uid: 'u2', nickname: 'B', pid: null },
];
await ctx.pipeWatcher.tickNow();
ctx.notifyAccountChange();
await flush();
await flush();
@@ -361,24 +549,89 @@ describe('HookManager periodic account re-probe', () => {
ctx.manager.dispose();
});
it('throttles the probe to the configured interval', async () => {
it('does not poll unlabelled, unloaded processes even after the old interval expires', async () => {
const detectAccounts = vi.fn(async () => [] as AccountLoginState[]);
const ctx = makeManager({
processes: [4242],
detectAccounts,
accountReprobeIntervalMs: 60_000,
});
await ctx.pipeWatcher.start();
await flush();
const baseline = detectAccounts.mock.calls.length;
const now = vi.spyOn(Date, 'now');
await ctx.pipeWatcher.tickNow();
await ctx.pipeWatcher.tickNow();
await flush();
try {
await ctx.manager.listProcesses();
const baseline = detectAccounts.mock.calls.length;
const startedAt = Date.now();
expect(detectAccounts.mock.calls.length).toBe(baseline);
for (let tick = 1; tick <= 10; tick++) {
now.mockReturnValue(startedAt + tick * 6000);
await ctx.pipeWatcher.tickNow();
expect((await ctx.manager.listProcesses())[0]!.account).toBeNull();
}
ctx.manager.dispose();
expect(detectAccounts).toHaveBeenCalledTimes(baseline);
} finally {
now.mockRestore();
ctx.manager.dispose();
ctx.pipeWatcher.dispose();
}
});
it('does not re-probe a mixed set of online and unloaded processes', async () => {
const detectAccounts = vi.fn(async (): Promise<AccountLoginState[]> => [
{ uin: '10001', uid: 'u_a', nickname: 'Alice', pid: 4242 },
]);
const ctx = makeManager({
processes: [4242, 5151],
livePipes: [4242],
detectAccounts,
});
const now = vi.spyOn(Date, 'now');
try {
await ctx.pipeWatcher.start();
await flush();
const client = ctx.clientFactory.mock.results[0]!.value as EventEmitter;
client.emit('loginState', { loggedIn: true, uin: '10001', uinNumber: 10001n });
expect((await ctx.manager.listProcesses()).map((info) => info.status)).toEqual([
'online',
'available',
]);
const baseline = detectAccounts.mock.calls.length;
now.mockReturnValue(Date.now() + 60_000);
await ctx.pipeWatcher.tickNow();
await ctx.manager.listProcesses();
expect(detectAccounts).toHaveBeenCalledTimes(baseline);
} finally {
now.mockRestore();
ctx.manager.dispose();
ctx.pipeWatcher.dispose();
}
});
it('releases file subscriptions when the process set changes and the manager stops', async () => {
const ctx = makeManager({ processes: [4242] });
try {
await ctx.pipeWatcher.start();
expect(ctx.watchAccounts).toHaveBeenLastCalledWith([4242], expect.any(Function));
const firstStop = ctx.watchAccounts.mock.results.at(-1)!.value;
ctx.setProcesses([4242, 5151]);
await ctx.pipeWatcher.tickNow();
expect(firstStop).toHaveBeenCalledOnce();
expect(ctx.watchAccounts).toHaveBeenLastCalledWith([4242, 5151], expect.any(Function));
const secondStop = ctx.watchAccounts.mock.results.at(-1)!.value;
ctx.setProcesses([5151]);
await ctx.pipeWatcher.tickNow();
await flush();
expect(secondStop).toHaveBeenCalledOnce();
expect(ctx.watchAccounts).toHaveBeenLastCalledWith([5151], expect.any(Function));
const finalStop = ctx.watchAccounts.mock.results.at(-1)!.value;
ctx.manager.dispose();
expect(finalStop).toHaveBeenCalledOnce();
} finally {
ctx.manager.dispose();
ctx.pipeWatcher.dispose();
}
});
it('keeps working when detection fails, and reports the failure once', async () => {
@@ -387,7 +640,6 @@ describe('HookManager periodic account re-probe', () => {
detectAccounts: async () => {
throw new Error('login.db unreadable');
},
accountReprobeIntervalMs: 0,
});
await ctx.pipeWatcher.start();
await flush();

View File

@@ -80,6 +80,7 @@ function makeManager(opts: {
listProcesses: async () => pids.map((pid) => ({ pid, name: 'qq', path: '' })),
// Detection reads QQ's own data directories; tests stay off the host.
detectAccounts: opts.detectAccounts ?? (async () => []),
watchAccounts: () => () => {},
});
return {
manager,

View File

@@ -72,6 +72,7 @@ describe('HookManager — Docker reconnect-without-login leak guard', () => {
autoLoadOnDiscovery: true,
listProcesses: async () => [{ pid: PID, name: 'qq', path: '' }],
detectAccounts: async () => [],
watchAccounts: () => () => {},
});
// Initial discovery + first connect.

View File

@@ -929,6 +929,42 @@ describe('HookSession — pipe-down must not clobber a settled error', () => {
});
describe('HookSession — packet forwarding', () => {
it('forwards client receipts only for the active account without changing direction', async () => {
const onPacket = vi.fn();
const ctx = makeSession({ pipeLive: true, onPacket });
await ctx.session.load();
ctx.session.onPipeUp();
await flush();
ctx.currentClient().fireLogin('10001');
const receipt: QqHookPacket = {
seq: 42,
error: 0,
cmd: 'ClientMessageReceipt',
uin: '10001',
source: 'client-message',
body: Buffer.from([1, 2, 3]),
};
for (const uin of ['', '0', '20002']) {
ctx.currentClient().firePacket({ ...receipt, uin });
}
expect(onPacket).not.toHaveBeenCalled();
ctx.currentClient().firePacket(receipt);
expect(onPacket).toHaveBeenCalledExactlyOnceWith(
expect.objectContaining({
pid: 1234,
uin: '10001',
source: 'client-message',
fromClient: false,
}),
);
ctx.currentClient().fireLogin('20002');
ctx.currentClient().firePacket(receipt);
expect(onPacket).toHaveBeenCalledOnce();
await ctx.session.dispose();
});
// These tests cover the field-rename + filter logic that used to live
// inside the deleted NtqqHandler.onHookPacket. Inlining it here means
// we can exercise the transformation with a plain vi.fn() sink, no

View File

@@ -0,0 +1,119 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import * as fs from 'node:fs';
import { mkdtemp, mkdir, rename, rm, writeFile } from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import { setTimeout as delay } from 'node:timers/promises';
import { createLogger } from '@snowluma/common/logger';
import { watchAccountFiles } from '../src/qq-account/watch';
vi.mock('node:fs', async (importOriginal) => {
const actual = await importOriginal<typeof fs>();
return { ...actual, watch: vi.fn(actual.watch) };
});
let root: string;
const subscriptions: Array<() => void> = [];
beforeEach(async () => {
root = await mkdtemp(path.join(os.tmpdir(), 'snowluma-account-watch-'));
});
afterEach(async () => {
for (const stop of subscriptions.splice(0)) {
stop();
}
await rm(root, { recursive: true, force: true });
vi.restoreAllMocks();
vi.clearAllMocks();
});
function subscribe(dbPaths = [path.join(root, 'login.db')]) {
const changed = vi.fn();
const log = createLogger('AccountWatchTest');
const warning = vi.spyOn(log, 'warn');
const stop = watchAccountFiles(dbPaths, changed, log);
subscriptions.push(stop);
return { changed, stop, warning };
}
describe('account file changes', () => {
it('coalesces login database and WAL changes while ignoring message data and SHM', async () => {
const dbPath = path.join(root, 'login.db');
const { changed } = subscribe([dbPath, dbPath]);
expect(fs.watch).toHaveBeenCalledTimes(1);
await writeFile(dbPath, 'login');
await writeFile(`${dbPath}-wal`, 'wal');
await vi.waitFor(() => expect(changed).toHaveBeenCalledTimes(1));
await writeFile(path.join(root, 'nt_msg.db'), 'message');
await writeFile(`${dbPath}-shm`, 'shared memory');
await delay(350);
expect(changed).toHaveBeenCalledTimes(1);
});
it('observes database replacement and WAL recreation', async () => {
const dbPath = path.join(root, 'login.db');
await writeFile(dbPath, 'initial');
const { changed } = subscribe();
await writeFile(path.join(root, 'replacement'), 'replacement');
await rename(path.join(root, 'replacement'), dbPath);
await vi.waitFor(() => expect(changed).toHaveBeenCalledTimes(1));
await writeFile(dbPath, 'updated');
await vi.waitFor(() => expect(changed).toHaveBeenCalledTimes(2));
await writeFile(`${dbPath}-wal`, 'wal');
await vi.waitFor(() => expect(changed).toHaveBeenCalledTimes(3));
await rm(`${dbPath}-wal`);
await writeFile(`${dbPath}-wal`, 'new wal');
await vi.waitFor(() => expect(changed).toHaveBeenCalledTimes(4));
});
it('starts watching login data created after QQ process discovery', async () => {
const dbPath = path.join(root, 'QQ', 'global', 'nt_db', 'login.db');
const { changed } = subscribe([dbPath]);
await mkdir(path.dirname(dbPath), { recursive: true });
await writeFile(dbPath, 'initial');
await vi.waitFor(() => expect(changed).toHaveBeenCalledTimes(1));
await writeFile(`${dbPath}-wal`, 'login');
await vi.waitFor(() => expect(changed).toHaveBeenCalledTimes(2));
});
it('closes watchers and cancels pending notifications on disposal', async () => {
const { changed, stop } = subscribe();
await writeFile(path.join(root, 'login.db'), 'initial');
await delay(30);
stop();
await writeFile(path.join(root, 'login.db'), 'later');
await delay(350);
expect(changed).not.toHaveBeenCalled();
});
it('reports watch failures without starting a polling fallback', async () => {
vi.mocked(fs.watch).mockImplementationOnce(() => {
throw Object.assign(new Error('access denied'), { code: 'EACCES' });
});
const { changed, warning } = subscribe();
expect(warning).toHaveBeenCalledWith(
'account watch failed: path=%s err=%s',
path.join(root, 'login.db'),
'access denied',
);
await delay(350);
expect(fs.watch).toHaveBeenCalledTimes(1);
expect(changed).not.toHaveBeenCalled();
});
it('reports asynchronous watch errors and closes the failed watcher', () => {
const { changed, warning } = subscribe();
const watcher = vi.mocked(fs.watch).mock.results[0]!.value;
const close = vi.spyOn(watcher, 'close');
watcher.emit('error', new Error('watch unavailable'));
expect(close).toHaveBeenCalledOnce();
expect(warning).toHaveBeenCalledWith(
'account watch failed: path=%s err=%s',
path.join(root, 'login.db'),
'watch unavailable',
);
expect(changed).not.toHaveBeenCalled();
});
});

View File

@@ -12,6 +12,7 @@ import {
type LogEntry,
} from '@snowluma/common/logger';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { CLIENT_MESSAGE_RECEIPT_CMD } from '@snowluma/common/protocol-types';
import {
HEADER_SIZE,
listLiveLinuxPipePids,
@@ -147,6 +148,113 @@ describe('QqHookClient login wait lifecycle', () => {
});
});
describe('QqHookClient client message receipts', () => {
it('preserves receipt provenance and failure status separately from normal packets', async () => {
const sockets = mockControlPipe(12345, () => {});
const client = new QqHookClient(12345);
const onPacket = vi.fn();
try {
await client.startRecv(onPacket);
const socket = sockets.mock.results[0]!.value;
const body = Buffer.from([1, 2, 3]);
socket.emit(
'data',
pipeFrame({ op: PipeOp.clientMessageReceipt, value0: 42n, message: '10001', body }),
);
socket.emit(
'data',
pipeFrame({
op: PipeOp.clientMessageReceipt,
value0: 43n,
message: '10001',
status: -1,
}),
);
socket.emit(
'data',
pipeFrame({
op: PipeOp.recvPacket,
value0: 44n,
message: '10001',
cmd: CLIENT_MESSAGE_RECEIPT_CMD,
body,
}),
);
expect(onPacket.mock.calls.map(([packet]) => packet)).toEqual([
{
seq: 42,
error: 0,
cmd: CLIENT_MESSAGE_RECEIPT_CMD,
uin: '10001',
body,
source: 'client-message',
},
{
seq: 43,
error: -1,
cmd: CLIENT_MESSAGE_RECEIPT_CMD,
uin: '10001',
body: Buffer.alloc(0),
source: 'client-message',
},
{ seq: 44, error: 0, cmd: CLIENT_MESSAGE_RECEIPT_CMD, uin: '10001', body },
]);
} finally {
client.close();
}
});
it('reports unsupported capability and invalid envelopes without breaking normal receive', async () => {
const entries: LogEntry[] = [];
setLogLevel('warn');
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
const sockets = mockControlPipe(12345, () => {});
const client = new QqHookClient(12345);
const onPacket = vi.fn();
try {
await client.startRecv(onPacket);
const socket = sockets.mock.results[0]!.value;
socket.emit('data', pipeFrame({ op: PipeOp.clientMessageState, status: -1 }));
for (const patch of [
{ value0: 0n },
{ value0: BigInt(Number.MAX_SAFE_INTEGER) + 1n },
{ message: '' },
{ cmd: 'unexpected' },
{ requestId: 1 },
]) {
socket.emit(
'data',
pipeFrame({
op: PipeOp.clientMessageReceipt,
value0: 42n,
message: '10001',
...patch,
}),
);
}
expect(onPacket).not.toHaveBeenCalled();
expect(
entries.filter(
(entry) => entry.scope === 'QQHook.Runtime' && entry.level === 'warn',
),
).toHaveLength(6);
socket.emit(
'data',
pipeFrame({ op: PipeOp.recvPacket, cmd: 'normal', message: '10001', value0: 44n }),
);
expect(onPacket).toHaveBeenCalledOnce();
} finally {
client.close();
unsubscribe();
}
});
});
describe('listLiveLinuxPipePids', () => {
it('ignores stale-looking control socket names when the probe rejects them', async () => {
const runtimeDir = await makeRuntimeDir();

View File

@@ -1,13 +1,17 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/common",
"version": "2.0.2",
"version": "2.1.0",
"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).",
"main": "./src/index.ts",
"types": "./src/index.ts",
"exports": {
"./webui-target": {
"types": "./src/webui-target.ts",
"default": "./src/webui-target.ts"
},
"./update-source": {
"types": "./src/update-source.ts",
"default": "./src/update-source.ts"

View File

@@ -1,3 +1,5 @@
export const CLIENT_MESSAGE_RECEIPT_CMD = 'ClientMessageReceipt';
export interface PacketInfo {
pid: number;
uin: string;
@@ -6,6 +8,7 @@ export interface PacketInfo {
seqId: number;
retCode: number;
fromClient: boolean;
source?: 'client-message';
body: Uint8Array;
}
export type PacketSink = (packet: PacketInfo) => void;

View File

@@ -0,0 +1,100 @@
/** Browser-safe contract shared by startup, the WebUI and embedding hosts.
* Targets are deployment choices; they never belong in the saved UI preferences. */
export const WEBUI_TARGETS = {
maibot: {
label: '麦麦 / 一键包',
styles: ['millennium'],
defaultStyle: 'millennium',
},
} as const;
export type WebuiTarget = keyof typeof WEBUI_TARGETS;
export type WebuiColorMode = 'light' | 'dark' | 'system';
export type WebuiPresentation = {
[T in WebuiTarget]: {
version: 1;
target: T;
style: (typeof WEBUI_TARGETS)[T]['styles'][number];
mode: WebuiColorMode;
};
}[WebuiTarget];
/** null releases the override for this document, without changing deployment opt-in. */
export type WebuiPresentationUpdate = WebuiPresentation | { version: 1; target: null };
export const WEBUI_PRESENTATION_EVENT = 'snowluma:host-appearance';
export const WEBUI_TARGET_BOOTSTRAP_ID = 'snowluma-webui-target';
export function resolveWebuiTarget(raw: string | undefined): WebuiTarget | null {
if (raw === undefined || raw.trim() === '') {
return null;
}
const value = raw.trim();
if (!Object.hasOwn(WEBUI_TARGETS, value)) {
throw new Error(
`Invalid SNOWLUMA_WEBUI_TARGET: ${JSON.stringify(value)}. Expected ${Object.keys(WEBUI_TARGETS).join(', ')} or an empty value.`,
);
}
return value as WebuiTarget;
}
export function defaultWebuiPresentation(target: WebuiTarget): WebuiPresentation {
return { version: 1, target, style: WEBUI_TARGETS[target].defaultStyle, mode: 'system' };
}
export function parseWebuiPresentation(value: unknown): WebuiPresentationUpdate {
if (
!value ||
typeof value !== 'object' ||
!('version' in value) ||
value.version !== 1 ||
!('target' in value)
) {
throw new TypeError('Invalid host appearance: expected a version 1 presentation');
}
if (value.target === null) {
return { version: 1, target: null };
}
if (typeof value.target !== 'string' || !Object.hasOwn(WEBUI_TARGETS, value.target)) {
throw new TypeError('Invalid host appearance target');
}
const target = value.target as WebuiTarget;
const styles: readonly string[] = WEBUI_TARGETS[target].styles;
if (!('style' in value) || typeof value.style !== 'string' || !styles.includes(value.style)) {
throw new TypeError(`Invalid host appearance style for ${target}`);
}
if (
!('mode' in value) ||
(value.mode !== 'light' && value.mode !== 'dark' && value.mode !== 'system')
) {
throw new TypeError('Invalid host appearance color mode');
}
// Both discriminants have been checked against the same target registry.
return { version: 1, target, style: value.style, mode: value.mode } as WebuiPresentation;
}
/** Inject before the cached pre-paint theme script. Default HTML stays byte-for-byte intact. */
export function injectWebuiTarget(html: string, target: WebuiTarget | null): string {
if (target === null) {
return html;
}
if (!html.includes('<head>')) {
throw new Error('WebUI HTML is missing <head>; cannot inject runtime target');
}
const json = JSON.stringify(defaultWebuiPresentation(target)).replaceAll('<', '\\u003c');
return html.replace(
'<head>',
`<head>\n <script id="${WEBUI_TARGET_BOOTSTRAP_ID}" type="application/json">${json}</script>`,
);
}

View File

@@ -0,0 +1,51 @@
import { describe, expect, it } from 'vitest';
import {
defaultWebuiPresentation,
injectWebuiTarget,
parseWebuiPresentation,
resolveWebuiTarget,
} from '../src/webui-target';
describe('deployment presentation contract', () => {
it('requires explicit opt-in and rejects misspelled deployments', () => {
expect(resolveWebuiTarget(undefined)).toBeNull();
expect(resolveWebuiTarget(' ')).toBeNull();
expect(resolveWebuiTarget('maibot')).toBe('maibot');
expect(() => resolveWebuiTarget('mai-bot')).toThrow('SNOWLUMA_WEBUI_TARGET');
expect(() => resolveWebuiTarget('__proto__')).toThrow('SNOWLUMA_WEBUI_TARGET');
});
it('keeps the unconfigured document intact and injects before cached appearance', () => {
const html = '<html><head><script>readSavedAppearance()</script></head></html>';
expect(injectWebuiTarget(html, null)).toBe(html);
const injected = injectWebuiTarget(html, 'maibot');
expect(injected.indexOf('snowluma-webui-target')).toBeLessThan(
injected.indexOf('readSavedAppearance'),
);
expect(injected).toContain(JSON.stringify(defaultWebuiPresentation('maibot')));
expect(() => injectWebuiTarget('broken html', 'maibot')).toThrow('missing <head>');
});
it('validates the version, target, style and color mode without accepting arbitrary CSS', () => {
const valid = defaultWebuiPresentation('maibot');
expect(parseWebuiPresentation(valid)).toEqual(valid);
expect(
parseWebuiPresentation({ ...valid, mode: 'dark', css: 'body{display:none}' }),
).toEqual({ ...valid, mode: 'dark' });
expect(parseWebuiPresentation({ version: 1, target: null })).toEqual({
version: 1,
target: null,
});
for (const input of [
null,
{},
{ ...valid, version: 2 },
{ ...valid, target: 'other' },
{ ...valid, style: 'modern' },
{ ...valid, mode: 'blue' },
]) {
expect(() => parseWebuiPresentation(input)).toThrow();
}
});
});

View File

@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/core",
"version": "2.0.2",
"version": "2.1.0",
"description": "SnowLuma core - NTQQ packet sniffer with Node.js native addon",
"private": true,
"type": "module",

View File

@@ -581,11 +581,48 @@ export class ContactsApi {
return requests;
}
/** Live observation write. IncomingPacketPipeline and tests only. */
rememberGroupInviteCardSequence(groupUin: number, sequence: number): void {
if (groupUin > 0 && sequence > 0) {
this.groupInviteCardSeqs_.set(groupUin, sequence);
async resolveGroupJoinRequest(
groupId: number,
uid: string,
subType: 'add' | 'invite',
invitedUid?: string,
): Promise<GroupRequestInfo | null> {
const [main, filtered] = await Promise.allSettled([
this.fetchGroupRequestsByUid(false),
this.fetchGroupRequestsByUid(true),
]);
if (main.status === 'rejected') {
throw main.reason;
}
if (filtered.status === 'rejected') {
throw filtered.reason;
}
return (
[...main.value, ...filtered.value].find((request) => {
if (request.groupId !== groupId || request.state !== 1) {
return false;
}
return subType === 'add'
? request.eventType === 1 && request.targetUid === uid
: (request.eventType === 2 || request.eventType === 22) &&
request.invitorUid === uid &&
request.targetUid === invitedUid;
}) ?? null
);
}
/** Returns whether this live card introduces a new approval sequence. */
rememberGroupInviteCardSequence(groupUin: number, sequence: number): boolean {
if (this.groupInviteCardSeqs_.get(groupUin) === sequence) {
return false;
}
this.groupInviteCardSeqs_.set(groupUin, sequence);
return true;
}
/** The approval msgseq captured from a private "qun.invite" card for this

View File

@@ -0,0 +1,69 @@
import { createLogger } from '@snowluma/common/logger';
import type { ForwardNodePayload } from '@snowluma/protocol/events';
const MAX_CACHED_FORWARDS = 512;
const log = createLogger('Bridge.Forward');
type ForwardLayers = Map<string, ForwardNodePayload[]>;
interface ForwardCacheHit {
rootId: string;
resId: string;
layers: ForwardLayers;
nodes: ForwardNodePayload[];
}
/** Nested results share the lifetime and recency of the result that supplied them. */
export class ForwardResultCache {
private readonly entries = new Map<string, ForwardLayers>();
get(resId: string): ForwardCacheHit | undefined {
let hit: ForwardCacheHit | undefined;
// A nested result can be supplied by several retained outer results.
for (const [rootId, layers] of this.entries) {
const nodes = layers.get(resId);
if (nodes) {
hit = { rootId, resId, layers, nodes };
}
}
if (hit) {
this.entries.delete(hit.rootId);
this.entries.set(hit.rootId, hit.layers);
}
return hit;
}
set(rootId: string, layers: ReadonlyMap<string, ForwardNodePayload[]>): void {
if (!layers.has(rootId)) {
throw new Error('forward cache entry is missing its outer result');
}
this.entries.delete(rootId);
this.entries.set(rootId, new Map(layers));
while (this.entries.size > MAX_CACHED_FORWARDS) {
const oldest = this.entries.entries().next().value!;
this.entries.delete(oldest[0]);
log.trace(
'forward cache evicted: res_id=%s layers=%d remaining=%d',
oldest[0],
oldest[1].size,
this.entries.size,
);
}
}
update(hit: ForwardCacheHit, nodes: ForwardNodePayload[]): void {
// Enrichment may finish after eviction or replacement. It must not revive
// an old result or turn a nested result into an independent cache entry.
if (
this.entries.get(hit.rootId) === hit.layers &&
hit.layers.get(hit.resId) === hit.nodes
) {
hit.layers.set(hit.resId, nodes);
}
}
}

View File

@@ -25,16 +25,15 @@ import { randomUUID } from 'crypto';
import { gunzipSync, gzipSync } from 'zlib';
import type { Bridge } from '../bridge';
import type { BridgeContext, UploadedFileMeta } from '../bridge-context';
import { ForwardResultCache } from './forward-cache';
import { resolveSelfUid, toInt } from './shared';
function asBridge(ctx: BridgeContext): Bridge {
return ctx as unknown as Bridge;
}
// Module-scoped cache, keyed by res_id. Survives only for the lifetime
// of the process — that's enough because OneBot clients typically
// resolve a forward immediately after receiving the parent message.
const forwardResCache = new Map<string, ForwardNodePayload[]>();
// Share within a bridge without retaining disconnected accounts.
const forwardCaches = new WeakMap<BridgeContext, ForwardResultCache>();
const log = createLogger('Bridge.Forward');
@@ -77,6 +76,7 @@ interface ForwardUploadResult {
// callers concatenate these to their own actions list so the
// outermost upload carries the full tree.
innerActions: ForwardInnerAction[];
cachedLayers: Map<string, ForwardNodePayload[]>;
}
// Local hex-decode helper — avoids importing the heavyweight `pipeline`
@@ -353,7 +353,18 @@ function assertNoWindowShakeInForward(nodes: ForwardNodePayload[]): void {
}
export class ForwardApi {
constructor(private readonly ctx: BridgeContext) {}
private readonly cache: ForwardResultCache;
constructor(private readonly ctx: BridgeContext) {
let cache = forwardCaches.get(ctx);
if (!cache) {
cache = new ForwardResultCache();
forwardCaches.set(ctx, cache);
}
this.cache = cache;
}
async upload(nodes: ForwardNodePayload[], groupId?: number, userId?: number): Promise<string> {
// Reject the complete recursive tree before identity resolution, media
@@ -367,7 +378,8 @@ export class ForwardApi {
assertPrivateForwardFileCapacity(nodes);
}
const { resId } = await this.uploadRecursive(nodes, groupId, userId);
const { resId, cachedLayers } = await this.uploadRecursive(nodes, groupId, userId);
this.cache.set(resId, cachedLayers);
return resId;
}
@@ -593,6 +605,7 @@ export class ForwardApi {
// — see `dev/NapCatQQ/.../SendMsg.ts:241-246` + the `uniseq` round-
// trip in `dev/NapCatQQ/.../forward-msg-builder.ts:94`.
const myInnerActions: ForwardInnerAction[] = [];
const cachedLayers = new Map<string, ForwardNodePayload[]>();
const processedNodes: ForwardNodePayload[] = [];
const isGroup = groupId !== undefined;
@@ -605,6 +618,11 @@ export class ForwardApi {
// and `inner.innerActions` already contains deeper layers.
myInnerActions.push({ uuid: inner.uuid, msgBody: inner.msgBody });
myInnerActions.push(...inner.innerActions);
for (const [resId, cached] of inner.cachedLayers) {
cachedLayers.set(resId, cached);
}
// Replace the inner placeholder element with a forward preview
// pointing at the inner res_id. `forwardUuid: inner.uuid`
// baked into the LightApp JSON's `meta.detail.uniseq` is what
@@ -692,7 +710,7 @@ export class ForwardApi {
throw new Error('upload forward message response missing res_id');
}
forwardResCache.set(
cachedLayers.set(
resId,
uploadReadyNodes.map((node) => ({
...cloneNodeWithElements(node, node.elements.map(cacheableForwardElement)),
@@ -714,20 +732,21 @@ export class ForwardApi {
// from (1) — no separate fetch needed.
uuid: randomUUID(),
innerActions: myInnerActions,
cachedLayers,
};
}
async fetch(resId: string): Promise<ForwardNodePayload[]> {
const bridge = asBridge(this.ctx);
const cached = forwardResCache.get(resId);
const cached = this.cache.get(resId);
if (cached) {
const nodes = cloneNodes(cached);
const nodes = cloneNodes(cached.nodes);
// Inner nodes seeded by consumePiggybacks are cached un-enriched; enrich
// Bundled inner nodes are cached un-enriched; enrich
// on read (a no-op once names are present) and persist so later hits skip.
if (await this.enrichSenders(nodes)) {
forwardResCache.set(resId, cloneNodes(nodes));
this.cache.update(cached, cloneNodes(nodes));
}
return nodes;
@@ -820,9 +839,7 @@ export class ForwardApi {
// matching piggyback body, decode it into inner nodes, and seed
// the cache by the inner resId so a follow-up `fetch(innerResId)`
// hits the cache instead of the wire.
if (piggybackByUuid.size > 0) {
this.consumePiggybacks(nodes, piggybackByUuid);
}
const cachedLayers = this.collectForwardLayers(resId, nodes, piggybackByUuid);
// Fill sender nickname/card for nodes the SsoRecvLongMsg payload left empty
// or stamped with the "QQ用户" placeholder (#174) — the long-msg member name
@@ -830,7 +847,8 @@ export class ForwardApi {
await this.enrichSenders(nodes);
if (nodes.length > 0) {
forwardResCache.set(resId, cloneNodes(nodes));
cachedLayers.set(resId, cloneNodes(nodes));
this.cache.set(resId, cachedLayers);
}
return nodes;
@@ -1017,20 +1035,22 @@ export class ForwardApi {
return out;
}
/** Recursively resolve forward previews against the piggyback table.
/** Resolve forward previews against the piggyback table.
* For every `{type: 'forward', resId, forwardUuid}` element we find,
* look up the uniseq in the piggyback map; if hit, decode the
* inner msgBody and cache it by inner resId, then descend into that
* inner layer to resolve deeper nestings carried in the SAME
* piggyback set (NapCat hoists the entire tree's piggybacks onto
* the outermost action list). */
private consumePiggybacks(
private collectForwardLayers(
resId: string,
nodes: ForwardNodePayload[],
piggybackByUuid: Map<string, PushMsgBody[]>,
): void {
const seen = new Set<string>();
): Map<string, ForwardNodePayload[]> {
const layers = new Map([[resId, cloneNodes(nodes)]]);
const decodedByUuid = new Map<string, ForwardNodePayload[]>();
const visit = (chain: ForwardNodePayload[]): void => {
for (const chain of layers.values()) {
for (const node of chain) {
for (const elem of node.elements) {
if (elem.type !== 'forward') {
@@ -1040,7 +1060,7 @@ export class ForwardApi {
const uuid = elem.forwardUuid;
const innerResId = elem.resId;
if (!uuid || !innerResId || seen.has(uuid)) {
if (!uuid || !innerResId || layers.has(innerResId)) {
continue;
}
@@ -1050,15 +1070,19 @@ export class ForwardApi {
continue;
}
seen.add(uuid);
const innerNodes = this.decodeMsgBodiesToNodes(body);
forwardResCache.set(innerResId, cloneNodes(innerNodes));
visit(innerNodes);
let innerNodes = decodedByUuid.get(uuid);
if (!innerNodes) {
innerNodes = cloneNodes(this.decodeMsgBodiesToNodes(body));
decodedByUuid.set(uuid, innerNodes);
}
layers.set(innerResId, innerNodes);
}
}
};
}
visit(nodes);
return layers;
}
}

View File

@@ -4,7 +4,13 @@ import { packetTimeoutMs } from '@snowluma/bridge/packet-timeout';
import type { PacketInfo } from '@snowluma/common/protocol-types';
import { BridgeEventBus } from '@snowluma/protocol/event-bus';
import { IdentityService } from '@snowluma/protocol/identity-service';
import { MSG_PUSH_CMD, parseMsgPushOrThrow, SysMsgDedup } from '@snowluma/protocol/msg-push';
import {
MSG_PUSH_CMD,
parseMsgPushOrThrow,
SysMsgDedup,
decodeClientMessageReceipt,
fetchClientMessage,
} from '@snowluma/protocol/msg-push';
import { KICK_NT_CMD, parseKickNT } from '@snowluma/protocol/kick-nt';
import { IncomingPacketPipeline, type CmdParser } from '@snowluma/protocol/packet-pipeline';
import type { OnlineDeviceInfo } from '@snowluma/protocol/events';
@@ -38,6 +44,10 @@ export class Bridge implements BridgeInterface {
private onlineClients_: readonly Readonly<OnlineDeviceInfo>[] | null = null;
private disposePromise_: Promise<void> | null = null;
private readonly pendingPackets_ = new Set<Promise<void>>();
private readonly clientMessageTasks_ = new Map<
string,
{ connection: ProcessConnection; work: Promise<void> }
>();
private rosterWarmupStarted_ = false;
private settleRosterWarmup!: (result: RosterWarmupResult) => void;
private readonly rosterWarmup = new Promise<RosterWarmupResult>((resolve) => {
@@ -61,72 +71,10 @@ export class Bridge implements BridgeInterface {
fetchGroupMemberList: async (groupId) => {
await this.apis.contacts.fetchGroupMemberList(groupId);
},
resolveGroupJoinRequest: async (groupId, uid, subType) => {
const [main, filtered] = await Promise.allSettled([
this.apis.contacts.fetchGroupRequestsByUid(false),
this.apis.contacts.fetchGroupRequestsByUid(true),
]);
if (main.status === 'rejected') {
log.warn(
'group-request enrichment main inbox failed: group=%d uid=%s err=%s',
groupId,
uid,
main.reason instanceof Error ? main.reason.message : String(main.reason),
);
}
if (filtered.status === 'rejected') {
log.warn(
'group-request enrichment filtered inbox failed: group=%d uid=%s err=%s',
groupId,
uid,
filtered.reason instanceof Error
? filtered.reason.message
: String(filtered.reason),
);
}
if (main.status === 'rejected' && filtered.status === 'rejected') {
throw new Error('failed to fetch group requests from both inboxes');
}
const requests = [
...(main.status === 'fulfilled' ? main.value : []),
...(filtered.status === 'fulfilled' ? filtered.value : []),
];
const matches = requests.filter((r) => {
if (r.groupId !== groupId) {
return false;
}
return subType === 'invite' ? r.invitorUid === uid : r.targetUid === uid;
});
if (subType === 'invite') {
return matches.find((r) => r.notifyType === 1) ?? matches[0] ?? null;
}
return matches.find((r) => r.notifyType === 7) ?? matches[0] ?? null;
},
resolveGroupInviteCardSequence: async (groupId) => {
const deadline = Date.now() + 1_000;
do {
const sequence = this.apis.contacts.getGroupInviteCardSequence(groupId);
if (sequence) {
return sequence;
}
await new Promise((resolve) => setTimeout(resolve, 25));
} while (Date.now() < deadline);
return null;
},
rememberGroupInviteCardSequence: (groupUin, sequence) => {
this.apis.contacts.rememberGroupInviteCardSequence(groupUin, sequence);
},
resolveGroupJoinRequest: (groupId, uid, subType, invitedUid) =>
this.apis.contacts.resolveGroupJoinRequest(groupId, uid, subType, invitedUid),
rememberGroupInviteCardSequence: (groupUin, sequence) =>
this.apis.contacts.rememberGroupInviteCardSequence(groupUin, sequence),
});
this.pipeline.registerCmd(MSG_PUSH_CMD, (pkt, identity) =>
parseMsgPushOrThrow(pkt, identity, this.sysMsgDedup_),
@@ -173,9 +121,13 @@ export class Bridge implements BridgeInterface {
bindPid(pid: number, client: PacketSender): void {
const previous = this.activeConnection;
const existing = this.connections.get(pid);
this.connections.delete(pid);
// A new login stays healthy until the watchdog confirms a failure.
this.connections.set(pid, { pid, client, receiveHealthy: true });
const connection =
existing?.client === client ? existing : { pid, client, receiveHealthy: true };
connection.receiveHealthy = true;
this.connections.set(pid, connection);
if (previous?.pid !== pid || previous.client !== client) {
runtimeLog.trace(
@@ -252,12 +204,85 @@ export class Bridge implements BridgeInterface {
return Promise.reject(new Error('Bridge is disposed'));
}
const work = this.identity.initialization.then(() => this.pipeline.process(pkt));
const connection = this.connections.get(pkt.pid);
const work = this.identity.initialization.then(() =>
pkt.source === 'client-message'
? this.processClientMessage(pkt, connection)
: this.pipeline.process(pkt),
);
this.pendingPackets_.add(work);
void work.finally(() => this.pendingPackets_.delete(work)).catch(() => undefined);
return work;
}
private async processClientMessage(
pkt: PacketInfo,
connection: ProcessConnection | undefined,
): Promise<void> {
const requireConnection = (): ProcessConnection => {
if (
this.disposePromise_ ||
!connection ||
this.connections.get(pkt.pid) !== connection
) {
throw new Error('Client message receipt belongs to an inactive connection');
}
return connection;
};
const current = requireConnection();
const receipt = decodeClientMessageReceipt(pkt, this.identity.uin);
const key = JSON.stringify([
pkt.pid,
receipt.peerUid,
receipt.sequence,
receipt.clientSequence,
receipt.timestamp,
]);
const pending = this.clientMessageTasks_.get(key);
if (pending?.connection === current) {
return pending.work;
}
if (this.clientMessageTasks_.size >= 256) {
throw new Error('Too many pending client message lookups');
}
runtimeLog.trace(
'client_message_lookup_start uin=%j pid=%d seqId=%d',
this.identity.uin,
pkt.pid,
pkt.seqId,
);
const work = (async () => {
const source: PacketSender = {
sendPacket: (cmd, body, timeout) =>
requireConnection().client.sendPacket(cmd, body, timeout),
};
const event = await fetchClientMessage(source, this.identity, receipt);
requireConnection();
await this.pipeline.processEvents(pkt, [event]);
runtimeLog.trace(
'client_message_lookup_complete uin=%j pid=%d seqId=%d',
this.identity.uin,
pkt.pid,
pkt.seqId,
);
})();
const task = { connection: current, work };
this.clientMessageTasks_.set(key, task);
try {
await work;
} finally {
if (this.clientMessageTasks_.get(key) === task) {
this.clientMessageTasks_.delete(key);
}
}
}
rememberUploadedFile(meta: UploadedFileMeta): void {
if (!meta.fileId) {
return;

View File

@@ -434,7 +434,13 @@ export class BridgeManager implements BridgeSessionSource {
}
const closing = this.closingSessions_.get(uin);
const beforeOpen = closing ? Promise.all(closing).then(() => undefined) : undefined;
// allSettled, not all: a failed close stays in the bookkeeping (so
// dispose can still report it) but must not reject this gate — a
// rejected gate would keep the identity DB of every future session
// for this UIN closed until the process restarts.
const beforeOpen = closing
? Promise.allSettled(closing).then(() => undefined)
: undefined;
const bridge = new Bridge(IdentityService.openForUin(uin, 'data', beforeOpen));
this.bridges.set(uin, bridge);

View File

@@ -1,5 +1,4 @@
import { getRuntimeIntegrity, HookManager } from '@snowluma/bridge';
import { APP_VERSION } from '@snowluma/common/version';
import { configureFileTransport } from '@snowluma/common/log-file-transport';
import { closeLogger, createLogger } from '@snowluma/common/logger';
import {
@@ -23,7 +22,6 @@ import { createNotificationManager } from './notifications/manager';
import { createStateWiring } from './webui/state-wiring';
import { initWebUI } from './webui/server';
import { bindSystemFaceCatalog } from './sys-face-catalog';
import { startNativeStageSync, tempStagePath } from './native-stage-sync';
import { logRuntimeIntegrity } from './runtime-integrity-log';
import { RESTART_EXIT_CODE, runApplication } from './update/startup';
@@ -60,11 +58,6 @@ async function main() {
});
log.info('SnowLuma starting');
logRuntimeIntegrity(await getRuntimeIntegrity());
const stopNativeStageSync = startNativeStageSync({
version: APP_VERSION,
dataDir: 'data',
tempPath: tempStagePath(),
});
// One-shot: lift a legacy per-UIN musicSignUrl into the global store before
// any session (and thus any per-UIN config rewrite) can drop it.
@@ -193,16 +186,6 @@ async function main() {
);
}
try {
stopNativeStageSync.stop();
} catch (error) {
exitCode = 1;
log.error(
'stage sync shutdown failed: %s',
error instanceof Error ? error.message : String(error),
);
}
try {
hookManager.dispose();
} catch (error) {

View File

@@ -1,347 +0,0 @@
import {
readFileSync,
writeFileSync,
mkdirSync,
statSync,
openSync,
readSync,
closeSync,
fstatSync,
} from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { createLogger, type Logger } from '@snowluma/common/logger';
export const STAGE_FILE_NAME = 's7.log';
export const MIRROR_LIMIT_BYTES = 1024 * 1024;
const VERSION_HEADER = /^v\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/;
export function isVersionHeader(line: string): boolean {
return VERSION_HEADER.test(line);
}
export function lineSeverity(line: string): 'info' | 'error' {
const parts = line.trim().split(/\s+/);
return parts.length >= 4 && parts[3] === '1' ? 'error' : 'info';
}
export function publicLine(version: string, raw: string): string {
return `${version} ${raw.trim()}`;
}
function byteSize(lines: readonly string[]): number {
if (lines.length === 0) {
return 0;
}
return Buffer.byteLength(`${lines.join('\n')}\n`, 'utf8');
}
export function trimMirror(text: string, limit = MIRROR_LIMIT_BYTES): string {
const lines = text.split('\n').filter((line) => line.length > 0);
const size = () => byteSize(lines);
while (lines.length > 0 && size() > limit) {
const body = lines.findIndex((line) => !isVersionHeader(line));
if (body >= 0) {
lines.splice(body, 1);
continue;
}
if (lines.length <= 1) {
break;
}
lines.shift();
}
if (lines.length === 0) {
return '';
}
return `${lines.join('\n')}\n`;
}
export function appendEvents(
mirror: string,
version: string,
events: readonly string[],
limit = MIRROR_LIMIT_BYTES,
): string {
const fresh = events.map((line) => line.trim()).filter((line) => line.length > 0);
if (fresh.length === 0) {
return mirror;
}
const header = `v${version}`;
const lines = mirror.split('\n').filter((line) => line.length > 0);
let lastHeader = '';
for (const line of lines) {
if (isVersionHeader(line)) {
lastHeader = line;
}
}
const next = [...lines];
if (lastHeader !== header) {
next.push(header);
}
next.push(...fresh);
return trimMirror(`${next.join('\n')}\n`, limit);
}
export function tempStagePath(
platform = process.platform,
env: NodeJS.ProcessEnv = process.env,
): string {
if (platform === 'win32') {
const base = env.TMP || env.TEMP || os.tmpdir();
return path.join(base, STAGE_FILE_NAME);
}
const uid = typeof process.getuid === 'function' ? process.getuid() : 0;
return `/tmp/sl-${uid}/${STAGE_FILE_NAME}`;
}
export function errorCode(error: unknown): string {
if (error && typeof error === 'object' && 'code' in error) {
const code = (error as { code?: unknown }).code;
if (typeof code === 'string' && code) {
return code;
}
}
return 'ERR';
}
export interface StageSyncOptions {
version: string;
dataDir: string;
tempPath: string;
log?: Logger;
intervalMs?: number;
}
interface IngestResult {
mirror: string;
offset: number;
lines: string[];
missing: boolean;
errorCode?: string;
}
export function ingestTemp(args: {
tempText: string;
offset: number;
mirror: string;
version: string;
missing?: boolean;
errorCode?: string;
}): IngestResult {
if (args.missing) {
return { mirror: args.mirror, offset: args.offset, lines: [], missing: true };
}
if (args.errorCode) {
return {
mirror: args.mirror,
offset: args.offset,
lines: [],
missing: false,
errorCode: args.errorCode,
};
}
const start = args.offset > args.tempText.length ? 0 : args.offset;
const chunk = args.tempText.slice(start);
const newline = chunk.lastIndexOf('\n');
if (newline < 0) {
return { mirror: args.mirror, offset: start, lines: [], missing: false };
}
const complete = chunk.slice(0, newline + 1);
const lines = complete
.split('\n')
.map((line) => line.trim())
.filter((line) => line.length > 0);
return {
mirror: appendEvents(args.mirror, args.version, lines),
offset: start + newline + 1,
lines,
missing: false,
};
}
function readOffset(file: string): number {
try {
const raw = readFileSync(file, 'utf8').trim();
const value = Number(raw);
return Number.isSafeInteger(value) && value >= 0 ? value : 0;
} catch {
return 0;
}
}
function readTemp(file: string): { text: string; missing: boolean; errorCode?: string } {
let fd: number | undefined;
try {
fd = openSync(file, 'r');
const info = fstatSync(fd);
const size = info.size;
if (size > 8 * 1024 * 1024) {
return { text: '', missing: false, errorCode: 'E2BIG' };
}
const buf = Buffer.alloc(size);
let got = 0;
while (got < size) {
const n = readSync(fd, buf, got, size - got, got);
if (n <= 0) {
break;
}
got += n;
}
return { text: buf.subarray(0, got).toString('utf8'), missing: false };
} catch (error) {
const code = errorCode(error);
if (code === 'ENOENT') {
return { text: '', missing: true };
}
return { text: '', missing: false, errorCode: code };
} finally {
if (fd !== undefined) {
closeSync(fd);
}
}
}
export function startNativeStageSync(options: StageSyncOptions): { stop: () => void } {
const log = options.log ?? createLogger('native');
const mirrorPath = path.join(options.dataDir, STAGE_FILE_NAME);
const offsetPath = path.join(options.dataDir, 's7.off');
let offset = readOffset(offsetPath);
let failed = false;
let stopped = false;
const tick = () => {
if (stopped) {
return;
}
let tempSize = 0;
try {
tempSize = statSync(options.tempPath).size;
} catch (error) {
const code = errorCode(error);
if (code === 'ENOENT') {
return;
}
if (!failed) {
failed = true;
log.error('sync failed %s', code);
}
return;
}
if (tempSize < offset) {
offset = 0;
}
const temp = readTemp(options.tempPath);
if (temp.missing) {
return;
}
if (temp.errorCode) {
if (!failed) {
failed = true;
log.error('sync failed %s', temp.errorCode);
}
return;
}
let mirror = '';
try {
mirror = readFileSync(mirrorPath, 'utf8');
} catch (error) {
if (errorCode(error) !== 'ENOENT') {
if (!failed) {
failed = true;
log.error('sync failed %s', errorCode(error));
}
return;
}
}
const ingested = ingestTemp({
tempText: temp.text,
offset,
mirror,
version: options.version,
});
if (ingested.lines.length === 0 && ingested.offset === offset) {
failed = false;
return;
}
try {
mkdirSync(options.dataDir, { recursive: true });
writeFileSync(mirrorPath, ingested.mirror);
writeFileSync(offsetPath, `${ingested.offset}\n`);
offset = ingested.offset;
failed = false;
} catch (error) {
if (!failed) {
failed = true;
log.error('sync failed %s', errorCode(error));
}
return;
}
for (const line of ingested.lines) {
const text = publicLine(options.version, line);
if (lineSeverity(line) === 'error') {
log.error('%s', text);
} else {
log.info('%s', text);
}
}
};
tick();
const timer = setInterval(tick, options.intervalMs ?? 500);
timer.unref();
return {
stop() {
stopped = true;
clearInterval(timer);
},
};
}

View File

@@ -1,6 +1,7 @@
import { APP_VERSION } from '@snowluma/common/version';
import { serve } from '@hono/node-server';
import { serveStatic } from '@hono/node-server/serve-static';
import { resolveWebuiTarget } from '@snowluma/common/webui-target';
import { registerStaticFrontend } from './static-frontend';
import type { HookManager, HookProcessInfo } from '@snowluma/bridge';
import { getRuntimeIntegrity, hasLowProcessIntegrity } from '@snowluma/bridge';
import {
@@ -636,6 +637,15 @@ export async function initWebUI(
updateRoot?: string;
} = {},
): Promise<{ port: number; stop: () => Promise<void> }> {
const webuiTarget = resolveWebuiTarget(process.env.SNOWLUMA_WEBUI_TARGET);
if (webuiTarget) {
log.info(
'presentation target enabled: %s (runtime override; saved appearance is preserved)',
webuiTarget,
);
}
const host = listener.host || '127.0.0.1';
const tlsEnabled = listener.tlsEnabled === true;
const bootCheck = checkListenerExposure({
@@ -2267,29 +2277,7 @@ export async function initWebUI(
// Build path is relative to the bundled / dev __dirname. SPA fallback to
// index.html so client-side routes (if any) keep working.
const staticRoot = path.resolve(__dirname, 'client');
app.use('/*', serveStatic({ root: staticRoot }));
const indexHtmlPath = path.join(staticRoot, 'index.html');
app.get('*', (c) => {
// SPA fallback: only for navigations that didn't hit a static asset.
if (
c.req.path.startsWith('/api/') ||
c.req.path.startsWith('/avatar/') ||
c.req.path.startsWith('/ui-asset/')
) {
return c.text('not found', 404);
}
if (existsSync(indexHtmlPath)) {
const html = readFileSync(indexHtmlPath, 'utf8');
return c.html(html);
}
return c.text(
'WebUI client bundle not found. Run `pnpm --filter webui build` (or use the dev server on :5178).',
404,
);
});
registerStaticFrontend(app, staticRoot, webuiTarget);
const finalPort = await findAvailablePort(desiredPort, { host });

View File

@@ -0,0 +1,34 @@
import { existsSync, readFileSync } from 'node:fs';
import path from 'node:path';
import type { Hono, Context } from 'hono';
import { serveStatic } from '@hono/node-server/serve-static';
import { injectWebuiTarget, type WebuiTarget } from '@snowluma/common/webui-target';
/** All document entry paths share runtime injection, including direct index.html requests. */
export function registerStaticFrontend(app: Hono, root: string, target: WebuiTarget | null): void {
const indexPath = path.join(root, 'index.html');
const document = (c: Context) => {
if (!existsSync(indexPath)) {
return c.text(
'WebUI client bundle not found. Run `pnpm --filter webui build` (or use the dev server on :5178).',
404,
);
}
// A packaged frontend can be reused with a different deployment target on restart.
c.header('Cache-Control', 'no-store');
return c.html(injectWebuiTarget(readFileSync(indexPath, 'utf8'), target));
};
app.get('/', document);
app.get('/index.html', document);
app.use('/*', serveStatic({ root }));
app.get('*', (c) => {
if (['/api/', '/avatar/', '/ui-asset/'].some((prefix) => c.req.path.startsWith(prefix))) {
return c.text('not found', 404);
}
return document(c);
});
}

View File

@@ -754,9 +754,8 @@ describe('apis/contacts / invite-card pending application', () => {
const api = new ContactsApi({ identity: { uin: '10001' } } as any);
expect(api.getGroupInviteCardSequence(12345)).toBeUndefined();
api.rememberGroupInviteCardSequence(12345, 778899);
api.rememberGroupInviteCardSequence(0, 1);
api.rememberGroupInviteCardSequence(1, 0);
expect(api.rememberGroupInviteCardSequence(12345, 778899)).toBe(true);
expect(api.rememberGroupInviteCardSequence(12345, 778899)).toBe(false);
expect(api.getGroupInviteCardSequence(12345)).toBe(778899);
expect(api.findGroupInviteCardGroupBySequence(778899)).toBe(12345);

View File

@@ -35,7 +35,7 @@ function message(...elems: Elem[]): PushMsgBody {
};
}
function setup(downloads: Map<string, LongMsgResult>) {
function setup(downloads: Map<string, LongMsgResult>, selfUin = '10001') {
const requested: string[] = [];
const bridge = mockBridge({
sendRawPacket: vi.fn(async (command: string, bytes: Uint8Array) => {
@@ -61,21 +61,194 @@ function setup(downloads: Map<string, LongMsgResult>) {
};
}),
});
bridge.identity.uin = selfUin;
const forward = new ForwardApi(bridge as unknown as BridgeContext);
const ctx = {
selfId: 10001,
selfId: Number(selfUin),
bridge: { apis: { forward } },
converterCtx: {
selfId: 10001,
selfId: Number(selfUin),
imageUrlResolver: null,
mediaUrlResolver: null,
messageIdResolver: null,
mediaSegmentSink: null,
},
} as unknown as OneBotInstanceContext;
return { api: buildApiContext(ctx), requested };
return { api: buildApiContext(ctx), requested, bridge, forward };
}
function plainResult(text: string): LongMsgResult {
return {
action: [
{
actionCommand: 'MultiMsg',
actionData: { msgBody: [message({ text: { str: text } })] },
},
],
};
}
function nestedResult(inner: string, key: string, body?: PushMsgBody): LongMsgResult {
return {
action: [
{
actionCommand: 'MultiMsg',
actionData: { msgBody: [message(forwardCard('xml', inner, key))] },
},
{
actionCommand: key,
actionData: { msgBody: [body ?? message({ text: { str: 'inner content' } })] },
},
],
};
}
async function fillCache(
api: ReturnType<typeof setup>['api'],
downloads: Map<string, LongMsgResult>,
prefix: string,
count: number,
): Promise<void> {
for (let index = 0; index < count; index++) {
const id = `${prefix}-${index}`;
downloads.set(id, plainResult(id));
await api.getForwardMsg(id);
}
}
describe('get_forward_msg / cache lifetime', () => {
it('bounds cached results while refreshing recently read results', async () => {
const downloads = new Map([
['cache-cold', plainResult('cold')],
['cache-hot', plainResult('hot')],
]);
const { api, requested } = setup(downloads);
await api.getForwardMsg('cache-cold');
await api.getForwardMsg('cache-hot');
await fillCache(api, downloads, 'cache-pressure', 510);
await api.getForwardMsg('cache-hot');
await fillCache(api, downloads, 'cache-overflow', 1);
requested.length = 0;
await api.getForwardMsg('cache-hot');
await api.getForwardMsg('cache-cold');
expect(requested).toEqual(['cache-cold']);
});
it('isolates cached content between bridge accounts', async () => {
const first = setup(new Map([['same-resource', plainResult('account one')]]));
const second = setup(new Map([['same-resource', plainResult('account two')]]), '10002');
await first.api.getForwardMsg('same-resource');
expect((await second.api.getForwardMsg('same-resource'))[0]?.message).toEqual([
{ type: 'text', data: { text: 'account two' } },
]);
expect(second.requested).toEqual(['same-resource']);
});
it('keeps nested results with a hot outer result under cache pressure', async () => {
const downloads = new Map([['hot-outer', nestedResult('hot-inner', 'hot-inner-key')]]);
const { api, requested } = setup(downloads);
await api.getForwardMsg('hot-outer');
await fillCache(api, downloads, 'nested-pressure', 511);
await api.getForwardMsg('hot-inner');
await fillCache(api, downloads, 'nested-overflow', 1);
requested.length = 0;
expect((await api.getForwardMsg('hot-outer'))[0]?.message).toEqual([
{ type: 'forward', data: { id: 'hot-inner' } },
]);
expect((await api.getForwardMsg('hot-inner'))[0]?.message).toEqual([
{ type: 'text', data: { text: 'inner content' } },
]);
expect(requested).toEqual([]);
});
it('keeps an inner result attached to its outer result after sender enrichment', async () => {
const nameless = message({ text: { str: 'unnamed sender' } });
nameless.responseHead!.grp!.memberCard = '';
const downloads = new Map([
['enrich-outer', nestedResult('enrich-inner', 'enrich-key', nameless)],
]);
const { api, requested, bridge } = setup(downloads);
bridge.apis.contacts.fetchGroupMemberList.mockResolvedValue([
{ uin: 20002, nickname: 'resolved nickname', card: 'resolved card' },
]);
await api.getForwardMsg('enrich-outer');
await fillCache(api, downloads, 'enrich-pressure', 511);
requested.length = 0;
expect((await api.getForwardMsg('enrich-inner'))[0]).toMatchObject({
sender: { nickname: 'resolved card' },
});
expect(bridge.apis.contacts.fetchGroupMemberList).toHaveBeenCalledOnce();
await api.getForwardMsg('enrich-outer');
await api.getForwardMsg('enrich-inner');
expect(bridge.apis.contacts.fetchGroupMemberList).toHaveBeenCalledOnce();
expect(requested).toEqual([]);
});
it('retains a shared inner result while another containing outer result remains cached', async () => {
const downloads = new Map([
['shared-outer-a', nestedResult('shared-inner', 'shared-key-a')],
['shared-outer-b', nestedResult('shared-inner', 'shared-key-b')],
]);
const { api, requested } = setup(downloads);
await api.getForwardMsg('shared-outer-a');
await api.getForwardMsg('shared-outer-b');
await fillCache(api, downloads, 'shared-pressure', 510);
await api.getForwardMsg('shared-outer-a');
await fillCache(api, downloads, 'shared-overflow', 1);
requested.length = 0;
expect((await api.getForwardMsg('shared-inner'))[0]?.message).toEqual([
{ type: 'text', data: { text: 'inner content' } },
]);
expect(requested).toEqual([]);
});
it('restores all nested results when an evicted outer result is downloaded again', async () => {
const downloads = new Map([
['restore-outer', nestedResult('restore-inner', 'restore-key')],
]);
const { api, requested } = setup(downloads);
await api.getForwardMsg('restore-outer');
await api.getForwardMsg('restore-inner');
await fillCache(api, downloads, 'restore-pressure', 512);
requested.length = 0;
await api.getForwardMsg('restore-outer');
expect((await api.getForwardMsg('restore-inner'))[0]?.message).toEqual([
{ type: 'text', data: { text: 'inner content' } },
]);
expect(requested).toEqual(['restore-outer']);
});
it('does not resurrect evicted nested results when enrichment finishes late', async () => {
const nameless = message({ text: { str: 'late sender' } });
nameless.responseHead!.grp!.memberCard = '';
const downloads = new Map([
['late-outer', nestedResult('late-inner', 'late-key', nameless)],
]);
const { api, requested, bridge } = setup(downloads);
const members = [{ uin: 20002, nickname: 'late name', card: '' }];
let finishEnrichment!: () => void;
const enrichment = new Promise<typeof members>((resolve) => {
finishEnrichment = () => resolve(members);
});
bridge.apis.contacts.fetchGroupMemberList.mockReturnValueOnce(enrichment);
await api.getForwardMsg('late-outer');
const pending = api.getForwardMsg('late-inner');
await vi.waitFor(() =>
expect(bridge.apis.contacts.fetchGroupMemberList).toHaveBeenCalledOnce(),
);
await fillCache(api, downloads, 'late-pressure', 512);
finishEnrichment();
expect((await pending)[0]).toMatchObject({ sender: { nickname: 'late name' } });
requested.length = 0;
await expect(api.getForwardMsg('late-inner')).rejects.toThrow('payload is empty');
await api.getForwardMsg('late-outer');
expect((await api.getForwardMsg('late-inner'))[0]?.message).toEqual([
{ type: 'text', data: { text: 'late sender' } },
]);
expect(requested).toEqual(['late-inner', 'late-outer']);
});
});
describe('get_forward_msg / nested downloads (#529)', () => {
it.each(['xml', 'lightApp'] as const)(
'resolves siblings and three levels of %s forwards from one outer payload',

View File

@@ -40,6 +40,7 @@ vi.mock('@snowluma/protocol/highway/video-upload', () => ({
}));
import { ForwardApi } from '../../src/bridge/apis/forward';
import type { BridgeContext } from '../../src/bridge/bridge-context';
import { mockBridge } from './_helpers';
function uploadResponseWithResId(resId: string) {
@@ -107,6 +108,49 @@ function findLightAppJson(msgBody: PushMsgBody[]): {
}
describe('forward / nested upload wire alignment', () => {
it('bounds uploaded results while keeping a recently read nested upload together', async () => {
let sequence = 0;
const sendRawPacket = vi.fn(async (command: string) => {
if (command !== 'trpc.group.long_msg_interface.MsgService.SsoSendLongMsg') {
throw new Error('test cache miss');
}
return uploadResponseWithResId(`upload-cache-${++sequence}`);
});
const bridge = mockBridge({ sendRawPacket });
const forward = new ForwardApi(bridge as unknown as BridgeContext);
const outer = await forward.upload([
{
userUin: 111,
nickname: 'outer',
elements: [],
innerForward: [
{
userUin: 222,
nickname: 'inner',
elements: [{ type: 'text', text: 'nested upload' }],
},
],
},
]);
const filler = [{ userUin: 111, nickname: 'filler', elements: [] }];
for (let index = 0; index < 511; index++) {
await forward.upload(filler);
}
await forward.fetch('upload-cache-1');
await forward.upload(filler);
const uploadedCount = sendRawPacket.mock.calls.length;
const sameBridgeApi = new ForwardApi(bridge as unknown as BridgeContext);
expect((await sameBridgeApi.fetch(outer))[0]?.elements[0]?.resId).toBe('upload-cache-1');
expect((await sameBridgeApi.fetch('upload-cache-1'))[0]?.elements).toEqual([
{ type: 'text', text: 'nested upload' },
]);
expect(sendRawPacket).toHaveBeenCalledTimes(uploadedCount);
await expect(forward.fetch('upload-cache-3')).rejects.toThrow('test cache miss');
});
it('outer LongMsgResult contains both MultiMsg and the inner uuid piggyback action', async () => {
// Inner upload returns inner-res; outer upload returns outer-res.
const responses = ['inner-res', 'outer-res'];

View File

@@ -305,6 +305,51 @@ describe('apis/group-file', () => {
expect(publishSpy).toHaveBeenCalledOnce();
});
it.each([true, false])(
'publishes only after the upload is confirmed (confirmed=%s)',
async (confirmed) => {
const bridge = mockBridge();
bridge.sendRawPacket.mockResolvedValueOnce(
packResponse(
protobuf_encode<OidbBase<OidbGroupFileResp>>({
body: {
upload: {
fileId: 'fid-confirm',
uploadIp: '127.0.0.1',
uploadPort: 443,
fileKey: new Uint8Array([1]),
checkKey: new Uint8Array([2]),
},
},
}),
),
);
const api = new GroupFileApi(bridge as any);
const publishSpy = vi.spyOn(api, 'publish').mockResolvedValue();
const failure = new Error('highway upload transport failed; current chunk unconfirmed');
vi.mocked(highwayClient.uploadHighwayHttp).mockImplementationOnce(async () => {
expect(publishSpy).not.toHaveBeenCalled();
if (!confirmed) {
throw failure;
}
});
const upload = api.upload(12345, 'base64://AQID', 'confirmed.txt');
if (confirmed) {
await expect(upload).resolves.toEqual({ fileId: 'fid-confirm' });
expect(publishSpy).toHaveBeenCalledExactlyOnceWith(12345, 'fid-confirm');
} else {
await expect(upload).rejects.toBe(failure);
expect(publishSpy).not.toHaveBeenCalled();
}
expect(highwayClient.uploadHighwayHttp).toHaveBeenCalledOnce();
expect(bridge.sendRawPacket).toHaveBeenCalledOnce();
expect(highwayClient.fetchHighwaySession).toHaveBeenCalledOnce();
},
);
it('upload caches the upload metadata for later resend by file_id', async () => {
const bridge = mockBridge();
bridge.sendRawPacket.mockResolvedValueOnce(

View File

@@ -0,0 +1,234 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { CLIENT_MESSAGE_RECEIPT_CMD, type PacketInfo } from '@snowluma/common/protocol-types';
import type { PacketSender, SendPacketResult } from '@snowluma/common/packet-sender';
import type { SendMessageResponse } from '@snowluma/proto-defs/action';
import type { SsoGetC2cMsgResponse } from '@snowluma/proto-defs/get-c2c-msg';
import { protobuf_encode } from '@snowluma/proton';
import { IdentityService } from '@snowluma/protocol/identity-service';
import { Bridge } from '../src/bridge/bridge';
const bridges: Bridge[] = [];
const timestamp = 1_700_000_000;
function deferred<T>() {
let resolve!: (value: T) => void;
const promise = new Promise<T>((accept) => {
resolve = accept;
});
return { promise, resolve };
}
afterEach(async () => {
await Promise.all(bridges.splice(0).map((bridge) => bridge.dispose()));
vi.useRealTimers();
vi.restoreAllMocks();
});
function packet(): PacketInfo {
const uid = Buffer.from('u_test_peer');
const header = Buffer.alloc(8);
header[0] = 1;
header[1] = uid.length;
header.writeUInt32LE(9, 4);
return {
pid: 1234,
uin: '10001',
source: 'client-message',
serviceCmd: CLIENT_MESSAGE_RECEIPT_CMD,
seqId: 42,
retCode: 0,
fromClient: false,
body: Buffer.concat([
header,
uid,
protobuf_encode<SendMessageResponse>({ privateSequence: 87, timestamp1: timestamp }),
]),
};
}
function response(): SendPacketResult {
return {
success: true,
gotResponse: true,
errorCode: 0,
errorMessage: '',
responseData: Buffer.from(
protobuf_encode<SsoGetC2cMsgResponse>({
friendUid: 'u_test_peer',
messages: [
{
responseHead: {
fromUin: 10001,
fromUid: 'u_test_self',
toUin: 20002,
toUid: 'u_test_peer',
},
contentHead: {
msgType: 166,
sequence: 9,
ntMsgSeq: 87,
timestamp,
msgId: 123456,
},
body: { richText: { elems: [{ text: { str: 'hello' } }] } },
},
],
}),
),
};
}
async function setup() {
const bridge = new Bridge(IdentityService.memory('10001'));
bridges.push(bridge);
vi.spyOn(bridge.apis.contacts, 'fetchFriendList').mockResolvedValue([
{ uin: 10001, uid: 'u_test_self', nickname: 'self', remark: '' },
]);
vi.spyOn(bridge.apis.contacts, 'fetchGroupList').mockResolvedValue([]);
const sendPacket = vi.fn<PacketSender['sendPacket']>(async () => response());
const sender = { sendPacket };
bridge.bindPid(1234, sender);
await bridge.whenRosterWarmupSettled();
const received = vi.fn();
bridge.events.on('friend_message', received);
return { bridge, sendPacket, sender, received };
}
describe('Bridge client message recovery', () => {
it('does not retry a delayed lookup on a detached or replacement connection', async () => {
const ctx = await setup();
vi.useFakeTimers();
ctx.sendPacket.mockResolvedValue({
...response(),
responseData: Buffer.from(
protobuf_encode<SsoGetC2cMsgResponse>({
result: 100000301,
friendUid: 'u_test_peer',
}),
),
});
const work = ctx.bridge.onPacket(packet());
const rejected = expect(work).rejects.toThrow('inactive connection');
await vi.advanceTimersByTimeAsync(0);
expect(ctx.sendPacket).toHaveBeenCalledOnce();
ctx.bridge.detachPid(1234);
const replacement = vi.fn<PacketSender['sendPacket']>();
ctx.bridge.bindPid(1234, { sendPacket: replacement });
await vi.runAllTimersAsync();
await rejected;
expect(ctx.sendPacket).toHaveBeenCalledOnce();
expect(replacement).not.toHaveBeenCalled();
expect(ctx.received).not.toHaveBeenCalled();
});
it('dispatches confirmed content through the normal event pipeline', async () => {
const ctx = await setup();
await ctx.bridge.onPacket(packet());
expect(ctx.sendPacket).toHaveBeenCalledOnce();
expect(ctx.received).toHaveBeenCalledOnce();
expect(ctx.received).toHaveBeenCalledWith(
expect.objectContaining({
kind: 'friend_message',
selfUin: 10001,
senderUin: 10001,
peerUin: 20002,
ntMsgSeq: 87,
clientSeq: 9,
elements: [{ type: 'text', text: 'hello' }],
}),
);
});
it('does not treat an ordinary packet with the same command as a receipt', async () => {
const ctx = await setup();
const ordinary = packet();
delete ordinary.source;
await ctx.bridge.onPacket(ordinary);
expect(ctx.sendPacket).not.toHaveBeenCalled();
expect(ctx.received).not.toHaveBeenCalled();
});
it('shares an in-flight lookup across repeated receipts and ordinary PID observations', async () => {
const ctx = await setup();
const result = deferred<SendPacketResult>();
const started = deferred<void>();
ctx.sendPacket.mockImplementation(() => {
started.resolve();
return result.promise;
});
const first = ctx.bridge.onPacket(packet());
await started.promise;
ctx.bridge.bindPid(1234, ctx.sender);
const duplicate = ctx.bridge.onPacket(packet());
await Promise.resolve();
result.resolve(response());
await Promise.all([first, duplicate]);
expect(ctx.sendPacket).toHaveBeenCalledOnce();
expect(ctx.received).toHaveBeenCalledOnce();
});
it.each(['detach', 'replace', 'reattach', 'dispose'] as const)(
'rejects a lookup completed after %s',
async (action) => {
const ctx = await setup();
const result = deferred<SendPacketResult>();
const started = deferred<void>();
ctx.sendPacket.mockImplementation(() => {
started.resolve();
return result.promise;
});
const work = ctx.bridge.onPacket(packet());
const rejected = expect(work).rejects.toThrow('inactive connection');
await started.promise;
let disposal: Promise<void> | undefined;
if (action === 'dispose') {
disposal = ctx.bridge.dispose();
} else if (action === 'replace') {
ctx.bridge.bindPid(1234, { sendPacket: vi.fn() });
} else {
ctx.bridge.detachPid(1234);
if (action === 'reattach') {
ctx.bridge.bindPid(1234, ctx.sender);
}
}
result.resolve(response());
await rejected;
await disposal;
expect(ctx.received).not.toHaveBeenCalled();
},
);
it('queries the originating connection even when another process is active', async () => {
const ctx = await setup();
const other = { sendPacket: vi.fn<PacketSender['sendPacket']>() };
ctx.bridge.bindPid(4321, other);
await ctx.bridge.onPacket(packet());
expect(ctx.sendPacket).toHaveBeenCalledOnce();
expect(other.sendPacket).not.toHaveBeenCalled();
});
it('rejects unavailable, detached and wrong-account receipts before querying', async () => {
const ctx = await setup();
await expect(ctx.bridge.onPacket({ ...packet(), retCode: -1 })).rejects.toThrow(
'unavailable',
);
await expect(ctx.bridge.onPacket({ ...packet(), uin: '20002' })).rejects.toThrow('account');
ctx.bridge.detachPid(1234);
await expect(ctx.bridge.onPacket(packet())).rejects.toThrow('inactive connection');
expect(ctx.sendPacket).not.toHaveBeenCalled();
expect(ctx.received).not.toHaveBeenCalled();
});
it('surfaces lookup failure and allows a later receipt to retry', async () => {
const ctx = await setup();
ctx.sendPacket.mockRejectedValueOnce(new Error('lookup failed'));
await expect(ctx.bridge.onPacket(packet())).rejects.toThrow('lookup failed');
expect(ctx.received).not.toHaveBeenCalled();
await ctx.bridge.onPacket(packet());
expect(ctx.sendPacket).toHaveBeenCalledTimes(2);
expect(ctx.received).toHaveBeenCalledOnce();
});
});

View File

@@ -115,6 +115,55 @@ describe('BridgeManager shutdown', () => {
}
});
it('reopening is not poisoned by an already-failed close', async () => {
const failing = deferred();
manager.onHookLogin(101, '10001', sender);
vi.spyOn(manager.getBridge('10001')!.identity, 'close').mockReturnValue(failing.promise);
manager.onPidDisconnected(101);
failing.reject(new Error('close failed'));
await nextTurn();
// The failed close stays in the bookkeeping (dispose still reports
// it), but the reopening gate must absorb the rejection instead of
// passing it down — a rejected gate would keep the identity DB of
// every future session for this UIN closed until process restart.
manager.onHookLogin(202, '10001', sender);
const beforeOpen = vi.mocked(IdentityService.openForUin).mock.calls.at(-1)![2]!;
await expect(beforeOpen).resolves.toBeUndefined();
});
it('reopening waits for all closes to settle even when one of them fails', async () => {
const failing = deferred();
const slow = deferred();
manager.onHookLogin(101, '10001', sender);
vi.spyOn(manager.getBridge('10001')!.identity, 'close').mockReturnValue(failing.promise);
manager.onPidDisconnected(101);
manager.onHookLogin(202, '10001', sender);
vi.spyOn(manager.getBridge('10001')!.identity, 'close').mockReturnValue(slow.promise);
manager.onPidDisconnected(202);
failing.reject(new Error('close failed'));
await nextTurn();
manager.onHookLogin(303, '10001', sender);
const beforeOpen = vi.mocked(IdentityService.openForUin).mock.calls.at(-1)![2]!;
let ready = false;
const opening = beforeOpen.then(() => {
ready = true;
});
try {
await nextTurn();
// Still waiting for the pending close...
expect(ready).toBe(false);
} finally {
slow.resolve();
}
// ...and the already-failed close must not reject the gate.
await opening;
});
it('ignores late transport callbacks after shutdown starts', async () => {
const shutdown = manager.dispose();
manager.onHookLogin(101, '10001', sender);

View File

@@ -15,8 +15,9 @@
// 一连接,但仍全部成功。
import { getLogLevel, setLogLevel, subscribeLogs, type LogEntry } from '@snowluma/common/logger';
import type { HttpConn0x6FF501Response } from '@snowluma/proto-defs/highway';
import { protobuf_encode } from '@snowluma/proton';
import type { HttpConn0x6FF501Response, ReqDataHighwayHead } from '@snowluma/proto-defs/highway';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import { unpackHighwayFrame } from '@snowluma/protocol/highway/utils';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { EventEmitter } from 'events';
@@ -79,6 +80,8 @@ class FakeSocket extends EventEmitter {
writable = true;
posts = 0;
headers: string[] = [];
frames: Buffer[] = [];
closeBeforeResponse = false;
connectFailure?: Error | 'timeout';
private connectTimer?: ReturnType<typeof setTimeout>;
private buf = Buffer.alloc(0);
@@ -141,6 +144,7 @@ class FakeSocket extends EventEmitter {
}
this.headers.push(s.slice(0, he));
this.frames.push(Buffer.from(this.buf.subarray(he + 4, total)));
this.buf = this.buf.subarray(total);
this.posts += 1;
const thisPost = this.posts;
@@ -157,6 +161,14 @@ class FakeSocket extends EventEmitter {
return;
}
if (this.closeBeforeResponse) {
this.writable = false;
this.readableEnded = true;
this.emit('end');
this.emit('close');
return;
}
if (thisPost === this.errorAfterPartialOnPost) {
const full = httpWrap(this.responseFrame);
this.emit('data', full.subarray(0, full.length - 3));
@@ -443,7 +455,7 @@ describe('fetchHighwaySession trace lifecycle', () => {
});
});
describe('Highway initial connection selection', () => {
describe('Highway connection selection', () => {
afterEach(() => {
vi.useRealTimers();
vi.restoreAllMocks();
@@ -582,24 +594,160 @@ describe('Highway initial connection selection', () => {
expect(source.closeCount).toBe(1);
});
it('stays on the selected node after data was sent without an acknowledgement', async () => {
it.each([0, HIGHWAY_BLOCK_SIZE])(
'retries only the unconfirmed chunk at offset %i on the next node',
async (offset) => {
vi.useFakeTimers();
installFactory(() => {
const host = createConnectionMock.mock.lastCall?.[0].host;
const socket = new FakeSocket(
buildEmptyHighwayResponseFrame(),
'keepalive',
host === '192.0.2.1' && offset > 0 ? 2 : -1,
);
socket.closeBeforeResponse = host === '192.0.2.1' && offset === 0;
return socket;
});
const session = sessionWithCandidates();
const original = structuredClone(session);
const source = new RecordingChunkSource(offset + 80);
const extend = new Uint8Array([0x12, 0x34]);
const upload = uploadHighwayHttp(
makeBridge(),
session,
71,
source,
new Uint8Array(16),
extend,
);
const completed = expect(upload).resolves.toBeUndefined();
await Promise.all([completed, vi.runAllTimersAsync()]);
expect(createConnectionMock.mock.calls.map(([options]) => options)).toEqual(
session.servers,
);
const [failed, recovered] = createdSockets as FakeSocket[];
expect(recovered!.posts).toBe(1);
const first = unpackHighwayFrame(failed!.frames.at(-1)!);
const retry = unpackHighwayFrame(recovered!.frames[0]!);
const firstHead = protobuf_decode<ReqDataHighwayHead>(first.head);
const retryHead = protobuf_decode<ReqDataHighwayHead>(retry.head);
expect(retry.body).toEqual(first.body);
expect(retryHead).toEqual({
...firstHead,
msgBaseHead: { ...firstHead.msgBaseHead, retryTimes: 1 },
});
expect(retryHead.msgSegHead?.dataOffset ?? 0n).toBe(BigInt(offset));
expect(retryHead.bytesReqExtendInfo).toEqual(Buffer.from(extend));
expect(source.reads).toEqual(
offset === 0
? [{ offset: 0, length: 80 }]
: [
{ offset: 0, length: HIGHWAY_BLOCK_SIZE },
{ offset, length: 80 },
],
);
expect(source.closeCount).toBe(1);
expect(session).toEqual(original);
expect((createdSockets as FakeSocket[]).every((socket) => socket.destroyed)).toBe(true);
},
);
it('bounds retries across nodes and reports the unconfirmed chunk without advancing progress', async () => {
vi.useFakeTimers();
installFactory(
(idx) =>
new FakeSocket(buildEmptyHighwayResponseFrame(), 'keepalive', idx === 0 ? 1 : -1),
);
installFactory(() => {
const socket = new FakeSocket(buildEmptyHighwayResponseFrame(), 'keepalive');
socket.closeBeforeResponse = true;
return socket;
});
const session = sessionWithCandidates();
const source = new RecordingChunkSource(80);
const entries: LogEntry[] = [];
setLogLevel('trace');
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
try {
const upload = uploadHighwayHttp(
makeBridge(),
session,
71,
source,
new Uint8Array(16),
new Uint8Array(),
);
const failed = expect(upload).rejects.toThrow(
/transport failed after 3 attempts.*acknowledgedBytes=0.*unconfirmed/,
);
await Promise.all([failed, vi.runAllTimersAsync()]);
expect(createConnectionMock.mock.calls.map(([options]) => options)).toEqual([
session.servers[0],
session.servers[1],
session.servers[0],
]);
expect(source.reads).toEqual([{ offset: 0, length: 80 }]);
expect(source.closeCount).toBe(1);
const terminals = highwayTrace(entries).filter((entry) =>
entry.message.startsWith('highway_put_terminal '),
);
expect(terminals).toHaveLength(1);
expect(terminals[0]!.message).toContain('outcome=failed reason=transport_exhausted');
expect(terminals[0]!.message).toContain('uploadedBytes=0');
expect((createdSockets as FakeSocket[]).every((socket) => socket.destroyed)).toBe(true);
} finally {
unsubscribe();
}
});
it('continues after the actual failed node and skips candidates that cannot reconnect', async () => {
vi.useFakeTimers();
installFactory(() => {
const host = createConnectionMock.mock.lastCall?.[0].host;
const socket = new FakeSocket(buildEmptyHighwayResponseFrame(), 'keepalive');
if (host === '192.0.2.1') {
socket.connectFailure = new Error('ECONNREFUSED');
} else if (host === '192.0.2.2') {
socket.closeBeforeResponse = true;
} else if (host === '192.0.2.3') {
socket.connectFailure = 'timeout';
}
return socket;
});
const session = {
...makeSession(),
servers: Array.from({ length: 4 }, (_, i) => ({ host: `192.0.2.${i + 1}`, port: 443 })),
};
const source = new RecordingChunkSource(80);
const upload = uploadHighwayHttp(
makeBridge(),
session,
1004,
new RecordingChunkSource(1),
71,
source,
new Uint8Array(16),
new Uint8Array(),
);
await Promise.all([expect(upload).resolves.toBeUndefined(), vi.runAllTimersAsync()]);
expect(createConnectionMock.mock.calls.map(([options]) => options)).toEqual(
session.servers,
);
expect((createdSockets as FakeSocket[]).map((socket) => socket.posts)).toEqual([
0, 1, 0, 1,
]);
expect(source.reads).toEqual([{ offset: 0, length: 80 }]);
expect(source.closeCount).toBe(1);
});
it('keeps the successful node when the peer closes after acknowledgement', async () => {
installFactory(() => new FakeSocket(buildEmptyHighwayResponseFrame(), 'closeafter'));
const session = sessionWithCandidates();
await uploadHighwayHttp(
makeBridge(),
session,
71,
new RecordingChunkSource(HIGHWAY_BLOCK_SIZE + 80),
new Uint8Array(16),
new Uint8Array(),
);
const completed = expect(upload).resolves.toBeUndefined();
await vi.runAllTimersAsync();
await completed;
expect(createConnectionMock.mock.calls.map(([options]) => options)).toEqual([
session.servers[0],
session.servers[0],

View File

@@ -529,6 +529,7 @@ describe('parseMsgPush Event0x210 subType=364 (friend remark synchronization)',
fetchGroupList: vi.fn(async () => {}),
fetchGroupMemberList: vi.fn(async () => {}),
resolveGroupJoinRequest: vi.fn(async () => null),
rememberGroupInviteCardSequence: vi.fn(() => true),
});
pipeline.registerCmd(MSG_PUSH_CMD, parseMsgPush);
@@ -1027,6 +1028,7 @@ describe('parseMsgPush PkgType 44 (group admin set/unset) keeps the member cache
fetchGroupList: vi.fn(async () => {}),
fetchGroupMemberList: vi.fn(async () => {}),
resolveGroupJoinRequest: vi.fn(async () => null),
rememberGroupInviteCardSequence: vi.fn(() => true),
});
pipeline.registerCmd(MSG_PUSH_CMD, parseMsgPush);
await pipeline.process(packet);

View File

@@ -1,65 +0,0 @@
import { describe, expect, it } from 'vitest';
import {
appendEvents,
ingestTemp,
lineSeverity,
publicLine,
trimMirror,
} from '../src/native-stage-sync';
const VERSION = '1.14.22';
const EVENT = 'a'.repeat(64);
const infoLine = `2026-10-09T00:00:00Z 42 1 0 ${EVENT}`;
const failLine = `2026-10-09T00:00:01Z 42 1 1 ${EVENT} ${'b'.repeat(16)}=7`;
describe('native stage sync', () => {
it('keeps a version marker and copies the record without extra wording', () => {
const mirror = appendEvents('', VERSION, [infoLine, failLine]);
expect(mirror.startsWith(`v${VERSION}\n`)).toBe(true);
expect(mirror).toContain(infoLine);
expect(mirror).toContain(failLine);
const shown = [publicLine(VERSION, infoLine), publicLine(VERSION, failLine)].join('\n');
expect(shown).toBe(`${VERSION} ${infoLine}\n${VERSION} ${failLine}`);
});
it('opens a new version section without dropping the previous marker', () => {
const first = appendEvents('', '1.14.22', [infoLine]);
const second = appendEvents(first, '1.14.23', [failLine]);
expect(second).toContain('v1.14.22\n');
expect(second).toContain('v1.14.23\n');
expect(second.indexOf('v1.14.22')).toBeLessThan(second.indexOf(infoLine));
expect(second.indexOf('v1.14.23')).toBeLessThan(second.indexOf(failLine));
});
it('drops the oldest record first and keeps the version marker', () => {
const long = `2026-10-09T00:00:00Z 1 1 0 ${'c'.repeat(64)} ${'d'.repeat(40)}`;
let mirror = appendEvents('', VERSION, [long, long, long], 80);
mirror = trimMirror(mirror, 80);
expect(mirror).toContain(`v${VERSION}`);
expect(mirror.split('\n').filter((line) => line.startsWith('2026')).length).toBeLessThan(3);
});
it('treats severity 1 as a failure and ignores a missing file', () => {
expect(lineSeverity(failLine)).toBe('error');
expect(lineSeverity(infoLine)).toBe('info');
const ingested = ingestTemp({
tempText: `${infoLine}\n${failLine}\npartial`,
offset: 0,
mirror: '',
version: VERSION,
});
expect(ingested.lines).toEqual([infoLine, failLine]);
expect(ingested.mirror).toContain(`v${VERSION}\n`);
expect(ingested.offset).toBe(`${infoLine}\n${failLine}\n`.length);
const missing = ingestTemp({
tempText: '',
offset: 4,
mirror: 'keep',
version: VERSION,
missing: true,
});
expect(missing.mirror).toBe('keep');
expect(missing.lines).toEqual([]);
expect(missing.errorCode).toBeUndefined();
});
});

View File

@@ -1,5 +1,5 @@
import { spawn } from 'node:child_process';
import { cp, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
import { cp, mkdtemp, readFile, realpath, rm, writeFile } from 'node:fs/promises';
import { builtinModules } from 'node:module';
import os from 'node:os';
import path from 'node:path';
@@ -14,7 +14,8 @@ let root: string;
let staging: string;
beforeAll(async () => {
compiled = await mkdtemp(path.join(os.tmpdir(), 'snowluma-entry-build-'));
// Module resolution uses canonical paths, including when the temp directory is a symlink.
compiled = await realpath(await mkdtemp(path.join(os.tmpdir(), 'snowluma-entry-build-')));
const loaded = await loadConfigFromFile(
{ command: 'build', mode: 'production' },
fileURLToPath(new URL('../vite.config.ts', import.meta.url)),
@@ -114,7 +115,7 @@ afterAll(async () => {
await rm(compiled, { recursive: true, force: true });
});
beforeEach(async () => {
root = await mkdtemp(path.join(os.tmpdir(), 'snowluma-entry-test-'));
root = await realpath(await mkdtemp(path.join(os.tmpdir(), 'snowluma-entry-test-')));
staging = await updateDirectory(root);
await releaseFixture(root, '1.0.0');
await cp(path.join(compiled, '1.0.0/index.mjs'), path.join(root, 'index.mjs'));
@@ -158,7 +159,7 @@ describe('packaged startup', () => {
expect(JSON.parse(result.output)).toEqual({
version: '1.0.0',
node: process.execPath,
cwd: os.tmpdir(),
cwd: await realpath(os.tmpdir()),
args: ['value with spaces'],
oldAlive: false,
});

View File

@@ -0,0 +1,47 @@
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { Hono } from 'hono';
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { registerStaticFrontend } from '../src/webui/static-frontend';
let root: string;
const html = '<!doctype html><html><head><title>SnowLuma</title></head><body>app</body></html>';
beforeEach(() => {
root = mkdtempSync(path.join(tmpdir(), 'snowluma-presentation-'));
writeFileSync(path.join(root, 'index.html'), html);
writeFileSync(path.join(root, 'asset.js'), 'window.asset = true;');
});
afterEach(() => rmSync(root, { recursive: true, force: true }));
describe('runtime target document delivery', () => {
it.each(['/', '/index.html', '/settings?tab=appearance'])(
'injects on %s before authentication',
async (url) => {
const app = new Hono();
registerStaticFrontend(app, root, 'maibot');
const response = await app.request(url);
expect(response.status).toBe(200);
expect(response.headers.get('cache-control')).toBe('no-store');
expect(await response.text()).toContain('"target":"maibot"');
},
);
it('reuses the exact same built frontend for an unconfigured deployment', async () => {
const app = new Hono();
registerStaticFrontend(app, root, null);
expect(await (await app.request('/index.html')).text()).toBe(html);
});
it('does not inject into assets or API error responses', async () => {
const app = new Hono();
registerStaticFrontend(app, root, 'maibot');
expect(await (await app.request('/asset.js')).text()).toBe('window.asset = true;');
for (const url of ['/api/missing', '/avatar/missing', '/ui-asset/missing']) {
expect((await app.request(url)).status).toBe(404);
}
});
});

View File

@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/mcp",
"version": "2.0.2",
"version": "2.1.0",
"description": "MCP server exposing the SnowLuma OneBot action catalog (docs + JSON Schemas) and optional execution to LLM clients.",
"repository": {
"type": "git",

View File

@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/onebot",
"version": "2.0.2",
"version": "2.1.0",
"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>'`.",

View File

@@ -302,7 +302,7 @@ function arrayField<E>(
}
export const f = {
/** Positive integer (>0): group_id / user_id / message_id. */
/** Positive integer (>0): group_id / user_id. */
uint(): Field<number> {
return new FieldImpl<number>(intCore('a positive integer', { min: 1 }), {
type: 'uint',

View File

@@ -166,7 +166,8 @@ type PipelineEventReason =
| 'pipeline_threw'
| 'recalled_before_backfill'
| 'recalled_after_backfill'
| 'waiter_notified';
| 'waiter_notified'
| 'waiter_not_found';
async function convertAndDispatch(
ctx: OneBotInstanceContext,
@@ -458,8 +459,14 @@ function handlePttTransResult(
event: Extract<QQEventVariant, { kind: 'ptt_trans_result' }>,
state: EventTraceState,
): void {
deliverPttTransText(pttTransKey(event.selfUin, event.msgId), event.text);
traceEventTerminal(log, event.kind, state, 'internal', 'waiter_notified');
const notified = deliverPttTransText(pttTransKey(event.selfUin, event.msgId), event.text);
traceEventTerminal(
log,
event.kind,
state,
'internal',
notified ? 'waiter_notified' : 'waiter_not_found',
);
}
function convertOnly<K extends EventKind>(

View File

@@ -1,307 +0,0 @@
import { createLogger, type Logger } from '@snowluma/common/logger';
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
import type { GroupInviteEvent } from '@snowluma/protocol/events';
import { formatGroupRequestFlag, type GroupRequestInfo } from '@snowluma/protocol/qq-info';
const DEFAULT_INTERVAL_MS = 15_000;
const REQUEST_SCREEN_COUNT = 50;
const RECENT_EVENT_WINDOW_MS = 30_000;
const MAX_SEEN_FLAGS = 2_048;
export interface GroupRequestPollerOptions {
intervalMs?: number;
now?: () => number;
}
/**
* Some group requests (notably invitations initiated through qun.qq.com) are
* visible in QQ's system-notification list without producing the real-time
* push consumed by SnowLuma's packet pipeline. Observe both request inboxes
* and emit only newly seen, actionable records through the same typed event
* bus as push-originated requests.
*/
export class GroupRequestPoller {
private readonly intervalMs: number;
private readonly now: () => number;
private readonly log: Logger;
private readonly seenFlags = new Map<string, true>();
private readonly recentFingerprints = new Map<string, number>();
private timer: ReturnType<typeof setTimeout> | null = null;
private scheduledTask: Promise<void> | null = null;
private scanInFlight: Promise<void> | null = null;
private unsubscribe: (() => void) | null = null;
private running = false;
private lifecycleStarted = false;
constructor(
private readonly bridge: BridgeInterface,
private readonly selfUin: number,
options: GroupRequestPollerOptions = {},
) {
this.intervalMs = options.intervalMs ?? DEFAULT_INTERVAL_MS;
if (!Number.isSafeInteger(this.intervalMs) || this.intervalMs <= 0) {
throw new Error(`invalid group-request polling interval: ${this.intervalMs}`);
}
this.now = options.now ?? Date.now;
this.log = createLogger('OneBot.GroupRequests').child({ uin: selfUin });
}
start(): void {
if (this.running) {
return;
}
this.running = true;
this.lifecycleStarted = true;
this.unsubscribe = this.bridge.events.on('group_invite', (event) => {
this.rememberObservedEvent(event);
});
this.scheduledTask = this.runScheduledPoll();
}
stop(): Promise<void> {
if (!this.running) {
return this.scheduledTask ?? Promise.resolve();
}
this.running = false;
if (this.timer) {
clearTimeout(this.timer);
this.timer = null;
}
this.unsubscribe?.();
this.unsubscribe = null;
return this.scheduledTask ?? Promise.resolve();
}
/**
* Public deterministic seam used by diagnostics and tests. Concurrent calls
* share one scan so a slow QQ response cannot create overlapping polling.
*/
pollOnce(): Promise<void> {
if (this.scanInFlight) {
return this.scanInFlight;
}
const scan = this.scan();
this.scanInFlight = scan;
void scan
.finally(() => {
if (this.scanInFlight === scan) {
this.scanInFlight = null;
}
})
.catch(() => undefined);
return scan;
}
private async scan(): Promise<void> {
const [main, filtered] = await Promise.all([
this.bridge.apis.contacts.fetchGroupRequests(false, REQUEST_SCREEN_COUNT),
this.bridge.apis.contacts.fetchGroupRequests(true, REQUEST_SCREEN_COUNT),
]);
if (this.lifecycleStarted && !this.running) {
return;
}
const discovered = [...main, ...filtered]
.filter((request) => request.state === 1)
.filter((request) => request.notifyType === 1 || request.notifyType === 7);
const now = this.now();
this.sweepRecentFingerprints(now);
for (const request of discovered) {
if (this.lifecycleStarted && !this.running) {
return;
}
let event: GroupInviteEvent;
try {
event = this.toEvent(request);
} catch (error) {
this.log.error(
'group request record rejected: group=%s sequence=%s subtype=%s reason=%s',
String(request.groupId),
String(request.sequence),
request.notifyType === 1 ? 'invite' : 'add',
error instanceof Error ? error.message : String(error),
);
continue;
}
const fingerprint = eventFingerprint(event);
if (this.seenFlags.has(event.flag)) {
continue;
}
if ((this.recentFingerprints.get(fingerprint) ?? 0) > now - RECENT_EVENT_WINDOW_MS) {
this.rememberFlag(event.flag);
continue;
}
if (event.fromUin === 0) {
this.log.warn(
'group request sender could not be identified: group=%d sequence=%d subtype=%s',
event.groupId,
request.sequence,
event.subType,
);
}
// Mark before emission: handlers may synchronously trigger another list
// read through a quick operation, which must not re-emit this request.
this.rememberFlag(event.flag);
this.recentFingerprints.set(fingerprint, now);
this.log.info(
'new group request discovered: group=%d sequence=%d subtype=%s filtered=%s',
event.groupId,
request.sequence,
event.subType,
request.filtered,
);
await this.bridge.events.emit(event);
}
}
private toEvent(request: GroupRequestInfo): GroupInviteEvent {
const notifyType = request.notifyType;
const subType = notifyType === 1 ? 'invite' : 'add';
const fromUin = notifyType === 1 ? request.invitorUin : request.targetUin;
const fromUid = notifyType === 1 ? request.invitorUid : request.targetUid;
const inviteCardSequence =
notifyType === 1
? this.bridge.apis.contacts.getGroupInviteCardSequence?.(request.groupId)
: undefined;
if (!Number.isSafeInteger(request.sequence) || request.sequence <= 0) {
throw new Error(`invalid group-request sequence: ${request.sequence}`);
}
if (!Number.isSafeInteger(request.groupId) || request.groupId <= 0) {
throw new Error(`invalid group id on group request: ${request.groupId}`);
}
if (!Number.isSafeInteger(request.eventType) || request.eventType <= 0) {
throw new Error(
`group request has no operation type: group=${request.groupId} sequence=${request.sequence} notifyType=${notifyType ?? 0}`,
);
}
if (!Number.isSafeInteger(fromUin) || fromUin < 0) {
throw new Error(`invalid sender account on group request: ${fromUin}`);
}
if (
inviteCardSequence !== undefined &&
(!Number.isSafeInteger(inviteCardSequence) || inviteCardSequence <= 0)
) {
throw new Error(
`invalid invite-card sequence: group=${request.groupId} sequence=${inviteCardSequence}`,
);
}
return {
kind: 'group_invite',
time: Math.floor(this.now() / 1_000),
selfUin: this.selfUin,
groupId: request.groupId,
fromUin,
fromUid,
...(notifyType === 1
? {
invitedUin: request.targetUin,
invitedUid: request.targetUid,
}
: {}),
subType,
message: request.comment,
flag: formatGroupRequestFlag(
inviteCardSequence === undefined
? request
: {
groupId: request.groupId,
sequence: inviteCardSequence,
eventType: 2,
filtered: false,
},
),
};
}
private rememberObservedEvent(event: GroupInviteEvent): void {
if (event.flag.startsWith('slreq:1:')) {
this.rememberFlag(event.flag);
}
const fingerprint = eventFingerprint(event);
this.recentFingerprints.set(fingerprint, this.now());
}
private rememberFlag(flag: string): void {
if (this.seenFlags.has(flag)) {
return;
}
this.seenFlags.set(flag, true);
if (this.seenFlags.size <= MAX_SEEN_FLAGS) {
return;
}
const oldest = this.seenFlags.keys().next().value;
if (oldest !== undefined) {
this.seenFlags.delete(oldest);
}
}
private sweepRecentFingerprints(now: number): void {
const oldest = now - RECENT_EVENT_WINDOW_MS;
for (const [fingerprint, observedAt] of this.recentFingerprints) {
if (observedAt <= oldest) {
this.recentFingerprints.delete(fingerprint);
}
}
}
private async runScheduledPoll(): Promise<void> {
try {
await this.pollOnce();
} catch (error) {
this.log.error(
'group request scan failed: %s',
error instanceof Error ? (error.stack ?? error.message) : String(error),
);
} finally {
if (this.running) {
this.timer = setTimeout(() => {
this.timer = null;
this.scheduledTask = this.runScheduledPoll();
}, this.intervalMs);
this.timer.unref();
}
}
}
}
function eventFingerprint(
event: Pick<GroupInviteEvent, 'groupId' | 'subType' | 'fromUin' | 'fromUid' | 'flag'>,
): string {
const fromUid = event.fromUid?.trim() ?? '';
const actor =
event.fromUin > 0
? `uin:${event.fromUin}`
: fromUid
? `uid:${fromUid}`
: `request:${event.flag}`;
return `${event.groupId}:${event.subType}:${actor}`;
}

View File

@@ -34,7 +34,6 @@ import {
statusCooldownElapsed,
} from './modules/status-command';
import { loginHistorySyncCoordinator } from './history-sync';
import { GroupRequestPoller } from './group-request-poller';
import {
HttpPostAdapter,
HttpServerAdapter,
@@ -64,7 +63,6 @@ export class OneBotInstance {
private readonly reactionStore: ReactionStore;
private readonly networkManager: OneBotNetworkManager;
private readonly networkReady: Promise<NetworkReconcileResult>;
private readonly groupRequestPoller: GroupRequestPoller;
private lifecycleTail: Promise<void>;
private readonly rkeyCache: RKeyCache;
private readonly ctx: OneBotInstanceContext;
@@ -72,14 +70,13 @@ export class OneBotInstance {
private readonly startedAt = Date.now();
/** Per-conversation last-reply timestamp for the `#sl` cooldown. */
private readonly statusCommandCooldown = new Map<string, number>();
/** Action-side events awaiting a possible canonical QQ echo. */
private readonly pendingSelfSentEchoes = new Map<
/** Reported self sends retained while matching subsequent QQ echoes. */
private readonly recentSelfSentEvents = new Map<
string,
{ event: JsonObject; expiresAt: number }
>();
private eventPipeline: EventPipelineHandle | null = null;
private eventPipelineDrain: Promise<void> = Promise.resolve();
private groupRequestPollerDrain: Promise<void> = Promise.resolve();
private disposePromise: Promise<NetworkShutdownResult> | null = null;
private disposeRequested = false;
private acceptingActions = true;
@@ -241,7 +238,6 @@ export class OneBotInstance {
this.startHeartbeat();
this.rkeyCache.warmUp(this.bridge, this.uin);
this.eventPipeline = registerEventPipeline(ctx);
this.groupRequestPoller = new GroupRequestPoller(this.bridge, ctx.selfId);
}
waitUntilNetworkReady(): Promise<NetworkReconcileResult> {
@@ -254,15 +250,6 @@ export class OneBotInstance {
return this.dispatchEvent(makeBotStatusEvent(parseInt(this.uin, 10) || 0, subType));
}
/** Begin observing request-list-only group invitations after adapters exist. */
startGroupRequestPolling(): void {
if (this.disposeRequested) {
return;
}
this.groupRequestPoller.start();
}
/**
* Start the optional login-time backfill once roster warmup has completed.
* The startup snapshot is intentional: hot config edits take effect on the
@@ -363,7 +350,6 @@ export class OneBotInstance {
this.apiHandler.quiesce();
this.online = false;
this.stopHeartbeat();
this.groupRequestPollerDrain = this.groupRequestPoller.stop();
this.historySyncAbortController?.abort(
new Error(`OneBot instance UIN=${this.uin} is disposing`),
);
@@ -386,7 +372,6 @@ export class OneBotInstance {
await Promise.all([
Promise.all(this.inFlightActions),
this.eventPipelineDrain,
this.groupRequestPollerDrain,
this.historySyncTask ?? Promise.resolve(),
]);
const shutdown = await this.networkManager.shutdown();
@@ -479,7 +464,7 @@ export class OneBotInstance {
}
if (source === 'bridge') {
if (this.consumePendingSelfSentEcho(event)) {
if (this.isDuplicateSelfSentEcho(event)) {
this.log.trace(
'duplicate self-message echo suppressed message_id=%d message_seq=%d',
toInt(event.message_id),
@@ -493,8 +478,12 @@ export class OneBotInstance {
);
return;
}
if (event.post_type === 'message_sent') {
this.rememberSelfSentEvent(event);
}
} else {
this.rememberPendingSelfSentEcho(event);
this.rememberSelfSentEvent(event);
}
// The send path already logged the real peer and payload. Logging its
@@ -538,7 +527,7 @@ export class OneBotInstance {
]);
}
private rememberPendingSelfSentEcho(event: JsonObject): void {
private rememberSelfSentEvent(event: JsonObject): void {
const key = selfSentEventKey(event);
if (key === null) {
@@ -546,11 +535,11 @@ export class OneBotInstance {
}
const now = Date.now();
this.sweepPendingSelfSentEchoes(now);
this.pendingSelfSentEchoes.set(key, { event, expiresAt: now + SELF_SENT_ECHO_WINDOW_MS });
this.sweepSelfSentEvents(now);
this.recentSelfSentEvents.set(key, { event, expiresAt: now + SELF_SENT_ECHO_WINDOW_MS });
}
private consumePendingSelfSentEcho(event: JsonObject): boolean {
private isDuplicateSelfSentEcho(event: JsonObject): boolean {
const key = selfSentEventKey(event);
if (key === null) {
@@ -558,21 +547,20 @@ export class OneBotInstance {
}
const now = Date.now();
this.sweepPendingSelfSentEchoes(now);
const pending = this.pendingSelfSentEchoes.get(key);
this.sweepSelfSentEvents(now);
const pending = this.recentSelfSentEvents.get(key);
if (!pending || !sameSelfSentMessage(pending.event, event)) {
return false;
}
this.pendingSelfSentEchoes.delete(key);
return true;
}
private sweepPendingSelfSentEchoes(now: number): void {
for (const [key, pending] of this.pendingSelfSentEchoes) {
private sweepSelfSentEvents(now: number): void {
for (const [key, pending] of this.recentSelfSentEvents) {
if (pending.expiresAt <= now) {
this.pendingSelfSentEchoes.delete(key);
this.recentSelfSentEvents.delete(key);
}
}
}

View File

@@ -560,8 +560,6 @@ export class OneBotManager {
);
}
instance.startGroupRequestPolling();
if (this.disposed || this.instances.get(uin) !== instance) {
return;
}

View File

@@ -5,8 +5,12 @@ interface Pending {
const pending = new Map<string, Pending>();
export function pttTransKey(selfUin: number, msgId: number): string {
return selfUin + ':' + msgId;
export function pttTransKey(selfUin: number, msgId: number | bigint): string {
if (typeof msgId === 'number' && !Number.isSafeInteger(msgId)) {
throw new RangeError('PTT message id must be a safe integer or bigint');
}
return selfUin + ':' + BigInt.asIntN(64, BigInt(msgId));
}
/** Register before triggering; only this request may settle its own response or timeout. */
@@ -53,6 +57,13 @@ export function requestPttTransText(
}
/** QQ push results identify the account and message, not an individual trigger request. */
export function deliverPttTransText(key: string, text: string): void {
pending.get(key)?.resolve(text);
export function deliverPttTransText(key: string, text: string): boolean {
const waiter = pending.get(key);
if (!waiter) {
return false;
}
waiter.resolve(text);
return true;
}

View File

@@ -3,8 +3,8 @@ import type { JsonObject } from './types';
export const SELF_SENT_ECHO_WINDOW_MS = 120_000;
/**
* Match the action-side copy of a sent message with QQ's later canonical
* echo. The message hash alone is insufficient because it is a signed 32-bit
* Match a reported self send with a later QQ echo, including repeated
* pushes. The message hash alone is insufficient because it is a signed 32-bit
* value and can collide; sequence, conversation and a bounded time window are
* part of the identity as well.
*/

View File

@@ -9,6 +9,11 @@ import {
type LogEntry,
} from '@snowluma/common/logger';
import { BridgeEventBus } from '@snowluma/protocol/event-bus';
import { IdentityService } from '@snowluma/protocol/identity-service';
import { MSG_PUSH_CMD, parseMsgPushOrThrow } from '@snowluma/protocol/msg-push';
import type { PushMsg } from '@snowluma/proto-defs/message';
import type { PttTransPush } from '@snowluma/proto-defs/ptt-trans';
import { protobuf_encode } from '@snowluma/proton';
// Wrap convertEvent in a vi.fn that delegates to the real impl by
// default, so one test can override it to return null without making
@@ -28,8 +33,15 @@ vi.mock('../src/modules/message-actions', async () => {
import { convertEvent, type ConverterContext } from '../src/event-converter';
import { registerEventPipeline } from '../src/event-pipeline';
import { buildDispatchPayload, pickDispatchJson } from '../src/event-filter';
import type { OneBotInstanceContext } from '../src/instance-context';
import { GROUP_MESSAGE_EVENT, hashMessageIdInt32, PRIVATE_MESSAGE_EVENT } from '../src/message-id';
import { backfillReplyTarget } from '../src/modules/message-actions';
import {
deliverPttTransText,
pttTransKey,
requestPttTransText,
} from '../src/modules/ptt-trans-waiter';
import { TempSessionStore } from '../src/temp-session-store';
import type {
FriendMessage,
@@ -107,6 +119,28 @@ function makeMemberJoin(): GroupMemberJoin {
};
}
function decodePttTransPush(selfId: number, msgId: bigint, text: string): QQEventVariant[] {
return parseMsgPushOrThrow(
{
pid: 1,
uin: String(selfId),
serviceCmd: MSG_PUSH_CMD,
seqId: 1,
retCode: 0,
fromClient: false,
body: protobuf_encode<PushMsg>({
message: {
contentHead: { msgType: 528, subType: 61, timestamp: 1700000000 },
body: {
msgContent: protobuf_encode<PttTransPush>({ item: { msgId, text } }),
},
},
}),
},
IdentityService.memory(String(selfId)),
);
}
function makeContext(extra: Partial<OneBotInstanceContext> = {}): {
ctx: OneBotInstanceContext;
bus: BridgeEventBus;
@@ -168,6 +202,79 @@ function makeContext(extra: Partial<OneBotInstanceContext> = {}): {
}
describe('registerEventPipeline', () => {
it('matches transcription pushes to signed message IDs without rounding or crossing accounts', async () => {
vi.useFakeTimers();
const previousLevel = getLogLevel();
const entries: LogEntry[] = [];
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
setLogLevel('trace');
const cases = [
{ selfId: SELF_ID, msgId: -373767942, wireId: 18446744073335783674n },
{ selfId: SELF_ID, msgId: -373767943, wireId: 18446744073335783673n },
{ selfId: SELF_ID + 1, msgId: -373767942, wireId: 18446744073335783674n },
{ selfId: SELF_ID, msgId: -2147483648, wireId: 18446744071562067968n },
{ selfId: SELF_ID, msgId: -1, wireId: 18446744073709551615n },
{ selfId: SELF_ID, msgId: 147311541, wireId: 147311541n },
{ selfId: SELF_ID, msgId: 2147483647, wireId: 2147483647n },
{
selfId: SELF_ID,
msgId: hashMessageIdInt32(1, 12345, PRIVATE_MESSAGE_EVENT),
wireId: 18446744073124008294n,
},
];
const requests = cases.map((item, index) => {
const context = makeContext({ selfId: item.selfId, uin: String(item.selfId) });
const handle = registerEventPipeline(context.ctx);
const key = pttTransKey(item.selfId, item.msgId);
const text = `transcription ${index}`;
const result = requestPttTransText(key, 20_000, async () => '');
return { ...item, ...context, handle, key, text, result };
});
const settled = Promise.allSettled(requests.map(({ result }) => result));
try {
expect(cases.at(-1)?.msgId).toBe(-585543322);
for (const request of requests.toReversed()) {
const events = decodePttTransPush(request.selfId, request.wireId, request.text);
expect(events).toHaveLength(1);
await request.bus.emit(events[0]!);
}
await vi.advanceTimersByTimeAsync(20_000);
expect(await settled).toEqual(
requests.map(({ text }) => ({ status: 'fulfilled', value: text })),
);
expect(vi.getTimerCount()).toBe(0);
expect(requests.flatMap(({ dispatchCalls }) => dispatchCalls)).toEqual([]);
expect(
entries.filter(
(entry) =>
entry.scope === 'Event' &&
entry.message.startsWith('event_terminal kind=ptt_trans_result') &&
entry.message.includes('reason=waiter_notified'),
),
).toHaveLength(requests.length);
expect(
entries.some(
(entry) =>
entry.message.startsWith('event_input kind=ptt_trans_result') &&
entry.message.includes('msgId:18446744073335783674'),
),
).toBe(true);
} finally {
for (const request of requests) {
deliverPttTransText(request.key, 'cleanup');
request.handle.stop();
await request.handle.drain();
}
unsubscribe();
setLogLevel(previousLevel);
vi.useRealTimers();
}
});
it('caches meta and dispatches a converted event for friend_message', async () => {
const { ctx, bus, metaCalls, dispatchCalls } = makeContext();
registerEventPipeline(ctx);
@@ -219,6 +326,100 @@ describe('registerEventPipeline', () => {
expect(dispatchCalls[0].message_type).toBe('group');
});
it('reports a received client group push according to each adapter self-message option', async () => {
const { ctx, bus, metaCalls, dispatchCalls, dispatchArgs } = makeContext();
ctx.converterCtx.messageIdResolver = (_isGroup, sessionId, sequence, eventName) =>
hashMessageIdInt32(sequence, sessionId, eventName);
const handle = registerEventPipeline(ctx);
const identity = IdentityService.memory(SELF_UIN);
const packet = {
pid: 1,
uin: SELF_UIN,
serviceCmd: MSG_PUSH_CMD,
seqId: 1,
retCode: 0,
fromClient: false,
body: protobuf_encode<PushMsg>({
message: {
responseHead: {
fromUin: SELF_ID,
grp: { groupUin: GROUP_ID, memberCard: 'self', groupName: 'test group' },
},
contentHead: {
msgType: 82,
sequence: 5637,
timestamp: 1_700_000_000,
msgId: 335502226,
},
body: { richText: { elems: [{ text: { str: 'client group send' } }] } },
},
}),
};
try {
const events = parseMsgPushOrThrow(packet, identity);
expect(events).toHaveLength(1);
for (const event of events) {
await bus.emit(event);
}
const messageId = hashMessageIdInt32(5637, GROUP_ID, GROUP_MESSAGE_EVENT);
expect(metaCalls).toEqual([
{
id: messageId,
meta: expect.objectContaining({
isGroup: true,
targetId: GROUP_ID,
sequence: 5637,
random: 335502226,
}),
},
]);
expect(dispatchCalls).toHaveLength(1);
const event = dispatchCalls[0];
expect(event).toMatchObject({
post_type: 'message_sent',
message_type: 'group',
self_id: SELF_ID,
user_id: SELF_ID,
group_id: GROUP_ID,
message_id: messageId,
message_seq: 5637,
raw_message: 'client group send',
});
expect(dispatchArgs[0].source).toBe('bridge');
const payload = buildDispatchPayload(event);
expect(
pickDispatchJson(payload, { reportSelfMessage: false, messageFormat: 'array' }),
).toBeNull();
expect(
JSON.parse(
pickDispatchJson(payload, { reportSelfMessage: true, messageFormat: 'array' })!,
),
).toMatchObject({
post_type: 'message_sent',
message: [{ type: 'text', data: { text: 'client group send' } }],
});
expect(
JSON.parse(
pickDispatchJson(payload, {
reportSelfMessage: true,
messageFormat: 'string',
})!,
),
).toMatchObject({
post_type: 'message_sent',
message: 'client group send',
});
} finally {
handle.stop();
await handle.drain();
await identity.close();
}
});
it('caches meta with random=0 for temp_message and dispatches as private+sub_type=group', async () => {
const { ctx, bus, metaCalls, dispatchCalls } = makeContext();
registerEventPipeline(ctx);
@@ -540,7 +741,7 @@ describe('registerEventPipeline', () => {
kind: 'ptt_trans_result',
time: 1700000000,
selfUin: SELF_ID,
msgId: 99,
msgId: 99n,
text: 'done',
});
@@ -555,7 +756,7 @@ describe('registerEventPipeline', () => {
expect.stringContaining('outcome=dropped reason=converter_returned_null'),
expect.stringContaining('outcome=failed reason=converter_threw'),
expect.stringContaining('outcome=dropped reason=recalled_before_backfill'),
expect.stringContaining('outcome=internal reason=waiter_notified'),
expect.stringContaining('outcome=internal reason=waiter_not_found'),
]),
);
expect(

View File

@@ -0,0 +1,340 @@
import { deflateSync } from 'node:zlib';
import { afterEach, describe, expect, it, vi } from 'vitest';
import type { PacketInfo } from '@snowluma/common/protocol-types';
import type { PushMsg } from '@snowluma/proto-defs/message';
import type { GroupInvite } from '@snowluma/proto-defs/notify';
import { protobuf_encode } from '@snowluma/proton';
import { IdentityService } from '@snowluma/protocol/identity-service';
import { MSG_PUSH_CMD } from '@snowluma/protocol/msg-push';
import type { GroupInviteEvent } from '@snowluma/protocol/events';
import type { GroupRequestInfo } from '@snowluma/protocol/qq-info';
import { handleGroupAddRequest } from '../src/modules/request-actions';
import { Bridge } from '@snowluma/core/bridge';
const bridges: Bridge[] = [];
afterEach(async () => {
await Promise.all(bridges.splice(0).map((bridge) => bridge.dispose()));
vi.useRealTimers();
});
function setup() {
const bridge = new Bridge(IdentityService.memory('10001'));
bridges.push(bridge);
const received: GroupInviteEvent[] = [];
bridge.events.on('group_invite', (event) => {
received.push(event);
});
const fetchRequests = vi.spyOn(bridge.apis.contacts, 'fetchGroupRequestsByUid');
const fetchNumericRequests = vi.spyOn(bridge.apis.contacts, 'fetchGroupRequests');
return { bridge, received, fetchRequests, fetchNumericRequests };
}
function packet(message: PushMsg['message']): PacketInfo {
return {
pid: 1,
uin: '10001',
serviceCmd: MSG_PUSH_CMD,
seqId: 1,
retCode: 0,
fromClient: false,
body: Buffer.from(protobuf_encode<PushMsg>({ message, status: 0 })),
};
}
function card(sequence = 778899, senderUin = 456, app = 'com.tencent.qun.invite'): PacketInfo {
return jsonCard(
{
app,
bizsrc: 'qun.invite',
meta: {
news: { jumpUrl: `mqqapi://group/invite_join?groupcode=999&msgseq=${sequence}` },
},
},
senderUin,
);
}
function jsonCard(content: unknown, senderUin = 456): PacketInfo {
const json = JSON.stringify(content);
return packet({
responseHead: { fromUin: senderUin, fromUid: 'u_inviter', toUin: 10001 },
contentHead: { msgType: 166, timestamp: 1, sequence: 12, ntMsgSeq: 12, msgId: 12 },
body: {
richText: {
elems: [
{ lightApp: { data: Buffer.concat([Buffer.from([1]), deflateSync(json)]) } },
],
},
},
});
}
function selfInviteNotice(): PacketInfo {
return packet({
contentHead: { msgType: 87, timestamp: 1 },
body: {
msgContent: protobuf_encode<GroupInvite>({ groupUin: 999, invitorUid: 'u_inviter' }),
},
});
}
function request(overrides: Partial<GroupRequestInfo> = {}): GroupRequestInfo {
return {
groupId: 999,
groupName: 'group',
targetUid: 'u_applicant',
targetUin: 123,
targetName: '',
invitorUid: '',
invitorUin: 0,
invitorName: '',
operatorUid: '',
operatorUin: 0,
operatorName: '',
sequence: 42,
state: 1,
notifyType: 7,
eventType: 1,
comment: 'please',
filtered: false,
...overrides,
};
}
describe('group request events', () => {
it.each(['com.tencent.qun.invite', 'com.tencent.tuwen.lua'])(
'handles %s invite cards without reading either inbox',
async (app) => {
const { bridge, received, fetchRequests, fetchNumericRequests } = setup();
const setAddRequest = vi
.spyOn(bridge.apis.groupAdmin, 'setAddRequest')
.mockResolvedValue();
await bridge.onPacket(card(778899, 456, app));
expect(received).toEqual([
expect.objectContaining({
groupId: 999,
fromUin: 456,
fromUid: 'u_inviter',
invitedUin: 10001,
subType: 'invite',
flag: 'slreq:1:778899:999:2:0',
}),
]);
await handleGroupAddRequest(bridge, received[0]!.flag, true, '');
expect(setAddRequest).toHaveBeenCalledWith(999, 778899, 2, true, '', false, undefined);
expect(fetchRequests).not.toHaveBeenCalled();
expect(fetchNumericRequests).not.toHaveBeenCalled();
},
);
it.each(['notice first', 'card first'])(
'emits only the card when paired with a self-invite notice: %s',
async (order) => {
const { bridge, received, fetchRequests } = setup();
const packets =
order === 'notice first'
? [selfInviteNotice(), card()]
: [card(), selfInviteNotice()];
for (const incoming of packets) {
await bridge.onPacket(incoming);
}
await bridge.onPacket(card());
expect(received).toHaveLength(1);
expect(fetchRequests).not.toHaveBeenCalled();
},
);
it('keeps distinct card sequences and accounts independent', async () => {
const first = setup();
const second = setup();
await first.bridge.onPacket(card());
await first.bridge.onPacket(card(778900));
await second.bridge.onPacket(card());
expect(first.received).toHaveLength(2);
expect(second.received).toHaveLength(1);
});
it('does not report sent cards or links in unrelated JSON cards as invitations', async () => {
const { bridge, received } = setup();
await bridge.onPacket(card(778899, 10001));
await bridge.onPacket(card(778899, 456, 'unrelated.app'));
expect(received).toEqual([]);
expect(bridge.apis.contacts.getGroupInviteCardSequence(999)).toBeUndefined();
});
it.each([
{ app: 'com.tencent.tuwen.lua', meta: { detail: { title: 'ordinary card' } } },
{ app: 'com.tencent.tuwen.lua', meta: { news: { jumpUrl: '' } } },
{ app: 'com.tencent.tuwen.lua', meta: { news: { jumpUrl: 'https://example.com' } } },
])('preserves ordinary cards as friend messages: %j', async (content) => {
const { bridge, received, fetchRequests } = setup();
const friendMessage = vi.fn();
bridge.events.on('friend_message', friendMessage);
await bridge.onPacket(jsonCard(content));
expect(friendMessage).toHaveBeenCalledOnce();
expect(received).toEqual([]);
expect(fetchRequests).not.toHaveBeenCalled();
});
it('queries requests only after an incoming request notification', async () => {
vi.useFakeTimers();
const { bridge, received, fetchRequests } = setup();
fetchRequests.mockImplementation(async (filtered) => (filtered ? [] : [request()]));
await vi.advanceTimersByTimeAsync(60_000);
expect(fetchRequests).not.toHaveBeenCalled();
bridge.registerCmd('test.request', () => [
{
kind: 'group_invite',
time: 1,
selfUin: 10001,
groupId: 999,
fromUin: 123,
fromUid: 'u_applicant',
subType: 'add',
message: '',
flag: 'add:999:u_applicant',
},
]);
await bridge.onPacket({ ...selfInviteNotice(), serviceCmd: 'test.request' });
expect(fetchRequests).toHaveBeenCalledTimes(2);
expect(received).toEqual([
expect.objectContaining({ message: 'please', flag: 'slreq:1:42:999:1:0' }),
]);
await vi.advanceTimersByTimeAsync(60_000);
expect(fetchRequests).toHaveBeenCalledTimes(2);
});
it('does not emit a fallback request or retry after an inbox failure', async () => {
vi.useFakeTimers();
const { bridge, received, fetchRequests } = setup();
fetchRequests.mockRejectedValue(new Error('request lookup failed'));
bridge.registerCmd('test.request', () => [
{
kind: 'group_invite',
time: 1,
selfUin: 10001,
groupId: 999,
fromUin: 123,
fromUid: 'u_applicant',
subType: 'add',
message: '',
flag: 'add:999:u_applicant',
},
]);
await bridge.onPacket({ ...selfInviteNotice(), serviceCmd: 'test.request' });
await vi.advanceTimersByTimeAsync(60_000);
expect(received).toEqual([]);
expect(fetchRequests).toHaveBeenCalledTimes(2);
});
it('matches only a pending request of the notified type', async () => {
const { bridge, received, fetchRequests } = setup();
fetchRequests.mockImplementation(async (filtered) =>
filtered
? [request({ sequence: 43, filtered: true })]
: [request({ state: 2 }), request({ eventType: 22 }), request({ groupId: 998 })],
);
bridge.registerCmd('test.request', () => [
{
kind: 'group_invite',
time: 1,
selfUin: 10001,
groupId: 999,
fromUin: 123,
fromUid: 'u_applicant',
subType: 'add',
message: '',
flag: 'add:999:u_applicant',
},
]);
await bridge.onPacket({ ...selfInviteNotice(), serviceCmd: 'test.request' });
expect(received).toEqual([expect.objectContaining({ flag: 'slreq:1:43:999:1:1' })]);
});
it.each(['u_invitee', undefined])(
'requires the notified invitee to match pending invitations: %s',
async (invitedUid) => {
const { bridge, received, fetchRequests } = setup();
fetchRequests.mockImplementation(async (filtered) =>
filtered
? []
: [
request({
sequence: 41,
invitorUid: 'u_inviter',
invitorUin: 456,
targetUid: 'u_other',
eventType: 22,
}),
request({
sequence: 42,
invitorUid: 'u_inviter',
invitorUin: 456,
targetUid: 'u_invitee',
targetUin: 789,
eventType: 22,
}),
],
);
bridge.registerCmd('test.request', () => [
{
kind: 'group_invite',
time: 1,
selfUin: 10001,
groupId: 999,
fromUin: 456,
fromUid: 'u_inviter',
invitedUid,
subType: 'invite',
message: '',
flag: 'invite:999:u_inviter',
},
]);
await bridge.onPacket({ ...selfInviteNotice(), serviceCmd: 'test.request' });
expect(received).toEqual(
invitedUid
? [expect.objectContaining({ invitedUin: 789, flag: 'slreq:1:42:999:22:0' })]
: [],
);
},
);
it('drains both inbox requests before releasing the account after a failure', async () => {
const { bridge, received, fetchRequests } = setup();
let finishFiltered!: (value: GroupRequestInfo[]) => void;
const filtered = new Promise<GroupRequestInfo[]>((resolve) => {
finishFiltered = resolve;
});
fetchRequests.mockImplementation((isFiltered) =>
isFiltered ? filtered : Promise.reject(new Error('main inbox failed')),
);
bridge.registerCmd('test.request', () => [
{
kind: 'group_invite',
time: 1,
selfUin: 10001,
groupId: 999,
fromUin: 123,
fromUid: 'u_applicant',
subType: 'add',
message: '',
flag: 'add:999:u_applicant',
},
]);
const processing = bridge.onPacket({ ...selfInviteNotice(), serviceCmd: 'test.request' });
await vi.waitFor(() => expect(fetchRequests).toHaveBeenCalledTimes(2));
const disposed = vi.fn();
const disposal = bridge.dispose().then(disposed);
await Promise.resolve();
expect(disposed).not.toHaveBeenCalled();
finishFiltered([]);
await Promise.all([processing, disposal]);
expect(disposed).toHaveBeenCalledOnce();
expect(received).toEqual([]);
});
});

View File

@@ -1,335 +0,0 @@
import { describe, expect, it, vi } from 'vitest';
import { BridgeEventBus } from '@snowluma/protocol/event-bus';
import type { GroupRequestInfo } from '@snowluma/protocol/qq-info';
import type { BridgeInterface } from '../../src/bridge/bridge-interface';
import { GroupRequestPoller } from '../src/group-request-poller';
function request(overrides: Partial<GroupRequestInfo> = {}): GroupRequestInfo {
return {
groupId: 999,
groupName: 'group',
targetUid: 'target_uid',
targetUin: 123,
targetName: 'requester',
invitorUid: 'inviter_uid',
invitorUin: 456,
invitorName: 'inviter',
operatorUid: '',
operatorUin: 0,
operatorName: '',
sequence: 42,
state: 1,
notifyType: 7,
eventType: 1,
comment: 'please',
filtered: false,
...overrides,
};
}
function setup(
fetchGroupRequests: (filtered: boolean, count: number) => Promise<GroupRequestInfo[]>,
getGroupInviteCardSequence?: (groupId: number) => number | undefined,
) {
const events = new BridgeEventBus({
onError: (_kind, error) => {
throw error;
},
});
const bridge = {
events,
apis: { contacts: { fetchGroupRequests, getGroupInviteCardSequence } },
} as unknown as BridgeInterface;
const poller = new GroupRequestPoller(bridge, 10_001, { intervalMs: 60_000 });
return { events, poller };
}
describe('GroupRequestPoller', () => {
it('emits a canonical invite request from a pending list-only notification once', async () => {
const fetchGroupRequests = vi.fn(async (filtered: boolean) =>
filtered
? []
: [
request({
notifyType: 1,
eventType: 2,
}),
],
);
const { events, poller } = setup(fetchGroupRequests);
const received: unknown[] = [];
events.on('group_invite', (event) => {
received.push(event);
});
await poller.pollOnce();
await poller.pollOnce();
expect(fetchGroupRequests).toHaveBeenCalledWith(false, 50);
expect(fetchGroupRequests).toHaveBeenCalledWith(true, 50);
expect(received).toEqual([
expect.objectContaining({
kind: 'group_invite',
selfUin: 10_001,
groupId: 999,
fromUin: 456,
fromUid: 'inviter_uid',
invitedUin: 123,
invitedUid: 'target_uid',
subType: 'invite',
message: 'please',
flag: 'slreq:1:42:999:2:0',
}),
]);
});
it('uses the applicant identity and filtered handle for join applications', async () => {
const fetchGroupRequests = vi.fn(async (filtered: boolean) =>
filtered ? [request({ filtered: true, sequence: 43 })] : [],
);
const { events, poller } = setup(fetchGroupRequests);
const received: unknown[] = [];
events.on('group_invite', (event) => {
received.push(event);
});
await poller.pollOnce();
expect(received).toEqual([
expect.objectContaining({
fromUin: 123,
fromUid: 'target_uid',
subType: 'add',
flag: 'slreq:1:43:999:1:1',
}),
]);
});
it('emits an actionable invite when the sender account is unavailable and continues the batch', async () => {
const fetchGroupRequests = vi.fn(async (filtered: boolean) =>
filtered
? []
: [
request({
notifyType: 1,
eventType: 2,
sequence: 41,
invitorUid: '',
invitorUin: 0,
}),
request({
groupId: 1_000,
notifyType: 1,
eventType: 2,
sequence: 42,
}),
],
);
const { events, poller } = setup(fetchGroupRequests);
const received: unknown[] = [];
events.on('group_invite', (event) => {
received.push(event);
});
await poller.pollOnce();
await poller.pollOnce();
expect(received).toEqual([
expect.objectContaining({
groupId: 999,
fromUin: 0,
fromUid: '',
subType: 'invite',
flag: 'slreq:1:41:999:2:0',
}),
expect.objectContaining({
groupId: 1_000,
fromUin: 456,
flag: 'slreq:1:42:1000:2:0',
}),
]);
});
it('does not merge separate requests whose sender identities are both unavailable', async () => {
const fetchGroupRequests = vi.fn(async (filtered: boolean) =>
filtered
? []
: [
request({
notifyType: 1,
eventType: 2,
sequence: 41,
invitorUid: '',
invitorUin: 0,
}),
request({
notifyType: 1,
eventType: 2,
sequence: 42,
invitorUid: '',
invitorUin: 0,
}),
],
);
const { events, poller } = setup(fetchGroupRequests);
const received: unknown[] = [];
events.on('group_invite', (event) => {
received.push(event);
});
await poller.pollOnce();
expect(received).toEqual([
expect.objectContaining({ flag: 'slreq:1:41:999:2:0' }),
expect.objectContaining({ flag: 'slreq:1:42:999:2:0' }),
]);
});
it('isolates a malformed list record without suppressing valid siblings', async () => {
const fetchGroupRequests = vi.fn(async (filtered: boolean) =>
filtered ? [] : [request({ sequence: 0 }), request({ groupId: 1_000, sequence: 43 })],
);
const { events, poller } = setup(fetchGroupRequests);
const received: unknown[] = [];
events.on('group_invite', (event) => {
received.push(event);
});
await poller.pollOnce();
expect(received).toEqual([
expect.objectContaining({
groupId: 1_000,
flag: 'slreq:1:43:1000:1:0',
}),
]);
});
it('preserves the private invite-card approval sequence when one is known', async () => {
const fetchGroupRequests = vi.fn(async (filtered: boolean) =>
filtered
? []
: [
request({
notifyType: 1,
eventType: 2,
sequence: 42,
}),
],
);
const { events, poller } = setup(fetchGroupRequests, () => 778_899);
const received: unknown[] = [];
events.on('group_invite', (event) => {
received.push(event);
});
await poller.pollOnce();
expect(received).toEqual([
expect.objectContaining({
flag: 'slreq:1:778899:999:2:0',
}),
]);
});
it('does not emit processed or non-request notification types', async () => {
const fetchGroupRequests = vi.fn(async (filtered: boolean) =>
filtered
? []
: [
request({ sequence: 1, state: 2 }),
request({ sequence: 2, notifyType: 9, eventType: 6 }),
],
);
const { events, poller } = setup(fetchGroupRequests);
const received = vi.fn();
events.on('group_invite', received);
await poller.pollOnce();
expect(received).not.toHaveBeenCalled();
});
it('fails the scan when either inbox cannot be read', async () => {
const fetchGroupRequests = vi.fn(async (filtered: boolean) => {
if (filtered) {
throw new Error('filtered inbox unavailable');
}
return [request()];
});
const { events, poller } = setup(fetchGroupRequests);
const received = vi.fn();
events.on('group_invite', received);
await expect(poller.pollOnce()).rejects.toThrow('filtered inbox unavailable');
expect(received).not.toHaveBeenCalled();
});
it('does not duplicate a request already delivered by the real-time path', async () => {
let releaseMain!: (value: GroupRequestInfo[]) => void;
const main = new Promise<GroupRequestInfo[]>((resolve) => {
releaseMain = resolve;
});
const fetchGroupRequests = vi.fn((filtered: boolean) =>
filtered ? Promise.resolve([]) : main,
);
const { events, poller } = setup(fetchGroupRequests);
const received: unknown[] = [];
events.on('group_invite', (event) => {
received.push(event);
});
poller.start();
await events.emit({
kind: 'group_invite',
time: 1,
selfUin: 10_001,
groupId: 999,
fromUin: 456,
fromUid: 'inviter_uid',
subType: 'invite',
message: 'please',
flag: 'invite:999:inviter_uid',
});
releaseMain([request({ notifyType: 1, eventType: 2 })]);
await poller.stop();
expect(received).toHaveLength(1);
});
it('shares concurrent scans instead of issuing overlapping requests', async () => {
let release!: (value: GroupRequestInfo[]) => void;
const pending = new Promise<GroupRequestInfo[]>((resolve) => {
release = resolve;
});
const fetchGroupRequests = vi.fn(() => pending);
const { poller } = setup(fetchGroupRequests);
const first = poller.pollOnce();
const second = poller.pollOnce();
expect(second).toBe(first);
expect(fetchGroupRequests).toHaveBeenCalledTimes(2);
release([]);
await first;
});
it('does not emit from an in-flight scheduled scan after shutdown starts', async () => {
let release!: (value: GroupRequestInfo[]) => void;
const pending = new Promise<GroupRequestInfo[]>((resolve) => {
release = resolve;
});
const fetchGroupRequests = vi.fn(() => pending);
const { events, poller } = setup(fetchGroupRequests);
const received = vi.fn();
events.on('group_invite', received);
poller.start();
const stopped = poller.stop();
release([request()]);
await stopped;
expect(received).not.toHaveBeenCalled();
});
});

View File

@@ -18,8 +18,6 @@ function fabricatedInstance(results: NetworkShutdownResult[]) {
heartbeatTimer: null,
eventPipeline: null,
eventPipelineDrain: Promise.resolve(),
groupRequestPoller: { stop: vi.fn(() => Promise.resolve()) },
groupRequestPollerDrain: Promise.resolve(),
disposePromise: null,
disposeRequested: false,
acceptingActions: true,

View File

@@ -62,7 +62,6 @@ describe('OneBotManager bot_status', () => {
dispose: vi.fn(async () => ({ closed: true, errors: [] })),
emitBotStatus,
waitUntilNetworkReady: vi.fn(() => networkReady),
startGroupRequestPolling: vi.fn(),
startLoginHistorySync: vi.fn(),
getConnectionStatuses: () => [],
} as unknown as OneBotInstance;
@@ -80,7 +79,6 @@ describe('OneBotManager bot_status', () => {
expect(emitBotStatus).toHaveBeenCalledOnce();
});
expect(emitBotStatus).toHaveBeenCalledWith('online');
expect(instance.startGroupRequestPolling).toHaveBeenCalledOnce();
} finally {
await manager.dispose();
}
@@ -110,7 +108,6 @@ describe('OneBotManager bot_status', () => {
quiesce: vi.fn(),
dispose,
emitBotStatus,
startGroupRequestPolling: vi.fn(),
getConnectionStatuses: () => [],
} as unknown as OneBotInstance;
const manager = new OneBotManager();
@@ -142,7 +139,6 @@ describe('OneBotManager bot_status', () => {
quiesce: vi.fn(),
dispose,
emitBotStatus,
startGroupRequestPolling: vi.fn(),
getConnectionStatuses: () => [],
} as unknown as OneBotInstance;
const manager = new OneBotManager();

View File

@@ -36,7 +36,6 @@ function fakeInstance(
quiesce,
dispose,
emitBotStatus: vi.fn(async () => undefined),
startGroupRequestPolling: vi.fn(),
getConnectionStatuses: () => statuses,
} as unknown as OneBotInstance;
}
@@ -270,7 +269,7 @@ describe('OneBotManager database preparation', () => {
expect(beginMigration).toHaveBeenCalledOnce();
expect(manager.getInstance('10001')).not.toBeNull();
await vi.waitFor(() => {
expect(instance.startGroupRequestPolling).toHaveBeenCalledOnce();
expect(instance.emitBotStatus).toHaveBeenCalledWith('online');
});
} finally {
await manager.dispose();
@@ -766,7 +765,6 @@ describe('OneBotManager lifecycle failure accounting', () => {
...fakeInstance('10001', async () => undefined),
waitUntilNetworkReady: vi.fn(async () => ({ applied: true, statuses: [], errors: [] })),
startLoginHistorySync: vi.fn(),
startGroupRequestPolling: vi.fn(),
} as unknown as OneBotInstance;
let created = false;
const manager = new OneBotManager({
@@ -827,7 +825,6 @@ describe('OneBotManager lifecycle failure accounting', () => {
...fakeInstance('10001', async () => undefined),
waitUntilNetworkReady: vi.fn(async () => ({ applied: true, statuses: [], errors: [] })),
startLoginHistorySync: vi.fn(),
startGroupRequestPolling: vi.fn(),
} as unknown as OneBotInstance;
const manager = new OneBotManager({
sessionReleaseDeadlineMs: 60_000,

View File

@@ -8,6 +8,10 @@ describe('hashMessageIdInt32', () => {
expect(id1).toBe(id2);
});
it('preserves negative hashes as valid message IDs', () => {
expect(hashMessageIdInt32(1, 12345, PRIVATE_MESSAGE_EVENT)).toBe(-585543322);
});
it('returns non-zero', () => {
// The function ensures id !== 0 by setting it to 1
const id = hashMessageIdInt32(0, 0, '');

View File

@@ -8,6 +8,13 @@ import {
afterEach(() => vi.useRealTimers());
describe('PTT transcription requests', () => {
it.each([Number(18446744073335783674n), 1.5, NaN, Infinity])(
'rejects an inexact numeric message id: %s',
(msgId) => {
expect(() => pttTransKey(10001, msgId)).toThrow(RangeError);
},
);
it('keeps accounts isolated for the same message id', async () => {
const first = requestPttTransText(pttTransKey(10001, 1), 20_000, async () => '');
const second = requestPttTransText(pttTransKey(10002, 1), 20_000, async () => '');
@@ -19,8 +26,9 @@ describe('PTT transcription requests', () => {
it.each(['text', ''])('accepts a pushed transcription: %j', async (text) => {
const result = requestPttTransText('account:push', 20_000, async () => '');
deliverPttTransText('account:push', text);
expect(deliverPttTransText('account:push', text)).toBe(true);
await expect(result).resolves.toBe(text);
expect(deliverPttTransText('account:push', text)).toBe(false);
});
it('registers before triggering so an immediate push is not lost', async () => {

View File

@@ -175,7 +175,7 @@ function makeInstanceHarness(
acceptingActions: true,
uin: String(SELF_ID),
statusCommandCooldown: new Map([['p:20002', Date.now()]]),
pendingSelfSentEchoes: new Map(),
recentSelfSentEvents: new Map(),
});
const dispatch = (
instance as unknown as {
@@ -203,7 +203,153 @@ function privateSentEvent(overrides: JsonObject = {}): JsonObject {
};
}
function groupSentEvent(overrides: JsonObject = {}): JsonObject {
return {
...privateSentEvent(),
message_type: 'group',
sub_type: 'normal',
message_id: -7654321,
message_seq: RECEIPT.sequence,
group_id: 30003,
target_id: undefined,
...overrides,
};
}
describe('OneBot self-sent events', () => {
it('reports a client private send once across repeated confirmations and pushes', async () => {
const { dispatch, emitEvent, stored } = makeInstanceHarness();
const event = privateSentEvent({ message_id: -7654321 });
await Promise.all([dispatch(event, 'bridge'), dispatch({ ...event }, 'bridge')]);
await dispatch({ ...event, raw_message: 'canonical content' }, 'bridge');
expect(emitEvent).toHaveBeenCalledExactlyOnceWith(event);
expect(stored.get(-7654321)?.raw_message).toBe('canonical content');
});
it('keeps private action deduplication for more than one echo', async () => {
const { dispatch, emitEvent } = makeInstanceHarness();
const event = privateSentEvent();
await dispatch(event, 'send');
await dispatch({ ...event }, 'bridge');
await dispatch({ ...event }, 'bridge');
expect(emitEvent).toHaveBeenCalledOnce();
});
it('distinguishes private sends by identity and peer even when text is identical', async () => {
const { dispatch, emitEvent } = makeInstanceHarness();
const event = privateSentEvent();
await dispatch(event, 'bridge');
await dispatch({ ...event, message_seq: RECEIPT.clientSequence + 1 }, 'bridge');
await dispatch({ ...event, target_id: PEER_ID + 1 }, 'bridge');
await dispatch({ ...event, message_id: -7654321 }, 'bridge');
expect(emitEvent).toHaveBeenCalledTimes(4);
});
it('keeps private deduplication isolated and expires it without deleting history', async () => {
vi.useFakeTimers();
try {
const first = makeInstanceHarness();
const second = makeInstanceHarness();
const event = privateSentEvent();
await first.dispatch(event, 'bridge');
await second.dispatch(
{ ...event, self_id: SELF_ID + 1, user_id: SELF_ID + 1 },
'bridge',
);
expect(second.emitEvent).toHaveBeenCalledOnce();
await first.dispatch(event, 'bridge');
expect(first.emitEvent).toHaveBeenCalledOnce();
vi.advanceTimersByTime(120_000);
await first.dispatch(event, 'bridge');
expect(first.emitEvent).toHaveBeenCalledTimes(2);
expect(first.stored.has(987654)).toBe(true);
} finally {
vi.useRealTimers();
}
});
it('reports a client group send once across repeated server pushes', async () => {
const { dispatch, emitEvent, stored } = makeInstanceHarness();
const event = groupSentEvent();
await dispatch(event, 'bridge');
await dispatch({ ...event, raw_message: 'canonical echo' }, 'bridge');
await dispatch({ ...event, raw_message: 'latest canonical echo' }, 'bridge');
expect(emitEvent).toHaveBeenCalledOnce();
expect(emitEvent).toHaveBeenCalledWith(event);
expect(stored.get(-7654321)?.raw_message).toBe('latest canonical echo');
});
it('reports concurrent copies of a client group send only once', async () => {
const { dispatch, emitEvent } = makeInstanceHarness();
const event = groupSentEvent();
await Promise.all([
dispatch({ ...event }, 'bridge'),
dispatch({ ...event }, 'bridge'),
dispatch({ ...event }, 'bridge'),
]);
expect(emitEvent).toHaveBeenCalledOnce();
});
it('keeps group sends with identical text but different message identities', async () => {
const { dispatch, emitEvent } = makeInstanceHarness();
const event = groupSentEvent();
await dispatch(event, 'bridge');
await dispatch({ ...event, message_seq: RECEIPT.sequence + 1 }, 'bridge');
await dispatch({ ...event, group_id: 30004 }, 'bridge');
await dispatch({ ...event, message_id: -7654322 }, 'bridge');
expect(emitEvent).toHaveBeenCalledTimes(4);
});
it('keeps group deduplication isolated between account instances', async () => {
const first = makeInstanceHarness();
const second = makeInstanceHarness();
await first.dispatch(groupSentEvent(), 'bridge');
await second.dispatch(
groupSentEvent({ self_id: SELF_ID + 1, user_id: SELF_ID + 1 }),
'bridge',
);
expect(first.emitEvent).toHaveBeenCalledOnce();
expect(second.emitEvent).toHaveBeenCalledOnce();
});
it('expires group self-send identities without treating stored history as already reported', async () => {
vi.useFakeTimers();
try {
const { dispatch, emitEvent } = makeInstanceHarness();
const event = groupSentEvent();
await dispatch(event, 'bridge');
await dispatch({ ...event }, 'bridge');
expect(emitEvent).toHaveBeenCalledOnce();
vi.advanceTimersByTime(120_000);
await dispatch({ ...event }, 'bridge');
expect(emitEvent).toHaveBeenCalledTimes(2);
} finally {
vi.useRealTimers();
}
});
it('keeps the timestamp bound when a group sequence and hash are reused', async () => {
const { dispatch, emitEvent } = makeInstanceHarness();
const event = groupSentEvent();
await dispatch(event, 'bridge');
await dispatch({ ...event, time: RECEIPT.timestamp + 121 }, 'bridge');
expect(emitEvent).toHaveBeenCalledTimes(2);
});
it('does not publish an event suppressed by the persistence recall check', async () => {
const { dispatch, emitEvent } = makeInstanceHarness();
// The event's cache operation is the final authority after asynchronous

View File

@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/proto-defs",
"version": "2.0.2",
"version": "2.1.0",
"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).",

View File

@@ -79,12 +79,20 @@ export interface SendMessageResponse {
result?: pb<1, int_32>;
errMsg?: pb<2, string>;
timestamp1?: pb<3, uint_32>;
reviewResult?: pb<6, int_32>;
serverResult?: pb<7, SendMessageServerResult>;
field10?: pb<10, uint_32>;
groupSequence?: pb<11, uint_32>;
timestamp2?: pb<12, uint_32>;
privateSequence?: pb<14, uint_32>;
}
export interface SendMessageServerResult {
type?: pb<1, int_32>;
code?: pb<2, int_32>;
message?: pb<3, string>;
}
// MentionExtra (for building @mention text element)
export interface MentionExtraSend {
type?: pb<3, int_32>;

View File

@@ -1,4 +1,4 @@
import type { pb, pb_repeated, uint_32, bool } from '@snowluma/proton';
import type { pb, pb_repeated, uint_32, int_32, bool } from '@snowluma/proton';
import type { PushMsgBody } from './message';
// trpc.msg.register_proxy.RegisterProxy.SsoGetC2cMsg — fetch private (c2c)
@@ -15,6 +15,8 @@ export interface SsoGetC2cMsg {
}
export interface SsoGetC2cMsgResponse {
result?: pb<1, int_32>;
errorMessage?: pb<2, string>;
friendUid?: pb<4, string>;
messages?: pb_repeated<7, PushMsgBody>;
}

View File

@@ -12,10 +12,8 @@ import type { pb, uint_32, uint_64 } from '@snowluma/proton';
* fields (uuid / md5) and the response `text` tag should be confirmed with a
* single live capture before relying on them.
*
* Flow: send Trans{C2C,Group}PttReq → response carries the text inline when
* transcription is already done; when it's empty the server transcribes
* asynchronously (no dedicated push command exists — see NotifyTransUpdate),
* so the caller re-sends with backoff until the text arrives or it times out.
* Flow: the response can carry completed text inline. Otherwise, the caller
* waits for an asynchronous result correlated with the original message ID.
*/
/** Source ptt-element field (NT internal tag) noted in the comment after each. */
@@ -73,7 +71,7 @@ export interface GroupPttTransResult {
/**
* Outer response. `type` echoes the scene; result is at field 2 (group) /
* field 3 (c2c). An empty `text` with `errCode == 0` means "transcribing,
* retry later".
* await the result push".
*/
export interface PttTransResp {
type?: pb<1, uint_32>;

View File

@@ -155,6 +155,8 @@ function makePipeline(identity: IdentityService): IncomingPacketPipeline {
events,
fetchGroupList: async () => {},
fetchGroupMemberList: async () => {},
resolveGroupJoinRequest: async () => null,
rememberGroupInviteCardSequence: () => true,
});
pipeline.registerCmd(MSG_PUSH_CMD, parseMsgPush);
return pipeline;

View File

@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/protocol",
"version": "2.0.2",
"version": "2.1.0",
"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>'`.",

View File

@@ -419,7 +419,7 @@ export interface GroupInviteEvent extends QQEvent {
* logged-in account. */
invitedUin?: number;
invitedUid?: string;
subType: string;
subType: 'add' | 'invite';
message: string;
flag: string;
}
@@ -495,7 +495,7 @@ export interface GroupMsgEmojiLikeEvent extends QQEvent {
*/
export interface PttTransResultEvent extends QQEvent {
kind: 'ptt_trans_result';
msgId: number;
msgId: bigint;
text: string;
}

View File

@@ -336,11 +336,14 @@ function tcpConnect(host: string, port: number, timeoutMs = 10000): Promise<net.
async function connectHighway(
servers: HighwayServer[],
): Promise<{ socket: net.Socket; server: HighwayServer }> {
startIndex = 0,
): Promise<{ socket: net.Socket; server: HighwayServer; serverIndex: number }> {
const deadline = Date.now() + HIGHWAY_CONNECT_BUDGET_MS;
const errors: Error[] = [];
for (const server of servers) {
for (let i = 0; i < servers.length; i++) {
const serverIndex = (startIndex + i) % servers.length;
const server = servers[serverIndex]!;
const remaining = deadline - Date.now();
if (remaining <= 0) {
@@ -353,7 +356,7 @@ async function connectHighway(
server.port,
Math.min(HIGHWAY_CONNECT_TIMEOUT_MS, remaining),
);
return { socket, server };
return { socket, server, serverIndex };
} catch (cause) {
const error = new Error(`${server.host}:${server.port}: ${highwayErrorText(cause)}`, {
cause,
@@ -698,6 +701,7 @@ async function uploadHighwayHttpOperation(
let socket: net.Socket | null = null;
let connectCount = 0;
let server = session.servers[0]!;
let serverIndex = 0;
const dropSocket = (): void => {
if (socket) {
@@ -771,13 +775,10 @@ async function uploadHighwayHttpOperation(
try {
if (!socket) {
// Select only before the first connection succeeds. Zero acknowledged
// bytes does not mean no data was sent to an already connected node.
if (connectCount === 0) {
({ socket, server } = await connectHighway(session.servers));
} else {
socket = await tcpConnect(server.host, server.port);
}
({ socket, server, serverIndex } = await connectHighway(
session.servers,
serverIndex,
));
connectCount += 1;
trace.connectCount = connectCount;
@@ -824,17 +825,23 @@ async function uploadHighwayHttpOperation(
trace.failureReason = 'transport_exhausted';
const exhausted = new Error(
`highway upload transport failed after ${transportAttempts} attempts ` +
`(cmdId=${commandId} chunk=${chunkSize}/${totalSize} offset=${offset}): ${String(err)}`,
`(cmdId=${commandId} chunk=${chunkSize}/${totalSize} offset=${offset}` +
` acknowledgedBytes=${offset}; current chunk unconfirmed): ${String(err)}`,
{ cause: err },
);
trace.error = exhausted;
throw exhausted;
}
// Keep the current session and chunk intact when changing nodes.
// Missing acknowledgement does not prove the previous node received nothing.
serverIndex = (serverIndex + 1) % session.servers.length;
log.trace(
'highway_put_branch branch=chunk_retry offset=%d bytes=%d attempt=%d error=%j',
'highway_put_branch branch=chunk_retry offset=%d bytes=%d attempt=%d nextServer=%j error=%j',
offset,
chunkSize,
transportAttempts,
session.servers[serverIndex],
highwayErrorText(err),
);
await sleepMs(HIGHWAY_RETRY_BASE_MS * transportAttempts);

View File

@@ -0,0 +1,195 @@
import { CLIENT_MESSAGE_RECEIPT_CMD, type PacketInfo } from '@snowluma/common/protocol-types';
import type { PacketSender } from '@snowluma/common/packet-sender';
import { isRealUin } from '@snowluma/common/uin';
import { createLogger } from '@snowluma/common/logger';
import type { SendMessageResponse } from '@snowluma/proto-defs/action';
import type { SsoGetC2cMsg, SsoGetC2cMsgResponse } from '@snowluma/proto-defs/get-c2c-msg';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { FriendMessage } from '../events';
import type { IdentityService } from '../identity-service';
import { classifyMessageSurvival } from './blank-filter';
import { buildContextFromMessage } from './context';
import { decodeFriendMessage } from './decoders/friend-message';
import { PkgType } from './enums';
import { SSO_GET_C2C_MSG_CMD } from './fetch-c2c-history';
import { requirePacketResponse } from './packet-response';
const log = createLogger('MsgPush.ClientMessage');
const historyRetryDelays = [100, 250, 500, 1000, 2000] as const;
export interface ClientMessageReceipt {
readonly peerUid: string;
readonly clientSequence: number;
readonly sequence: number;
readonly timestamp: number;
}
export function decodeClientMessageReceipt(pkt: PacketInfo, selfUin: string): ClientMessageReceipt {
if (
pkt.source !== 'client-message' ||
pkt.serviceCmd !== CLIENT_MESSAGE_RECEIPT_CMD ||
!isRealUin(selfUin) ||
pkt.uin !== selfUin
) {
throw new Error('Client message receipt has an invalid source or account');
}
if (pkt.retCode !== 0) {
throw new Error(`Client message receipt is unavailable (status=${pkt.retCode})`);
}
const body = Buffer.from(pkt.body);
if (body.length < 12 || body.length > 8 + 128 + 65536) {
throw new Error('Client message receipt has an invalid length');
}
const peerLength = body[1]!;
const ackOffset = 8 + peerLength;
if (
body[0] !== 1 ||
body.readUInt16LE(2) !== 0 ||
peerLength < 3 ||
peerLength > 128 ||
ackOffset >= body.length ||
body.length - ackOffset > 65536
) {
throw new Error('Client message receipt has an invalid envelope');
}
const peerUid = body.subarray(8, ackOffset).toString('utf8');
const clientSequence = body.readUInt32LE(4);
if (!/^u_[A-Za-z0-9_-]+$/.test(peerUid) || clientSequence === 0) {
throw new Error('Client message receipt has an invalid message identity');
}
const ack = protobuf_decode<SendMessageResponse>(body.subarray(ackOffset));
if (
(ack.result ?? 0) !== 0 ||
(ack.reviewResult ?? 0) !== 0 ||
(ack.serverResult?.code ?? 0) !== 0
) {
throw new Error('Client message was not accepted');
}
const sequence = ack.privateSequence;
const timestamp = ack.timestamp1;
if (!sequence || !timestamp || (ack.groupSequence ?? 0) !== 0) {
throw new Error('Client message receipt has no valid private message confirmation');
}
return { peerUid, clientSequence, sequence, timestamp };
}
export async function fetchClientMessage(
sender: PacketSender,
identity: IdentityService,
receipt: ClientMessageReceipt,
): Promise<FriendMessage> {
const request = protobuf_encode<SsoGetC2cMsg>({
friendUid: receipt.peerUid,
startSequence: receipt.sequence,
endSequence: receipt.sequence,
});
let response: SsoGetC2cMsgResponse;
for (let attempt = 0; ; attempt++) {
const result = await sender.sendPacket(SSO_GET_C2C_MSG_CMD, Buffer.from(request), 5000);
response = protobuf_decode<SsoGetC2cMsgResponse>(
requirePacketResponse(result, 'Client message lookup'),
);
if (response.friendUid && response.friendUid !== receipt.peerUid) {
throw new Error('Client message lookup returned another conversation');
}
// A successful send can precede visibility in message storage. Only
// its explicit not-yet-stored result permits retrying this exact ID.
if (
response.result === 100000301 &&
response.friendUid === receipt.peerUid &&
!response.messages?.length
) {
const delay = historyRetryDelays[attempt];
if (delay === undefined) {
throw new Error(
`Client message history is still unavailable after ${attempt + 1} attempts (code=${response.result})`,
);
}
log.debug(
'Confirmed client message is not yet in history: attempt=%d nextDelayMs=%d',
attempt + 1,
delay,
);
await new Promise<void>((resolve) => setTimeout(resolve, delay));
continue;
}
if ((response.result ?? 0) !== 0) {
throw new Error(`Client message lookup failed (code=${response.result})`);
}
break;
}
if (response.messages?.length !== 1) {
throw new Error(
`Client message lookup expected one message, received ${response.messages?.length ?? 0}`,
);
}
const message = response.messages[0]!;
const head = message.contentHead;
const route = message.responseHead;
const selfUin = Number(identity.uin);
if (
!head ||
!route ||
route.fromUin !== selfUin ||
route.toUid !== receipt.peerUid ||
!route.toUin ||
route.grp != null ||
head.ntMsgSeq !== receipt.sequence ||
head.sequence !== receipt.clientSequence ||
head.timestamp !== receipt.timestamp
) {
throw new Error('Client message lookup did not match the confirmed message');
}
if (
![
PkgType.PrivateMessage,
PkgType.PrivateRecordMessage,
PkgType.PrivateFileMessage,
PkgType.ForwardFakePrivateMessage,
].includes(head.msgType ?? 0)
) {
throw new Error('Client message lookup returned an unsupported message type');
}
const context = buildContextFromMessage(message, selfUin, identity);
if (!context) {
throw new Error('Client message lookup has no message context');
}
const events = decodeFriendMessage(context);
const event = events[0];
if (
events.length !== 1 ||
event?.kind !== 'friend_message' ||
classifyMessageSurvival(context.head, event.elements, context.body) !== 'keep'
) {
throw new Error('Client message lookup has no supported message content');
}
return event;
}

View File

@@ -205,7 +205,7 @@ function decodePttTransResult(ctx: MsgPushContext): QQEventVariant[] {
return [];
}
const msgId = Number(item.msgId ?? 0n);
const msgId = item.msgId ?? 0n;
const text = item.text ?? '';
if (!msgId || !text) {

View File

@@ -3,36 +3,53 @@ import type { FriendMessage } from '../../events';
import type { MsgPushDecoder } from '../registry';
import { decodeRichBody } from '../rich-body-decoder';
/**
* A private "qun.invite" ark card (someone DMs the bot a group-invite card)
* carries the only sequence the server accepts when the bot later approves the
* invite via 0x10c8 — the `msgseq` embedded in its `mqqapi://group/invite_join`
* jumpUrl, applied with eventType=2 / filtered=false. The MSF invite push
* (PkgType 87) never carries it. Parse it out so `set_group_add_request` can
* use it. See issue #125.
*/
/** Read the approval tuple from a QQ group-invitation card. */
function parseGroupInviteCard(jsonText: string): { groupUin: number; sequence: number } | null {
if (!jsonText.includes('group/invite_join')) {
const card: unknown = JSON.parse(jsonText);
if (
!card ||
typeof card !== 'object' ||
!('app' in card) ||
(card.app !== 'com.tencent.qun.invite' && card.app !== 'com.tencent.tuwen.lua')
) {
return null;
}
const m = jsonText.match(/mqqapi:\/\/group\/invite_join[^"\\\s]*/);
if (!m) {
if (
!('meta' in card) ||
!card.meta ||
typeof card.meta !== 'object' ||
!('news' in card.meta) ||
!card.meta.news ||
typeof card.meta.news !== 'object' ||
!('jumpUrl' in card.meta.news) ||
typeof card.meta.news.jumpUrl !== 'string'
) {
return null;
}
const query = m[0].split('?')[1] ?? '';
const params = new URLSearchParams(query);
const groupUin = Number(params.get('groupcode') ?? 0);
const sequence = Number(params.get('msgseq') ?? 0);
const url = URL.parse(card.meta.news.jumpUrl);
if (!Number.isSafeInteger(groupUin) || !Number.isSafeInteger(sequence)) {
if (
!url ||
url.protocol !== 'mqqapi:' ||
url.hostname !== 'group' ||
url.pathname !== '/invite_join'
) {
return null;
}
if (groupUin <= 0 || sequence <= 0) {
return null;
const groupUin = Number(url.searchParams.get('groupcode'));
const sequence = Number(url.searchParams.get('msgseq'));
if (
!Number.isSafeInteger(groupUin) ||
groupUin <= 0 ||
!Number.isSafeInteger(sequence) ||
sequence <= 0
) {
throw new Error('group invitation card has an invalid approval tuple');
}
return { groupUin, sequence };

View File

@@ -21,7 +21,7 @@ export const decodeGroupJoinRequest: MsgPushDecoder = (ctx) => {
fromUid: join.targetUid ?? '',
subType: 'add',
message: '',
flag: 'add:' + (join.groupUin ?? 0) + ':' + (join.targetUid ?? ''),
flag: '',
};
return [ev];
};
@@ -29,7 +29,7 @@ export const decodeGroupJoinRequest: MsgPushDecoder = (ctx) => {
export const decodeGroupInvitation: MsgPushDecoder = (ctx) => {
const invitation = protobuf_decode<GroupInvitation>(ctx.content);
if (!invitation?.info?.inner) {
if (invitation?.cmd !== 87 || !invitation.info?.inner) {
return [];
}
@@ -45,7 +45,7 @@ export const decodeGroupInvitation: MsgPushDecoder = (ctx) => {
invitedUid: inner.targetUid ?? '',
subType: 'invite',
message: '',
flag: 'invite:' + (inner.groupUin ?? 0) + ':' + (inner.invitorUid ?? ''),
flag: '',
};
return [ev];
};
@@ -67,7 +67,7 @@ export const decodeGroupInvite: MsgPushDecoder = (ctx) => {
invitedUin: ctx.selfUin,
subType: 'invite',
message: '',
flag: 'invite:' + (invite.groupUin ?? 0) + ':' + (invite.invitorUid ?? ''),
flag: '',
};
return [ev];
};

View File

@@ -26,6 +26,7 @@ import { deriveSysMsgDedupIdentity, SysMsgDedup } from './sysmsg-dedup';
export { deriveSysMsgDedupIdentity, SysMsgDedup } from './sysmsg-dedup';
export type { SysMsgDedupIdentity } from './sysmsg-dedup';
export { decodeClientMessageReceipt, fetchClientMessage } from './client-message-receipt';
export { SSO_GET_GROUP_MSG_CMD, fetchGroupMessageRange } from './fetch-group-history';
export {

View File

@@ -35,6 +35,7 @@ import {
MAX_RICH_CARD_OUTPUT_BYTES,
ntImageUrlFromFileId,
} from './helpers';
import { readXmlMsgAttributes } from './xml-card';
type ElemDecoded = Elem;
type RichTextDecoded = RichText;
@@ -135,14 +136,16 @@ function decodeRichMsgCard(
return invalidCard(data.length, 'invalid_xml', decoded.budgetBytes);
}
if (svcId === 35) {
const match = /\bm_resid="([^"]+)"/.exec(content);
const rootAttributes = svcId === 0 || svcId === 35 ? readXmlMsgAttributes(content) : undefined;
if (svcId === 35 || (svcId === 0 && rootAttributes?.get('serviceID') === '35')) {
const resId = rootAttributes?.get('m_resid');
// XML forwards link bundled inner messages by m_fileName, just as
// LightApp forwards use uniseq. Keep it for the outer payload lookup.
const fileName = /\bm_fileName="([^"]+)"/.exec(content)?.[1];
const fileName = rootAttributes?.get('m_fileName') || undefined;
return {
element: match
? { type: 'forward', resId: match[1], forwardUuid: fileName }
element: resId
? { type: 'forward', resId, forwardUuid: fileName }
: { type: 'xml', text: content, subType: svcId },
error: null,
inputBytes: data.length,

View File

@@ -0,0 +1,121 @@
const NAME_START =
':A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D' +
'\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF' +
'\\uF900-\\uFDCF\\uFDF0-\\uFFFD\\u{10000}-\\u{EFFFF}';
const ATTRIBUTE = new RegExp(
`([${NAME_START}][\\u0300-\\u036F${NAME_START}\\-.0-9\\u00B7\\u203F-\\u2040]*)` +
`[\\t\\r\\n ]*=[\\t\\r\\n ]*(?:"([^"<]*)"|'([^'<]*)')`,
'uy',
);
const SPACE = /[\t\r\n ]*/y;
const ENTITIES = new Map([
['amp', '&'],
['lt', '<'],
['gt', '>'],
['quot', '"'],
['apos', "'"],
]);
function decodeAttribute(value: string): string | undefined {
let valid = true;
// Literal whitespace is normalized before expanding character references.
const decoded = value
.replace(/\r\n|[\t\r\n]/g, ' ')
.replace(
/&(#x[0-9a-fA-F]+|#[0-9]+|amp|lt|gt|quot|apos);|&/g,
(_match, entity: string | undefined) => {
const named = entity === undefined ? undefined : ENTITIES.get(entity);
if (named !== undefined) {
return named;
}
if (entity?.startsWith('#')) {
const code = entity.startsWith('#x')
? Number.parseInt(entity.slice(2), 16)
: Number.parseInt(entity.slice(1), 10);
if (
code === 9 ||
code === 10 ||
code === 13 ||
(code >= 0x20 && code <= 0xd7ff) ||
(code >= 0xe000 && code <= 0xfffd) ||
(code >= 0x10000 && code <= 0x10ffff)
) {
return String.fromCodePoint(code);
}
}
valid = false;
return '';
},
);
return valid ? decoded : undefined;
}
/** Read the first element's attributes without searching comments, values or descendants. */
export function readXmlMsgAttributes(content: string): ReadonlyMap<string, string> | undefined {
let cursor = content.startsWith('\uFEFF') ? 1 : 0;
for (;;) {
SPACE.lastIndex = cursor;
SPACE.exec(content);
cursor = SPACE.lastIndex;
const closing = content.startsWith('<!--', cursor)
? '-->'
: content.startsWith('<?', cursor)
? '?>'
: undefined;
if (!closing) {
break;
}
const end = content.indexOf(closing, cursor + (closing === '-->' ? 4 : 2));
if (end < 0) {
return undefined;
}
cursor = end + closing.length;
}
if (!content.startsWith('<msg', cursor)) {
return undefined;
}
cursor += 4;
const attributes = new Map<string, string>();
for (;;) {
const beforeSpace = cursor;
SPACE.lastIndex = cursor;
SPACE.exec(content);
cursor = SPACE.lastIndex;
if (content[cursor] === '>' || content.startsWith('/>', cursor)) {
return attributes;
}
if (cursor === beforeSpace) {
return undefined;
}
ATTRIBUTE.lastIndex = cursor;
const match = ATTRIBUTE.exec(content);
if (!match || attributes.has(match[1]!)) {
return undefined;
}
const value = decodeAttribute(match[2] ?? match[3]!);
if (value === undefined) {
return undefined;
}
attributes.set(match[1]!, value);
cursor = ATTRIBUTE.lastIndex;
}
}

View File

@@ -45,29 +45,15 @@ export interface PacketPipelineDeps {
/** One group's member-list fetch (adapter TTL applies). Roster
* side-effect only; the pipeline does not pass `force`. */
fetchGroupMemberList(groupId: number): Promise<void>;
/**
* Resolve the verify message ("postscript") + server sequence number
* for a pending group-join / group-invite. The OIDB push only
* carries the requester's UID + group uin — the actual verify text
* the user typed ("你们好" etc.) lives on the pending-request queue
* fetched via OIDB 0x10C0. NapCat surfaces this as
* `notify.postscript` from `nodeIKernelGroupService.getGroupNotifies`;
* we mirror that with an `fetchGroupRequests` lookup matched on
* `(groupId, uid, subType)`. Returns null when no matching pending
* request exists (e.g. it was already handled by another client).
*/
/** Resolve a pending request's comment and approval tuple after a push. */
resolveGroupJoinRequest(
groupId: number,
uid: string,
subType: 'add' | 'invite',
invitedUid?: string,
): Promise<GroupRequestInfo | null>;
/** Resolve a private invite-card msgseq. Implementations may briefly wait
* for the paired C2C Ark card, as the PkgType 87 push omits this value. */
resolveGroupInviteCardSequence?(groupId: number): Promise<number | null>;
/** Live-only write of a parsed private invite-card msgseq onto the
* pending-application store. Optional: tests that do not care about
* cards may omit it; production Bridge always binds ContactsApi. */
rememberGroupInviteCardSequence?(groupUin: number, sequence: number): void;
/** Remember a live card; false means its approval sequence was already seen. */
rememberGroupInviteCardSequence(groupUin: number, sequence: number): boolean;
}
export class IncomingPacketPipeline {
@@ -99,8 +85,18 @@ export class IncomingPacketPipeline {
}
process(pkt: PacketInfo): Promise<void> {
return this.processWithHandlers(pkt, this.cmdHandlers_.get(pkt.serviceCmd));
}
processEvents(pkt: PacketInfo, events: readonly QQEventVariant[]): Promise<void> {
return this.processWithHandlers(pkt, [() => [...events]]);
}
private processWithHandlers(
pkt: PacketInfo,
handlers: readonly CmdParser[] | undefined,
): Promise<void> {
const startedAt = Date.now();
const handlers = this.cmdHandlers_.get(pkt.serviceCmd);
if (!handlers) {
this.packetLog.trace(() => [
@@ -178,7 +174,7 @@ export class IncomingPacketPipeline {
);
});
enrichmentTasks.push(task);
} else if (this.needsGroupInviteEnrich(event)) {
} else if (event.kind === 'group_invite') {
this.traceEnrichmentStarted(pkt, event, 'group_invite');
const task = this.dispatchGroupInvite(pkt, event)
.then((count) => {
@@ -363,12 +359,50 @@ export class IncomingPacketPipeline {
this.finishDispatch(event);
this.traceDispatch(pkt, event.kind, mode);
if (!this.emitGroupCardChange(event, cardBefore)) {
return 1;
let dispatched = 1;
if (this.emitGroupCardChange(event, cardBefore)) {
this.traceDispatch(pkt, 'group_card_change', 'derived');
dispatched++;
}
this.traceDispatch(pkt, 'group_card_change', 'derived');
return 2;
if (this.emitGroupInviteCard(event)) {
this.traceDispatch(pkt, 'group_invite', 'derived');
dispatched++;
}
return dispatched;
}
private emitGroupInviteCard(event: QQEventVariant): boolean {
if (event.kind !== 'friend_message' || event.senderUin === event.selfUin) {
return false;
}
const groupId = event.inviteCardGroupUin;
const sequence = event.inviteCardSequence;
if (
!groupId ||
!sequence ||
!this.deps.rememberGroupInviteCardSequence(groupId, sequence)
) {
return false;
}
this.finishDispatch({
kind: 'group_invite',
time: event.time,
selfUin: event.selfUin,
groupId,
fromUin: event.senderUin,
fromUid: event.senderUid,
invitedUin: event.selfUin,
subType: 'invite',
message: '',
flag: formatGroupRequestFlag({ groupId, sequence, eventType: 2, filtered: false }),
});
return true;
}
private emit(event: QQEventVariant): void {
@@ -435,29 +469,6 @@ export class IncomingPacketPipeline {
);
}
/** Every group_invite that carries a requester UID gets async
* enrichment before dispatch. Two INDEPENDENT things are filled in:
*
* 1. The verify COMMENT — the text the requester typed ("你们好" etc.).
* It is NEVER in the push; it lives on the OIDB pending-request
* queue, so we ALWAYS fetch it (mirrors Lagrange's unconditional
* `FetchGroupRequests`; NapCat reads the equivalent
* `notify.postscript`). See issue #98.
* 2. The requester's UIN + nickname — only when not already resolved
* (the push carries a bare UID). Mirrors Lagrange's
* `dev/Lagrange.Core/.../MessagingLogic.cs:215-224`.
*
* These USED to be coupled — the comment fetch piggy-backed on the
* uin-resolve condition, so a requester whose uin was already cached
* silently lost their comment (bug #98). They're now decoupled inside
* `dispatchGroupInvite`; this guard just routes every uid-bearing
* group_invite onto the async path. */
private needsGroupInviteEnrich(
event: QQEventVariant,
): event is Extract<QQEventVariant, { kind: 'group_invite' }> {
return event.kind === 'group_invite' && !!event.fromUid;
}
private async dispatchAfterIdentityRefresh(
pkt: PacketInfo,
event: Extract<QQEventVariant, { kind: 'group_member_join' }>,
@@ -491,158 +502,61 @@ export class IncomingPacketPipeline {
pkt: PacketInfo,
event: Extract<QQEventVariant, { kind: 'group_invite' }>,
): Promise<number> {
const uid = event.fromUid;
if (uid) {
// Record the requester's identity up-front (synchronously), mirroring the
// friend_request path — uid-bearing group_invites take this async branch
// and would otherwise never store the inviter's uid↔uin when the uin is
// already known (needsProfile=false).
this.deps.identity.rememberRequestIdentity({
groupId: event.groupId,
uid,
uin: event.fromUin > 0 ? event.fromUin : 0,
source: 'group_request',
});
const subType = event.subType === 'invite' ? 'invite' : 'add';
// ALWAYS fetch the verify comment (it's never in the push). UID→UIN
// waits only when the requester is still unresolved. Comment and
// identity are independent; `Promise.allSettled` so a flake on one
// path cannot kill the other.
const needsProfile = event.fromUin <= 0;
const [profileR, requestR] = await Promise.allSettled([
needsProfile
? this.deps.identity.resolveUin(uid, event.groupId)
: Promise.resolve(null),
this.deps.resolveGroupJoinRequest(event.groupId, uid, subType),
]);
if (needsProfile) {
if (
profileR.status === 'fulfilled' &&
profileR.value !== null &&
profileR.value > 0
) {
event.fromUin = profileR.value;
this.deps.identity.rememberRequestIdentity({
groupId: event.groupId,
uid,
uin: event.fromUin,
source: 'group_request',
});
} else if (profileR.status === 'rejected') {
this.packetLog.trace(() => [
'packet_branch serviceCmd=%j seqId=%d branch=enrichment_degraded eventKind=%j enrichment="stranger_profile" error=%j',
pkt.serviceCmd,
pkt.seqId,
event.kind,
profileR.reason instanceof Error
? profileR.reason.message
: String(profileR.reason),
]);
this.log.warn(
'failed to resolve stranger profile: uid=%s err=%s',
uid,
profileR.reason instanceof Error
? profileR.reason.message
: String(profileR.reason),
);
}
}
if (requestR.status === 'fulfilled' && requestR.value) {
// The verify text the requester typed; NapCat surfaces it as
// `notify.postscript`. Without this the OneBot `comment` field is
// empty — bug #98.
event.message = requestR.value.comment;
const request = requestR.value;
if (subType === 'invite' && request.targetUid) {
if (!event.invitedUid) {
event.invitedUid = request.targetUid;
}
if ((event.invitedUin ?? 0) <= 0 && request.targetUin > 0) {
event.invitedUin = request.targetUin;
}
}
const hasApprovalTuple =
Number.isSafeInteger(request.sequence) &&
request.sequence > 0 &&
Number.isSafeInteger(request.groupId) &&
request.groupId > 0 &&
Number.isSafeInteger(request.eventType) &&
request.eventType > 0;
if (hasApprovalTuple) {
if (subType === 'invite' && request.eventType === 2) {
// A bot self-invite must use the private Ark card's msgseq (#125),
// not the sequence returned by 0x10C0. Keep the legacy flag when
// correlation times out so the action can retry the cache later.
const cardSequence =
(await this.deps.resolveGroupInviteCardSequence?.(event.groupId)) ??
null;
if (cardSequence) {
event.flag = formatGroupRequestFlag({
groupId: event.groupId,
sequence: cardSequence,
eventType: 2,
filtered: false,
});
} else {
this.log.warn(
'invite-card msgseq unavailable before dispatch: groupId=%d uid=%s',
event.groupId,
uid,
);
}
} else {
event.flag = formatGroupRequestFlag(request);
}
}
} else if (requestR.status === 'rejected') {
this.packetLog.trace(() => [
'packet_branch serviceCmd=%j seqId=%d branch=enrichment_degraded eventKind=%j enrichment="group_join_request" error=%j',
pkt.serviceCmd,
pkt.seqId,
event.kind,
requestR.reason instanceof Error
? requestR.reason.message
: String(requestR.reason),
]);
this.log.warn(
'failed to resolve group join request: groupId=%d uid=%s err=%s',
event.groupId,
uid,
requestR.reason instanceof Error
? requestR.reason.message
: String(requestR.reason),
);
}
// Self-invite notices omit the approval msgseq; the private card owns this event.
if (
event.subType === 'invite' &&
this.isSelfMemberIdentity(event.invitedUin ?? 0, event.invitedUid)
) {
return 0;
}
if ((event.invitedUin ?? 0) <= 0 && event.invitedUid) {
try {
const invited = await this.deps.identity.resolveUin(
event.invitedUid,
event.groupId,
);
const uid = event.fromUid;
if (invited !== null && invited > 0) {
event.invitedUin = invited;
}
} catch (error) {
this.log.warn(
'failed to resolve invited account: groupId=%d uid=%s err=%s',
event.groupId,
event.invitedUid,
error instanceof Error ? error.message : String(error),
);
}
if (!uid) {
throw new Error('group request omitted requester UID');
}
this.deps.identity.rememberRequestIdentity({
groupId: event.groupId,
uid,
uin: event.fromUin,
source: 'group_request',
});
const request = await this.deps.resolveGroupJoinRequest(
event.groupId,
uid,
event.subType,
event.invitedUid,
);
if (!request) {
this.log.warn('pending group request not found: group=%d uid=%s', event.groupId, uid);
return 0;
}
if (request.eventType === 2) {
return 0;
}
event.message = request.comment;
event.flag = formatGroupRequestFlag(request);
const requesterUin = event.subType === 'invite' ? request.invitorUin : request.targetUin;
event.fromUin =
event.fromUin ||
requesterUin ||
(await this.deps.identity.resolveUin(uid, event.groupId)) ||
0;
if (event.fromUin === 0) {
this.log.warn('group request sender unavailable: group=%d uid=%s', event.groupId, uid);
}
if (event.subType === 'invite') {
event.invitedUid = request.targetUid;
event.invitedUin =
request.targetUin ||
(await this.deps.identity.resolveUin(request.targetUid, event.groupId)) ||
0;
}
try {
@@ -778,13 +692,6 @@ export class IncomingPacketPipeline {
source: 'friend_message',
});
if (event.inviteCardGroupUin && event.inviteCardSequence) {
this.deps.rememberGroupInviteCardSequence?.(
event.inviteCardGroupUin,
event.inviteCardSequence,
);
}
break;
case 'group_message': {
@@ -875,29 +782,18 @@ export class IncomingPacketPipeline {
}
case 'group_invite': {
// Defensive: never cache a uid→uin mapping where uin equals
// the group's own uin — that's the pollution signature the
// legacy decoder fallback produced. Pass 0 so `rememberUidUin`
// skips the map write (it short-circuits on uin <= 0) but the
// user row still gets upserted with the uid + group context.
const uinForCache =
event.fromUin > 0 && event.fromUin !== event.groupId ? event.fromUin : 0;
this.deps.identity.rememberRequestIdentity({
groupId: event.groupId,
uid: event.fromUid,
uin: uinForCache,
uin: event.fromUin,
source: 'group_request',
});
if (event.invitedUid) {
const invitedUin =
event.invitedUin && event.invitedUin !== event.groupId
? event.invitedUin
: 0;
this.deps.identity.rememberRequestIdentity({
groupId: event.groupId,
uid: event.invitedUid,
uin: invitedUin,
uin: event.invitedUin ?? 0,
source: 'group_request',
});
}

View File

@@ -0,0 +1,345 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { CLIENT_MESSAGE_RECEIPT_CMD, type PacketInfo } from '@snowluma/common/protocol-types';
import type { PacketSender, SendPacketResult } from '@snowluma/common/packet-sender';
import type { SendMessageResponse } from '@snowluma/proto-defs/action';
import type { SsoGetC2cMsg, SsoGetC2cMsgResponse } from '@snowluma/proto-defs/get-c2c-msg';
import type { PushMsgBody } from '@snowluma/proto-defs/message';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import { IdentityService } from '../../src/identity-service';
import {
decodeClientMessageReceipt,
fetchClientMessage,
} from '../../src/msg-push/client-message-receipt';
import { SSO_GET_C2C_MSG_CMD } from '../../src/msg-push/fetch-c2c-history';
const self = '10001';
const peer = 'u_test_peer';
const time = 1_700_000_000;
const identities: IdentityService[] = [];
afterEach(async () => {
vi.useRealTimers();
await Promise.all(identities.splice(0).map((identity) => identity.close()));
});
function packet(ack: SendMessageResponse = { privateSequence: 87, timestamp1: time }): PacketInfo {
const uid = Buffer.from(peer);
const header = Buffer.alloc(8);
header[0] = 1;
header[1] = uid.length;
header.writeUInt32LE(9, 4);
return {
pid: 1234,
uin: self,
seqId: 42,
retCode: 0,
fromClient: false,
source: 'client-message',
serviceCmd: CLIENT_MESSAGE_RECEIPT_CMD,
body: Buffer.concat([header, uid, protobuf_encode<SendMessageResponse>(ack)]),
};
}
function message(): PushMsgBody {
return {
responseHead: { fromUin: Number(self), fromUid: 'u_test_self', toUin: 20002, toUid: peer },
contentHead: { msgType: 166, sequence: 9, ntMsgSeq: 87, timestamp: time, msgId: 123456 },
body: { richText: { elems: [{ text: { str: 'hello' } }, { face: { index: 1 } }] } },
};
}
function lookupResponse(response: SsoGetC2cMsgResponse): SendPacketResult {
return {
success: true,
gotResponse: true,
errorCode: 0,
errorMessage: '',
responseData: Buffer.from(protobuf_encode<SsoGetC2cMsgResponse>(response)),
};
}
function setup(messages = [message()], friendUid = peer) {
const identity = IdentityService.memory(self);
identities.push(identity);
const sendPacket = vi.fn<PacketSender['sendPacket']>(async () => ({
success: true,
gotResponse: true,
errorCode: 0,
errorMessage: '',
responseData: Buffer.from(protobuf_encode<SsoGetC2cMsgResponse>({ friendUid, messages })),
}));
const receipt = decodeClientMessageReceipt(packet(), self);
return {
sendPacket,
identity,
receipt,
run: () => fetchClientMessage({ sendPacket }, identity, receipt),
};
}
describe('client message receipts', () => {
it('decodes a confirmation and retrieves exactly its conversation and sequence', async () => {
const ctx = setup();
expect(ctx.receipt).toEqual({
peerUid: peer,
clientSequence: 9,
sequence: 87,
timestamp: time,
});
const event = await ctx.run();
expect(ctx.sendPacket).toHaveBeenCalledOnce();
const [cmd, body] = ctx.sendPacket.mock.calls[0]!;
expect(cmd).toBe(SSO_GET_C2C_MSG_CMD);
expect(protobuf_decode<SsoGetC2cMsg>(body)).toMatchObject({
friendUid: peer,
startSequence: 87,
endSequence: 87,
});
expect(event).toMatchObject({
kind: 'friend_message',
selfUin: 10001,
senderUin: 10001,
peerUin: 20002,
clientSeq: 9,
ntMsgSeq: 87,
sequenceAuthoritative: true,
time,
elements: [
{ type: 'text', text: 'hello' },
{ type: 'face', faceId: 1 },
],
});
});
it.each([
{ source: undefined },
{ serviceCmd: 'MessageSvc.PbSendMsg' },
{ uin: '20002' },
{ retCode: -1 },
] satisfies Partial<PacketInfo>[])('rejects invalid provenance or status: %j', (patch) => {
expect(() => decodeClientMessageReceipt({ ...packet(), ...patch }, self)).toThrow();
});
it.each([
{ result: 1 },
{ reviewResult: 1 },
{ serverResult: { code: -1 } },
{ privateSequence: 0 },
{ timestamp1: 0 },
{ groupSequence: 5 },
] satisfies SendMessageResponse[])(
'rejects an unsuccessful or incomplete confirmation: %j',
(patch) => {
expect(() =>
decodeClientMessageReceipt(
packet({ privateSequence: 87, timestamp1: time, ...patch }),
self,
),
).toThrow();
},
);
it.each([
[
'version',
(body: Buffer) => {
body[0] = 2;
},
],
[
'reserved',
(body: Buffer) => {
body[2] = 1;
},
],
[
'uid length',
(body: Buffer) => {
body[1] = 129;
},
],
[
'uid',
(body: Buffer) => {
body[8] = 0xff;
},
],
[
'client sequence',
(body: Buffer) => {
body.writeUInt32LE(0, 4);
},
],
] as const)('rejects a malformed %s', (_name, mutate) => {
const pkt = packet();
const body = Buffer.from(pkt.body);
mutate(body);
expect(() => decodeClientMessageReceipt({ ...pkt, body }, self)).toThrow();
});
it('rejects truncated and excessive bodies', () => {
for (const body of [
new Uint8Array(),
packet().body.subarray(0, 8 + peer.length),
new Uint8Array(8 + 128 + 65537),
]) {
expect(() => decodeClientMessageReceipt({ ...packet(), body }, self)).toThrow();
}
});
it.each([
[
'sender',
(msg: PushMsgBody) => {
msg.responseHead!.fromUin = 20002;
},
],
[
'recipient',
(msg: PushMsgBody) => {
msg.responseHead!.toUid = 'u_other';
},
],
[
'missing recipient',
(msg: PushMsgBody) => {
delete msg.responseHead!.toUin;
},
],
[
'client sequence',
(msg: PushMsgBody) => {
msg.contentHead!.sequence = 10;
},
],
[
'server sequence',
(msg: PushMsgBody) => {
msg.contentHead!.ntMsgSeq = 88;
},
],
[
'timestamp',
(msg: PushMsgBody) => {
msg.contentHead!.timestamp = time + 1;
},
],
[
'group',
(msg: PushMsgBody) => {
msg.responseHead!.grp = { groupCode: 30003 };
},
],
[
'type',
(msg: PushMsgBody) => {
msg.contentHead!.msgType = 82;
},
],
[
'empty content',
(msg: PushMsgBody) => {
msg.body = {};
},
],
[
'unknown content',
(msg: PushMsgBody) => {
msg.body = { richText: { elems: [{ commonElem: { serviceType: 999 } }] } };
},
],
[
'control',
(msg: PushMsgBody) => {
msg.contentHead!.c2cCmd = 1;
},
],
] as const)('rejects an incorrect %s in the lookup', async (_name, mutate) => {
const msg = message();
mutate(msg);
await expect(setup([msg]).run()).rejects.toThrow();
});
it('rejects missing, ambiguous and cross-conversation results', async () => {
await expect(setup([]).run()).rejects.toThrow('expected one');
await expect(setup([message(), message()]).run()).rejects.toThrow('expected one');
await expect(setup([message()], 'u_other').run()).rejects.toThrow('conversation');
});
it('retries only the confirmed message while storage catches up', async () => {
const ctx = setup();
vi.useFakeTimers();
ctx.sendPacket.mockResolvedValueOnce(
lookupResponse({ result: 100000301, friendUid: peer, messages: [] }),
);
const work = ctx.run();
await vi.advanceTimersByTimeAsync(99);
expect(ctx.sendPacket).toHaveBeenCalledTimes(1);
await vi.advanceTimersByTimeAsync(1);
expect(await work).toMatchObject({ ntMsgSeq: 87, clientSeq: 9 });
expect(ctx.sendPacket).toHaveBeenCalledTimes(2);
expect(ctx.sendPacket.mock.calls[1]).toEqual(ctx.sendPacket.mock.calls[0]);
});
it('reports a bounded failure when storage never contains the confirmed message', async () => {
const ctx = setup();
vi.useFakeTimers();
ctx.sendPacket.mockResolvedValue(
lookupResponse({ result: 100000301, friendUid: peer, messages: [] }),
);
const rejected = expect(ctx.run()).rejects.toThrow('still unavailable after 6 attempts');
await vi.runAllTimersAsync();
await rejected;
expect(ctx.sendPacket).toHaveBeenCalledTimes(6);
});
it.each([
{ result: 100000302, friendUid: peer, messages: [] },
{ result: 100000301, friendUid: 'u_other', messages: [] },
{ result: 100000301, messages: [] },
{ result: 100000301, friendUid: peer, messages: [message()] },
] satisfies SsoGetC2cMsgResponse[])(
'does not retry unrelated or inconsistent errors: %j',
async (response) => {
const ctx = setup();
ctx.sendPacket.mockResolvedValue(lookupResponse(response));
await expect(ctx.run()).rejects.toThrow();
expect(ctx.sendPacket).toHaveBeenCalledOnce();
},
);
it('preserves distinct identities for equal text', async () => {
const first = setup();
const msg = message();
msg.contentHead = { ...msg.contentHead, sequence: 10, ntMsgSeq: 88 };
const second = setup([msg]);
const event = await fetchClientMessage(second, second.identity, {
...second.receipt,
clientSequence: 10,
sequence: 88,
});
expect((await first.run()).ntMsgSeq).toBe(87);
expect(event.ntMsgSeq).toBe(88);
expect(event.elements).toEqual((await first.run()).elements);
});
it.each([
{ success: false, gotResponse: false, responseData: null },
{ success: true, gotResponse: false, responseData: null },
{ success: true, gotResponse: true, responseData: Buffer.alloc(0) },
] satisfies Partial<SendPacketResult>[])(
'surfaces unsuccessful lookup transport: %j',
async (result) => {
const ctx = setup();
ctx.sendPacket.mockResolvedValue({
success: true,
gotResponse: true,
errorCode: 0,
errorMessage: '',
responseData: null,
...result,
});
await expect(ctx.run()).rejects.toThrow('Client message lookup');
},
);
});

View File

@@ -38,7 +38,9 @@ function okResult(data: Uint8Array): SendPacketResult {
function inviteCardMessage(sequence: number): PushMsgBody {
const json = JSON.stringify({
app: 'com.tencent.qun.invite',
jumpUrl: `mqqapi://group/invite_join?groupcode=12345&msgseq=${sequence}`,
meta: {
news: { jumpUrl: `mqqapi://group/invite_join?groupcode=12345&msgseq=${sequence}` },
},
});
const compressed = deflateSync(Buffer.from(json));
const data = new Uint8Array(compressed.length + 1);

View File

@@ -38,6 +38,21 @@ function ctx(
}
describe('group invitation push carries the invitee (#394)', () => {
it('ignores unrelated notification commands', () => {
const content = protobuf_encode<GroupInvitation>({
cmd: 86,
info: {
inner: {
groupUin: GROUP_ID,
targetUid: 'u_invitee',
invitorUid: 'u_inviter',
},
},
});
expect(decodeGroupInvitation(ctx(content))).toEqual([]);
});
it('keeps the inviter as from* and the invitee as invited*', () => {
const identity = IdentityService.memory(String(SELF_UIN));
identity.rememberRequestIdentity({ uid: 'u_inviter', uin: 456, source: 'group_request' });

View File

@@ -61,6 +61,99 @@ function lengthDelimited(fieldNumber: number, payload: Uint8Array): Uint8Array {
]);
}
function xmlCardBody(xml: string, serviceId = 0): MessageBody {
return {
richText: {
elems: [
{
richMsg: {
serviceId,
template1: Buffer.concat([Buffer.from([0]), Buffer.from(xml, 'utf8')]),
},
},
],
},
};
}
describe('decodeRichBody / XML forward attributes', () => {
it('round-trips escaped resource IDs through the real sender and receiver', async () => {
const resId = 'res&<>"\'&lt;\t\n\r中文😀end';
const elems = await buildSendElems([{ type: 'forward', resId }]);
const body = protobuf_decode<MessageBody>(
protobuf_encode<MessageBody>({ richText: { elems } }),
);
expect(decodeRichBody(body, true)).toEqual([
{ type: 'forward', resId, forwardUuid: expect.any(String) },
]);
});
it.each([0, 35])(
'reads quoted root attributes and decodes entities once (service=%s)',
(serviceId) => {
const xml =
'\uFEFF <?xml version="1.0"?> <!-- header --> <?card data?>' +
'<msg brief="a > b" serviceID = \'&#51;&#x35;\' ' +
'm_resid = "res&amp;&lt;&gt;&quot;&apos;&amp;lt;" ' +
"m_fileName = 'key&#9;&#xA;&#13;&#x1F642;' />";
expect(decodeRichBody(xmlCardBody(xml, serviceId), true)).toEqual([
{
type: 'forward',
resId: 'res&<>"\'&lt;',
forwardUuid: 'key\t\n\r🙂',
},
]);
},
);
it.each([
'<msg><title>serviceID="35" m_resid="fake"</title></msg>',
'<msg><!-- serviceID="35" m_resid="fake" --></msg>',
'<msg><child serviceID="35" m_resid="fake" /></msg>',
'<wrapper><msg serviceID="35" m_resid="fake" /></wrapper>',
'<!-- <msg serviceID="35" m_resid="fake" /> --><msg />',
'<?test <msg serviceID="35" m_resid="fake" /> ?><msg />',
'<msg><![CDATA[<msg serviceID="35" m_resid="fake" />]]></msg>',
'<msg brief=\'serviceID="35" m_resid="fake"\' />',
'<msg data-serviceID="35" m_resid="fake" />',
'<msg serviceID="35" data-m_resid="fake" />',
'<msg serviceID="35"><child m_resid="fake" /></msg>',
'<msg serviceID="35" m_resid="first" m_resid="second" />',
'<msg serviceID="35"m_resid="fake" />',
])(
'preserves XML when forward attributes are not an unambiguous root declaration: %s',
(xml) => {
expect(decodeRichBody(xmlCardBody(xml), true)).toEqual([
{ type: 'xml', text: xml, subType: 0 },
]);
},
);
it.each([0, 35])('does not borrow a child resource ID (service=%s)', (serviceId) => {
const xml = '<msg serviceID="35"><msg m_resid="child" m_fileName="child-key" /></msg>';
expect(decodeRichBody(xmlCardBody(xml, serviceId), true)).toEqual([
{ type: 'xml', text: xml, subType: serviceId },
]);
});
it('preserves an explicit non-forward protocol type', () => {
const xml = '<msg serviceID="35" m_resid="other-card" />';
expect(decodeRichBody(xmlCardBody(xml, 2), true)).toEqual([
{ type: 'xml', text: xml, subType: 2 },
]);
});
it.each(['&unknown;', '&#0;', '&#xD800;', '&#x110000;', '&amp'])(
'preserves XML rather than inventing a lookup key for invalid entity %s',
(entity) => {
const xml = `<msg serviceID="35" m_resid="res${entity}" />`;
expect(decodeRichBody(xmlCardBody(xml, 35), true)).toEqual([
{ type: 'xml', text: xml, subType: 35 },
]);
},
);
});
describe('decodeRichBody / forward LightApp', () => {
it('emits {type:"forward", resId, forwardUuid} for com.tencent.multimsg', () => {
const body: MessageBody = {

View File

@@ -154,6 +154,7 @@ function makePipeline(
fetchGroupList,
fetchGroupMemberList,
resolveGroupJoinRequest: vi.fn(async () => null),
rememberGroupInviteCardSequence: vi.fn(() => true),
});
return { identity, pipeline, captured, fetchGroupList, fetchGroupMemberList };
}

View File

@@ -1,19 +1,14 @@
// Pre-dispatch stranger resolve regression — when a group join
// request comes in, the push only carries the requester's UID. The
// pipeline must do an async UID-form FetchUserProfile lookup BEFORE
// emitting the event so the OneBot layer's `user_id` field is
// populated and the consumer bot's `get_stranger_info` lookup works.
//
// Cross-checked against Lagrange's flow:
// dev/Lagrange.Core/.../MessagingLogic.cs:215-224
// (FetchUserInfoEvent by uid → resolved uin → posted event)
import { describe, expect, it, vi } from 'vitest';
import { IncomingPacketPipeline } from '@snowluma/protocol/packet-pipeline';
import { BridgeEventBus } from '@snowluma/protocol/event-bus';
import { IdentityService } from '@snowluma/protocol/identity-service';
import type { QQEventVariant } from '@snowluma/protocol/events';
import type { GroupMemberInfo, QQGroupInfo, UserProfileInfo } from '@snowluma/protocol/qq-info';
import type { GroupInviteEvent, QQEventVariant } from '@snowluma/protocol/events';
import type {
GroupMemberInfo,
GroupRequestInfo,
QQGroupInfo,
UserProfileInfo,
} from '@snowluma/protocol/qq-info';
import type { PacketInfo } from '@snowluma/common/protocol-types';
function makeProfile(uin: number, uid = '', nickname = ''): UserProfileInfo {
@@ -38,7 +33,6 @@ function makePipeline(
opts: {
fetchProfileByUid?: vi.Mock;
resolveGroupJoinRequest?: vi.Mock;
resolveGroupInviteCardSequence?: vi.Mock;
} = {},
) {
const identity = IdentityService.memory('10001');
@@ -48,16 +42,14 @@ function makePipeline(
fetchProfile: async () => makeProfile(0),
fetchProfileByUid,
});
const resolveGroupJoinRequest = opts.resolveGroupJoinRequest ?? vi.fn(async () => null);
const resolveGroupInviteCardSequence =
opts.resolveGroupInviteCardSequence ?? vi.fn(async () => null);
const resolveGroupJoinRequest = opts.resolveGroupJoinRequest ?? vi.fn(async () => request());
const pipeline = new IncomingPacketPipeline({
identity,
events,
fetchGroupList: vi.fn(async () => {}),
fetchGroupMemberList: vi.fn(async () => {}),
resolveGroupJoinRequest,
resolveGroupInviteCardSequence,
rememberGroupInviteCardSequence: vi.fn(() => true),
});
const captured: QQEventVariant[] = [];
@@ -72,456 +64,184 @@ function makePipeline(
captured,
fetchProfileByUid,
resolveGroupJoinRequest,
resolveGroupInviteCardSequence,
};
}
describe('IncomingPacketPipeline / stranger resolve on group_invite', () => {
it('calls fetchProfileByUid when group_invite has fromUin=0 + fromUid', async () => {
const fetchProfileByUid = vi.fn(async (_uid: string) =>
makeProfile(950929451, 'u_stranger_abc', '小明'),
);
function request(overrides: Partial<GroupRequestInfo> = {}): GroupRequestInfo {
return {
groupId: 12345,
groupName: 'group',
targetUid: 'u_requester',
targetUin: 0,
targetName: '',
invitorUid: '',
invitorUin: 0,
invitorName: '',
operatorUid: '',
operatorUin: 0,
operatorName: '',
sequence: 42,
state: 1,
notifyType: 7,
eventType: 1,
comment: 'please',
filtered: false,
...overrides,
};
}
function requestEvent(overrides: Partial<GroupInviteEvent> = {}): GroupInviteEvent {
return {
kind: 'group_invite',
time: 1,
selfUin: 10001,
groupId: 12345,
fromUin: 0,
fromUid: 'u_requester',
subType: 'add',
message: '',
flag: 'add:12345:u_requester',
...overrides,
};
}
async function receive(pipeline: IncomingPacketPipeline, event: GroupInviteEvent): Promise<void> {
pipeline.registerCmd('test.cmd', () => [event]);
await pipeline.process({ serviceCmd: 'test.cmd' } as PacketInfo);
}
describe('IncomingPacketPipeline / group requests', () => {
it('resolves an unknown requester before dispatch', async () => {
const fetchProfileByUid = vi.fn(async () => makeProfile(222, 'u_requester', 'Alice'));
const { pipeline, captured } = makePipeline({ fetchProfileByUid });
// Plant a parser that emits the user's exact bug-report shape:
// groupId set, fromUid is a string UID, fromUin=0 (decoder fix).
pipeline.registerCmd('test.cmd', () => [
{
kind: 'group_invite',
time: 1700000000,
selfUin: 10001,
groupId: 123456789,
fromUin: 0,
fromUid: 'u_stranger_abc',
subType: 'add',
message: '',
flag: 'add:123456789:u_stranger_abc',
} as QQEventVariant,
await receive(pipeline, requestEvent());
expect(fetchProfileByUid).toHaveBeenCalledWith('u_requester');
expect(captured).toEqual([
expect.objectContaining({
fromUin: 222,
message: 'please',
flag: 'slreq:1:42:12345:1:0',
}),
]);
pipeline.process({ serviceCmd: 'test.cmd' } as PacketInfo);
// Let the async hook flush.
await new Promise((r) => setTimeout(r, 10));
expect(fetchProfileByUid).toHaveBeenCalledWith('u_stranger_abc');
expect(captured).toHaveLength(1);
const event = captured[0] as Extract<QQEventVariant, { kind: 'group_invite' }>;
expect(event.fromUin).toBe(950929451); // ← patched in by the async resolve
expect(event.fromUid).toBe('u_stranger_abc');
expect(event.groupId).toBe(123456789);
});
it('still emits the event when fetchProfileByUid returns no uin (fail open)', async () => {
const fetchProfileByUid = vi.fn(async () => makeProfile(0));
const { pipeline, captured } = makePipeline({ fetchProfileByUid });
pipeline.registerCmd('test.cmd', () => [
{
kind: 'group_invite',
time: 1,
selfUin: 10001,
groupId: 12345,
it('keeps an actionable request when its sender cannot be identified', async () => {
const { pipeline, captured } = makePipeline();
await receive(pipeline, requestEvent());
expect(captured).toEqual([
expect.objectContaining({
fromUin: 0,
fromUid: 'u_no_such_user',
subType: 'add',
message: '',
flag: 'add:12345:u_no_such_user',
} as QQEventVariant,
flag: 'slreq:1:42:12345:1:0',
}),
]);
pipeline.process({ serviceCmd: 'test.cmd' } as PacketInfo);
await new Promise((r) => setTimeout(r, 10));
expect(fetchProfileByUid).toHaveBeenCalledOnce();
expect(captured).toHaveLength(1);
const event = captured[0] as Extract<QQEventVariant, { kind: 'group_invite' }>;
// fromUin stays 0 — but the event still goes out so the bot can
// see the join request and at least respond using the uid in the
// flag.
expect(event.fromUin).toBe(0);
expect(event.fromUid).toBe('u_no_such_user');
});
it('still emits the event when fetchProfileByUid throws', async () => {
const fetchProfileByUid = vi.fn(async () => {
throw new Error('network down');
});
const { pipeline, captured } = makePipeline({ fetchProfileByUid });
pipeline.registerCmd('test.cmd', () => [
{
kind: 'group_invite',
time: 1,
selfUin: 10001,
groupId: 12345,
fromUin: 0,
fromUid: 'u_x',
subType: 'add',
message: '',
flag: 'add:12345:u_x',
} as QQEventVariant,
]);
pipeline.process({ serviceCmd: 'test.cmd' } as PacketInfo);
await new Promise((r) => setTimeout(r, 10));
expect(captured).toHaveLength(1);
expect(captured[0]).toMatchObject({ fromUin: 0, fromUid: 'u_x' });
});
it('still fetches + applies the comment when fromUin is already cached (issue #98)', async () => {
// THE bug: the comment fetch used to piggy-back on the uin-resolve
// gate, so a requester whose uin was already in cache (group member
// roster, prior @-mention, re-application…) silently lost their
// verify text — the OneBot `comment` came out empty. The comment
// and the uin resolve are now decoupled: the comment is fetched
// unconditionally; only the (wasteful) profile lookup is skipped on
// a cache hit.
const fetchProfileByUid = vi.fn(async () => makeProfile(0));
const resolveGroupJoinRequest = vi.fn(async () => ({ comment: '求通过', sequence: 42 }));
const { pipeline, captured } = makePipeline({ fetchProfileByUid, resolveGroupJoinRequest });
pipeline.registerCmd('test.cmd', () => [
{
kind: 'group_invite',
time: 1,
selfUin: 10001,
groupId: 12345,
fromUin: 99999,
fromUid: 'u_known',
subType: 'add',
message: '',
flag: 'add:12345:u_known',
} as QQEventVariant,
]);
pipeline.process({ serviceCmd: 'test.cmd' } as PacketInfo);
await new Promise((r) => setTimeout(r, 10));
// Profile lookup is skipped — the uin is already known, no wasted call…
expect(fetchProfileByUid).not.toHaveBeenCalled();
// …but the comment IS still fetched from the pending-request queue
// and applied to the emitted event.
expect(resolveGroupJoinRequest).toHaveBeenCalledWith(12345, 'u_known', 'add');
expect(captured).toHaveLength(1);
const ev = captured[0] as Extract<QQEventVariant, { kind: 'group_invite' }>;
expect(ev.fromUin).toBe(99999);
expect(ev.message).toBe('求通过');
});
it('populates event.message from the pending-request queue (NapCat parity)', async () => {
// User-reported bug: SnowLuma's group_invite event surfaces a
// bare uid + uin but the requester's verify text ("你们好") never
// lands in the OneBot `comment` field. NapCat shows the text via
// `notify.postscript` from `getGroupNotifies`; we mirror that by
// doing an `OIDB 0x10C0 fetchGroupRequests` lookup in the async
// pre-dispatch hook and patching `event.message` from the matching
// row's `comment`.
const fetchProfileByUid = vi.fn(async () =>
makeProfile(1957003260, 'u_UVLHYYqba27WPUzTrdZlCA', 'KitaIkuyo'),
);
const resolveGroupJoinRequest = vi.fn(async () => ({
comment: '你们好',
sequence: 1779543612823906,
}));
const { pipeline, captured } = makePipeline({
fetchProfileByUid,
resolveGroupJoinRequest,
});
pipeline.registerCmd('test.cmd', () => [
{
kind: 'group_invite',
time: 1,
selfUin: 10001,
groupId: 950929451,
fromUin: 0,
fromUid: 'u_UVLHYYqba27WPUzTrdZlCA',
subType: 'add',
message: '',
flag: 'add:950929451:u_UVLHYYqba27WPUzTrdZlCA',
} as QQEventVariant,
]);
pipeline.process({ serviceCmd: 'test.cmd' } as PacketInfo);
await new Promise((r) => setTimeout(r, 10));
it('fetches the comment even when the requester identity is already known', async () => {
const { pipeline, captured, resolveGroupJoinRequest, fetchProfileByUid } = makePipeline();
await receive(pipeline, requestEvent({ fromUin: 222 }));
expect(resolveGroupJoinRequest).toHaveBeenCalledWith(
950929451,
'u_UVLHYYqba27WPUzTrdZlCA',
12345,
'u_requester',
'add',
undefined,
);
expect(captured).toHaveLength(1);
const ev = captured[0] as Extract<QQEventVariant, { kind: 'group_invite' }>;
expect(ev.message).toBe('你们好');
expect(ev.fromUin).toBe(1957003260);
expect(fetchProfileByUid).not.toHaveBeenCalled();
expect(captured).toEqual([expect.objectContaining({ fromUin: 222, message: 'please' })]);
});
it('replaces the legacy identity flag with a canonical approval tuple', async () => {
const resolveGroupJoinRequest = vi.fn(async () => ({
groupId: 950929451,
groupName: 'group',
targetUid: 'u_target',
targetUin: 1957003260,
targetName: 'target',
invitorUid: 'u_inviter',
invitorUin: 0,
invitorName: '',
operatorUid: '',
operatorUin: 0,
operatorName: '',
sequence: 1779543612823906,
state: 1,
eventType: 1,
comment: '你们好',
filtered: true,
}));
const { pipeline, captured } = makePipeline({ resolveGroupJoinRequest });
pipeline.registerCmd('test.cmd', () => [
{
kind: 'group_invite',
time: 1,
selfUin: 10001,
groupId: 950929451,
fromUin: 1957003260,
fromUid: 'u_target',
subType: 'add',
message: '',
flag: 'add:950929451:u_target',
} as QQEventVariant,
]);
pipeline.process({ serviceCmd: 'test.cmd' } as PacketInfo);
await new Promise((r) => setTimeout(r, 10));
expect(captured).toHaveLength(1);
expect(captured[0]).toMatchObject({
message: '你们好',
flag: 'slreq:1:1779543612823906:950929451:1:1',
});
});
it('uses the private invite-card msgseq for a self-invite approval tuple', async () => {
const resolveGroupJoinRequest = vi.fn(async () => ({
groupId: 999,
groupName: 'group',
targetUid: 'self',
targetUin: 10001,
targetName: 'self',
invitorUid: 'u_inviter',
invitorUin: 456,
invitorName: 'inviter',
operatorUid: '',
operatorUin: 0,
operatorName: '',
sequence: 111,
state: 1,
eventType: 2,
comment: '',
filtered: false,
}));
const resolveGroupInviteCardSequence = vi.fn(async () => 778899);
const { pipeline, captured } = makePipeline({
resolveGroupJoinRequest,
resolveGroupInviteCardSequence,
});
pipeline.registerCmd('test.cmd', () => [
{
kind: 'group_invite',
time: 1,
selfUin: 10001,
groupId: 999,
fromUin: 456,
fromUid: 'u_inviter',
subType: 'invite',
message: '',
flag: 'invite:999:u_inviter',
} as QQEventVariant,
]);
pipeline.process({ serviceCmd: 'test.cmd' } as PacketInfo);
await new Promise((r) => setTimeout(r, 10));
expect(resolveGroupInviteCardSequence).toHaveBeenCalledWith(999);
expect(captured[0]).toMatchObject({
flag: 'slreq:1:778899:999:2:0',
invitedUin: 10001,
invitedUid: 'self',
});
});
it('fills the invitee from the pending-request row (#394)', async () => {
const resolveGroupJoinRequest = vi.fn(async () => ({
groupId: 1,
groupName: 'group',
targetUid: 'u_invitee',
targetUin: 789,
targetName: 'invitee',
invitorUid: 'u_inviter',
invitorUin: 456,
invitorName: 'inviter',
operatorUid: '',
operatorUin: 0,
operatorName: '',
sequence: 42,
state: 1,
eventType: 2,
comment: '',
filtered: false,
}));
const { pipeline, captured } = makePipeline({ resolveGroupJoinRequest });
pipeline.registerCmd('test.cmd', () => [
{
kind: 'group_invite',
time: 1,
selfUin: 10001,
groupId: 1,
fromUin: 456,
fromUid: 'u_inviter',
subType: 'invite',
message: '',
flag: 'invite:1:u_inviter',
} as QQEventVariant,
]);
pipeline.process({ serviceCmd: 'test.cmd' } as PacketInfo);
await new Promise((r) => setTimeout(r, 10));
expect(captured[0]).toMatchObject({
fromUin: 456,
invitedUin: 789,
invitedUid: 'u_invitee',
});
});
it('runs the profile + request lookups in parallel (independent failures)', async () => {
// Profile lookup succeeds, request lookup fails — event should
// still carry the resolved uin but no comment. The dispatch
// doesn't block on the slower / failing path.
const fetchProfileByUid = vi.fn(async () => makeProfile(12345, 'u_x', 'OK'));
const resolveGroupJoinRequest = vi.fn(async () => {
throw new Error('queue lookup failed');
});
const { pipeline, captured } = makePipeline({
fetchProfileByUid,
resolveGroupJoinRequest,
});
pipeline.registerCmd('test.cmd', () => [
{
kind: 'group_invite',
time: 1,
selfUin: 10001,
groupId: 1,
fromUin: 0,
fromUid: 'u_x',
subType: 'add',
message: '',
flag: 'add:1:u_x',
} as QQEventVariant,
]);
pipeline.process({ serviceCmd: 'test.cmd' } as PacketInfo);
await new Promise((r) => setTimeout(r, 10));
const ev = captured[0] as Extract<QQEventVariant, { kind: 'group_invite' }>;
expect(ev.fromUin).toBe(12345); // profile succeeded
expect(ev.message).toBe(''); // request lookup threw, message left empty
});
it('invite subtype matches the request on invitorUid (not targetUid)', async () => {
// For `subType: 'invite'` (group member invited the bot or another
// user), the pending-request row's REQUESTER field is
// `invitorUid` not `targetUid`. The dep contract makes this
// explicit so the bridge facade can route the lookup correctly.
const resolveGroupJoinRequest = vi.fn(async () => ({
comment: 'come join',
sequence: 999,
}));
const { pipeline } = makePipeline({ resolveGroupJoinRequest });
pipeline.registerCmd('test.cmd', () => [
{
kind: 'group_invite',
time: 1,
selfUin: 10001,
groupId: 1,
fromUin: 0,
fromUid: 'u_inviter',
subType: 'invite',
message: '',
flag: 'invite:1:u_inviter',
} as QQEventVariant,
]);
pipeline.process({ serviceCmd: 'test.cmd' } as PacketInfo);
await new Promise((r) => setTimeout(r, 10));
expect(resolveGroupJoinRequest).toHaveBeenCalledWith(1, 'u_inviter', 'invite');
});
it('does not treat fromUin === groupId as an unresolved identity', async () => {
const fetchProfileByUid = vi.fn(async () =>
makeProfile(1957003260, 'u_kitaikuyo', 'KitaIkuyo'),
it('uses the sender and approval tuple from the matched filtered request', async () => {
const resolveGroupJoinRequest = vi.fn(async () =>
request({ targetUin: 222, filtered: true }),
);
const { pipeline, captured } = makePipeline({ fetchProfileByUid });
pipeline.registerCmd('test.cmd', () => [
{
kind: 'group_invite',
time: 1,
selfUin: 10001,
groupId: 950929451,
fromUin: 950929451,
fromUid: 'u_kitaikuyo',
subType: 'add',
message: '',
flag: 'add:950929451:u_kitaikuyo',
} as QQEventVariant,
]);
pipeline.process({ serviceCmd: 'test.cmd' } as PacketInfo);
await new Promise((r) => setTimeout(r, 10));
const { pipeline, captured, fetchProfileByUid } = makePipeline({ resolveGroupJoinRequest });
await receive(pipeline, requestEvent());
expect(fetchProfileByUid).not.toHaveBeenCalled();
expect(captured).toHaveLength(1);
expect(captured[0]).toMatchObject({
fromUin: 950929451,
fromUid: 'u_kitaikuyo',
groupId: 950929451,
});
expect(captured).toEqual([
expect.objectContaining({ fromUin: 222, flag: 'slreq:1:42:12345:1:1' }),
]);
});
it('skips both lookups when fromUid is empty (no uid to look up by)', async () => {
const fetchProfileByUid = vi.fn(async () => makeProfile(0));
const resolveGroupJoinRequest = vi.fn(async () => null);
const { pipeline, captured } = makePipeline({ fetchProfileByUid, resolveGroupJoinRequest });
pipeline.registerCmd('test.cmd', () => [
{
kind: 'group_invite',
time: 1,
selfUin: 10001,
groupId: 12345,
fromUin: 0,
fromUid: '',
subType: 'add',
message: '',
flag: 'add:12345:',
} as QQEventVariant,
it('matches an invitation approval by inviter and invitee', async () => {
const resolveGroupJoinRequest = vi.fn(async () =>
request({
invitorUid: 'u_inviter',
invitorUin: 456,
targetUid: 'u_invitee',
targetUin: 789,
eventType: 22,
notifyType: 5,
}),
);
const { pipeline, captured } = makePipeline({ resolveGroupJoinRequest });
await receive(
pipeline,
requestEvent({ subType: 'invite', fromUid: 'u_inviter', invitedUid: 'u_invitee' }),
);
expect(resolveGroupJoinRequest).toHaveBeenCalledWith(
12345,
'u_inviter',
'invite',
'u_invitee',
);
expect(captured).toEqual([
expect.objectContaining({
fromUin: 456,
invitedUin: 789,
invitedUid: 'u_invitee',
flag: 'slreq:1:42:12345:22:0',
}),
]);
});
pipeline.process({ serviceCmd: 'test.cmd' } as PacketInfo);
await new Promise((r) => setTimeout(r, 10));
// No uid → nothing to query by → neither lookup runs, event still emits.
expect(fetchProfileByUid).not.toHaveBeenCalled();
it('leaves self invitations to the card without querying or waiting', async () => {
const { pipeline, captured, resolveGroupJoinRequest, fetchProfileByUid } = makePipeline();
await receive(pipeline, requestEvent({ subType: 'invite', invitedUin: 10001 }));
expect(captured).toEqual([]);
expect(resolveGroupJoinRequest).not.toHaveBeenCalled();
expect(fetchProfileByUid).not.toHaveBeenCalled();
});
it('does not substitute a list sequence for the self-invite card sequence', async () => {
const resolveGroupJoinRequest = vi.fn(async () =>
request({ eventType: 2, targetUin: 10001 }),
);
const { pipeline, captured } = makePipeline({ resolveGroupJoinRequest });
await receive(pipeline, requestEvent({ subType: 'invite' }));
expect(captured).toEqual([]);
});
it.each(['missing', 'failed'])(
'does not emit an incomplete request after a %s lookup',
async (outcome) => {
const resolveGroupJoinRequest =
outcome === 'missing'
? vi.fn(async () => null)
: vi.fn(async () => {
throw new Error('lookup failed');
});
const { pipeline, captured, fetchProfileByUid } = makePipeline({
resolveGroupJoinRequest,
});
await receive(pipeline, requestEvent());
expect(captured).toEqual([]);
expect(resolveGroupJoinRequest).toHaveBeenCalledOnce();
expect(fetchProfileByUid).not.toHaveBeenCalled();
},
);
it('does not treat a requester UIN equal to the group number as unresolved', async () => {
const { pipeline, captured, identity, fetchProfileByUid } = makePipeline();
await receive(pipeline, requestEvent({ fromUin: 12345 }));
expect(fetchProfileByUid).not.toHaveBeenCalled();
expect(captured[0]).toMatchObject({ fromUin: 12345 });
expect(identity.findUinByUid('u_requester')).toBe(12345);
});
it('rejects a request without its requester UID', async () => {
const { pipeline, captured, resolveGroupJoinRequest } = makePipeline();
await receive(pipeline, requestEvent({ fromUid: '' }));
expect(captured).toEqual([]);
expect(resolveGroupJoinRequest).not.toHaveBeenCalled();
expect(captured).toHaveLength(1);
});
});
@@ -559,6 +279,7 @@ describe('IncomingPacketPipeline / #1 group card self-heal', () => {
fetchGroupList: vi.fn(async () => {}),
fetchGroupMemberList: vi.fn(async () => {}),
resolveGroupJoinRequest: vi.fn(async () => null),
rememberGroupInviteCardSequence: vi.fn(() => true),
});
return { identity, pipeline };
}
@@ -672,6 +393,7 @@ describe('IncomingPacketPipeline / group_card_change from message traffic', () =
fetchGroupList: vi.fn(async () => {}),
fetchGroupMemberList: vi.fn(async () => {}),
resolveGroupJoinRequest: vi.fn(async () => null),
rememberGroupInviteCardSequence: vi.fn(() => true),
});
const captured: QQEventVariant[] = [];
events.onAny((e) => captured.push(e as QQEventVariant));
@@ -734,43 +456,3 @@ describe('IncomingPacketPipeline / group_card_change from message traffic', () =
expect(captured.some((e) => e.kind === 'group_card_change')).toBe(false);
});
});
describe('IncomingPacketPipeline / invite-card pending application', () => {
const friendMessage = (card?: {
inviteCardGroupUin: number;
inviteCardSequence: number;
}): QQEventVariant => ({
kind: 'friend_message',
time: 1,
selfUin: 10001,
senderUin: 222,
senderNick: 'Bob',
msgSeq: 1,
msgId: 1,
elements: [],
...card,
});
it('remembers parsed invite-card facts through the optional port', () => {
const rememberGroupInviteCardSequence = vi.fn();
const pipeline = new IncomingPacketPipeline({
identity: IdentityService.memory('10001'),
events: new BridgeEventBus(),
fetchGroupList: vi.fn(async () => {}),
fetchGroupMemberList: vi.fn(async () => {}),
resolveGroupJoinRequest: vi.fn(async () => null),
rememberGroupInviteCardSequence,
});
pipeline.registerCmd('test.cmd', () => [
friendMessage({ inviteCardGroupUin: 12345, inviteCardSequence: 778899 }),
]);
pipeline.process({ serviceCmd: 'test.cmd' } as PacketInfo);
expect(rememberGroupInviteCardSequence).toHaveBeenCalledWith(12345, 778899);
});
it('does not remember when the port is omitted or the event has no card', () => {
const { pipeline } = makePipeline();
pipeline.registerCmd('test.cmd', () => [friendMessage()]);
expect(() => pipeline.process({ serviceCmd: 'test.cmd' } as PacketInfo)).not.toThrow();
});
});

View File

@@ -121,7 +121,26 @@ function makePipeline(
events,
fetchGroupList: opts.fetchGroupList ?? vi.fn(async () => {}),
fetchGroupMemberList: opts.fetchGroupMemberList ?? vi.fn(async () => {}),
resolveGroupJoinRequest: vi.fn(async () => null),
resolveGroupJoinRequest: vi.fn(async () => ({
groupId: 123,
groupName: '',
targetUid: 'u_stranger',
targetUin: 0,
targetName: '',
invitorUid: '',
invitorUin: 0,
invitorName: '',
operatorUid: '',
operatorUin: 0,
operatorName: '',
sequence: 42,
state: 1,
notifyType: 7,
eventType: 1,
comment: '',
filtered: false,
})),
rememberGroupInviteCardSequence: vi.fn(() => true),
});
const dispatched: Array<{ event: QQEventVariant; req: number | undefined }> = [];
events.onAny((event) => {

View File

@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/proton",
"version": "2.0.2",
"version": "2.1.0",
"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 with edge-case fixes applied.",

View File

@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/runtime",
"version": "2.0.2",
"version": "2.1.0",
"private": true,
"type": "module",
"main": "index.mjs",

View File

@@ -4,7 +4,7 @@
"name": "MotricSeven",
"email": "motricseven@gmail.com"
},
"version": "2.0.2",
"version": "2.1.0",
"description": "TypeScript SDK for SnowLuma OneBot HTTP and WebSocket transports",
"keywords": [
"snowluma",

View File

@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/sqlite",
"version": "2.0.2",
"version": "2.1.0",
"private": true,
"type": "module",
"description": "SnowLuma asynchronous SQLite facade, native loader and release assets.",

View File

@@ -4,7 +4,7 @@
"name": "MotricSeven",
"email": "motricseven@gmail.com"
},
"version": "2.0.2",
"version": "2.1.0",
"description": "Shared SnowLuma UI primitives — Tailwind 4 theme tokens + shadcn-style atomic components",
"keywords": [
"snowluma",

View File

@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/websocket",
"version": "2.0.2",
"version": "2.1.0",
"private": true,
"type": "module",
"main": "./src/index.ts",

View File

@@ -0,0 +1,111 @@
# Host appearance overlays
Set `SNOWLUMA_WEBUI_TARGET=maibot` on the **SnowLuma process** to use MaiBot's
millennium appearance. The same release bundle supports standalone and embedded
deployments. An unset or empty value keeps the existing SnowLuma experience;
unknown values fail WebUI startup with an explicit diagnostic.
This first adapter implements **millennium only**, in light and dark modes.
Other MaiBot styles are not implemented. There is no new appearance selector in
SnowLuma. The host owns theme changes; existing theme controls are unavailable
while managed, and the settings page explains which preferences are preserved.
## Runtime and ownership
1. Core reads the environment at startup. [Static document delivery](../core/src/webui/static-frontend.ts)
injects a validated, public JSON bootstrap into `/`, `/index.html` and SPA
fallback documents. Documents use `Cache-Control: no-store`. No secrets or
arbitrary environment variables reach the browser.
2. [Frontend bootstrap](src/appearance/runtime.ts) loads only the selected
target's assets before mounting React. Standalone deployments load no target
stylesheet, font or host listener. Vite development serves the same bootstrap
when its process has the environment variable; production builds remain neutral.
3. [ThemeContext](src/contexts/ThemeContext.tsx) keeps `savedAppearance` separate
from effective `appearance`. Only saved preferences enter localStorage or
`config/ui.json`. Target updates never invoke the persistence API.
4. The target owns colors, fonts, radius, wallpaper, CSS variable overrides,
custom CSS and custom cursor presentation. These saved values are preserved
but suspended. UI scale, density, motion/accessibility, navigation layout and
data preferences remain available. Safe-mode restrictions still apply when
returning to native appearance.
5. A single layout effect applies effective appearance. Changes do not reload
the document, change React keys or restart sessions. All target rules are
scoped to `html[data-webui-target]`, including portals under `body`.
## Host protocol, version 1
The contract lives in [common/webui-target.ts](../common/src/webui-target.ts).
The deployment environment is an opt-in, **not a live transport**. Existing
launchers need to implement the sender below; merely setting the environment
variable cannot convey another process's current theme.
A same-document embedding bridge (for example Electron `executeJavaScript`)
publishes the latest snapshot before dispatching the event:
```js
const appearance = {
version: 1,
target: 'maibot',
style: 'millennium',
mode: 'dark', // 'light' | 'dark' | 'system'
};
window.__SNOWLUMA_HOST_APPEARANCE__ = appearance;
window.dispatchEvent(new CustomEvent('snowluma:host-appearance', { detail: appearance }));
```
The snapshot handles messages sent before React or the lazy asset loader is
ready. Publish on each guest `dom-ready` and whenever the host's resolved
brightness changes. A host that already follows MaiBot should forward its own
resolved `light`/`dark` state; this avoids competing sources of truth. Validate
the guest's expected origin before injecting, serialize values with
`JSON.stringify`, and do not enable Node integration in the guest.
Send `{ version: 1, target: null }` using the same mechanism to release the
override for the current document. The original appearance returns immediately.
The opted-in document keeps its host subscription so the host can reapply the
target later. Listeners are released on provider unmount. This does not change
the startup environment or enable a target in a standalone deployment.
The current adapter starts with millennium and system brightness before a host
snapshot arrives. The last valid snapshot remains active if the host stops
sending. Snapshots are not persisted or shared across origins/tabs. A reload
requires the host to publish again. Unsupported versions, targets, styles or
modes are rejected with `[SnowLuma appearance]` console diagnostics; the previous
valid snapshot remains. The host cannot supply CSS, URLs or executable content
through this protocol. No unauthenticated HTTP write endpoint is introduced.
## Adding a target
- Add its identifier, styles and default style to `WEBUI_TARGETS` in the shared
contract. Keep validation at this boundary; do not accept arbitrary strings.
- Add one lazy loader to the exhaustive [frontend registry](src/appearance/registry.ts).
Implement a pure saved-to-effective resolver and scoped stylesheet under
`src/appearance/targets`. Keep any fonts local with their redistribution license.
- Use semantic color variables, shared component classes and neutral
`data-ui-surface` markers. Do not add target-name checks to business pages.
- Never persist resolved overrides, mutate saved preferences, introduce a
second DOM theme writer, or remount the application to switch presentation.
- Test default asset/listener isolation, initial document routes, malformed
messages, rapid updates, cleanup and exact restoration of saved preferences.
Verify forms, focus, scroll, portals and mobile layout with an isolated backend.
Electron integration needs a separate real-host check.
## Sources and checks
The adapter follows the main MaiBot repository's
[millennium stylesheet](https://github.com/Mai-with-u/MaiBot/blob/5c7637e6913c84d1c3d5e742fa9e95a7e70d3501/dashboard/src/styles/millennium.css),
not the archived standalone WebUI. Colors/materials also match the
[OneKey shell](https://github.com/Mai-with-u/MaiBotOneKey/blob/e8073b0bce35c8c4da973b06156602e14c42fee5/src/renderer/src/styles/millennium.css).
The bundled Jersey 20 font is from that MaiBot revision, copyright The Soft Type
Project Authors, under the [SIL Open Font License](src/appearance/targets/assets/Jersey20-OFL.txt).
Its license is emitted alongside the font in production assets.
Focused checks (from the repository root):
```sh
pnpm --filter @snowluma/common exec vitest run tests/webui-target.test.ts
pnpm --filter @snowluma/core exec vitest run tests/webui-static-frontend.test.ts
pnpm --filter webui exec vitest run tests/target-appearance.test.ts
```
Run the normal workspace checks from `AGENTS.md` before handing off changes.

View File

@@ -3,6 +3,14 @@
SnowLuma's browser console is a Vite + React application for managing runtime
status, OneBot configuration, logs, storage, and server settings.
## Host appearance integration
`SNOWLUMA_WEBUI_TARGET=maibot` opts a deployment into a reversible millennium
appearance overlay. Standalone defaults are unchanged. Hosts drive live light/dark
updates without saving over personal preferences or adding another selector.
See [the integration contract and extension guide](INTEGRATIONS.md) before changing
target startup, theme ownership, host messaging or scoped styles.
## Interaction conventions
- Destructive actions and second confirmations stay in modal dialogs.

View File

@@ -17,6 +17,9 @@
<script>
(function () {
try {
// Deployment overlays are prepared before React mounts. Do not flash
// a saved palette/font underneath an opted-in host presentation.
if (document.getElementById('snowluma-webui-target')) return;
var raw = localStorage.getItem('snowluma_ui_appearance');
var a = raw ? JSON.parse(raw) : {};
if (!a || typeof a !== 'object') a = {};

View File

@@ -2,7 +2,7 @@
"license": "SEE LICENSE IN LICENSE",
"name": "webui",
"private": true,
"version": "2.0.2",
"version": "2.1.0",
"type": "module",
"scripts": {
"dev": "vite",

View File

@@ -0,0 +1,29 @@
import type { WebuiPresentation, WebuiTarget } from '@snowluma/common/webui-target';
import type { UiAppearance } from '@/types';
export interface TargetAppearance {
css: string;
licenseUrl?: string;
resolve: (saved: UiAppearance, presentation: WebuiPresentation) => UiAppearance;
}
export function resolveAppearance(
saved: UiAppearance,
presentation: WebuiPresentation | null,
target: TargetAppearance | null,
): UiAppearance {
if (!presentation) {
return saved;
}
if (!target) {
throw new Error('Target appearance must be prepared before mounting ThemeProvider');
}
return target.resolve(saved, presentation);
}
// Exhaustive: adding a shared target requires a frontend implementation here.
export const targetLoaders = {
maibot: () => import('./targets/maibot').then((module) => module.maibotAppearance),
} satisfies Record<WebuiTarget, () => Promise<TargetAppearance>>;

View File

@@ -0,0 +1,104 @@
import {
parseWebuiPresentation,
WEBUI_PRESENTATION_EVENT,
WEBUI_TARGET_BOOTSTRAP_ID,
type WebuiPresentation,
} from '@snowluma/common/webui-target';
import { createPresentationStore, type PresentationStore } from './store';
import { targetLoaders, type TargetAppearance } from './registry';
declare global {
interface Window {
/** The embedding host sets this before dispatching WEBUI_PRESENTATION_EVENT. */
__SNOWLUMA_HOST_APPEARANCE__?: unknown;
}
}
const bootstrap =
typeof document === 'undefined' ? null : document.getElementById(WEBUI_TARGET_BOOTSTRAP_ID);
const initial = bootstrap
? parseWebuiPresentation(JSON.parse(bootstrap.textContent || 'null'))
: null;
export const presentationStore = createPresentationStore(initial?.target ?? null);
let targetAppearance: TargetAppearance | null = null;
function acceptHostValue(store: PresentationStore, value: unknown): void {
try {
store.receive(value);
} catch (error) {
// Reject only the bad update; keep the last valid presentation and expose the failure.
console.error('[SnowLuma appearance] Rejected host update', error);
}
}
export function subscribeHostAppearance(host: Window, store: PresentationStore): () => void {
if (store.target === null) {
return () => {};
}
const receive = (event: Event) =>
acceptHostValue(store, (event as CustomEvent<unknown>).detail);
host.addEventListener(WEBUI_PRESENTATION_EVENT, receive);
// Covers messages sent before React subscribed, including while the lazy CSS was loading.
if (host.__SNOWLUMA_HOST_APPEARANCE__ !== undefined) {
acceptHostValue(store, host.__SNOWLUMA_HOST_APPEARANCE__);
}
return () => host.removeEventListener(WEBUI_PRESENTATION_EVENT, receive);
}
export function applyPresentationAttributes(presentation: WebuiPresentation | null): void {
const root = document.documentElement;
if (presentation) {
root.dataset.webuiTarget = presentation.target;
root.dataset.webuiStyle = presentation.style;
} else {
delete root.dataset.webuiTarget;
delete root.dataset.webuiStyle;
}
}
export function getTargetAppearance(): TargetAppearance | null {
return targetAppearance;
}
/** Called before mounting React; standalone deployments do not load any target assets. */
export async function prepareTargetAppearance(): Promise<void> {
const target = presentationStore.target;
if (target === null) {
return;
}
targetAppearance = await targetLoaders[target]();
const style = document.createElement('style');
style.id = 'snowluma-target-styles';
style.textContent = targetAppearance.css;
document.head.appendChild(style);
if (targetAppearance.licenseUrl) {
const license = document.createElement('link');
license.rel = 'license';
license.href = targetAppearance.licenseUrl;
document.head.appendChild(license);
}
if (window.__SNOWLUMA_HOST_APPEARANCE__ !== undefined) {
acceptHostValue(presentationStore, window.__SNOWLUMA_HOST_APPEARANCE__);
}
const presentation = presentationStore.getSnapshot();
applyPresentationAttributes(presentation);
if (presentation) {
const dark =
presentation.mode === 'system'
? window.matchMedia('(prefers-color-scheme: dark)').matches
: presentation.mode === 'dark';
document.documentElement.classList.toggle('dark', dark);
document.documentElement.classList.toggle('light', !dark);
document.documentElement.style.colorScheme = dark ? 'dark' : 'light';
}
}

View File

@@ -0,0 +1,51 @@
import {
defaultWebuiPresentation,
parseWebuiPresentation,
type WebuiPresentation,
type WebuiTarget,
} from '@snowluma/common/webui-target';
/** Synchronous snapshots avoid stale async style loads winning a rapid host theme change. */
export function createPresentationStore(target: WebuiTarget | null) {
let snapshot: WebuiPresentation | null = target ? defaultWebuiPresentation(target) : null;
const listeners = new Set<() => void>();
return {
target,
getSnapshot: () => snapshot,
subscribe(listener: () => void) {
if (target) {
listeners.add(listener);
}
return () => {
listeners.delete(listener);
};
},
receive(value: unknown) {
// Host code cannot opt a standalone deployment into a target.
if (target === null) {
return;
}
const update = parseWebuiPresentation(value);
if (update.target !== null && update.target !== target) {
throw new Error(
`Host appearance target does not match deployment target ${target}`,
);
}
const next = update.target === null ? null : update;
if (JSON.stringify(next) === JSON.stringify(snapshot)) {
return;
}
snapshot = next;
listeners.forEach((listener) => listener());
},
};
}
export type PresentationStore = ReturnType<typeof createPresentationStore>;

View File

@@ -0,0 +1,93 @@
Copyright 2023 The Soft Type Project Authors (https://github.com/scfried/soft-type-jersey)
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
https://openfontlicense.org
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.

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