Compare commits
23 Commits
native/aut
...
v2.1.0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8fc68c0ec3 | ||
|
|
b4ece8671b | ||
|
|
bde7f2805d | ||
|
|
491b531841 | ||
|
|
617e7581dd | ||
|
|
27120f884a | ||
|
|
3a4c1eeea2 | ||
|
|
5cd4ae61dd | ||
|
|
28f64113e7 | ||
|
|
c537311ed1 | ||
|
|
9d8df59370 | ||
|
|
76846f40b1 | ||
|
|
79522d949f | ||
|
|
db142db9e6 | ||
|
|
e5cfec01bd | ||
|
|
1b74747251 | ||
|
|
38fc636088 | ||
|
|
9c3c768968 | ||
|
|
059faf79c0 | ||
|
|
20cf7394e5 | ||
|
|
68deb48811 | ||
|
|
bdf224cbc9 | ||
|
|
a69ec6fedb |
@@ -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.
|
||||
|
||||
@@ -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 进程行的刷新/重连。
|
||||
|
||||
## 接入与文档
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "snowluma-monorepo",
|
||||
"version": "2.0.0",
|
||||
"version": "2.1.0",
|
||||
"description": "SnowLuma monorepo workspace (pnpm)",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "@snowluma/bridge",
|
||||
"version": "2.0.0",
|
||||
"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).",
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
@@ -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),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
|
||||
115
packages/bridge/src/qq-account/watch.ts
Normal file
115
packages/bridge/src/qq-account/watch.ts
Normal 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();
|
||||
};
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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
|
||||
|
||||
119
packages/bridge/tests/qq-account-watch.test.ts
Normal file
119
packages/bridge/tests/qq-account-watch.test.ts
Normal 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();
|
||||
});
|
||||
});
|
||||
@@ -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();
|
||||
|
||||
@@ -1,13 +1,21 @@
|
||||
{
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "@snowluma/common",
|
||||
"version": "2.0.0",
|
||||
"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"
|
||||
},
|
||||
"./semver": {
|
||||
"types": "./src/semver.ts",
|
||||
"default": "./src/semver.ts"
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import { isObject } from './coerce';
|
||||
import { normalizeUpdateSourceConfig, type UpdateSourceConfig } from './update-source';
|
||||
|
||||
export interface RuntimeConfig {
|
||||
updateSource?: UpdateSourceConfig;
|
||||
webuiPort?: number;
|
||||
/** When true, every newly-discovered QQ process gets auto-injected by
|
||||
* the HookManager. Also overridable at runtime via SNOWLUMA_HOOK_AUTOLOAD.
|
||||
@@ -43,6 +45,9 @@ export const MAX_LOG_RETAIN_DAYS = Math.floor(Number.MAX_SAFE_INTEGER / (24 * 60
|
||||
export function normalizeRuntimeConfig(parsed: unknown): RuntimeConfig {
|
||||
const obj = isObject(parsed) ? parsed : {};
|
||||
return {
|
||||
...(obj.updateSource === undefined
|
||||
? {}
|
||||
: { updateSource: normalizeUpdateSourceConfig(obj.updateSource) }),
|
||||
webuiPort: normalizePort(obj.webuiPort ?? DEFAULT_WEBUI_PORT, DEFAULT_WEBUI_PORT),
|
||||
hookAutoLoad: normalizeBool(obj.hookAutoLoad, false),
|
||||
webuiHost: normalizeHost(obj.webuiHost),
|
||||
@@ -217,7 +222,8 @@ function sameRuntimeConfig(parsed: Record<string, unknown>, n: RuntimeConfig): b
|
||||
parsed.trustProxy === n.trustProxy &&
|
||||
parsed.logMaxTotalMb === n.logMaxTotalMb &&
|
||||
parsed.logRetainDays === n.logRetainDays &&
|
||||
parsed.logPerUin === n.logPerUin
|
||||
parsed.logPerUin === n.logPerUin &&
|
||||
JSON.stringify(parsed.updateSource) === JSON.stringify(n.updateSource)
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
60
packages/common/src/update-source.ts
Normal file
60
packages/common/src/update-source.ts
Normal file
@@ -0,0 +1,60 @@
|
||||
export interface UpdateSourceConfig {
|
||||
mode: 'auto' | 'direct' | 'mirror';
|
||||
mirror: string;
|
||||
mirrors: string[];
|
||||
}
|
||||
|
||||
export function normalizeMirrorUrl(value: unknown): string {
|
||||
if (typeof value !== 'string' || value.length > 2048) {
|
||||
throw new Error('镜像地址必须是 HTTP(S) URL');
|
||||
}
|
||||
|
||||
let url: URL;
|
||||
|
||||
try {
|
||||
url = new URL(value.trim());
|
||||
} catch {
|
||||
throw new Error('镜像地址必须是 HTTP(S) URL');
|
||||
}
|
||||
|
||||
if (
|
||||
!['http:', 'https:'].includes(url.protocol) ||
|
||||
url.username ||
|
||||
url.password ||
|
||||
url.search ||
|
||||
url.hash
|
||||
) {
|
||||
throw new Error('镜像地址仅支持 HTTP(S),不能包含账号、密码、查询参数或片段');
|
||||
}
|
||||
|
||||
return url.href.replace(/\/+$/, '');
|
||||
}
|
||||
|
||||
export function normalizeUpdateSourceConfig(value: unknown): UpdateSourceConfig {
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value)) {
|
||||
throw new Error('更新来源必须是对象');
|
||||
}
|
||||
|
||||
if (
|
||||
!('mode' in value) ||
|
||||
(value.mode !== 'auto' && value.mode !== 'direct' && value.mode !== 'mirror')
|
||||
) {
|
||||
throw new Error('更新来源模式无效');
|
||||
}
|
||||
|
||||
if (!('mirrors' in value) || !Array.isArray(value.mirrors) || value.mirrors.length > 16) {
|
||||
throw new Error('自动筛选最多支持 16 个镜像');
|
||||
}
|
||||
|
||||
const mirror = 'mirror' in value && value.mirror !== '' ? normalizeMirrorUrl(value.mirror) : '';
|
||||
|
||||
if (value.mode === 'mirror' && !mirror) {
|
||||
throw new Error('请指定镜像地址');
|
||||
}
|
||||
|
||||
return {
|
||||
mode: value.mode,
|
||||
mirror,
|
||||
mirrors: [...new Set(value.mirrors.map(normalizeMirrorUrl))],
|
||||
};
|
||||
}
|
||||
100
packages/common/src/webui-target.ts
Normal file
100
packages/common/src/webui-target.ts
Normal 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>`,
|
||||
);
|
||||
}
|
||||
54
packages/common/tests/update-source.test.ts
Normal file
54
packages/common/tests/update-source.test.ts
Normal file
@@ -0,0 +1,54 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { normalizeMirrorUrl, normalizeUpdateSourceConfig } from '../src/update-source';
|
||||
import { normalizeRuntimeConfig } from '../src/runtime';
|
||||
|
||||
describe('update source configuration', () => {
|
||||
it('normalizes proxy prefixes, deduplicates mirrors and retains order', () => {
|
||||
expect(
|
||||
normalizeUpdateSourceConfig({
|
||||
mode: 'auto',
|
||||
mirror: '',
|
||||
mirrors: [
|
||||
' https://EXAMPLE.com/proxy/ ',
|
||||
'https://example.com/proxy',
|
||||
'https://other.example',
|
||||
],
|
||||
}),
|
||||
).toEqual({
|
||||
mode: 'auto',
|
||||
mirror: '',
|
||||
mirrors: ['https://example.com/proxy', 'https://other.example'],
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
'',
|
||||
'file:///tmp/x',
|
||||
'ftp://example.com',
|
||||
'https://user:secret@example.com',
|
||||
'https://example.com/?token=a',
|
||||
'https://example.com/#a',
|
||||
null,
|
||||
])('rejects invalid mirror %s', (url) => {
|
||||
expect(() => normalizeMirrorUrl(url)).toThrow();
|
||||
});
|
||||
|
||||
it.each([
|
||||
null,
|
||||
[],
|
||||
{ mode: ['auto'], mirrors: [] },
|
||||
{ mode: 'mirror', mirror: '', mirrors: [] },
|
||||
{ mode: 'auto', mirrors: Array(17).fill('https://example.com') },
|
||||
])('rejects invalid configuration %j', (config) => {
|
||||
expect(() => normalizeUpdateSourceConfig(config)).toThrow();
|
||||
});
|
||||
|
||||
it('retains configured update sources when normalizing runtime settings', () => {
|
||||
const updateSource = { mode: 'direct', mirror: '', mirrors: [] };
|
||||
expect(normalizeRuntimeConfig({ updateSource, webuiPort: 7777 })).toMatchObject({
|
||||
updateSource,
|
||||
webuiPort: 7777,
|
||||
});
|
||||
expect(normalizeRuntimeConfig({})).not.toHaveProperty('updateSource');
|
||||
});
|
||||
});
|
||||
51
packages/common/tests/webui-target.test.ts
Normal file
51
packages/common/tests/webui-target.test.ts
Normal 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();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "@snowluma/core",
|
||||
"version": "2.0.0",
|
||||
"version": "2.1.0",
|
||||
"description": "SnowLuma core - NTQQ packet sniffer with Node.js native addon",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
|
||||
@@ -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
|
||||
|
||||
69
packages/core/src/bridge/apis/forward-cache.ts
Normal file
69
packages/core/src/bridge/apis/forward-cache.ts
Normal 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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);
|
||||
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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);
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -2,10 +2,12 @@ import { APP_VERSION } from '@snowluma/common/version';
|
||||
import { compareVersions, parseVersion } from '@snowluma/common/semver';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import { createSingleFlightCache } from '@snowluma/common/single-flight-cache';
|
||||
import type { UpdateSourceConfig } from '@snowluma/common/update-source';
|
||||
import { fetchRelease } from './release';
|
||||
import { readUpdateSource } from './sources';
|
||||
|
||||
const log = createLogger('Update');
|
||||
|
||||
const LATEST_RELEASE_URL = 'https://api.github.com/repos/SnowLuma/SnowLuma/releases/latest';
|
||||
const CACHE_TTL_MS = 6 * 60 * 60 * 1000; // 6h — comfortably under the rate limit
|
||||
const FETCH_TIMEOUT_MS = 8_000;
|
||||
const NOTES_MAX = 4_000; // cap the release-body we hand back to the client
|
||||
@@ -29,13 +31,6 @@ export interface UpdateCheckResult {
|
||||
error?: string;
|
||||
}
|
||||
|
||||
interface GithubRelease {
|
||||
tag_name?: string;
|
||||
html_url?: string;
|
||||
body?: string;
|
||||
published_at?: string;
|
||||
}
|
||||
|
||||
function isEnabled(): boolean {
|
||||
const v = (process.env.SNOWLUMA_UPDATE_CHECK ?? '').trim().toLowerCase();
|
||||
return v !== '0' && v !== 'false' && v !== 'off' && v !== 'no';
|
||||
@@ -47,8 +42,10 @@ function isEnabled(): boolean {
|
||||
const updateCache = createSingleFlightCache<string, UpdateCheckResult>({
|
||||
ttlMs: CACHE_TTL_MS,
|
||||
shouldCache: (r) => !r.error,
|
||||
load: async (current) => {
|
||||
const result = await fetchLatest(current);
|
||||
load: async (key) => {
|
||||
// This key is constructed below from our version and normalized settings.
|
||||
const [current, source] = JSON.parse(key) as [string, UpdateSourceConfig];
|
||||
const result = await fetchLatest(current, source);
|
||||
|
||||
if (result.error) {
|
||||
log.debug('update check failed: %s', result.error);
|
||||
@@ -60,7 +57,10 @@ const updateCache = createSingleFlightCache<string, UpdateCheckResult>({
|
||||
},
|
||||
});
|
||||
|
||||
async function fetchLatest(current: string): Promise<UpdateCheckResult> {
|
||||
async function fetchLatest(
|
||||
current: string,
|
||||
source: UpdateSourceConfig,
|
||||
): Promise<UpdateCheckResult> {
|
||||
const base: UpdateCheckResult = {
|
||||
current,
|
||||
latest: null,
|
||||
@@ -74,21 +74,19 @@ async function fetchLatest(current: string): Promise<UpdateCheckResult> {
|
||||
try {
|
||||
// `/releases/latest` already excludes drafts and prereleases, so this is
|
||||
// stable-channel by construction.
|
||||
const res = await fetch(LATEST_RELEASE_URL, {
|
||||
headers: {
|
||||
Accept: 'application/vnd.github+json',
|
||||
'User-Agent': `SnowLuma/${current}`,
|
||||
'X-GitHub-Api-Version': '2022-11-28',
|
||||
},
|
||||
signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
|
||||
});
|
||||
const { data: rel } = await fetchRelease(
|
||||
undefined,
|
||||
source,
|
||||
`SnowLuma/${current}`,
|
||||
FETCH_TIMEOUT_MS,
|
||||
);
|
||||
|
||||
if (!res.ok) {
|
||||
return { ...base, error: `github ${res.status}` };
|
||||
if (!rel || typeof rel !== 'object' || Array.isArray(rel)) {
|
||||
return { ...base, error: 'invalid release info' };
|
||||
}
|
||||
|
||||
const rel = (await res.json()) as GithubRelease;
|
||||
const tag = typeof rel.tag_name === 'string' ? rel.tag_name.trim() : '';
|
||||
const tag =
|
||||
'tag_name' in rel && typeof rel.tag_name === 'string' ? rel.tag_name.trim() : '';
|
||||
|
||||
if (!tag) {
|
||||
return { ...base, error: 'no tag' };
|
||||
@@ -104,9 +102,15 @@ async function fetchLatest(current: string): Promise<UpdateCheckResult> {
|
||||
current,
|
||||
latest,
|
||||
hasUpdate: compareVersions(latest, current) > 0,
|
||||
htmlUrl: rel.html_url ?? null,
|
||||
notes: rel.body ? rel.body.slice(0, NOTES_MAX) : null,
|
||||
publishedAt: rel.published_at ?? null,
|
||||
htmlUrl: 'html_url' in rel && typeof rel.html_url === 'string' ? rel.html_url : null,
|
||||
notes:
|
||||
'body' in rel && typeof rel.body === 'string' && rel.body
|
||||
? rel.body.slice(0, NOTES_MAX)
|
||||
: null,
|
||||
publishedAt:
|
||||
'published_at' in rel && typeof rel.published_at === 'string'
|
||||
? rel.published_at
|
||||
: null,
|
||||
checkedAt: Date.now(),
|
||||
};
|
||||
} catch (e) {
|
||||
@@ -120,14 +124,26 @@ async function fetchLatest(current: string): Promise<UpdateCheckResult> {
|
||||
* failures come back as a result with `error` set and `hasUpdate: false`, and
|
||||
* are not cached so the next check retries.
|
||||
*/
|
||||
export async function getUpdateInfo(force = false): Promise<UpdateCheckResult> {
|
||||
export async function getUpdateInfo(
|
||||
force = false,
|
||||
source?: UpdateSourceConfig,
|
||||
): Promise<UpdateCheckResult> {
|
||||
const current = APP_VERSION;
|
||||
|
||||
if (!isEnabled()) {
|
||||
return { ...emptyResult(current), error: 'disabled' };
|
||||
}
|
||||
|
||||
return updateCache.get(current, { force });
|
||||
try {
|
||||
return await updateCache.get(JSON.stringify([current, source ?? readUpdateSource()]), {
|
||||
force,
|
||||
});
|
||||
} catch (error) {
|
||||
return {
|
||||
...emptyResult(current),
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function emptyResult(current: string): UpdateCheckResult {
|
||||
|
||||
@@ -1,43 +1,30 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
import { createWriteStream } from 'node:fs';
|
||||
import { mkdir, readFile, writeFile } from 'node:fs/promises';
|
||||
import { mkdir, readFile, writeFile, rm } from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import { Readable, Transform } from 'node:stream';
|
||||
import { pipeline } from 'node:stream/promises';
|
||||
import { unzipSync } from 'fflate';
|
||||
import { x as extractTar } from 'tar';
|
||||
import { isRuntimeEntry, readManifest } from './files';
|
||||
import { assetName, fetchRelease } from './release';
|
||||
export { assetName } from './release';
|
||||
import { readUpdateSource, sourceUrls } from './sources';
|
||||
import type { UpdateSourceConfig } from '@snowluma/common/update-source';
|
||||
|
||||
interface ReleaseAsset {
|
||||
url: string;
|
||||
size: number;
|
||||
size: number | null;
|
||||
digest: string;
|
||||
}
|
||||
|
||||
export function assetName(version: string, target: string): string {
|
||||
const platform = target.replace('win32', 'win');
|
||||
return `SnowLuma-v${version}-${platform}-lite.${target.startsWith('win32') ? 'zip' : 'tar.gz'}`;
|
||||
}
|
||||
|
||||
async function releaseAsset(version: string, target: string): Promise<ReleaseAsset> {
|
||||
async function releaseAsset(
|
||||
version: string,
|
||||
target: string,
|
||||
source: UpdateSourceConfig,
|
||||
): Promise<ReleaseAsset> {
|
||||
const name = assetName(version, target);
|
||||
const response = await fetch(
|
||||
`https://api.github.com/repos/SnowLuma/SnowLuma/releases/tags/v${version}`,
|
||||
{
|
||||
headers: {
|
||||
Accept: 'application/vnd.github+json',
|
||||
'User-Agent': 'SnowLuma',
|
||||
'X-GitHub-Api-Version': '2022-11-28',
|
||||
},
|
||||
signal: AbortSignal.timeout(15_000),
|
||||
},
|
||||
);
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`获取更新失败: GitHub ${response.status}`);
|
||||
}
|
||||
|
||||
const release: unknown = await response.json();
|
||||
const { data: release, fromPage } = await fetchRelease(version, source);
|
||||
|
||||
if (
|
||||
!release ||
|
||||
@@ -58,9 +45,10 @@ async function releaseAsset(version: string, target: string): Promise<ReleaseAss
|
||||
!asset ||
|
||||
typeof asset !== 'object' ||
|
||||
!('size' in asset) ||
|
||||
typeof asset.size !== 'number' ||
|
||||
!Number.isSafeInteger(asset.size) ||
|
||||
asset.size <= 0 ||
|
||||
!(
|
||||
(fromPage && asset.size === null) ||
|
||||
(typeof asset.size === 'number' && Number.isSafeInteger(asset.size) && asset.size > 0)
|
||||
) ||
|
||||
!('digest' in asset) ||
|
||||
typeof asset.digest !== 'string' ||
|
||||
!/^sha256:[a-f0-9]{64}$/.test(asset.digest)
|
||||
@@ -94,37 +82,98 @@ export async function downloadUpdate(
|
||||
directory: string,
|
||||
version: string,
|
||||
target: string,
|
||||
source = readUpdateSource(),
|
||||
): Promise<void> {
|
||||
const asset = await releaseAsset(version, target);
|
||||
const response = await fetch(asset.url, { signal: AbortSignal.timeout(10 * 60_000) });
|
||||
|
||||
if (!response.ok || !response.body) {
|
||||
throw new Error(`下载更新失败: HTTP ${response.status}`);
|
||||
}
|
||||
|
||||
const asset = await releaseAsset(version, target, source);
|
||||
const archive = path.join(directory, 'archive');
|
||||
const hash = createHash('sha256');
|
||||
let received = 0;
|
||||
await pipeline(
|
||||
Readable.fromWeb(response.body),
|
||||
new Transform({
|
||||
transform(chunk: Buffer, _encoding, callback) {
|
||||
received += chunk.length;
|
||||
const urls = sourceUrls(asset.url, source);
|
||||
const failures: string[] = [];
|
||||
|
||||
if (received > asset.size) {
|
||||
callback(new Error('更新包大小不匹配'));
|
||||
return;
|
||||
}
|
||||
for (const [index, url] of urls.entries()) {
|
||||
let created = false;
|
||||
|
||||
hash.update(chunk);
|
||||
callback(null, chunk);
|
||||
},
|
||||
}),
|
||||
createWriteStream(archive, { flags: 'wx' }),
|
||||
);
|
||||
try {
|
||||
const headersTimeout = new AbortController();
|
||||
const timer = setTimeout(() => headersTimeout.abort(), 8_000);
|
||||
let response: Response;
|
||||
|
||||
if (received !== asset.size || `sha256:${hash.digest('hex')}` !== asset.digest) {
|
||||
throw new Error('更新包校验失败');
|
||||
try {
|
||||
response = await fetch(url, {
|
||||
signal: AbortSignal.any([
|
||||
headersTimeout.signal,
|
||||
AbortSignal.timeout(10 * 60_000),
|
||||
]),
|
||||
});
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
|
||||
if (!response.ok || !response.body) {
|
||||
await response.body?.cancel();
|
||||
throw new Error(`下载更新失败: HTTP ${response.status}`);
|
||||
}
|
||||
|
||||
if (/text\/html/i.test(response.headers.get('content-type') ?? '')) {
|
||||
await response.body.cancel();
|
||||
throw new Error('下载源返回了 HTML 页面,而不是更新包');
|
||||
}
|
||||
|
||||
const hash = createHash('sha256');
|
||||
const length = response.headers.get('content-length');
|
||||
const size =
|
||||
asset.size ?? (length === null ? null : /^\d+$/.test(length) ? Number(length) : 0);
|
||||
|
||||
if (size !== null && (!Number.isSafeInteger(size) || size <= 0)) {
|
||||
await response.body.cancel();
|
||||
throw new Error('下载源返回了无效的更新包大小');
|
||||
}
|
||||
|
||||
let received = 0;
|
||||
const output = createWriteStream(archive, { flags: 'wx' });
|
||||
output.once('open', () => {
|
||||
created = true;
|
||||
});
|
||||
await pipeline(
|
||||
Readable.fromWeb(response.body),
|
||||
new Transform({
|
||||
transform(chunk: Buffer, _encoding, callback) {
|
||||
received += chunk.length;
|
||||
|
||||
if (received > (size ?? 256 * 1024 * 1024)) {
|
||||
callback(new Error('更新包大小不匹配'));
|
||||
return;
|
||||
}
|
||||
|
||||
hash.update(chunk);
|
||||
callback(null, chunk);
|
||||
},
|
||||
}),
|
||||
output,
|
||||
);
|
||||
|
||||
if (
|
||||
(size !== null && received !== size) ||
|
||||
`sha256:${hash.digest('hex')}` !== asset.digest
|
||||
) {
|
||||
throw new Error('更新包校验失败');
|
||||
}
|
||||
|
||||
break;
|
||||
} catch (error) {
|
||||
if (error && typeof error === 'object' && 'code' in error && error.code === 'EEXIST') {
|
||||
throw error;
|
||||
}
|
||||
|
||||
failures.push(error instanceof Error ? error.message : String(error));
|
||||
|
||||
if (index === urls.length - 1) {
|
||||
throw new Error([...new Set(failures)].join(';'));
|
||||
}
|
||||
|
||||
if (created) {
|
||||
await rm(archive);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const payload = path.join(directory, 'payload');
|
||||
|
||||
196
packages/core/src/update/release.ts
Normal file
196
packages/core/src/update/release.ts
Normal file
@@ -0,0 +1,196 @@
|
||||
import { parseVersion } from '@snowluma/common/semver';
|
||||
import type { UpdateSourceConfig } from '@snowluma/common/update-source';
|
||||
import { RELEASE_ROOT, sourceUrls } from './sources';
|
||||
|
||||
export function assetName(version: string, target: string): string {
|
||||
const platform = target.replace('win32', 'win');
|
||||
return `SnowLuma-v${version}-${platform}-lite.${target.startsWith('win32') ? 'zip' : 'tar.gz'}`;
|
||||
}
|
||||
|
||||
async function readText(response: Response, limit: number): Promise<string> {
|
||||
if (!response.body) {
|
||||
throw new Error('发布信息为空');
|
||||
}
|
||||
|
||||
const reader = response.body.getReader();
|
||||
const chunks: Uint8Array[] = [];
|
||||
let size = 0;
|
||||
|
||||
try {
|
||||
for (;;) {
|
||||
const { value, done } = await reader.read();
|
||||
|
||||
if (done) {
|
||||
break;
|
||||
}
|
||||
|
||||
size += value.length;
|
||||
|
||||
if (size > limit) {
|
||||
await reader.cancel();
|
||||
throw new Error('发布信息过大');
|
||||
}
|
||||
|
||||
chunks.push(value);
|
||||
}
|
||||
} finally {
|
||||
reader.releaseLock();
|
||||
}
|
||||
|
||||
return Buffer.concat(chunks).toString('utf8');
|
||||
}
|
||||
|
||||
function attribute(tag: string, name: string): string | undefined {
|
||||
return new RegExp(`\\s${name}\\s*=\\s*(["'])(.*?)\\1`, 'i')
|
||||
.exec(tag)?.[2]
|
||||
.replaceAll('&', '&')
|
||||
.replaceAll(''', "'")
|
||||
.replaceAll('"', '"');
|
||||
}
|
||||
|
||||
export function parseLatestReleasePage(html: string) {
|
||||
const meta = html
|
||||
.match(/<meta\b[^>]*>/gi)
|
||||
?.find((tag) => attribute(tag, 'property') === 'og:url');
|
||||
const canonical = meta && attribute(meta, 'content');
|
||||
|
||||
if (!canonical) {
|
||||
throw new Error('发布页面缺少版本信息');
|
||||
}
|
||||
|
||||
const url = new URL(canonical, 'https://github.com');
|
||||
const tag = /^\/SnowLuma\/SnowLuma\/releases\/tag\/([^/]+)$/.exec(url.pathname)?.[1];
|
||||
const decoded = tag && decodeURIComponent(tag);
|
||||
const version = decoded?.startsWith('v') ? decoded.slice(1) : undefined;
|
||||
const parsed = parseVersion(version);
|
||||
|
||||
if (url.origin !== 'https://github.com' || !parsed || parsed.prerelease.length) {
|
||||
throw new Error('发布页面不是 SnowLuma 正式版本');
|
||||
}
|
||||
|
||||
return { tag_name: `v${parsed.raw}`, html_url: `${RELEASE_ROOT}/tag/v${parsed.raw}` };
|
||||
}
|
||||
|
||||
/** Match the digest in the same asset row; never borrow a neighbouring asset's hash. */
|
||||
export function parseReleaseAssetsPage(html: string, version: string) {
|
||||
const assets: { name: string; size: null; digest: string }[] = [];
|
||||
const expected = ['win32-x64', 'linux-x64', 'linux-arm64'].map((target) =>
|
||||
assetName(version, target),
|
||||
);
|
||||
|
||||
for (const row of html.match(/<li\b[^>]*>[\s\S]*?<\/li>/gi) ?? []) {
|
||||
const links = row.match(/<a\b[^>]*>/gi) ?? [];
|
||||
const name = expected.find((candidate) =>
|
||||
links.some((link) => {
|
||||
const href = attribute(link, 'href');
|
||||
return (
|
||||
href === `/SnowLuma/SnowLuma/releases/download/v${version}/${candidate}` ||
|
||||
href === `${RELEASE_ROOT}/download/v${version}/${candidate}`
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
if (!name) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const digests = (row.match(/<clipboard-copy\b[^>]*>/gi) ?? [])
|
||||
.map((tag) => attribute(tag, 'value'))
|
||||
.filter((value): value is string =>
|
||||
Boolean(value && /^sha256:[a-f0-9]{64}$/.test(value)),
|
||||
);
|
||||
|
||||
if (digests.length !== 1 || assets.some((asset) => asset.name === name)) {
|
||||
throw new Error('发布页面缺少唯一的文件校验信息');
|
||||
}
|
||||
|
||||
// GitHub renders a rounded size in HTML. Verify the exact digest even
|
||||
// when a proxy streams the asset without Content-Length.
|
||||
assets.push({ name, size: null, digest: digests[0]! });
|
||||
}
|
||||
|
||||
if (!assets.length) {
|
||||
throw new Error('发布页面没有可验证的更新包');
|
||||
}
|
||||
|
||||
return { tag_name: `v${version}`, assets };
|
||||
}
|
||||
|
||||
export interface ReleaseResult {
|
||||
data: unknown;
|
||||
fromPage: boolean;
|
||||
}
|
||||
|
||||
export async function fetchRelease(
|
||||
version: string | undefined,
|
||||
source: UpdateSourceConfig,
|
||||
userAgent = 'SnowLuma',
|
||||
timeoutMs = 8_000,
|
||||
): Promise<ReleaseResult> {
|
||||
const apiUrl = `https://api.github.com/repos/SnowLuma/SnowLuma/releases/${version ? `tags/v${version}` : 'latest'}`;
|
||||
let primaryError: unknown;
|
||||
|
||||
try {
|
||||
const response = await fetch(apiUrl, {
|
||||
headers: {
|
||||
Accept: 'application/vnd.github+json',
|
||||
'User-Agent': userAgent,
|
||||
'X-GitHub-Api-Version': '2022-11-28',
|
||||
},
|
||||
signal: AbortSignal.timeout(timeoutMs),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
await response.body?.cancel();
|
||||
throw new Error(`GitHub ${response.status}`);
|
||||
}
|
||||
|
||||
return {
|
||||
data: JSON.parse(await readText(response, 256 * 1024)) as unknown,
|
||||
fromPage: false,
|
||||
};
|
||||
} catch (error) {
|
||||
primaryError = error;
|
||||
}
|
||||
|
||||
const originalUrl = version
|
||||
? `${RELEASE_ROOT}/expanded_assets/v${version}`
|
||||
: `${RELEASE_ROOT}/latest`;
|
||||
const controller = new AbortController();
|
||||
|
||||
try {
|
||||
// Only a parsed release page can win. Fast errors and HTML interstitials
|
||||
// cannot cancel a slower working source.
|
||||
// Download proxies often only support assets. Always retain GitHub's
|
||||
// release page for version/digest lookup, even with a pinned download mirror.
|
||||
const urls = [...new Set([originalUrl, ...sourceUrls(originalUrl, source)])];
|
||||
const data = await Promise.any(
|
||||
urls.map(async (url) => {
|
||||
const response = await fetch(url, {
|
||||
signal: AbortSignal.any([controller.signal, AbortSignal.timeout(timeoutMs)]),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
await response.body?.cancel();
|
||||
throw new Error(`HTTP ${response.status}`);
|
||||
}
|
||||
|
||||
const html = await readText(response, 1024 * 1024);
|
||||
return version
|
||||
? parseReleaseAssetsPage(html, version)
|
||||
: parseLatestReleasePage(html);
|
||||
}),
|
||||
);
|
||||
return { data, fromPage: true };
|
||||
} catch (error) {
|
||||
const failures = error instanceof AggregateError ? error.errors : [error];
|
||||
const details = [primaryError, ...failures]
|
||||
.filter(Boolean)
|
||||
.map((failure: unknown) =>
|
||||
failure instanceof Error ? failure.message : String(failure),
|
||||
);
|
||||
throw new Error(`${[...new Set(details)].join(';')};请在更新来源中检测或指定可用镜像`);
|
||||
} finally {
|
||||
controller.abort();
|
||||
}
|
||||
}
|
||||
125
packages/core/src/update/sources.ts
Normal file
125
packages/core/src/update/sources.ts
Normal file
@@ -0,0 +1,125 @@
|
||||
import { APP_VERSION } from '@snowluma/common/version';
|
||||
import { readRuntimeConfig, updateRuntimeConfig } from '@snowluma/common/runtime';
|
||||
import {
|
||||
normalizeUpdateSourceConfig,
|
||||
type UpdateSourceConfig,
|
||||
} from '@snowluma/common/update-source';
|
||||
|
||||
export const RELEASE_ROOT = 'https://github.com/SnowLuma/SnowLuma/releases';
|
||||
export const DEFAULT_UPDATE_SOURCE: UpdateSourceConfig = {
|
||||
mode: 'auto',
|
||||
mirror: '',
|
||||
mirrors: [
|
||||
'https://ghfast.top',
|
||||
'https://ghproxy.net',
|
||||
'https://gh-proxy.com',
|
||||
'https://github.chenc.dev',
|
||||
'https://fastgit.cc',
|
||||
'https://gh.noki.icu',
|
||||
'https://cors.isteed.cc',
|
||||
'https://gh-proxy.org',
|
||||
'https://githubproxy.gohj99.site',
|
||||
'https://github.xxlab.tech',
|
||||
],
|
||||
};
|
||||
|
||||
export function readUpdateSource(): UpdateSourceConfig {
|
||||
return normalizeUpdateSourceConfig(readRuntimeConfig().updateSource ?? DEFAULT_UPDATE_SOURCE);
|
||||
}
|
||||
|
||||
export function saveUpdateSource(value: unknown): UpdateSourceConfig {
|
||||
const config = normalizeUpdateSourceConfig(value);
|
||||
updateRuntimeConfig({ updateSource: config });
|
||||
return config;
|
||||
}
|
||||
|
||||
export function sourceUrls(url: string, config: UpdateSourceConfig): string[] {
|
||||
if (config.mode === 'direct') {
|
||||
return [url];
|
||||
}
|
||||
|
||||
if (config.mode === 'mirror') {
|
||||
return [`${config.mirror}/${url}`];
|
||||
}
|
||||
|
||||
return [url, ...config.mirrors.map((mirror) => `${mirror}/${url}`)];
|
||||
}
|
||||
|
||||
export interface MirrorProbeResult {
|
||||
mirror: string;
|
||||
available: boolean;
|
||||
latencyMs: number;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export async function testUpdateSources(value: unknown): Promise<MirrorProbeResult[]> {
|
||||
const config = normalizeUpdateSourceConfig(value);
|
||||
const mirrors = [
|
||||
...new Set(['', ...config.mirrors, ...(config.mirror ? [config.mirror] : [])]),
|
||||
];
|
||||
const target = process.platform === 'win32' ? 'win-x64' : `linux-${process.arch}`;
|
||||
const extension = process.platform === 'win32' ? 'zip' : 'tar.gz';
|
||||
const probeUrl = `${RELEASE_ROOT}/download/v${APP_VERSION}/SnowLuma-v${APP_VERSION}-${target}-lite.${extension}`;
|
||||
const results = await Promise.all(
|
||||
mirrors.map(async (mirror): Promise<MirrorProbeResult> => {
|
||||
const start = performance.now();
|
||||
|
||||
try {
|
||||
const response = await fetch(mirror ? `${mirror}/${probeUrl}` : probeUrl, {
|
||||
headers: { Range: 'bytes=0-3' },
|
||||
signal: AbortSignal.timeout(5_000),
|
||||
});
|
||||
|
||||
if (!response.ok || !response.body) {
|
||||
await response.body?.cancel();
|
||||
throw new Error(`HTTP ${response.status}`);
|
||||
}
|
||||
|
||||
if (/text\/html/i.test(response.headers.get('content-type') ?? '')) {
|
||||
await response.body.cancel();
|
||||
throw new Error('返回了 HTML 页面,而不是更新包');
|
||||
}
|
||||
|
||||
const reader = response.body.getReader();
|
||||
const prefix: number[] = [];
|
||||
|
||||
try {
|
||||
while (prefix.length < 4) {
|
||||
const { value, done } = await reader.read();
|
||||
|
||||
if (done) {
|
||||
break;
|
||||
}
|
||||
|
||||
prefix.push(...value.subarray(0, 4 - prefix.length));
|
||||
}
|
||||
} finally {
|
||||
await reader.cancel();
|
||||
reader.releaseLock();
|
||||
}
|
||||
|
||||
const signature = extension === 'zip' ? [0x50, 0x4b, 0x03, 0x04] : [0x1f, 0x8b];
|
||||
|
||||
if (!signature.every((byte, index) => prefix[index] === byte)) {
|
||||
throw new Error('返回内容不是有效的更新包');
|
||||
}
|
||||
|
||||
return {
|
||||
mirror,
|
||||
available: true,
|
||||
latencyMs: Math.round(performance.now() - start),
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
mirror,
|
||||
available: false,
|
||||
latencyMs: Math.round(performance.now() - start),
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
};
|
||||
}
|
||||
}),
|
||||
);
|
||||
return results.sort(
|
||||
(a, b) => Number(b.available) - Number(a.available) || a.latencyMs - b.latencyMs,
|
||||
);
|
||||
}
|
||||
@@ -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 });
|
||||
|
||||
|
||||
34
packages/core/src/webui/static-frontend.ts
Normal file
34
packages/core/src/webui/static-frontend.ts
Normal 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);
|
||||
});
|
||||
}
|
||||
@@ -1,10 +1,52 @@
|
||||
import { Hono } from 'hono';
|
||||
import type { HttpBindings } from '@hono/node-server';
|
||||
import type { UpdateService } from '../update/service';
|
||||
import { readUpdateSource, saveUpdateSource, testUpdateSources } from '../update/sources';
|
||||
import {
|
||||
normalizeUpdateSourceConfig,
|
||||
type UpdateSourceConfig,
|
||||
} from '@snowluma/common/update-source';
|
||||
|
||||
export function updateRoutes(service: UpdateService, restart: () => void) {
|
||||
const app = new Hono<{ Bindings: HttpBindings }>();
|
||||
app.get('/status', (c) => c.json(service.status()));
|
||||
app.get('/sources', (c) => {
|
||||
try {
|
||||
return c.json({ config: readUpdateSource() });
|
||||
} catch (error) {
|
||||
return c.json({ message: error instanceof Error ? error.message : String(error) }, 500);
|
||||
}
|
||||
});
|
||||
app.post('/sources', async (c) => {
|
||||
let config: UpdateSourceConfig;
|
||||
|
||||
try {
|
||||
config = normalizeUpdateSourceConfig(await c.req.json());
|
||||
} catch (error) {
|
||||
return c.json({ message: error instanceof Error ? error.message : String(error) }, 400);
|
||||
}
|
||||
|
||||
try {
|
||||
saveUpdateSource(config);
|
||||
return c.json({
|
||||
config,
|
||||
saved: true,
|
||||
applied: true,
|
||||
online: true,
|
||||
errors: [],
|
||||
message: '更新来源已保存',
|
||||
});
|
||||
} catch (error) {
|
||||
return c.json({ message: error instanceof Error ? error.message : String(error) }, 500);
|
||||
}
|
||||
});
|
||||
app.post('/sources/test', async (c) => {
|
||||
try {
|
||||
return c.json({ results: await testUpdateSources(await c.req.json()) });
|
||||
} catch (error) {
|
||||
return c.json({ message: error instanceof Error ? error.message : String(error) }, 400);
|
||||
}
|
||||
});
|
||||
app.post('/download', async (c) => {
|
||||
let body: unknown;
|
||||
|
||||
|
||||
@@ -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);
|
||||
|
||||
389
packages/core/tests/actions/forward-nested-fetch.test.ts
Normal file
389
packages/core/tests/actions/forward-nested-fetch.test.ts
Normal file
@@ -0,0 +1,389 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { deflateSync, gzipSync } from 'zlib';
|
||||
import { buildApiContext, type OneBotInstanceContext } from '@snowluma/onebot/instance-context';
|
||||
import type { Elem } from '@snowluma/proto-defs/element';
|
||||
import type { LongMsgResult, RecvLongMsgReq, RecvLongMsgResp } from '@snowluma/proto-defs/longmsg';
|
||||
import type { PushMsgBody } from '@snowluma/proto-defs/message';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import { ForwardApi } from '../../src/bridge/apis/forward';
|
||||
import type { BridgeContext } from '../../src/bridge/bridge-context';
|
||||
import { mockBridge } from './_helpers';
|
||||
|
||||
function forwardCard(format: 'xml' | 'lightApp', resId: string, key?: string): Elem {
|
||||
const content =
|
||||
format === 'xml'
|
||||
? `<msg serviceID="35" m_resid="${resId}"${key ? ` m_fileName="${key}"` : ''} />`
|
||||
: JSON.stringify({
|
||||
app: 'com.tencent.multimsg',
|
||||
meta: { detail: { resid: resId, uniseq: key } },
|
||||
});
|
||||
const data = Buffer.concat([Buffer.from([1]), deflateSync(Buffer.from(content))]);
|
||||
return format === 'xml'
|
||||
? { richMsg: { serviceId: 35, template1: data } }
|
||||
: { lightApp: { data } };
|
||||
}
|
||||
|
||||
function message(...elems: Elem[]): PushMsgBody {
|
||||
return {
|
||||
responseHead: {
|
||||
fromUin: 20002,
|
||||
fromUid: 'sender-uid',
|
||||
grp: { groupUin: 12345, memberCard: 'alice' },
|
||||
},
|
||||
contentHead: { msgType: 82, sequence: 10, timestamp: 1700000000 },
|
||||
body: { richText: { elems } },
|
||||
};
|
||||
}
|
||||
|
||||
function setup(downloads: Map<string, LongMsgResult>, selfUin = '10001') {
|
||||
const requested: string[] = [];
|
||||
const bridge = mockBridge({
|
||||
sendRawPacket: vi.fn(async (command: string, bytes: Uint8Array) => {
|
||||
expect(command).toBe('trpc.group.long_msg_interface.MsgService.SsoRecvLongMsg');
|
||||
const resId = protobuf_decode<RecvLongMsgReq>(bytes).info!.resId!;
|
||||
requested.push(resId);
|
||||
const data = downloads.get(resId);
|
||||
return {
|
||||
success: true,
|
||||
gotResponse: true,
|
||||
errorCode: 0,
|
||||
errorMessage: '',
|
||||
responseData: Buffer.from(
|
||||
protobuf_encode<RecvLongMsgResp>({
|
||||
result: {
|
||||
resId,
|
||||
payload: data
|
||||
? gzipSync(protobuf_encode<LongMsgResult>(data))
|
||||
: undefined,
|
||||
},
|
||||
}),
|
||||
),
|
||||
};
|
||||
}),
|
||||
});
|
||||
bridge.identity.uin = selfUin;
|
||||
const forward = new ForwardApi(bridge as unknown as BridgeContext);
|
||||
const ctx = {
|
||||
selfId: Number(selfUin),
|
||||
bridge: { apis: { forward } },
|
||||
converterCtx: {
|
||||
selfId: Number(selfUin),
|
||||
imageUrlResolver: null,
|
||||
mediaUrlResolver: null,
|
||||
messageIdResolver: null,
|
||||
mediaSegmentSink: null,
|
||||
},
|
||||
} as unknown as OneBotInstanceContext;
|
||||
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',
|
||||
async (format) => {
|
||||
const outer = `nested-fetch-${format}-outer`;
|
||||
const inner = `nested-fetch-${format}-inner`;
|
||||
const sibling = `nested-fetch-${format}-sibling`;
|
||||
const leaf = `nested-fetch-${format}-leaf`;
|
||||
const { api, requested } = setup(
|
||||
new Map([
|
||||
[
|
||||
outer,
|
||||
{
|
||||
action: [
|
||||
{
|
||||
actionCommand: 'MultiMsg',
|
||||
actionData: {
|
||||
msgBody: [
|
||||
message(forwardCard(format, inner, 'inner-key')),
|
||||
message(forwardCard(format, sibling, 'sibling-key')),
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
actionCommand: 'leaf-key',
|
||||
actionData: {
|
||||
msgBody: [
|
||||
message(
|
||||
{ text: { str: 'deepest content' } },
|
||||
{
|
||||
customFace: {
|
||||
md5: Buffer.alloc(16, 0xab),
|
||||
origUrl: 'https://example.com/forward.png',
|
||||
width: 32,
|
||||
height: 24,
|
||||
},
|
||||
},
|
||||
),
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
actionCommand: 'sibling-key',
|
||||
actionData: {
|
||||
msgBody: [message({ text: { str: 'sibling content' } })],
|
||||
},
|
||||
},
|
||||
{
|
||||
actionCommand: 'inner-key',
|
||||
actionData: {
|
||||
msgBody: [message(forwardCard(format, leaf, 'leaf-key'))],
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
]),
|
||||
);
|
||||
|
||||
const parent = await api.getForwardMsg(outer);
|
||||
expect(parent.map((node) => node.message)).toEqual([
|
||||
[{ type: 'forward', data: { id: inner } }],
|
||||
[{ type: 'forward', data: { id: sibling } }],
|
||||
]);
|
||||
const middle = await api.getForwardMsg(inner);
|
||||
expect(middle[0]!.message).toEqual([{ type: 'forward', data: { id: leaf } }]);
|
||||
expect((await api.getForwardMsg(leaf))[0]).toMatchObject({
|
||||
sender: { user_id: 20002, nickname: 'alice' },
|
||||
time: 1700000000,
|
||||
message: [
|
||||
{ type: 'text', data: { text: 'deepest content' } },
|
||||
{ type: 'image', data: { url: 'https://example.com/forward.png' } },
|
||||
],
|
||||
});
|
||||
expect((await api.getForwardMsg(sibling))[0]!.message).toEqual([
|
||||
{ type: 'text', data: { text: 'sibling content' } },
|
||||
]);
|
||||
expect(requested).toEqual([outer]);
|
||||
},
|
||||
);
|
||||
|
||||
it.each([undefined, 'unmatched-key'])(
|
||||
'downloads by resId when the XML filename is %s and preserves empty-payload errors',
|
||||
async (key) => {
|
||||
const outer = `nested-fetch-fallback-${key}-outer`;
|
||||
const inner = `nested-fetch-fallback-${key}-inner`;
|
||||
const empty = `nested-fetch-fallback-${key}-empty`;
|
||||
const { api, requested } = setup(
|
||||
new Map([
|
||||
[
|
||||
outer,
|
||||
{
|
||||
action: [
|
||||
{
|
||||
actionCommand: 'MultiMsg',
|
||||
actionData: {
|
||||
msgBody: [
|
||||
message(forwardCard('xml', inner, key)),
|
||||
message(forwardCard('xml', empty, key)),
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
actionCommand: 'unrelated-key',
|
||||
actionData: {
|
||||
msgBody: [message({ text: { str: 'unrelated content' } })],
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
[
|
||||
inner,
|
||||
{
|
||||
action: [
|
||||
{
|
||||
actionCommand: 'MultiMsg',
|
||||
actionData: {
|
||||
msgBody: [message({ text: { str: 'downloaded content' } })],
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
]),
|
||||
);
|
||||
|
||||
await api.getForwardMsg(outer);
|
||||
expect((await api.getForwardMsg(inner))[0]!.message).toEqual([
|
||||
{ type: 'text', data: { text: 'downloaded content' } },
|
||||
]);
|
||||
await expect(api.getForwardMsg(empty)).rejects.toThrow(
|
||||
'download forward message payload is empty',
|
||||
);
|
||||
expect(requested).toEqual([outer, inner, empty]);
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -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'];
|
||||
|
||||
@@ -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(
|
||||
|
||||
234
packages/core/tests/bridge-client-message.test.ts
Normal file
234
packages/core/tests/bridge-client-message.test.ts
Normal 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();
|
||||
});
|
||||
});
|
||||
@@ -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);
|
||||
|
||||
@@ -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],
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
@@ -5,10 +5,14 @@ import path from 'node:path';
|
||||
import { zipSync } from 'fflate';
|
||||
import { c as createTar } from 'tar';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { archivePath, assetName, downloadUpdate } from '../src/update/download';
|
||||
import { archivePath, assetName, downloadUpdate as download } from '../src/update/download';
|
||||
import { readManifest } from '../src/update/files';
|
||||
import { releaseFixture } from './helpers/update-fixture';
|
||||
|
||||
const direct = { mode: 'direct', mirror: '', mirrors: [] } as const;
|
||||
const downloadUpdate = (directory: string, version: string, target: string) =>
|
||||
download(directory, version, target, { ...direct, mirrors: [] });
|
||||
|
||||
let root: string;
|
||||
beforeEach(async () => {
|
||||
root = await mkdtemp(path.join(os.tmpdir(), 'snowluma-download-test-'));
|
||||
@@ -43,6 +47,105 @@ function mockRelease(bytes: Uint8Array, target: string, digest?: string) {
|
||||
}
|
||||
|
||||
describe('release downloads', () => {
|
||||
it.each(['403', 'html', 'corrupt', 'interrupted'])(
|
||||
'cleans and retries a %s response through a mirror using HTML release checksums',
|
||||
async (failure) => {
|
||||
const manifest = await releaseFixture(path.join(root, 'source'), '2.0.0', 'win32-x64');
|
||||
const bytes = zipSync({
|
||||
'release.json': new TextEncoder().encode(JSON.stringify(manifest)),
|
||||
'app.mjs': new TextEncoder().encode('verified payload'),
|
||||
});
|
||||
const name = assetName('2.0.0', 'win32-x64');
|
||||
const digest = createHash('sha256').update(bytes).digest('hex');
|
||||
const fetchMock = vi.fn<typeof fetch>(async (input) => {
|
||||
const url = String(input);
|
||||
|
||||
if (url.includes('api.github.com')) {
|
||||
return new Response('rate limited', { status: 403 });
|
||||
}
|
||||
|
||||
if (url.includes('/expanded_assets/')) {
|
||||
return new Response(
|
||||
`<li><a href="/SnowLuma/SnowLuma/releases/download/v2.0.0/${name}">asset</a><clipboard-copy value="sha256:${digest}"></clipboard-copy></li>`,
|
||||
);
|
||||
}
|
||||
|
||||
if (url.startsWith('https://working.example/')) {
|
||||
// Mirrors may stream a verified archive without Content-Length.
|
||||
return new Response(new Uint8Array(bytes));
|
||||
}
|
||||
|
||||
if (failure === '403') {
|
||||
return new Response('blocked', { status: 403 });
|
||||
}
|
||||
|
||||
if (failure === 'html') {
|
||||
return new Response('<html>challenge</html>', {
|
||||
headers: { 'Content-Type': 'text/html' },
|
||||
});
|
||||
}
|
||||
|
||||
if (failure === 'interrupted') {
|
||||
let sent = false;
|
||||
return new Response(
|
||||
new ReadableStream({
|
||||
pull(controller) {
|
||||
if (sent) {
|
||||
controller.error(new Error('connection reset'));
|
||||
} else {
|
||||
controller.enqueue(new Uint8Array([1, 2, 3]));
|
||||
sent = true;
|
||||
}
|
||||
},
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
return new Response('corrupt archive');
|
||||
});
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
await download(root, '2.0.0', 'win32-x64', {
|
||||
mode: 'auto',
|
||||
mirror: '',
|
||||
mirrors: ['https://working.example'],
|
||||
});
|
||||
expect(await readFile(path.join(root, 'archive'))).toEqual(Buffer.from(bytes));
|
||||
expect(await readFile(path.join(root, 'payload/app.mjs'), 'utf8')).toBe(
|
||||
'verified payload',
|
||||
);
|
||||
expect(
|
||||
fetchMock.mock.calls
|
||||
.filter(([url]) => String(url).includes('/download/'))
|
||||
.map(([url]) => String(url)),
|
||||
).toEqual([
|
||||
`https://github.com/SnowLuma/SnowLuma/releases/download/v2.0.0/${name}`,
|
||||
`https://working.example/https://github.com/SnowLuma/SnowLuma/releases/download/v2.0.0/${name}`,
|
||||
]);
|
||||
},
|
||||
);
|
||||
|
||||
it('does not try other download sources in pinned mode', async () => {
|
||||
const bytes = new Uint8Array([1, 2, 3]);
|
||||
const fetchMock = mockRelease(bytes, 'win32-x64');
|
||||
const original = fetchMock.getMockImplementation()!;
|
||||
fetchMock.mockImplementation(async (input) =>
|
||||
String(input).includes('api.github.com')
|
||||
? original(input)
|
||||
: new Response('blocked', { status: 403 }),
|
||||
);
|
||||
await expect(
|
||||
download(root, '2.0.0', 'win32-x64', {
|
||||
mode: 'mirror',
|
||||
mirror: 'https://pinned.example',
|
||||
mirrors: ['https://other.example'],
|
||||
}),
|
||||
).rejects.toThrow('HTTP 403');
|
||||
expect(fetchMock.mock.calls.map(([url]) => url)).toEqual([
|
||||
'https://api.github.com/repos/SnowLuma/SnowLuma/releases/tags/v2.0.0',
|
||||
`https://pinned.example/https://github.com/SnowLuma/SnowLuma/releases/download/v2.0.0/${assetName('2.0.0', 'win32-x64')}`,
|
||||
]);
|
||||
expect(await readdir(root)).toEqual([]);
|
||||
});
|
||||
it.each(['win32-x64', 'linux-x64', 'linux-arm64'])(
|
||||
'downloads and validates the %s lite package',
|
||||
async (target) => {
|
||||
|
||||
@@ -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,
|
||||
});
|
||||
|
||||
126
packages/core/tests/update-release.test.ts
Normal file
126
packages/core/tests/update-release.test.ts
Normal file
@@ -0,0 +1,126 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import type { UpdateSourceConfig } from '@snowluma/common/update-source';
|
||||
import {
|
||||
assetName,
|
||||
fetchRelease,
|
||||
parseLatestReleasePage,
|
||||
parseReleaseAssetsPage,
|
||||
} from '../src/update/release';
|
||||
|
||||
const direct: UpdateSourceConfig = { mode: 'direct', mirror: '', mirrors: [] };
|
||||
const latest =
|
||||
'<meta property="og:url" content="https://github.com/SnowLuma/SnowLuma/releases/tag/v2.0.1">';
|
||||
const digest = `sha256:${'a'.repeat(64)}`;
|
||||
const name = assetName('2.0.1', 'win32-x64');
|
||||
const row = `<li><a href="/SnowLuma/SnowLuma/releases/download/v2.0.1/${name}">${name}</a><clipboard-copy value="${digest}"></clipboard-copy></li>`;
|
||||
|
||||
afterEach(() => vi.unstubAllGlobals());
|
||||
|
||||
describe('existing GitHub release pages', () => {
|
||||
it('reads the canonical stable release without a new metadata asset', () => {
|
||||
expect(parseLatestReleasePage(latest)).toEqual({
|
||||
tag_name: 'v2.0.1',
|
||||
html_url: 'https://github.com/SnowLuma/SnowLuma/releases/tag/v2.0.1',
|
||||
});
|
||||
expect(parseLatestReleasePage(latest.replace('https://github.com', '')).tag_name).toBe(
|
||||
'v2.0.1',
|
||||
);
|
||||
});
|
||||
|
||||
it.each([
|
||||
'<html>please sign in</html>',
|
||||
latest.replace('github.com', 'unrelated.example'),
|
||||
latest.replace('/SnowLuma/SnowLuma/', '/other/project/'),
|
||||
latest.replace('v2.0.1', 'v02.0.1'),
|
||||
latest.replace('v2.0.1', 'v2.0.1-rc.1'),
|
||||
])('rejects non-release or invalid version pages', (html) => {
|
||||
expect(() => parseLatestReleasePage(html)).toThrow();
|
||||
});
|
||||
|
||||
it('matches an asset with its own digest, ignoring rounded HTML sizes', () => {
|
||||
expect(parseReleaseAssetsPage(row, '2.0.1')).toEqual({
|
||||
tag_name: 'v2.0.1',
|
||||
assets: [{ name, size: null, digest }],
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
row.replace('v2.0.1/', 'v2.0.0/'),
|
||||
row.replace(digest, 'unavailable'),
|
||||
row + row,
|
||||
row.replace(`<clipboard-copy value="${digest}"></clipboard-copy>`, '') +
|
||||
`<li><clipboard-copy value="${digest}"></clipboard-copy></li>`,
|
||||
])('rejects absent, ambiguous or neighbouring checksum data', (html) => {
|
||||
expect(() => parseReleaseAssetsPage(html, '2.0.1')).toThrow();
|
||||
});
|
||||
|
||||
it('falls back from API 403 to the existing release page', async () => {
|
||||
const fetchMock = vi.fn<typeof fetch>(async (url) =>
|
||||
String(url).includes('api.github.com')
|
||||
? new Response('rate limited', { status: 403 })
|
||||
: new Response(latest),
|
||||
);
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
expect(await fetchRelease(undefined, direct)).toMatchObject({
|
||||
fromPage: true,
|
||||
data: { tag_name: 'v2.0.1' },
|
||||
});
|
||||
expect(fetchMock.mock.calls.map(([url]) => url)).toEqual([
|
||||
'https://api.github.com/repos/SnowLuma/SnowLuma/releases/latest',
|
||||
'https://github.com/SnowLuma/SnowLuma/releases/latest',
|
||||
]);
|
||||
});
|
||||
|
||||
it('waits for a valid mirror page after fast invalid responses and cancels other requests', async () => {
|
||||
let finish!: (response: Response) => void;
|
||||
const pending = new Promise<Response>((resolve) => {
|
||||
finish = resolve;
|
||||
});
|
||||
const fetchMock = vi.fn<typeof fetch>(async (url) => {
|
||||
if (String(url).startsWith('https://working.example/')) {
|
||||
return pending;
|
||||
}
|
||||
|
||||
return new Response('HTML challenge');
|
||||
});
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
const result = fetchRelease('2.0.1', {
|
||||
...direct,
|
||||
mode: 'auto',
|
||||
mirrors: ['https://bad.example', 'https://working.example'],
|
||||
});
|
||||
await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(4));
|
||||
finish(new Response(row));
|
||||
expect(await result).toMatchObject({
|
||||
fromPage: true,
|
||||
data: { assets: [{ name, digest }] },
|
||||
});
|
||||
expect(fetchMock.mock.calls.slice(1).every(([, options]) => options?.signal?.aborted)).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
it('keeps direct release lookup when the pinned download mirror cannot serve pages', async () => {
|
||||
const fetchMock = vi.fn<typeof fetch>(async (url) =>
|
||||
String(url) === 'https://github.com/SnowLuma/SnowLuma/releases/latest'
|
||||
? new Response(latest)
|
||||
: new Response('blocked', { status: 403 }),
|
||||
);
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
expect(
|
||||
await fetchRelease(undefined, {
|
||||
...direct,
|
||||
mode: 'mirror',
|
||||
mirror: 'https://files.example',
|
||||
}),
|
||||
).toMatchObject({ data: { tag_name: 'v2.0.1' } });
|
||||
});
|
||||
|
||||
it('rejects oversized release responses', async () => {
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn(async () => new Response('x'.repeat(1024 * 1024 + 1))),
|
||||
);
|
||||
await expect(fetchRelease(undefined, direct)).rejects.toThrow('发布信息过大');
|
||||
});
|
||||
});
|
||||
105
packages/core/tests/update-source-routes.test.ts
Normal file
105
packages/core/tests/update-source-routes.test.ts
Normal file
@@ -0,0 +1,105 @@
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { readRuntimeConfig, updateRuntimeConfig } from '@snowluma/common/runtime';
|
||||
import { createUpdateService } from '../src/update/service';
|
||||
import { updateRoutes } from '../src/webui/update-routes';
|
||||
|
||||
let directory: string;
|
||||
let previous: string;
|
||||
beforeEach(() => {
|
||||
directory = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-update-sources-'));
|
||||
previous = process.cwd();
|
||||
process.chdir(directory);
|
||||
});
|
||||
afterEach(() => {
|
||||
process.chdir(previous);
|
||||
vi.restoreAllMocks();
|
||||
vi.unstubAllGlobals();
|
||||
fs.rmSync(directory, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
async function routes() {
|
||||
return updateRoutes(await createUpdateService(undefined, '2.0.1'), vi.fn());
|
||||
}
|
||||
|
||||
describe('update source routes', () => {
|
||||
it('returns a JSON error when persisted source settings are invalid', async () => {
|
||||
fs.mkdirSync('config');
|
||||
fs.writeFileSync(
|
||||
'config/runtime.json',
|
||||
JSON.stringify({ updateSource: { mode: 'invalid' } }),
|
||||
);
|
||||
const response = await (await routes()).request('/sources');
|
||||
expect(response.status).toBe(500);
|
||||
expect(response.headers.get('content-type')).toContain('application/json');
|
||||
expect(await response.json()).toMatchObject({
|
||||
message: expect.stringContaining('模式无效'),
|
||||
});
|
||||
});
|
||||
it('persists settings for subsequent reads without changing other runtime values', async () => {
|
||||
updateRuntimeConfig({ webuiPort: 6789, webuiHost: '127.0.0.2' });
|
||||
const app = await routes();
|
||||
const config = {
|
||||
mode: 'mirror',
|
||||
mirror: 'https://example.com/proxy/',
|
||||
mirrors: ['https://second.example/'],
|
||||
};
|
||||
const response = await app.request('/sources', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(config),
|
||||
});
|
||||
expect(response.status).toBe(200);
|
||||
const normalized = {
|
||||
...config,
|
||||
mirror: 'https://example.com/proxy',
|
||||
mirrors: ['https://second.example'],
|
||||
};
|
||||
expect(await response.json()).toMatchObject({
|
||||
config: normalized,
|
||||
saved: true,
|
||||
applied: true,
|
||||
errors: [],
|
||||
});
|
||||
expect(readRuntimeConfig()).toMatchObject({
|
||||
updateSource: normalized,
|
||||
webuiPort: 6789,
|
||||
webuiHost: '127.0.0.2',
|
||||
});
|
||||
expect(await (await app.request('/sources')).json()).toEqual({ config: normalized });
|
||||
});
|
||||
|
||||
it.each(['not json', '{}', '[]', '{"mode":"mirror","mirrors":[]}'])(
|
||||
'rejects malformed input without saving or fetching: %s',
|
||||
async (body) => {
|
||||
const fetchMock = vi.fn();
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
const app = await routes();
|
||||
|
||||
for (const endpoint of ['/sources', '/sources/test']) {
|
||||
expect((await app.request(endpoint, { method: 'POST', body })).status).toBe(400);
|
||||
}
|
||||
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
expect(fs.existsSync('config/runtime.json')).toBe(false);
|
||||
},
|
||||
);
|
||||
|
||||
it('reports a persistence failure without claiming the config was saved', async () => {
|
||||
updateRuntimeConfig({ webuiPort: 6789 });
|
||||
const before = fs.readFileSync('config/runtime.json', 'utf8');
|
||||
vi.spyOn(fs, 'renameSync').mockImplementationOnce(() => {
|
||||
throw new Error('disk replacement failed');
|
||||
});
|
||||
const response = await (
|
||||
await routes()
|
||||
).request('/sources', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ mode: 'direct', mirror: '', mirrors: [] }),
|
||||
});
|
||||
expect(response.status).toBe(500);
|
||||
expect(await response.json()).toEqual({ message: 'disk replacement failed' });
|
||||
expect(fs.readFileSync('config/runtime.json', 'utf8')).toBe(before);
|
||||
});
|
||||
});
|
||||
81
packages/core/tests/update-sources.test.ts
Normal file
81
packages/core/tests/update-sources.test.ts
Normal file
@@ -0,0 +1,81 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { DEFAULT_UPDATE_SOURCE, sourceUrls, testUpdateSources } from '../src/update/sources';
|
||||
import type { UpdateSourceConfig } from '@snowluma/common/update-source';
|
||||
|
||||
const config: UpdateSourceConfig = {
|
||||
mode: 'auto',
|
||||
mirror: '',
|
||||
mirrors: [
|
||||
'https://good.example',
|
||||
'https://html.example',
|
||||
'https://fake.example',
|
||||
'https://failed.example',
|
||||
],
|
||||
};
|
||||
afterEach(() => vi.unstubAllGlobals());
|
||||
|
||||
describe('update mirror selection', () => {
|
||||
it('uses direct, ordered fallback or only the pinned mirror for downloads', () => {
|
||||
const url = 'https://github.com/project/asset';
|
||||
expect(sourceUrls(url, config)).toEqual([
|
||||
url,
|
||||
...config.mirrors.map((mirror) => `${mirror}/${url}`),
|
||||
]);
|
||||
expect(sourceUrls(url, { ...config, mode: 'direct' })).toEqual([url]);
|
||||
expect(
|
||||
sourceUrls(url, { ...config, mode: 'mirror', mirror: 'https://pinned.example/proxy' }),
|
||||
).toEqual([`https://pinned.example/proxy/${url}`]);
|
||||
expect(DEFAULT_UPDATE_SOURCE.mirrors.length).toBeGreaterThanOrEqual(7);
|
||||
});
|
||||
|
||||
it('probes actual archive prefixes, rejects HTML even with a binary content type, and cancels bodies', async () => {
|
||||
const cancelled = vi.fn();
|
||||
const signature =
|
||||
process.platform === 'win32' ? [0x50, 0x4b, 0x03, 0x04] : [0x1f, 0x8b, 0x08, 0];
|
||||
const fetchMock = vi.fn<typeof fetch>(async (url) => {
|
||||
if (String(url).startsWith('https://html.example')) {
|
||||
return new Response('<html>blocked</html>', {
|
||||
headers: { 'Content-Type': 'text/html' },
|
||||
});
|
||||
}
|
||||
|
||||
if (String(url).startsWith('https://fake.example')) {
|
||||
return new Response('<html>blocked</html>', {
|
||||
headers: { 'Content-Type': 'application/octet-stream' },
|
||||
});
|
||||
}
|
||||
|
||||
if (String(url).startsWith('https://failed.example')) {
|
||||
return new Response('blocked', { status: 403 });
|
||||
}
|
||||
|
||||
return new Response(
|
||||
new ReadableStream({
|
||||
start(controller) {
|
||||
controller.enqueue(new Uint8Array(signature));
|
||||
},
|
||||
cancel: cancelled,
|
||||
}),
|
||||
);
|
||||
});
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
const results = await testUpdateSources(config);
|
||||
expect(
|
||||
results
|
||||
.filter((result) => result.available)
|
||||
.map((result) => result.mirror)
|
||||
.sort(),
|
||||
).toEqual(['', 'https://good.example']);
|
||||
expect(results.filter((result) => !result.available)).toHaveLength(3);
|
||||
expect(results.at(-1)?.available).toBe(false);
|
||||
expect(cancelled).toHaveBeenCalledTimes(2);
|
||||
expect(
|
||||
fetchMock.mock.calls.every(
|
||||
([, options]) =>
|
||||
options?.headers &&
|
||||
'Range' in options.headers &&
|
||||
options.headers.Range === 'bytes=0-3',
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
47
packages/core/tests/webui-static-frontend.test.ts
Normal file
47
packages/core/tests/webui-static-frontend.test.ts
Normal 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);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,8 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { getUpdateInfo } from '../src/update/check';
|
||||
import { getUpdateInfo as checkUpdate } from '../src/update/check';
|
||||
|
||||
const getUpdateInfo = (force = false) =>
|
||||
checkUpdate(force, { mode: 'direct', mirror: '', mirrors: [] });
|
||||
|
||||
const LATEST_RELEASE_URL = 'https://api.github.com/repos/SnowLuma/SnowLuma/releases/latest';
|
||||
const NOTES_MAX = 4_000;
|
||||
@@ -85,7 +88,7 @@ describe('getUpdateInfo', () => {
|
||||
htmlUrl: null,
|
||||
notes: null,
|
||||
publishedAt: null,
|
||||
error: 'ECONNRESET',
|
||||
error: expect.stringContaining('ECONNRESET'),
|
||||
});
|
||||
|
||||
fetchMock.mockImplementation(async () => jsonResponse({ tag_name: 'v1.0.0' }));
|
||||
@@ -93,7 +96,7 @@ describe('getUpdateInfo', () => {
|
||||
expect(ok.latest).toBe('1.0.0');
|
||||
expect(ok.hasUpdate).toBe(true);
|
||||
expect(ok.error).toBeUndefined();
|
||||
expect(fetchMock).toHaveBeenCalledTimes(2);
|
||||
expect(fetchMock).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
|
||||
it.each(['', '1', 'true', 'yes', 'on', ' '] as const)(
|
||||
@@ -190,7 +193,7 @@ describe('getUpdateInfo', () => {
|
||||
htmlUrl: null,
|
||||
notes: null,
|
||||
publishedAt: null,
|
||||
error: 'github 403',
|
||||
error: expect.stringContaining('GitHub 403'),
|
||||
});
|
||||
});
|
||||
|
||||
@@ -230,7 +233,7 @@ describe('getUpdateInfo', () => {
|
||||
throw new Error('getaddrinfo ENOTFOUND');
|
||||
});
|
||||
const result = await getUpdateInfo(true);
|
||||
expect(result.error).toBe('getaddrinfo ENOTFOUND');
|
||||
expect(result.error).toContain('getaddrinfo ENOTFOUND');
|
||||
expect(result.hasUpdate).toBe(false);
|
||||
});
|
||||
|
||||
@@ -239,7 +242,7 @@ describe('getUpdateInfo', () => {
|
||||
throw 'timeout';
|
||||
});
|
||||
const result = await getUpdateInfo(true);
|
||||
expect(result.error).toBe('network error');
|
||||
expect(result.error).toContain('timeout');
|
||||
expect(result.hasUpdate).toBe(false);
|
||||
});
|
||||
|
||||
@@ -257,7 +260,7 @@ describe('getUpdateInfo', () => {
|
||||
throw new Error('boom');
|
||||
});
|
||||
await expect(getUpdateInfo(true)).resolves.toMatchObject({
|
||||
error: 'boom',
|
||||
error: expect.stringContaining('boom'),
|
||||
hasUpdate: false,
|
||||
});
|
||||
});
|
||||
@@ -298,12 +301,12 @@ describe('getUpdateInfo', () => {
|
||||
throw new Error('boom');
|
||||
});
|
||||
const bad = await getUpdateInfo(true);
|
||||
expect(bad.error).toBe('boom');
|
||||
expect(bad.error).toContain('boom');
|
||||
|
||||
const cached = await getUpdateInfo();
|
||||
expect(cached).toBe(good);
|
||||
expect(cached.error).toBeUndefined();
|
||||
expect(fetchMock).toHaveBeenCalledTimes(2);
|
||||
expect(fetchMock).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
|
||||
it('collapses concurrent checks onto one fetch', async () => {
|
||||
@@ -332,4 +335,15 @@ describe('getUpdateInfo', () => {
|
||||
});
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('does not reuse the previous source configuration cache after a mirror change', async () => {
|
||||
const source = { mode: 'auto', mirror: '', mirrors: ['https://first.example'] } as const;
|
||||
const fetchMock = mockFetch(async () => jsonResponse({ tag_name: 'v3.0.0' }));
|
||||
const first = await checkUpdate(false, { ...source, mirrors: [...source.mirrors] });
|
||||
fetchMock.mockImplementation(async () => jsonResponse({ tag_name: 'v3.0.1' }));
|
||||
const second = await checkUpdate(false, { ...source, mirrors: ['https://second.example'] });
|
||||
expect(first.latest).toBe('3.0.0');
|
||||
expect(second.latest).toBe('3.0.1');
|
||||
expect(fetchMock).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "@snowluma/mcp",
|
||||
"version": "2.0.0",
|
||||
"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",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "@snowluma/onebot",
|
||||
"version": "2.0.0",
|
||||
"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>'`.",
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -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>(
|
||||
|
||||
@@ -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}`;
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -560,8 +560,6 @@ export class OneBotManager {
|
||||
);
|
||||
}
|
||||
|
||||
instance.startGroupRequestPolling();
|
||||
|
||||
if (this.disposed || this.instances.get(uin) !== instance) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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.
|
||||
*/
|
||||
|
||||
@@ -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(
|
||||
|
||||
340
packages/onebot/tests/group-request-events.test.ts
Normal file
340
packages/onebot/tests/group-request-events.test.ts
Normal 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([]);
|
||||
});
|
||||
});
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
@@ -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,
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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, '');
|
||||
|
||||
@@ -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 () => {
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "@snowluma/proto-defs",
|
||||
"version": "2.0.0",
|
||||
"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).",
|
||||
|
||||
@@ -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>;
|
||||
|
||||
@@ -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>;
|
||||
}
|
||||
|
||||
@@ -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>;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "@snowluma/protocol",
|
||||
"version": "2.0.0",
|
||||
"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>'`.",
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
@@ -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);
|
||||
|
||||
195
packages/protocol/src/msg-push/client-message-receipt.ts
Normal file
195
packages/protocol/src/msg-push/client-message-receipt.ts
Normal 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;
|
||||
}
|
||||
@@ -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) {
|
||||
|
||||
@@ -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 };
|
||||
|
||||
@@ -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];
|
||||
};
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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,11 +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 = rootAttributes?.get('m_fileName') || undefined;
|
||||
return {
|
||||
element: match
|
||||
? { type: 'forward', resId: match[1] }
|
||||
element: resId
|
||||
? { type: 'forward', resId, forwardUuid: fileName }
|
||||
: { type: 'xml', text: content, subType: svcId },
|
||||
error: null,
|
||||
inputBytes: data.length,
|
||||
|
||||
121
packages/protocol/src/msg-push/xml-card.ts
Normal file
121
packages/protocol/src/msg-push/xml-card.ts
Normal 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;
|
||||
}
|
||||
}
|
||||
@@ -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',
|
||||
});
|
||||
}
|
||||
|
||||
345
packages/protocol/tests/msg-push/client-message-receipt.test.ts
Normal file
345
packages/protocol/tests/msg-push/client-message-receipt.test.ts
Normal 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');
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -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);
|
||||
|
||||
@@ -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' });
|
||||
|
||||
@@ -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&<>"\'<\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 = \'35\' ' +
|
||||
'm_resid = "res&<>"'&lt;" ' +
|
||||
"m_fileName = 'key	
 🙂' />";
|
||||
expect(decodeRichBody(xmlCardBody(xml, serviceId), true)).toEqual([
|
||||
{
|
||||
type: 'forward',
|
||||
resId: 'res&<>"\'<',
|
||||
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;', '�', '�', '�', '&'])(
|
||||
'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 = {
|
||||
@@ -218,6 +311,34 @@ describe('decodeRichBody / forward LightApp', () => {
|
||||
expect(out[0]!.type).toBe('json');
|
||||
});
|
||||
|
||||
it.each([false, true])(
|
||||
'preserves the XML forward filename for nested lookup (compressed=%s, #529)',
|
||||
(compressed) => {
|
||||
const xml = Buffer.from(
|
||||
'<msg serviceID="35" m_resid="inner-xml-res" m_fileName="inner-xml-key" />',
|
||||
);
|
||||
const body: MessageBody = {
|
||||
richText: {
|
||||
elems: [
|
||||
{
|
||||
richMsg: {
|
||||
serviceId: 35,
|
||||
template1: Buffer.concat([
|
||||
Buffer.from([compressed ? 1 : 0]),
|
||||
compressed ? deflateSync(xml) : xml,
|
||||
]),
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
expect(decodeRichBody(body, true)).toEqual([
|
||||
{ type: 'forward', resId: 'inner-xml-res', forwardUuid: 'inner-xml-key' },
|
||||
]);
|
||||
},
|
||||
);
|
||||
|
||||
it('still decodes the legacy richMsg serviceID=35 path (backward compat with mobile QQ)', () => {
|
||||
// Older clients (and some bridges) still emit the m_resid XML
|
||||
// shape. The decoder must keep treating it as a forward element
|
||||
|
||||
@@ -154,6 +154,7 @@ function makePipeline(
|
||||
fetchGroupList,
|
||||
fetchGroupMemberList,
|
||||
resolveGroupJoinRequest: vi.fn(async () => null),
|
||||
rememberGroupInviteCardSequence: vi.fn(() => true),
|
||||
});
|
||||
return { identity, pipeline, captured, fetchGroupList, fetchGroupMemberList };
|
||||
}
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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) => {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "@snowluma/proton",
|
||||
"version": "2.0.0",
|
||||
"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.",
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user