Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
744f25fd9b | ||
|
|
22bde5d949 | ||
|
|
ca61e6039f | ||
|
|
9df7b7524b | ||
|
|
0cb5daed5e | ||
|
|
f2ea3354f8 | ||
|
|
efcbf988b2 | ||
|
|
a341fa4b15 | ||
|
|
8bea681aa2 | ||
|
|
84f4cde85e | ||
|
|
6c8866b108 | ||
|
|
f2ade5603f | ||
|
|
87f7bd8c54 | ||
|
|
9edc255a02 | ||
|
|
7425cfae20 | ||
|
|
1b80487119 | ||
|
|
43b63e9a75 | ||
|
|
b0612d8d12 | ||
|
|
e031cd4108 | ||
|
|
b6b433af98 | ||
|
|
ae1ec3be0e | ||
|
|
33bebb4446 | ||
|
|
bab5aafd91 |
No files matched your search
@@ -84,6 +84,7 @@ Use focused tests while iterating. Before handing off a code change, run the ful
|
||||
- **MCP execution services:** keep background tasks and event connections opt-in. Persist task state before effects, never replay interrupted writes, and finish durable cleanup before draining the protocol on shutdown. Input continuations must retain their original arguments and execute at most once. Event buffers require explicit account binding, bounded storage and visible gaps. Build the bundled message preview through `packages/mcp/scripts/build-message-app.mjs`; loading a preview must not send a message. Test restart, cancellation and legacy compatibility using isolated transports, including the compiled CLI.
|
||||
- **Protocol codecs:** keep the existing Proton integration in tests so they exercise the same transformations as production. Import real implementations; do not duplicate the algorithm in the test.
|
||||
- **Video uploads:** preserve the single-connection default and the additive global setting in [HIGHWAY_UPLOADS.md](packages/protocol/HIGHWAY_UPLOADS.md). Only video bodies opt into parallel chunks. Confirm every chunk before completion, bound both concurrency and lookahead, and drain outstanding reads and requests before closing the source. Keep retries bounded and backpressure changes visible. Test the actual uploader with isolated transports; passing tests do not prove live throughput.
|
||||
- **Highway upload recovery:** all chunks and workers share one file transfer deadline. Keep node observations bounded, short-lived and isolated by account session, upload type and full host/port; select only current server-supplied candidates. Only validated acknowledgements establish success. Preserve terminal failure reporting and drain pending file reads after cancellation. Test deadline cleanup and candidate rotation with isolated transports, including real loopback sockets; see [upload policy](packages/protocol/HIGHWAY_UPLOADS.md#upload-timeouts-and-node-selection).
|
||||
- **Native coverage:** `pnpm test:native` is separate from default protocol tests and requires compatible native artifacts. A missing artifact or unavailable target is a reported limitation, not permission to bypass the check.
|
||||
- **OneBot SSE:** HTTP event streams share the HTTP adapter's binding and authentication. Preserve account isolation, bounded replay, visible expired-cursor errors, report filtering and slow-reader limits described in [HTTP_SSE.md](packages/onebot/HTTP_SSE.md). Token/report-policy changes revoke existing streams and invalidate replay; test shutdown and reload with active connections.
|
||||
- **Live QQ behavior:** fixture tests and a successful API response do not prove delivery or client rendering. State what was tested locally and what still needs a real client.
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
<img align="right" src="./assets/readme/mascot.png" width="34%" alt="SnowLuma 看板娘:紫发金瞳,戴着星饰贝雷帽的少女" />
|
||||
|
||||
# SnowLuma
|
||||
# SnowLuma<picture><img align="right" src="./assets/readme/mascot.png" width="34%" alt="" /></picture>
|
||||
|
||||
**让 QQ 原生会话,连接你的应用。**
|
||||
|
||||
@@ -12,6 +10,7 @@ OneBot v11 · WebUI · SDK · MCP
|
||||
<a href="https://github.com/SnowLuma/SnowLuma/actions/workflows/dev-build.yml"><img alt="构建状态" src="https://img.shields.io/github/actions/workflow/status/SnowLuma/SnowLuma/dev-build.yml?branch=dev&style=flat-square&label=build"></a>
|
||||
<a href="https://www.npmjs.com/package/@snowluma/sdk"><img alt="SnowLuma SDK 版本" src="https://img.shields.io/npm/v/%40snowluma%2Fsdk?style=flat-square&label=sdk&color=287fb8"></a>
|
||||
<a href="https://www.npmjs.com/package/@snowluma/mcp"><img alt="SnowLuma MCP 版本" src="https://img.shields.io/npm/v/%40snowluma%2Fmcp?style=flat-square&label=mcp&color=7658c7"></a>
|
||||
<a href="https://hub.docker.com/r/motricseven7/snowluma"><img alt="Docker 拉取次数" src="https://img.shields.io/docker/pulls/motricseven7/snowluma?style=flat-square&label=docker%20pulls"></a>
|
||||
<a href="https://github.com/SnowLuma/SnowLuma/stargazers"><img alt="GitHub Stars" src="https://img.shields.io/github/stars/SnowLuma/SnowLuma?style=flat-square"></a>
|
||||
</p>
|
||||
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "snowluma-monorepo",
|
||||
"version": "2.4.0",
|
||||
"version": "2.4.2",
|
||||
"description": "SnowLuma monorepo workspace (pnpm)",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "@snowluma/bridge",
|
||||
"version": "2.4.0",
|
||||
"version": "2.4.2",
|
||||
"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).",
|
||||
|
||||
@@ -117,6 +117,8 @@ export class HookSession extends EventEmitter {
|
||||
private cancelConnectAttempt: (() => void) | null = null;
|
||||
private pipeUpPending = false;
|
||||
private loginReconcileTimer: ReturnType<typeof setInterval> | null = null;
|
||||
private loginIdentityEpoch = 0;
|
||||
private invalidLoginStateReported = false;
|
||||
private detecting = false;
|
||||
private lastDetectFailure = '';
|
||||
private acceptedLoginHintUin = '';
|
||||
@@ -693,20 +695,10 @@ export class HookSession extends EventEmitter {
|
||||
this.hasConnected = true;
|
||||
this.stopInitialConnectionWatch();
|
||||
this.initialConnectionError = '';
|
||||
const loginState = client.getLoginState();
|
||||
|
||||
// handleLoginState owns the connected+loggedIn → 'online' (+ login
|
||||
// emit) transition; defer to it so the status is set once. Otherwise
|
||||
// we're connected-but-not-logged-in → 'loaded'.
|
||||
if (loginState.loggedIn) {
|
||||
this.handleLoginState(loginState);
|
||||
} else {
|
||||
this.applyStatus();
|
||||
// The native hook only PUSHES a loginState frame on the login edge;
|
||||
// if QQ logged in before/around connect (Docker auto-login) that edge
|
||||
// is missed and we'd wait forever. Keep re-detecting until logged in.
|
||||
runWithoutRequestContext(() => this.startLoginReconcile());
|
||||
}
|
||||
this._error = '';
|
||||
// Identity validation owns readiness and whether to keep checking.
|
||||
// A reported login alone does not establish a usable account.
|
||||
this.handleLoginState(client.getLoginState());
|
||||
|
||||
this.log.info('pipe connected: PID=%d', this.pid);
|
||||
this.log.trace(() => [
|
||||
@@ -915,19 +907,32 @@ export class HookSession extends EventEmitter {
|
||||
this.bound = false;
|
||||
this.connected = false;
|
||||
this.loggedIn = false;
|
||||
this.invalidLoginStateReported = false;
|
||||
this._outboundHealthy = true;
|
||||
this.resetLoginHint();
|
||||
}
|
||||
|
||||
private handleLoginState(state: QqHookLoginState): void {
|
||||
if (this.runtimeFailure) {
|
||||
if (this.disposed || this.runtimeFailure) {
|
||||
return;
|
||||
}
|
||||
|
||||
const wasLoggedIn = this.loggedIn;
|
||||
const previousUin = this._uin;
|
||||
this._uin = state.uin || state.uinNumber.toString();
|
||||
this.loggedIn = state.loggedIn && isRealUin(this._uin);
|
||||
const uin = state.uin || state.uinNumber.toString();
|
||||
const validIdentity = isRealUin(uin);
|
||||
const invalidLoginState = state.loggedIn && !validIdentity;
|
||||
|
||||
if (invalidLoginState && !this.invalidLoginStateReported) {
|
||||
this.log.warn(
|
||||
'Login readiness rejected: PID=%d reason=invalid_account_identity',
|
||||
this.pid,
|
||||
);
|
||||
}
|
||||
|
||||
this.invalidLoginStateReported = invalidLoginState;
|
||||
this._uin = validIdentity ? uin : '0';
|
||||
this.loggedIn = state.loggedIn && validIdentity;
|
||||
|
||||
// Login readiness has now been confirmed, so identity probing is done.
|
||||
if (this.loggedIn) {
|
||||
@@ -942,19 +947,30 @@ export class HookSession extends EventEmitter {
|
||||
} else {
|
||||
this.resetReceiveWatch();
|
||||
this._outboundHealthy = true;
|
||||
|
||||
if (wasLoggedIn) {
|
||||
this.resetLoginHint();
|
||||
}
|
||||
}
|
||||
|
||||
// Only the connected/logged-in states are ours to set here; when fully
|
||||
// down we leave the status the teardown path already settled.
|
||||
// Load-bearing invariant: `loggedIn ⇒ connected` (login can only be
|
||||
// observed on a live client, and teardown clears `loggedIn` before
|
||||
// `connected`), so statusFor lands 'online' here rather than the
|
||||
// disconnected/connecting branch.
|
||||
// Login may arrive while another channel is still handshaking; the
|
||||
// connection attempt revokes that binding if it fails to complete.
|
||||
if (this.connected || this.loggedIn) {
|
||||
this.applyStatus(wasLoggedIn, this.loggedIn ? '' : this._error);
|
||||
}
|
||||
|
||||
if (!this.loggedIn || !this.sender) {
|
||||
if (!this.loggedIn) {
|
||||
if (wasLoggedIn) {
|
||||
this.emit('disconnected', true);
|
||||
}
|
||||
|
||||
runWithoutRequestContext(() => this.startLoginReconcile());
|
||||
return;
|
||||
}
|
||||
|
||||
if (!this.sender) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1001,17 +1017,23 @@ export class HookSession extends EventEmitter {
|
||||
// reconciliation, but never synthesize online state from the detection.
|
||||
|
||||
private startLoginReconcile(): void {
|
||||
if (this.loginReconcileTimer || this.disposed || this.runtimeFailure) {
|
||||
if (
|
||||
this.loginReconcileTimer ||
|
||||
this.disposed ||
|
||||
this.runtimeFailure ||
|
||||
!this.connected ||
|
||||
this.loggedIn
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.log.info('awaiting login: PID=%d', this.pid);
|
||||
void this.detectLoginOnce(); // immediate — catch already-logged-in fast
|
||||
this.loginReconcileTimer = setInterval(
|
||||
() => void this.detectLoginOnce(),
|
||||
LOGIN_RECONCILE_INTERVAL_MS,
|
||||
);
|
||||
this.loginReconcileTimer.unref();
|
||||
void this.detectLoginOnce();
|
||||
}
|
||||
|
||||
private stopLoginReconcile(): void {
|
||||
@@ -1029,6 +1051,7 @@ export class HookSession extends EventEmitter {
|
||||
}
|
||||
|
||||
const client = this.client;
|
||||
const identityEpoch = this.loginIdentityEpoch;
|
||||
|
||||
if (this.disposed || !client || !this.connected || this.loggedIn || this.runtimeFailure) {
|
||||
this.stopLoginReconcile();
|
||||
@@ -1047,6 +1070,17 @@ export class HookSession extends EventEmitter {
|
||||
try {
|
||||
uin = await this.detectLoginUin(this.pid);
|
||||
} catch (error) {
|
||||
if (
|
||||
this.client !== client ||
|
||||
this.loginIdentityEpoch !== identityEpoch ||
|
||||
this.disposed ||
|
||||
!this.connected ||
|
||||
this.loggedIn ||
|
||||
this.runtimeFailure
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
const message = errorMessage(error);
|
||||
|
||||
if (this.lastDetectFailure !== message) {
|
||||
@@ -1061,9 +1095,10 @@ export class HookSession extends EventEmitter {
|
||||
return; // best-effort; the interval retries
|
||||
}
|
||||
|
||||
// A reconnect owns a new client; an older read cannot supply its identity.
|
||||
// A connection or readiness change invalidates earlier identity work.
|
||||
if (
|
||||
this.client !== client ||
|
||||
this.loginIdentityEpoch !== identityEpoch ||
|
||||
this.disposed ||
|
||||
!this.connected ||
|
||||
this.loggedIn ||
|
||||
@@ -1107,6 +1142,7 @@ export class HookSession extends EventEmitter {
|
||||
|
||||
if (
|
||||
this.client !== client ||
|
||||
this.loginIdentityEpoch !== identityEpoch ||
|
||||
this.disposed ||
|
||||
!this.connected ||
|
||||
this.loggedIn ||
|
||||
@@ -1119,7 +1155,14 @@ export class HookSession extends EventEmitter {
|
||||
this.nextLoginIdentityObservationAt =
|
||||
Date.now() + LOGIN_IDENTITY_OBSERVE_INTERVAL_MS;
|
||||
} catch (error) {
|
||||
if (this.client !== client || this.disposed || this.runtimeFailure) {
|
||||
if (
|
||||
this.client !== client ||
|
||||
this.loginIdentityEpoch !== identityEpoch ||
|
||||
this.disposed ||
|
||||
!this.connected ||
|
||||
this.loggedIn ||
|
||||
this.runtimeFailure
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1152,6 +1195,7 @@ export class HookSession extends EventEmitter {
|
||||
}
|
||||
|
||||
private resetLoginHint(): void {
|
||||
this.loginIdentityEpoch++;
|
||||
this.acceptedLoginHintUin = '';
|
||||
this.loginHintAttemptUin = '';
|
||||
this.loginHintAttempts = 0;
|
||||
|
||||
@@ -1479,6 +1479,302 @@ describe('HookSession — packet forwarding', () => {
|
||||
});
|
||||
|
||||
describe('HookSession — login reconcile (Docker auto-login safety net)', () => {
|
||||
it.each([
|
||||
{ uin: '1700000000000', uinNumber: 1700000000000n },
|
||||
{ uin: 'not-an-account', uinNumber: 0n },
|
||||
{ uin: '0', uinNumber: 0n },
|
||||
{ uin: '', uinNumber: 1700000000000n },
|
||||
])(
|
||||
'reconciles a rejected login identity received during connection: $uin',
|
||||
async (identity) => {
|
||||
vi.useFakeTimers();
|
||||
setLogLevel('warn');
|
||||
const entries: LogEntry[] = [];
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
const detectLoginUin = vi.fn(async () => '10001');
|
||||
const onPacket = vi.fn<PacketSink>();
|
||||
const state = { loggedIn: true, ...identity };
|
||||
const ctx = makeSession({
|
||||
pipeLive: true,
|
||||
detectLoginUin,
|
||||
onPacket,
|
||||
connectClient: async (client) => client.reconcileLoginState(state),
|
||||
});
|
||||
const login = vi.fn();
|
||||
ctx.session.on('login', login);
|
||||
|
||||
try {
|
||||
await ctx.session.load();
|
||||
ctx.session.onPipeUp();
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(ctx.currentClient().loginIdentityHints).toEqual(['10001']);
|
||||
expect(ctx.session.toInfo()).toMatchObject({
|
||||
connected: true,
|
||||
loggedIn: false,
|
||||
status: 'loaded',
|
||||
uin: '0',
|
||||
});
|
||||
expect(login).not.toHaveBeenCalled();
|
||||
|
||||
const packet = {
|
||||
seq: 1,
|
||||
error: 0,
|
||||
cmd: 'Test.Message',
|
||||
uin: '10001',
|
||||
body: Buffer.alloc(0),
|
||||
};
|
||||
ctx.currentClient().firePacket(packet);
|
||||
expect(onPacket).not.toHaveBeenCalled();
|
||||
ctx.currentClient().reconcileLoginState(state);
|
||||
await vi.advanceTimersByTimeAsync(9000);
|
||||
expect(ctx.currentClient().loginIdentityHints).toEqual(['10001']);
|
||||
expect(
|
||||
entries
|
||||
.filter((entry) => entry.scope === 'HookSession' && entry.level === 'warn')
|
||||
.map((entry) => entry.message),
|
||||
).toEqual(['Login readiness rejected: PID=1234 reason=invalid_account_identity']);
|
||||
|
||||
ctx.currentClient().fireLogin('10001');
|
||||
ctx.currentClient().firePacket(packet);
|
||||
expect(login).toHaveBeenCalledOnce();
|
||||
expect(onPacket).toHaveBeenCalledOnce();
|
||||
expect(ctx.session.toInfo()).toMatchObject({
|
||||
loggedIn: true,
|
||||
status: 'online',
|
||||
uin: '10001',
|
||||
});
|
||||
const detections = detectLoginUin.mock.calls.length;
|
||||
await vi.advanceTimersByTimeAsync(30_000);
|
||||
expect(detectLoginUin).toHaveBeenCalledTimes(detections);
|
||||
} finally {
|
||||
ctx.session.dispose();
|
||||
unsubscribe();
|
||||
vi.useRealTimers();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it('revokes a ready account and starts a fresh identity check when login readiness is lost', async () => {
|
||||
vi.useFakeTimers();
|
||||
const ctx = makeSession({ pipeLive: true, detectLoginUin: async () => '10001' });
|
||||
const login = vi.fn();
|
||||
const disconnected = vi.fn();
|
||||
ctx.session.on('login', login);
|
||||
ctx.session.on('disconnected', disconnected);
|
||||
|
||||
try {
|
||||
await ctx.session.load();
|
||||
ctx.session.onPipeUp();
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(ctx.currentClient().loginIdentityHints).toEqual(['10001']);
|
||||
ctx.currentClient().fireLogin('10001');
|
||||
expect(login).toHaveBeenCalledOnce();
|
||||
|
||||
ctx.currentClient().fireLogin('1700000000000');
|
||||
ctx.currentClient().fireLogin('1700000000001');
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(disconnected).toHaveBeenCalledExactlyOnceWith(true);
|
||||
expect(ctx.session.toInfo()).toMatchObject({
|
||||
status: 'loaded',
|
||||
loggedIn: false,
|
||||
uin: '0',
|
||||
});
|
||||
expect(ctx.currentClient().loginIdentityHints).toEqual(['10001', '10001']);
|
||||
expect(login).toHaveBeenCalledOnce();
|
||||
|
||||
ctx.currentClient().fireLogin('10001');
|
||||
expect(login).toHaveBeenCalledTimes(2);
|
||||
expect(ctx.session.status).toBe('online');
|
||||
} finally {
|
||||
ctx.session.dispose();
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it('does not probe a rejected login identity before a stalled connection times out', async () => {
|
||||
vi.useFakeTimers();
|
||||
const handshake = Promise.withResolvers<void>();
|
||||
const detectLoginUin = vi.fn(async () => '10001');
|
||||
const ctx = makeSession({ detectLoginUin, connectClient: () => handshake.promise });
|
||||
const login = vi.fn();
|
||||
ctx.session.on('login', login);
|
||||
|
||||
try {
|
||||
await ctx.session.load();
|
||||
ctx.setPipeLive(true);
|
||||
ctx.session.onPipeUp();
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
const previous = ctx.currentClient();
|
||||
previous.fireLogin('1700000000000');
|
||||
await vi.advanceTimersByTimeAsync(60_000);
|
||||
expect(ctx.session.toInfo()).toMatchObject({
|
||||
status: 'error',
|
||||
connected: false,
|
||||
loggedIn: false,
|
||||
});
|
||||
expect(detectLoginUin).not.toHaveBeenCalled();
|
||||
expect(previous.isClosed).toBe(true);
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
|
||||
previous.fireLogin('10001');
|
||||
handshake.resolve();
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(login).not.toHaveBeenCalled();
|
||||
await ctx.session.load();
|
||||
ctx.session.onPipeUp();
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(ctx.currentClient()).not.toBe(previous);
|
||||
expect(ctx.currentClient().loginIdentityHints).toEqual(['10001']);
|
||||
expect(ctx.session.toInfo()).toMatchObject({
|
||||
status: 'loaded',
|
||||
connected: true,
|
||||
loggedIn: false,
|
||||
});
|
||||
} finally {
|
||||
handshake.resolve();
|
||||
ctx.session.dispose();
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it('discards an identity acknowledgement from before login readiness was lost', async () => {
|
||||
vi.useFakeTimers();
|
||||
const hint = Promise.withResolvers<void>();
|
||||
const ctx = makeSession({
|
||||
pipeLive: true,
|
||||
detectLoginUin: async () => '10001',
|
||||
connectClient: async (client) => {
|
||||
vi.spyOn(client, 'reconcileLoginIdentity').mockImplementationOnce(async (uin) => {
|
||||
client.loginIdentityHints.push(uin);
|
||||
await hint.promise;
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
await ctx.session.load();
|
||||
ctx.session.onPipeUp();
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(ctx.currentClient().loginIdentityHints).toEqual(['10001']);
|
||||
ctx.currentClient().fireLogin('10001');
|
||||
ctx.currentClient().fireLogin('1700000000000');
|
||||
hint.resolve();
|
||||
await vi.advanceTimersByTimeAsync(3000);
|
||||
expect(ctx.currentClient().loginIdentityHints).toEqual(['10001', '10001']);
|
||||
expect(ctx.session.toInfo()).toMatchObject({ status: 'loaded', loggedIn: false });
|
||||
} finally {
|
||||
hint.resolve();
|
||||
ctx.session.dispose();
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it('discards an account observation from before login readiness was lost', async () => {
|
||||
vi.useFakeTimers();
|
||||
const observation = Promise.withResolvers<string | null>();
|
||||
const detectLoginUin = vi.fn<() => Promise<string | null>>().mockResolvedValue('20002');
|
||||
detectLoginUin.mockReturnValueOnce(observation.promise);
|
||||
const ctx = makeSession({ pipeLive: true, detectLoginUin });
|
||||
|
||||
try {
|
||||
await ctx.session.load();
|
||||
ctx.session.onPipeUp();
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
ctx.currentClient().fireLogin('10001');
|
||||
ctx.currentClient().fireLogin('1700000000000');
|
||||
observation.resolve('10001');
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(ctx.currentClient().loginIdentityHints).toEqual([]);
|
||||
await vi.advanceTimersByTimeAsync(3000);
|
||||
expect(ctx.currentClient().loginIdentityHints).toEqual(['20002']);
|
||||
} finally {
|
||||
observation.resolve(null);
|
||||
ctx.session.dispose();
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it.each(['observation', 'hint'] as const)(
|
||||
'ignores a late %s failure after login readiness is confirmed',
|
||||
async (phase) => {
|
||||
vi.useFakeTimers();
|
||||
setLogLevel('trace');
|
||||
const entries: LogEntry[] = [];
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
const pending = Promise.withResolvers<void>();
|
||||
const detectLoginUin = vi.fn(async () => {
|
||||
if (phase === 'observation') {
|
||||
await pending.promise;
|
||||
}
|
||||
|
||||
return '10001';
|
||||
});
|
||||
const ctx = makeSession({
|
||||
pipeLive: true,
|
||||
detectLoginUin,
|
||||
connectClient: async (client) => {
|
||||
if (phase === 'hint') {
|
||||
vi.spyOn(client, 'reconcileLoginIdentity').mockImplementationOnce(
|
||||
async (uin) => {
|
||||
client.loginIdentityHints.push(uin);
|
||||
await pending.promise;
|
||||
},
|
||||
);
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
await ctx.session.load();
|
||||
ctx.session.onPipeUp();
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(detectLoginUin).toHaveBeenCalledOnce();
|
||||
expect(ctx.currentClient().loginIdentityHints).toEqual(
|
||||
phase === 'hint' ? ['10001'] : [],
|
||||
);
|
||||
ctx.currentClient().fireLogin('10001');
|
||||
entries.length = 0;
|
||||
pending.reject(new Error('expired identity request'));
|
||||
await vi.advanceTimersByTimeAsync(30_000);
|
||||
expect(
|
||||
entries.some((entry) => entry.message.includes('expired identity request')),
|
||||
).toBe(false);
|
||||
expect(detectLoginUin).toHaveBeenCalledOnce();
|
||||
expect(ctx.session.toInfo()).toMatchObject({
|
||||
status: 'online',
|
||||
loggedIn: true,
|
||||
uin: '10001',
|
||||
});
|
||||
} finally {
|
||||
pending.resolve();
|
||||
ctx.session.dispose();
|
||||
unsubscribe();
|
||||
vi.useRealTimers();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it('clears the login check timer when identity detection disposes the session synchronously', async () => {
|
||||
vi.useFakeTimers();
|
||||
const detectLoginUin = vi.fn<() => Promise<string | null>>();
|
||||
const ctx = makeSession({ pipeLive: true, detectLoginUin });
|
||||
detectLoginUin.mockImplementation(async () => {
|
||||
ctx.session.dispose();
|
||||
return null;
|
||||
});
|
||||
|
||||
try {
|
||||
await ctx.session.load();
|
||||
ctx.session.onPipeUp();
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(ctx.session.isDisposed).toBe(true);
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
} finally {
|
||||
ctx.session.dispose();
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it('discards an identity read started before a pipe reconnect', async () => {
|
||||
const detection = Promise.withResolvers<string | null>();
|
||||
const ctx = makeSession({ pipeLive: true, detectLoginUin: () => detection.promise });
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
// pnpm --filter @snowluma/common exec vitest bench --run bench/logger.bench.ts
|
||||
import { bench, describe, vi } from 'vitest';
|
||||
|
||||
vi.stubEnv('SNOWLUMA_LOG_LEVEL', 'trace');
|
||||
vi.stubEnv('SNOWLUMA_LOG_FILE', '0');
|
||||
vi.stubEnv('SNOWLUMA_LOG_FILE_LEVEL', 'debug');
|
||||
vi.stubEnv('SNOWLUMA_TRACE_BUFFER', '5000');
|
||||
const { createLogger, getLogSnapshot, getRecentLogs, setLogLevel } = await import('../src/logger');
|
||||
const stdout = vi.spyOn(process.stdout, 'write').mockReturnValue(true);
|
||||
const log = createLogger('Benchmark');
|
||||
|
||||
for (let i = 0; i < 5000; i += 1) {
|
||||
log.trace('trace %d', i);
|
||||
|
||||
if (i % 5 === 0) {
|
||||
log.info('normal %d', i);
|
||||
}
|
||||
}
|
||||
|
||||
stdout.mockRestore();
|
||||
|
||||
describe('6,000 retained records', () => {
|
||||
bench('recent 30', () => {
|
||||
getRecentLogs(30);
|
||||
});
|
||||
bench('recent 300', () => {
|
||||
getRecentLogs(300);
|
||||
});
|
||||
bench('complete export', () => {
|
||||
getLogSnapshot();
|
||||
});
|
||||
});
|
||||
|
||||
setLogLevel('info');
|
||||
|
||||
describe('file-only debug records with disk disabled', () => {
|
||||
bench('format and route debug', () => {
|
||||
log.debug('packet command=%s bytes=%d', 'Example.Service', 1024);
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "@snowluma/common",
|
||||
"version": "2.4.0",
|
||||
"version": "2.4.2",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "SnowLuma shared infrastructure — leaf-package utilities with zero business dependencies. Logger / hex codec / log file transport / log line summariser / packet sender wire-protocol types / runtime config loader. Consumed by @snowluma/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).",
|
||||
|
||||
@@ -82,33 +82,48 @@ function skipEscSequence(line: string, start: number): number {
|
||||
* invisible payload into persisted or downloaded logs.
|
||||
*/
|
||||
export function sanitizeLogLine(line: string): string {
|
||||
let plain = '';
|
||||
const parts: string[] = [];
|
||||
let start = 0;
|
||||
|
||||
for (let i = 0; i < line.length;) {
|
||||
const code = line.charCodeAt(i);
|
||||
let next: number;
|
||||
|
||||
if (code === ESC) {
|
||||
i = skipEscSequence(line, i + 1);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (code === C1_CSI) {
|
||||
i = skipCsi(line, i + 1);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (code === C1_OSC || C1_STRING_STARTERS.has(code)) {
|
||||
i = skipControlString(line, i + 1, code === C1_OSC);
|
||||
continue;
|
||||
}
|
||||
|
||||
if ((code < 0x20 && code !== 0x09 && code !== 0x0a) || (code >= 0x7f && code <= 0x9f)) {
|
||||
next = skipEscSequence(line, i + 1);
|
||||
} else if (code === C1_CSI) {
|
||||
next = skipCsi(line, i + 1);
|
||||
} else if (code === C1_OSC || C1_STRING_STARTERS.has(code)) {
|
||||
next = skipControlString(line, i + 1, code === C1_OSC);
|
||||
} else if (
|
||||
(code < 0x20 && code !== 0x09 && code !== 0x0a) ||
|
||||
(code >= 0x7f && code <= 0x9f)
|
||||
) {
|
||||
next = i + 1;
|
||||
} else {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
plain += line[i];
|
||||
i += 1;
|
||||
parts.push(line.slice(start, i));
|
||||
start = next;
|
||||
i = next;
|
||||
}
|
||||
|
||||
if (start === 0) {
|
||||
return line;
|
||||
}
|
||||
|
||||
// Join contiguous spans once. Appending each character creates a retained
|
||||
// V8 cons-string node per character in the in-memory log rings.
|
||||
parts.push(line.slice(start));
|
||||
const plain = parts.join('');
|
||||
|
||||
// A single visible span can remain a slice of the original input after join.
|
||||
// Copy when that would retain more discarded text than visible text. Splitting
|
||||
// into UTF-16 code units preserves unpaired surrogates and works in browsers.
|
||||
if (plain.length > 0 && plain.length < line.length / 2) {
|
||||
return plain.split('').join('');
|
||||
}
|
||||
|
||||
return plain;
|
||||
|
||||
@@ -97,20 +97,13 @@ class RingBuffer<T> {
|
||||
this.start = (this.start + 1) % this.cap;
|
||||
} // full → overwrite oldest
|
||||
}
|
||||
/** Most recent `n` items, oldest→newest. */
|
||||
recent(n: number): T[] {
|
||||
const take = Math.max(0, Math.min(Math.trunc(n), this.count));
|
||||
const out: T[] = new Array<T>(take);
|
||||
const first = this.start + (this.count - take);
|
||||
|
||||
for (let i = 0; i < take; i += 1) {
|
||||
out[i] = this.buf[(first + i) % this.cap]!;
|
||||
/** Read from newest to oldest without copying the retained buffer. */
|
||||
newest(offset: number): T | undefined {
|
||||
if (offset >= this.count) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
toArray(): T[] {
|
||||
return this.recent(this.count);
|
||||
return this.buf[(this.start + this.count - 1 - offset) % this.cap];
|
||||
}
|
||||
get size(): number {
|
||||
return this.count;
|
||||
@@ -282,18 +275,22 @@ function emit(level: LogLevel, options: LogOptions, args: unknown[]): void {
|
||||
const formattedMessage = format(...realArgs);
|
||||
const message = level === 'trace' ? formattedMessage : redactLogMessage(formattedMessage);
|
||||
const line = render(level, options, message, reqId);
|
||||
const entry: LogEntry = {
|
||||
id: nextLogId++,
|
||||
time: new Date().toISOString(),
|
||||
level,
|
||||
scope: options.scope,
|
||||
...(options.uin !== undefined ? { uin: options.uin } : {}),
|
||||
...(reqId !== undefined ? { req: reqId } : {}),
|
||||
message,
|
||||
line: sanitizeLogLine(line),
|
||||
};
|
||||
const id = nextLogId++;
|
||||
|
||||
if (passesConsole) {
|
||||
// File-only records are sanitized by the transport and need no memory
|
||||
// entry, ISO timestamp, or second sanitized copy of the rendered line.
|
||||
const entry: LogEntry = {
|
||||
id,
|
||||
time: new Date().toISOString(),
|
||||
level,
|
||||
scope: options.scope,
|
||||
...(options.uin !== undefined ? { uin: options.uin } : {}),
|
||||
...(reqId !== undefined ? { req: reqId } : {}),
|
||||
message,
|
||||
line: sanitizeLogLine(line),
|
||||
};
|
||||
|
||||
// Trace gets its own ring so its volume never evicts the normal log buffer.
|
||||
(level === 'trace' ? traceRing : logRing).push(entry);
|
||||
|
||||
@@ -337,10 +334,28 @@ export function closeLogger(): Promise<void> {
|
||||
return getFileTransport().close();
|
||||
}
|
||||
|
||||
function mergeLogRings(): LogEntry[] {
|
||||
return traceRing.size > 0
|
||||
? [...logRing.toArray(), ...traceRing.toArray()].sort((a, b) => a.id - b.id)
|
||||
: logRing.toArray();
|
||||
function mergeLogRings(limit = logRing.size + traceRing.size): LogEntry[] {
|
||||
const take = Math.min(limit, logRing.size + traceRing.size);
|
||||
const entries = new Array<LogEntry>(take);
|
||||
let normalOffset = 0;
|
||||
let traceOffset = 0;
|
||||
|
||||
// Both rings already follow increasing IDs. Merge backwards so a small
|
||||
// WebUI request visits only the requested tail, even with a large TRACE ring.
|
||||
for (let i = take - 1; i >= 0; i -= 1) {
|
||||
const normal = logRing.newest(normalOffset);
|
||||
const trace = traceRing.newest(traceOffset);
|
||||
|
||||
if (normal && (!trace || normal.id > trace.id)) {
|
||||
entries[i] = normal;
|
||||
normalOffset += 1;
|
||||
} else {
|
||||
entries[i] = trace!;
|
||||
traceOffset += 1;
|
||||
}
|
||||
}
|
||||
|
||||
return entries;
|
||||
}
|
||||
|
||||
export function getLogSnapshot(): LogEntry[] {
|
||||
@@ -349,7 +364,8 @@ export function getLogSnapshot(): LogEntry[] {
|
||||
|
||||
export function getRecentLogs(limit = 300): LogEntry[] {
|
||||
const n = Math.max(1, Math.trunc(limit));
|
||||
return mergeLogRings().slice(-n);
|
||||
// Array.slice(-NaN) previously returned the full snapshot.
|
||||
return mergeLogRings(Number.isNaN(n) ? undefined : n);
|
||||
}
|
||||
|
||||
export function subscribeLogs(callback: (entry: LogEntry) => void): () => void {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/** TTL caching and request deduplication to limit repeated upstream requests. */
|
||||
|
||||
export interface SingleFlightCacheOptions<K, V> {
|
||||
/** Freshness window in ms. A cached entry older than this is reloaded. */
|
||||
/** Freshness window in ms. Expired values are released even while idle. */
|
||||
ttlMs: number;
|
||||
/** Load the value for a key. Rejections propagate and are never cached. */
|
||||
load: (key: K) => Promise<V>;
|
||||
@@ -22,6 +22,8 @@ export class SingleFlightCache<K, V> {
|
||||
private readonly now: () => number;
|
||||
private readonly fresh = new Map<K, { at: number; value: V }>();
|
||||
private readonly inflight = new Map<K, Promise<V>>();
|
||||
private expiryTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
private disposed = false;
|
||||
|
||||
constructor(opts: SingleFlightCacheOptions<K, V>) {
|
||||
this.ttlMs = opts.ttlMs;
|
||||
@@ -30,6 +32,11 @@ export class SingleFlightCache<K, V> {
|
||||
this.now = opts.now ?? Date.now;
|
||||
}
|
||||
|
||||
/** Number of retained values; pending loads are not counted. */
|
||||
get size(): number {
|
||||
return this.fresh.size;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the value for `key`.
|
||||
*
|
||||
@@ -41,10 +48,17 @@ export class SingleFlightCache<K, V> {
|
||||
* rather than starting a second one.
|
||||
*/
|
||||
get(key: K, opts: { force?: boolean } = {}): Promise<V> {
|
||||
if (!opts.force) {
|
||||
const hit = this.fresh.get(key);
|
||||
if (this.disposed) {
|
||||
return Promise.reject(new Error('SingleFlightCache is disposed'));
|
||||
}
|
||||
|
||||
if (hit && this.now() - hit.at < this.ttlMs) {
|
||||
const hit = this.fresh.get(key);
|
||||
|
||||
if (hit) {
|
||||
if (this.now() - hit.at >= this.ttlMs) {
|
||||
this.fresh.delete(key);
|
||||
this.cancelExpiryIfEmpty();
|
||||
} else if (!opts.force) {
|
||||
return Promise.resolve(hit.value);
|
||||
}
|
||||
}
|
||||
@@ -58,8 +72,11 @@ export class SingleFlightCache<K, V> {
|
||||
const load = async (): Promise<V> => {
|
||||
const value = await this.load(key);
|
||||
|
||||
if (this.inflight.get(key) === task && this.shouldCache(value)) {
|
||||
if (this.inflight.get(key) === task && this.ttlMs > 0 && this.shouldCache(value)) {
|
||||
// Keep insertion order aligned with expiry, including refreshes.
|
||||
this.fresh.delete(key);
|
||||
this.fresh.set(key, { at: this.now(), value });
|
||||
this.scheduleExpiry();
|
||||
}
|
||||
|
||||
return value;
|
||||
@@ -78,12 +95,58 @@ export class SingleFlightCache<K, V> {
|
||||
invalidate(key: K): void {
|
||||
this.fresh.delete(key);
|
||||
this.inflight.delete(key);
|
||||
this.cancelExpiryIfEmpty();
|
||||
}
|
||||
|
||||
/** Detach all entries and pending loads without aborting existing callers. */
|
||||
clear(): void {
|
||||
this.fresh.clear();
|
||||
this.inflight.clear();
|
||||
this.cancelExpiryIfEmpty();
|
||||
}
|
||||
|
||||
/** Release this owner's cache permanently; pending callers still settle. */
|
||||
dispose(): void {
|
||||
this.disposed = true;
|
||||
this.clear();
|
||||
}
|
||||
|
||||
private cancelExpiryIfEmpty(): void {
|
||||
if (this.fresh.size === 0 && this.expiryTimer !== undefined) {
|
||||
clearTimeout(this.expiryTimer);
|
||||
this.expiryTimer = undefined;
|
||||
}
|
||||
}
|
||||
|
||||
private scheduleExpiry(): void {
|
||||
if (this.expiryTimer !== undefined || !Number.isFinite(this.ttlMs)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const oldest = this.fresh.values().next().value;
|
||||
|
||||
if (!oldest) {
|
||||
return;
|
||||
}
|
||||
|
||||
// One unref'ed timer per cache, not one closure/timer per cached roster.
|
||||
// Clamp long TTLs to Node's timer range rather than overflowing to 1ms.
|
||||
const delay = Math.max(1, Math.min(2 ** 31 - 1, oldest.at + this.ttlMs - this.now()));
|
||||
this.expiryTimer = setTimeout(() => {
|
||||
this.expiryTimer = undefined;
|
||||
const now = this.now();
|
||||
|
||||
for (const [key, entry] of this.fresh) {
|
||||
if (now - entry.at < this.ttlMs) {
|
||||
break;
|
||||
}
|
||||
|
||||
this.fresh.delete(key);
|
||||
}
|
||||
|
||||
this.scheduleExpiry();
|
||||
}, delay);
|
||||
this.expiryTimer.unref();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import { sanitizeLogLine } from '../src/log-sanitize';
|
||||
|
||||
describe('sanitizeLogLine', () => {
|
||||
@@ -23,4 +24,64 @@ describe('sanitizeLogLine', () => {
|
||||
it('does not leak unterminated terminal strings', () => {
|
||||
expect(sanitizeLogLine('visible\x1b]8;;https://example.com')).toBe('visible');
|
||||
});
|
||||
|
||||
it('preserves long Unicode records and adjacent visible spans', () => {
|
||||
const body = '消息 🌌 e\u0301\tpacket=0011aabb\n'.repeat(1000);
|
||||
expect(sanitizeLogLine(body)).toBe(body);
|
||||
expect(sanitizeLogLine(`\x1b[32m${body}\x1b[0m\x00tail\x1b`)).toBe(`${body}tail`);
|
||||
});
|
||||
|
||||
it.each(['\x1bP', '\x1bX', '\x1b^', '\x1b_', '\u0090', '\u0098', '\u009e', '\u009f'])(
|
||||
'removes %j control strings between visible spans',
|
||||
(opener) => {
|
||||
expect(sanitizeLogLine(`before${opener}private\u009cafter`)).toBe('beforeafter');
|
||||
expect(sanitizeLogLine(`before${opener}private\x1b\\after`)).toBe('beforeafter');
|
||||
expect(sanitizeLogLine(`before${opener}private`)).toBe('before');
|
||||
},
|
||||
);
|
||||
|
||||
it('handles consecutive controls and records consisting only of controls', () => {
|
||||
expect(sanitizeLogLine('\x00\x1b[31m\u009b0m\r\u007f')).toBe('');
|
||||
expect(sanitizeLogLine('a\x00\x1b[31m\u009b0m\r\u007fb')).toBe('ab');
|
||||
expect(sanitizeLogLine('')).toBe('');
|
||||
});
|
||||
|
||||
it('preserves every visible UTF-16 code unit when removing a large hidden payload', () => {
|
||||
const visible = 'visible 🌌 e\u0301\ud800x\udc00';
|
||||
expect(sanitizeLogLine(`${visible}\x1b]${'hidden'.repeat(1000)}`)).toBe(visible);
|
||||
});
|
||||
|
||||
it('does not retain discarded control-string payloads through a short visible span', () => {
|
||||
const moduleUrl = new URL('../src/log-sanitize.ts', import.meta.url).href;
|
||||
const output = execFileSync(
|
||||
process.execPath,
|
||||
[
|
||||
'--expose-gc',
|
||||
'--input-type=module',
|
||||
'-e',
|
||||
`
|
||||
import { setImmediate } from 'node:timers/promises';
|
||||
import { sanitizeLogLine } from ${JSON.stringify(moduleUrl)};
|
||||
async function used() {
|
||||
await setImmediate();
|
||||
global.gc();
|
||||
global.gc();
|
||||
return process.memoryUsage().heapUsed;
|
||||
}
|
||||
function record(i) {
|
||||
return sanitizeLogLine('visible record ' + i + '\\x1b]' + 'x'.repeat(1024 * 1024));
|
||||
}
|
||||
const before = await used();
|
||||
const records = Array.from({ length: 16 }, (_, i) => record(i));
|
||||
const retained = (await used()) - before;
|
||||
console.log(JSON.stringify({ retained, records }));
|
||||
`,
|
||||
],
|
||||
{ encoding: 'utf8', timeout: 10_000 },
|
||||
);
|
||||
const result = JSON.parse(output);
|
||||
expect(result.records).toEqual(Array.from({ length: 16 }, (_, i) => `visible record ${i}`));
|
||||
// Leave ample GC/runtime overhead while rejecting retention of the 16 MiB input.
|
||||
expect(result.retained).toBeLessThan(4 * 1024 * 1024);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,99 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const { fileWrite } = vi.hoisted(() => ({ fileWrite: vi.fn() }));
|
||||
|
||||
vi.mock('../src/log-file-transport', () => ({
|
||||
getFileTransport: () => ({ write: fileWrite, close: async () => {} }),
|
||||
}));
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
vi.unstubAllEnvs();
|
||||
vi.resetModules();
|
||||
fileWrite.mockClear();
|
||||
});
|
||||
|
||||
async function setup() {
|
||||
vi.stubEnv('SNOWLUMA_LOG_LEVEL', 'trace');
|
||||
vi.stubEnv('SNOWLUMA_LOG_FILE_LEVEL', 'error');
|
||||
vi.stubEnv('SNOWLUMA_TRACE_BUFFER', '100');
|
||||
vi.spyOn(process.stdout, 'write').mockReturnValue(true);
|
||||
vi.spyOn(process.stderr, 'write').mockReturnValue(true);
|
||||
const logger = await import('../src/logger');
|
||||
return { ...logger, log: logger.createLogger('Snapshot') };
|
||||
}
|
||||
|
||||
describe('retained log snapshots', () => {
|
||||
it('returns empty snapshots before any record has been emitted', async () => {
|
||||
const logger = await setup();
|
||||
expect(logger.getRecentLogs()).toEqual([]);
|
||||
expect(logger.getLogSnapshot()).toEqual([]);
|
||||
});
|
||||
|
||||
it('merges wrapped rings in emission order and returns only the requested tail', async () => {
|
||||
const logger = await setup();
|
||||
const emitted: import('../src/logger').LogEntry[] = [];
|
||||
const unsubscribe = logger.subscribeLogs((entry) => emitted.push(entry));
|
||||
|
||||
for (let i = 0; i < 1100; i += 1) {
|
||||
logger.log.info('normal %d', i);
|
||||
logger.log.trace('trace %d', i);
|
||||
}
|
||||
|
||||
unsubscribe();
|
||||
const normal = emitted.filter((entry) => entry.level !== 'trace').slice(-1000);
|
||||
const trace = emitted.filter((entry) => entry.level === 'trace').slice(-100);
|
||||
const expected = [...normal, ...trace].sort((a, b) => a.id - b.id);
|
||||
expect(logger.getLogSnapshot()).toEqual(expected);
|
||||
|
||||
for (const limit of [1, 2, 30, 300, 1000, 1100, 2000, 0, -1, 2.9, NaN, Infinity]) {
|
||||
expect(logger.getRecentLogs(limit)).toEqual(
|
||||
expected.slice(-Math.max(1, Math.trunc(limit))),
|
||||
);
|
||||
}
|
||||
|
||||
expect(logger.getRecentLogs()).toEqual(expected.slice(-300));
|
||||
const snapshot = logger.getRecentLogs(5);
|
||||
snapshot.pop();
|
||||
expect(logger.getRecentLogs(5)).toEqual(expected.slice(-5));
|
||||
});
|
||||
|
||||
it.each(['info', 'trace'] as const)(
|
||||
'reads a tail when only the %s ring has records',
|
||||
async (level) => {
|
||||
const logger = await setup();
|
||||
logger.log[level]('first');
|
||||
logger.log[level]('second');
|
||||
expect(logger.getRecentLogs(1).map((entry) => entry.message)).toEqual(['second']);
|
||||
expect(logger.getLogSnapshot().map((entry) => entry.message)).toEqual([
|
||||
'first',
|
||||
'second',
|
||||
]);
|
||||
},
|
||||
);
|
||||
|
||||
it('preserves ID gaps and file routing without publishing file-only entries', async () => {
|
||||
const logger = await setup();
|
||||
vi.stubEnv('SNOWLUMA_LOG_FILE_LEVEL', 'debug');
|
||||
vi.resetModules();
|
||||
const fresh = await import('../src/logger');
|
||||
fresh.setLogLevel('info');
|
||||
const entries: import('../src/logger').LogEntry[] = [];
|
||||
const unsubscribe = fresh.subscribeLogs((entry) => entries.push(entry));
|
||||
const log = fresh.createLogger('FileOnly').child({ uin: 10001 });
|
||||
log.info('before');
|
||||
fresh.runWithRequestId(42, () => log.debug('password=secret file-only\x07'));
|
||||
log.info('after');
|
||||
unsubscribe();
|
||||
|
||||
expect(entries.map((entry) => entry.message)).toEqual(['before', 'after']);
|
||||
expect(entries[1]!.id).toBe(entries[0]!.id + 2);
|
||||
expect(fresh.getLogSnapshot()).toEqual(entries);
|
||||
expect(fileWrite).toHaveBeenCalledWith(
|
||||
expect.stringMatching(/\[req#42\] password=\*\*\* file-only/),
|
||||
10001,
|
||||
);
|
||||
expect(process.stdout.write).toHaveBeenCalledTimes(2);
|
||||
expect(logger.getLogSnapshot()).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { afterEach, describe, it, expect, vi } from 'vitest';
|
||||
import { createSingleFlightCache } from '../src/single-flight-cache';
|
||||
|
||||
/** A promise whose resolve/reject is exposed, for driving single-flight races. */
|
||||
@@ -13,6 +13,129 @@ function deferred<T>() {
|
||||
}
|
||||
|
||||
describe('SingleFlightCache', () => {
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it('disposes retained values and rejects new reads without restarting loads or timers', async () => {
|
||||
vi.useFakeTimers();
|
||||
const load = vi.fn(async (key: string) => ({ key }));
|
||||
const cache = createSingleFlightCache({ ttlMs: 300_000, load });
|
||||
await cache.get('first');
|
||||
await cache.get('second');
|
||||
expect(vi.getTimerCount()).toBe(1);
|
||||
|
||||
cache.dispose();
|
||||
cache.dispose();
|
||||
cache.clear();
|
||||
|
||||
expect(cache.size).toBe(0);
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
await expect(cache.get('first')).rejects.toThrow('disposed');
|
||||
await expect(cache.get('new', { force: true })).rejects.toThrow('disposed');
|
||||
expect(load).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it.each(['resolve', 'reject'] as const)(
|
||||
'preserves a pending %s after disposal without retaining the result',
|
||||
async (outcome) => {
|
||||
vi.useFakeTimers();
|
||||
const pending = deferred<string>();
|
||||
const cache = createSingleFlightCache({ ttlMs: 300_000, load: () => pending.promise });
|
||||
const first = cache.get('key');
|
||||
expect(cache.get('key')).toBe(first);
|
||||
cache.dispose();
|
||||
|
||||
if (outcome === 'resolve') {
|
||||
pending.resolve('late value');
|
||||
await expect(first).resolves.toBe('late value');
|
||||
} else {
|
||||
pending.reject(new Error('late failure'));
|
||||
await expect(first).rejects.toThrow('late failure');
|
||||
}
|
||||
|
||||
expect(cache.size).toBe(0);
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
},
|
||||
);
|
||||
|
||||
it('releases expired values while idle without expiring newer values early', async () => {
|
||||
vi.useFakeTimers();
|
||||
const load = vi.fn(async (key: string) => ({ key }));
|
||||
const cache = createSingleFlightCache({ ttlMs: 1000, load });
|
||||
await cache.get('old');
|
||||
await vi.advanceTimersByTimeAsync(500);
|
||||
const newer = await cache.get('new');
|
||||
|
||||
expect(cache.size).toBe(2);
|
||||
await vi.advanceTimersByTimeAsync(500);
|
||||
expect(cache.size).toBe(1);
|
||||
expect(await cache.get('new')).toBe(newer);
|
||||
expect(load).toHaveBeenCalledTimes(2);
|
||||
|
||||
await vi.advanceTimersByTimeAsync(500);
|
||||
expect(cache.size).toBe(0);
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
});
|
||||
|
||||
it('keeps a refreshed entry until its new deadline and expires other keys', async () => {
|
||||
vi.useFakeTimers();
|
||||
const cache = createSingleFlightCache({ ttlMs: 1000, load: async (key: string) => key });
|
||||
await cache.get('refreshed');
|
||||
await cache.get('old');
|
||||
await vi.advanceTimersByTimeAsync(500);
|
||||
await cache.get('refreshed', { force: true });
|
||||
|
||||
await vi.advanceTimersByTimeAsync(500);
|
||||
expect(cache.size).toBe(1);
|
||||
await vi.advanceTimersByTimeAsync(500);
|
||||
expect(cache.size).toBe(0);
|
||||
});
|
||||
|
||||
it.each(['invalidate', 'clear'] as const)(
|
||||
'%s cancels idle cleanup when the last value is removed',
|
||||
async (operation) => {
|
||||
vi.useFakeTimers();
|
||||
const cache = createSingleFlightCache({ ttlMs: 1000, load: async () => 'value' });
|
||||
await cache.get('key');
|
||||
expect(vi.getTimerCount()).toBe(1);
|
||||
cache[operation]('key');
|
||||
expect(cache.size).toBe(0);
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
|
||||
await cache.get('key');
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
expect(cache.size).toBe(0);
|
||||
},
|
||||
);
|
||||
|
||||
it('does not let expiration detach a pending refresh', async () => {
|
||||
vi.useFakeTimers();
|
||||
const pending = deferred<string>();
|
||||
const load = vi.fn().mockResolvedValueOnce('old').mockReturnValue(pending.promise);
|
||||
const cache = createSingleFlightCache<string, string>({ ttlMs: 1000, load });
|
||||
await cache.get('key');
|
||||
const refresh = cache.get('key', { force: true });
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
|
||||
expect(cache.size).toBe(0);
|
||||
expect(cache.get('key')).toBe(refresh);
|
||||
pending.resolve('new');
|
||||
await expect(refresh).resolves.toBe('new');
|
||||
expect(cache.size).toBe(1);
|
||||
expect(load).toHaveBeenCalledTimes(2);
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
expect(cache.size).toBe(0);
|
||||
});
|
||||
|
||||
it('does not retain values when caching is disabled by a zero TTL', async () => {
|
||||
vi.useFakeTimers();
|
||||
const cache = createSingleFlightCache({ ttlMs: 0, load: async () => 'value' });
|
||||
await expect(cache.get('key')).resolves.toBe('value');
|
||||
expect(cache.size).toBe(0);
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
});
|
||||
|
||||
it.each(['invalidate', 'clear'] as const)(
|
||||
'%s detaches pending loads from the cache',
|
||||
async (operation) => {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "@snowluma/core",
|
||||
"version": "2.4.0",
|
||||
"version": "2.4.2",
|
||||
"description": "SnowLuma core - NTQQ packet sniffer with Node.js native addon",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { GroupInviteTracker } from '@snowluma/protocol/group-invite-tracker';
|
||||
import { isSelfGroupInvitation } from '@snowluma/protocol/qq-info';
|
||||
import { groupRequestSubType } from '@snowluma/protocol/qq-info';
|
||||
import { FetchDownloadRkeys } from '@snowluma/protocol/oidb-services/contacts/fetch-download-rkeys';
|
||||
import {
|
||||
FetchFriendListPage,
|
||||
@@ -12,7 +12,8 @@ import { FetchGroupMemberListPage } from '@snowluma/protocol/oidb-services/conta
|
||||
import {
|
||||
FetchGroupRequests,
|
||||
FetchGroupRequestsByUid,
|
||||
groupRequestOperationType,
|
||||
groupRequestNotifyType,
|
||||
type DecodedGroupRequest,
|
||||
} from '@snowluma/protocol/oidb-services/contacts/fetch-group-requests';
|
||||
import {
|
||||
FetchRobotUinRanges,
|
||||
@@ -79,19 +80,43 @@ export function isRobotUin(uin: number, ranges: readonly RobotUinRange[]): boole
|
||||
);
|
||||
}
|
||||
|
||||
function normalizeGroupRequestSequence(
|
||||
rawSequence: bigint | number | undefined,
|
||||
function groupRequestMetadata(
|
||||
raw: Pick<
|
||||
DecodedGroupRequest,
|
||||
'sequence' | 'state' | 'eventType' | 'comment' | 'operateTransInfo'
|
||||
>,
|
||||
groupId: number,
|
||||
): number {
|
||||
const sequence = Number(rawSequence ?? 0);
|
||||
filtered: boolean,
|
||||
) {
|
||||
const sequence = Number(raw.sequence ?? 0);
|
||||
|
||||
if (!Number.isSafeInteger(sequence) || sequence <= 0) {
|
||||
throw new Error(
|
||||
`invalid group-request sequence: group=${groupId} sequence=${String(rawSequence ?? 0)}`,
|
||||
`invalid group-request sequence: group=${groupId} sequence=${String(raw.sequence ?? 0)}`,
|
||||
);
|
||||
}
|
||||
|
||||
return sequence;
|
||||
const eventType = raw.eventType ?? 0;
|
||||
const notifyType = groupRequestNotifyType(eventType);
|
||||
|
||||
if (notifyType === undefined) {
|
||||
log.warn(
|
||||
'unsupported group-request wire type: group=%d sequence=%d type=%d',
|
||||
groupId,
|
||||
sequence,
|
||||
eventType,
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
sequence,
|
||||
state: raw.state ?? 0,
|
||||
eventType,
|
||||
notifyType,
|
||||
comment: raw.comment ?? '',
|
||||
filtered,
|
||||
operateTransInfo: raw.operateTransInfo?.length ? raw.operateTransInfo : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
const MEMBER_LIST_TTL_MS = 60_000;
|
||||
@@ -132,6 +157,12 @@ export class ContactsApi {
|
||||
|
||||
constructor(private readonly ctx: BridgeContext) {}
|
||||
|
||||
dispose(): void {
|
||||
// Late roster responses must not start new profile loads after shutdown.
|
||||
this.memberListCache.dispose();
|
||||
this.friendProfiles.dispose();
|
||||
}
|
||||
|
||||
private fetchRobotUinRanges(groupId: number): Promise<RobotUinRangeSnapshot> {
|
||||
if (this.robotUinRangesPromise_) {
|
||||
return this.robotUinRangesPromise_;
|
||||
@@ -492,8 +523,7 @@ export class ContactsApi {
|
||||
member.isRobot = isRobotUin(member.uin, robotSnapshot.ranges);
|
||||
}
|
||||
|
||||
this.ctx.identity.rememberGroupMembers(groupId, members);
|
||||
return members;
|
||||
return this.ctx.identity.rememberGroupMembers(groupId, members);
|
||||
}
|
||||
|
||||
async fetchUserProfile(uin: number): Promise<UserProfileInfo> {
|
||||
@@ -550,18 +580,6 @@ export class ContactsApi {
|
||||
this.ctx.identity.findUidByUin(operatorUin, groupId) ||
|
||||
this.ctx.identity.findUidByUin(operatorUin) ||
|
||||
'';
|
||||
const notifyType = raw.eventType ?? 0;
|
||||
const operationType = groupRequestOperationType(notifyType);
|
||||
const sequence = normalizeGroupRequestSequence(raw.sequence, groupId);
|
||||
|
||||
if (operationType === null) {
|
||||
log.warn(
|
||||
'unsupported group-request notification type: group=%d sequence=%s type=%d',
|
||||
groupId,
|
||||
String(raw.sequence ?? 0n),
|
||||
notifyType,
|
||||
);
|
||||
}
|
||||
|
||||
requests.push({
|
||||
groupId,
|
||||
@@ -587,16 +605,7 @@ export class ContactsApi {
|
||||
this.ctx.identity.findUinByUid(operatorUid) ||
|
||||
0,
|
||||
operatorName: raw.operatorUser?.name ?? '',
|
||||
sequence,
|
||||
state: raw.state ?? 0,
|
||||
notifyType,
|
||||
eventType: operationType ?? 0,
|
||||
comment: raw.comment ?? '',
|
||||
filtered,
|
||||
operateTransInfo:
|
||||
raw.operateTransInfo && raw.operateTransInfo.length > 0
|
||||
? raw.operateTransInfo
|
||||
: undefined,
|
||||
...groupRequestMetadata(raw, groupId, filtered),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -620,18 +629,6 @@ export class ContactsApi {
|
||||
const targetUid = raw.target?.uid ?? '';
|
||||
const invitorUid = raw.invitor?.uid ?? '';
|
||||
const operatorUid = raw.operatorUser?.uid ?? '';
|
||||
const notifyType = raw.eventType ?? 0;
|
||||
const operationType = groupRequestOperationType(notifyType);
|
||||
const sequence = normalizeGroupRequestSequence(raw.sequence, groupId);
|
||||
|
||||
if (operationType === null) {
|
||||
log.warn(
|
||||
'unsupported group-request notification type: group=%d sequence=%s type=%d',
|
||||
groupId,
|
||||
String(raw.sequence ?? 0n),
|
||||
notifyType,
|
||||
);
|
||||
}
|
||||
|
||||
requests.push({
|
||||
groupId,
|
||||
@@ -654,16 +651,7 @@ export class ContactsApi {
|
||||
this.ctx.identity.findUinByUid(operatorUid) ??
|
||||
0,
|
||||
operatorName: raw.operatorUser?.name ?? '',
|
||||
sequence,
|
||||
state: raw.state ?? 0,
|
||||
notifyType,
|
||||
eventType: operationType ?? 0,
|
||||
comment: raw.comment ?? '',
|
||||
filtered,
|
||||
operateTransInfo:
|
||||
raw.operateTransInfo && raw.operateTransInfo.length > 0
|
||||
? raw.operateTransInfo
|
||||
: undefined,
|
||||
...groupRequestMetadata(raw, groupId, filtered),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -692,15 +680,17 @@ export class ContactsApi {
|
||||
|
||||
return (
|
||||
[...main.value, ...filtered.value].find((request) => {
|
||||
if (request.groupId !== groupId || request.state !== 1) {
|
||||
if (
|
||||
request.groupId !== groupId ||
|
||||
request.state !== 1 ||
|
||||
groupRequestSubType(request) !== subType
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return subType === 'add'
|
||||
? request.eventType === 1 && request.targetUid === uid
|
||||
: (isSelfGroupInvitation(request) || request.eventType === 22) &&
|
||||
request.invitorUid === uid &&
|
||||
request.targetUid === invitedUid;
|
||||
? request.targetUid === uid
|
||||
: request.invitorUid === uid && request.targetUid === invitedUid;
|
||||
}) ?? null
|
||||
);
|
||||
}
|
||||
|
||||
@@ -35,6 +35,9 @@ export interface PttTransInput {
|
||||
duration: number;
|
||||
size: number;
|
||||
format: number;
|
||||
/** Omitted by older callers for legacy voice media. */
|
||||
isNtv2?: boolean;
|
||||
storeRegion?: number;
|
||||
/** Group ptt numeric file id (group only; optional). */
|
||||
fileId?: number;
|
||||
}
|
||||
@@ -390,6 +393,8 @@ export class ExtrasApi {
|
||||
md5,
|
||||
},
|
||||
};
|
||||
req.isNtv2 = input.isNtv2 ? 1 : 0;
|
||||
req.storeRegion = input.isNtv2 ? (input.storeRegion ?? 0) : 0;
|
||||
const cmd = input.isGroup ? 'pttTrans.TransGroupPttReq' : 'pttTrans.TransC2CPttReq';
|
||||
|
||||
const result = await this.ctx.sendRawPacket(cmd, protobuf_encode<PttTransReq>(req));
|
||||
@@ -406,9 +411,11 @@ export class ExtrasApi {
|
||||
// sourced from cache, to tell a server-side ASR failure apart from our own
|
||||
// missing/zero field (md5/format/uuid). Behaviour unchanged — still throws.
|
||||
log.warn(
|
||||
'ptt translate errCode=%d isGroup=%s md5=%s format=%d uuid=%s dur=%d size=%d',
|
||||
'ptt translate errCode=%d isGroup=%s ntv2=%d region=%d md5=%s format=%d uuid=%s dur=%d size=%d',
|
||||
item.errCode,
|
||||
input.isGroup,
|
||||
req.isNtv2,
|
||||
req.storeRegion,
|
||||
input.md5Hex ? `${input.md5Hex.length / 2}B` : 'EMPTY',
|
||||
input.format,
|
||||
input.uuid ? 'set' : 'EMPTY',
|
||||
|
||||
@@ -406,6 +406,7 @@ export class ForwardApi {
|
||||
name: string,
|
||||
groupId?: number,
|
||||
userId?: number,
|
||||
allowTemporary = true,
|
||||
): Promise<MessageElementOf<'file'>> {
|
||||
if (groupId !== undefined) {
|
||||
const uploaded = await this.ctx.apis.groupFile.upload(
|
||||
@@ -415,6 +416,7 @@ export class ForwardApi {
|
||||
'/',
|
||||
true,
|
||||
false,
|
||||
{ allowTemporary },
|
||||
);
|
||||
|
||||
if (!uploaded.fileId) {
|
||||
@@ -482,6 +484,7 @@ export class ForwardApi {
|
||||
element: MessageElement,
|
||||
groupId?: number,
|
||||
userId?: number,
|
||||
allowTemporary = true,
|
||||
): Promise<MessageElement> {
|
||||
if (element.type !== 'file') {
|
||||
return element;
|
||||
@@ -495,6 +498,7 @@ export class ForwardApi {
|
||||
fileNameForUpload(element),
|
||||
groupId,
|
||||
userId,
|
||||
allowTemporary,
|
||||
);
|
||||
return {
|
||||
...stripFileSource(element),
|
||||
@@ -506,6 +510,14 @@ export class ForwardApi {
|
||||
const cached = this.ctx.recallUploadedFile(element.fileId);
|
||||
|
||||
if (isCachedFileUsableInTarget(cached, groupId, userId)) {
|
||||
if (groupId !== undefined && cached?.busId === 104 && !allowTemporary) {
|
||||
throw new MessageElementValidationError(
|
||||
'UNSENDABLE_TYPE',
|
||||
'temporary group files require only file or image segments in the same forward node',
|
||||
'file',
|
||||
);
|
||||
}
|
||||
|
||||
return element;
|
||||
}
|
||||
|
||||
@@ -515,6 +527,7 @@ export class ForwardApi {
|
||||
fileNameForUpload(element, cached),
|
||||
groupId,
|
||||
userId,
|
||||
allowTemporary,
|
||||
);
|
||||
return {
|
||||
...stripFileSource(element),
|
||||
@@ -532,9 +545,12 @@ export class ForwardApi {
|
||||
): Promise<ForwardNodePayload[]> {
|
||||
return Promise.all(
|
||||
nodes.map(async (node) => {
|
||||
const allowTemporary = node.elements.every(
|
||||
(element) => element.type === 'file' || element.type === 'image',
|
||||
);
|
||||
const elements = await Promise.all(
|
||||
node.elements.map((element) =>
|
||||
this.prepareForwardFileElement(element, groupId, userId),
|
||||
this.prepareForwardFileElement(element, groupId, userId, allowTemporary),
|
||||
),
|
||||
);
|
||||
return cloneNodeWithElements(node, elements);
|
||||
@@ -890,7 +906,7 @@ export class ForwardApi {
|
||||
}
|
||||
|
||||
for (const [groupId, groupNodes] of byGroup) {
|
||||
let byUin: Map<number, { nickname: string; card: string }>;
|
||||
let byUin: Map<number, { nickname: string; card?: string }>;
|
||||
|
||||
try {
|
||||
const members = await this.ctx.apis.contacts.fetchGroupMemberList(groupId);
|
||||
|
||||
@@ -76,6 +76,16 @@ export interface UploadFileResult {
|
||||
fileHash?: string | null;
|
||||
}
|
||||
|
||||
export interface GroupFileUploadResult {
|
||||
fileId: string;
|
||||
busId: number;
|
||||
}
|
||||
|
||||
export interface GroupFileUploadOptions {
|
||||
/** False when the enclosing message contains content a temporary file cannot carry. */
|
||||
allowTemporary?: boolean;
|
||||
}
|
||||
|
||||
// Re-export so callers don't have to dig into apis/shared.
|
||||
export type { MediaIndexNode } from './shared';
|
||||
|
||||
@@ -136,6 +146,7 @@ async function assertUnchanged(
|
||||
function buildGroupFileUploadExt(
|
||||
senderUin: number,
|
||||
groupId: number,
|
||||
busId: number,
|
||||
fileName: string,
|
||||
fileSize: number,
|
||||
md5: Uint8Array,
|
||||
@@ -150,7 +161,7 @@ function buildGroupFileUploadExt(
|
||||
unknown2: 1,
|
||||
entry: {
|
||||
busiBuff: {
|
||||
busId: 102,
|
||||
busId,
|
||||
senderUin: BigInt(senderUin),
|
||||
receiverUin: BigInt(groupId),
|
||||
groupCode: BigInt(groupId),
|
||||
@@ -255,12 +266,23 @@ export class GroupFileApi {
|
||||
|
||||
// ─────────────── publish (group file → chat) ───────────────
|
||||
|
||||
publish(groupId: number, fileId: string): Promise<void> {
|
||||
publish(groupId: number, fileId: string, busId?: number): Promise<void> {
|
||||
if (!fileId) {
|
||||
throw new Error('publish requires fileId');
|
||||
}
|
||||
|
||||
return PublishGroupFile.invoke(this.ctx, { groupId, fileId });
|
||||
return PublishGroupFile.invoke(this.ctx, {
|
||||
groupId,
|
||||
fileId,
|
||||
busId: busId ?? this.cachedBusId(groupId, fileId),
|
||||
});
|
||||
}
|
||||
|
||||
private cachedBusId(groupId: number, fileId: string): number {
|
||||
const cached = this.ctx.recallUploadedFile(fileId);
|
||||
return cached?.scope === 'group' && cached.groupId === groupId
|
||||
? (cached.busId ?? 102)
|
||||
: 102;
|
||||
}
|
||||
|
||||
trans(groupId: number, fileId: string): Promise<TransGroupFileResult> {
|
||||
@@ -290,7 +312,8 @@ export class GroupFileApi {
|
||||
folderId = '/',
|
||||
uploadFile = true,
|
||||
publishFile = uploadFile,
|
||||
): Promise<UploadFileResult> {
|
||||
options: GroupFileUploadOptions = {},
|
||||
): Promise<GroupFileUploadResult> {
|
||||
const bridge = this.ctx;
|
||||
// Group/private files may legitimately be up to 4 GiB on QQ's wire, so
|
||||
// override the default 1 GiB cap with the protocol ceiling. Stage onto a
|
||||
@@ -307,14 +330,36 @@ export class GroupFileApi {
|
||||
const guardStat = await fsp.stat(staged.filePath); // mutation-guard baseline
|
||||
const hashes = await hashFileStreaming(staged.filePath);
|
||||
|
||||
const upload = await UploadGroupFileRequest.invoke(this.ctx, {
|
||||
const params: UploadGroupFileRequest.Params = {
|
||||
groupId,
|
||||
fileName,
|
||||
folderId: normalizeDirectory(folderId),
|
||||
fileSize: staged.fileSize,
|
||||
fileSha1: hashes.sha1,
|
||||
fileMd5: hashes.md5,
|
||||
});
|
||||
busId: 102,
|
||||
};
|
||||
let upload = await UploadGroupFileRequest.invoke(this.ctx, params);
|
||||
|
||||
// These are the storage-limit responses for which QQ switches to
|
||||
// temporary storage. Never retry transport, permission or arbitrary
|
||||
// service errors, and never retry the temporary request itself.
|
||||
if (upload.retCode === -403 || upload.retCode === -9801 || upload.retCode === -98090) {
|
||||
if (options.allowTemporary === false) {
|
||||
throw new Error(
|
||||
`temporary group files require only file or image segments; remove text and other content before retrying (group file upload code=${upload.retCode})`,
|
||||
);
|
||||
}
|
||||
|
||||
log.warn(
|
||||
'Group %d permanent file storage rejected upload (code=%d); retrying as a temporary file',
|
||||
groupId,
|
||||
upload.retCode,
|
||||
);
|
||||
params.busId = 104;
|
||||
upload = await UploadGroupFileRequest.invoke(this.ctx, params);
|
||||
}
|
||||
|
||||
ensureRetCodeZero(
|
||||
'group file upload',
|
||||
upload.retCode,
|
||||
@@ -322,6 +367,18 @@ export class GroupFileApi {
|
||||
upload.clientWording,
|
||||
);
|
||||
|
||||
const busId = upload.busId || params.busId;
|
||||
|
||||
if (busId !== 102 && busId !== 104) {
|
||||
throw new Error(`group file upload returned unsupported storage type: ${busId}`);
|
||||
}
|
||||
|
||||
if (busId === 104 && options.allowTemporary === false) {
|
||||
throw new Error(
|
||||
'temporary group files require only file or image segments; remove text and other content before retrying',
|
||||
);
|
||||
}
|
||||
|
||||
const fileId =
|
||||
typeof upload.fileId === 'string' && upload.fileId ? upload.fileId : null;
|
||||
|
||||
@@ -329,23 +386,6 @@ export class GroupFileApi {
|
||||
throw new Error('group file upload response missing file_id');
|
||||
}
|
||||
|
||||
// Remember the upload so a later `send_group_msg` carrying just the
|
||||
// file_id can route via `publish` without forcing the OneBot caller
|
||||
// to thread fileName/size/md5 separately. For groups the wire
|
||||
// publish (OIDB 0x6d9_4) only needs the file_id itself, so this is
|
||||
// mainly for log-line correctness; the c2c counterpart in
|
||||
// `uploadPrivate` is where the cache is actually load-bearing.
|
||||
this.ctx.rememberUploadedFile({
|
||||
fileId,
|
||||
scope: 'group',
|
||||
groupId,
|
||||
fileName,
|
||||
fileSize: staged.fileSize,
|
||||
fileMd5: hashes.md5,
|
||||
fileSha1: hashes.sha1,
|
||||
rememberedAt: Date.now(),
|
||||
});
|
||||
|
||||
if (!upload.boolFileExist && uploadFile) {
|
||||
const senderUin = toInt(this.ctx.identity.uin);
|
||||
|
||||
@@ -366,6 +406,7 @@ export class GroupFileApi {
|
||||
const ext = buildGroupFileUploadExt(
|
||||
senderUin,
|
||||
groupId,
|
||||
busId,
|
||||
fileName,
|
||||
staged.fileSize,
|
||||
hashes.md5,
|
||||
@@ -386,6 +427,20 @@ export class GroupFileApi {
|
||||
await uploadHighwayHttp(bridge, session, 71, chunkSource, hashes.md5, ext);
|
||||
}
|
||||
|
||||
// Retain the storage type for later file_id publication and download.
|
||||
// A failed byte transfer must not leave a usable-looking cache entry.
|
||||
this.ctx.rememberUploadedFile({
|
||||
fileId,
|
||||
scope: 'group',
|
||||
groupId,
|
||||
busId,
|
||||
fileName,
|
||||
fileSize: staged.fileSize,
|
||||
fileMd5: hashes.md5,
|
||||
fileSha1: hashes.sha1,
|
||||
rememberedAt: Date.now(),
|
||||
});
|
||||
|
||||
// Stage 3: file is on the server, now publish it as a chat message.
|
||||
//
|
||||
// Without this, OIDB 0x6D6_0 + highway PUT only stages the bytes —
|
||||
@@ -398,7 +453,7 @@ export class GroupFileApi {
|
||||
// tests can mock at the same Api boundary.
|
||||
if (publishFile) {
|
||||
try {
|
||||
await this.publish(groupId, fileId);
|
||||
await this.publish(groupId, fileId, busId);
|
||||
} catch (err) {
|
||||
// Keep the completed upload identifiable, but a requested chat
|
||||
// publication must not be reported as a successful send.
|
||||
@@ -409,7 +464,7 @@ export class GroupFileApi {
|
||||
}
|
||||
}
|
||||
|
||||
return { fileId };
|
||||
return { fileId, busId };
|
||||
} finally {
|
||||
await staged.cleanup();
|
||||
}
|
||||
@@ -711,8 +766,12 @@ export class GroupFileApi {
|
||||
|
||||
// ─────────────── url fetch (group / private files) ───────────────
|
||||
|
||||
async getUrl(groupId: number, fileId: string, busId = 102): Promise<string> {
|
||||
return GetGroupFileUrl.invoke(this.ctx, { groupId, fileId, busId });
|
||||
async getUrl(groupId: number, fileId: string, busId?: number): Promise<string> {
|
||||
return GetGroupFileUrl.invoke(this.ctx, {
|
||||
groupId,
|
||||
fileId,
|
||||
busId: busId ?? this.cachedBusId(groupId, fileId),
|
||||
});
|
||||
}
|
||||
|
||||
async getPrivateUrl(userId: number, fileId: string, fileHash: string): Promise<string> {
|
||||
|
||||
@@ -17,6 +17,8 @@ import type { OnlineDeviceInfo } from '@snowluma/protocol/events';
|
||||
import { buildApiHub, type ApiHub } from './apis';
|
||||
import { AiVoiceChatType, type AiVoiceCategory, type StrangerStatus } from './apis/extras';
|
||||
import type { BridgeInterface, RosterWarmupResult } from './bridge-interface';
|
||||
import type { UploadedFileMeta } from './bridge-context';
|
||||
export type { UploadedFileMeta } from './bridge-context';
|
||||
|
||||
const log = createLogger('Bridge');
|
||||
const runtimeLog = createLogger('Bridge.Runtime');
|
||||
@@ -102,6 +104,7 @@ export class Bridge implements BridgeInterface {
|
||||
this.disposePromise_ = (async () => {
|
||||
try {
|
||||
await Promise.allSettled(this.pendingPackets_);
|
||||
this.apis.contacts.dispose();
|
||||
await this.identity.close();
|
||||
} finally {
|
||||
this.events.clear();
|
||||
@@ -593,23 +596,6 @@ export interface SendMessageReceipt {
|
||||
timestamp: number;
|
||||
}
|
||||
|
||||
export interface UploadedFileMeta {
|
||||
fileId: string;
|
||||
scope: 'group' | 'private';
|
||||
/** Group id if scope='group', else `undefined`. */
|
||||
groupId?: number;
|
||||
/** Friend uin if scope='private', else `undefined`. */
|
||||
userId?: number;
|
||||
fileName: string;
|
||||
fileSize: number;
|
||||
fileMd5: Uint8Array;
|
||||
fileSha1: Uint8Array;
|
||||
/** Server-issued hash returned alongside the upload (private only). */
|
||||
fileHash?: string;
|
||||
/** Insert time — used to evict the oldest entry when the cache fills. */
|
||||
rememberedAt: number;
|
||||
}
|
||||
|
||||
export interface DownloadRKeyInfo {
|
||||
rkey: string;
|
||||
ttlSeconds: number;
|
||||
|
||||
@@ -2,6 +2,7 @@ import { describe, expect, it, vi } from 'vitest';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import type { pb, pb_repeated, uint_32, uint_64 } from '@snowluma/proton';
|
||||
import type { SendPacketResult } from '@snowluma/common/packet-sender';
|
||||
import type { GroupMemberInfo } from '@snowluma/protocol/qq-info';
|
||||
import type {
|
||||
OidbBase,
|
||||
OidbEmpty,
|
||||
@@ -397,7 +398,7 @@ describe('apis/contacts / group requests', () => {
|
||||
requests: [
|
||||
{
|
||||
sequence: 1_785_525_232_784_291n,
|
||||
eventType: 7,
|
||||
eventType: 1,
|
||||
state: 1,
|
||||
group: { groupUin: 1_095_186_374, groupName: 'group' },
|
||||
target: { uin: 1_234_567_890, name: 'requester' },
|
||||
@@ -439,7 +440,7 @@ describe('apis/contacts / group requests', () => {
|
||||
requests: [
|
||||
{
|
||||
sequence: 42n,
|
||||
eventType: 7,
|
||||
eventType: 1,
|
||||
state: 1,
|
||||
group: { groupUin: 999, groupName: 'group' },
|
||||
target: { uid: 'target_uid', name: 'requester' },
|
||||
@@ -462,6 +463,8 @@ describe('apis/contacts / group requests', () => {
|
||||
targetUin: 1_234_567_890,
|
||||
invitorUid: 'inviter_uid',
|
||||
operatorUid: 'operator_uid',
|
||||
notifyType: 7,
|
||||
eventType: 1,
|
||||
filtered: true,
|
||||
}),
|
||||
]);
|
||||
@@ -650,7 +653,9 @@ describe('apis/contacts / categorized friend roster', () => {
|
||||
|
||||
describe('apis/contacts / robot group-member classification', () => {
|
||||
it('loads QQ robot ranges once and marks every fetched member', async () => {
|
||||
const rememberGroupMembers = vi.fn();
|
||||
const rememberGroupMembers = vi.fn(
|
||||
(_groupId: number, members: GroupMemberInfo[]) => members,
|
||||
);
|
||||
const sendRawPacket = vi.fn(
|
||||
async (cmd: string, _data: Uint8Array): Promise<SendPacketResult> => {
|
||||
if (cmd === 'OidbSvcTrpcTcp.0x496_0') {
|
||||
@@ -733,7 +738,9 @@ describe('apis/contacts / robot group-member classification', () => {
|
||||
throw new Error(`unexpected command: ${cmd}`);
|
||||
},
|
||||
);
|
||||
const rememberGroupMembers = vi.fn();
|
||||
const rememberGroupMembers = vi.fn(
|
||||
(_groupId: number, members: GroupMemberInfo[]) => members,
|
||||
);
|
||||
const api = new ContactsApi({
|
||||
sendRawPacket,
|
||||
identity: { uin: '10001', rememberGroupMembers },
|
||||
|
||||
@@ -73,6 +73,64 @@ function decodeLongMsgRequest(rawBytes: Uint8Array): LongMsgResult {
|
||||
}
|
||||
|
||||
describe('actions/forward — file segment inside forward node', () => {
|
||||
it('rejects cached temporary files mixed with text before building a forward payload', async () => {
|
||||
buildSendElemsMock.mockClear();
|
||||
const bridge = mockBridge({
|
||||
recallUploadedFile: vi.fn(() => ({ scope: 'group', groupId: 12345, busId: 104 })),
|
||||
});
|
||||
await expect(
|
||||
new ForwardApi(bridge as any).upload(
|
||||
[
|
||||
{
|
||||
userUin: 10001,
|
||||
nickname: 'alice',
|
||||
elements: [
|
||||
{ type: 'text', text: 'caption' },
|
||||
{ type: 'file', fileId: 'temp' },
|
||||
],
|
||||
},
|
||||
],
|
||||
12345,
|
||||
),
|
||||
).rejects.toThrow(/temporary group files.*only file or image/i);
|
||||
expect(buildSendElemsMock).not.toHaveBeenCalled();
|
||||
expect(bridge.sendRawPacket).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('disallows temporary fallback when a forward node mixes a new file with text', async () => {
|
||||
buildSendElemsMock.mockClear();
|
||||
const bridge = mockBridge();
|
||||
bridge.apis.groupFile.upload.mockRejectedValueOnce(
|
||||
new Error('temporary group files require only file or image segments'),
|
||||
);
|
||||
await expect(
|
||||
new ForwardApi(bridge as any).upload(
|
||||
[
|
||||
{
|
||||
userUin: 10001,
|
||||
nickname: 'alice',
|
||||
elements: [
|
||||
{ type: 'text', text: 'caption' },
|
||||
{ type: 'file', url: 'base64://AQID', fileName: 'note.txt' },
|
||||
],
|
||||
},
|
||||
],
|
||||
12345,
|
||||
),
|
||||
).rejects.toThrow(/temporary group files/);
|
||||
expect(bridge.apis.groupFile.upload).toHaveBeenCalledWith(
|
||||
12345,
|
||||
'base64://AQID',
|
||||
'note.txt',
|
||||
'/',
|
||||
true,
|
||||
false,
|
||||
{ allowTemporary: false },
|
||||
);
|
||||
expect(buildSendElemsMock).not.toHaveBeenCalled();
|
||||
expect(bridge.sendRawPacket).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects a recursive window shake before identity resolution or upload', async () => {
|
||||
buildSendElemsMock.mockClear();
|
||||
const resolveUserUid = vi.fn();
|
||||
@@ -288,7 +346,9 @@ describe('actions/forward — file segment inside forward node', () => {
|
||||
12345,
|
||||
);
|
||||
|
||||
expect(upload).toHaveBeenCalledWith(12345, 'base64://AQID', 'note.txt', '/', true, false);
|
||||
expect(upload).toHaveBeenCalledWith(12345, 'base64://AQID', 'note.txt', '/', true, false, {
|
||||
allowTemporary: true,
|
||||
});
|
||||
expect(publish).not.toHaveBeenCalled();
|
||||
const [elements] = buildSendElemsMock.mock.calls[0]!;
|
||||
expect(elements).toEqual([
|
||||
@@ -513,6 +573,7 @@ describe('actions/forward — file segment inside forward node', () => {
|
||||
'/',
|
||||
true,
|
||||
false,
|
||||
{ allowTemporary: true },
|
||||
);
|
||||
const [elements] = buildSendElemsMock.mock.calls[0]!;
|
||||
expect(elements).toEqual([
|
||||
|
||||
@@ -28,7 +28,7 @@ function message(...elems: Elem[]): PushMsgBody {
|
||||
responseHead: {
|
||||
fromUin: 20002,
|
||||
fromUid: 'sender-uid',
|
||||
grp: { groupUin: 12345, memberCard: 'alice' },
|
||||
grp: { groupUin: 12345, memberCard: Buffer.from('alice') },
|
||||
},
|
||||
contentHead: { msgType: 82, sequence: 10, timestamp: 1700000000 },
|
||||
body: { richText: { elems } },
|
||||
@@ -163,7 +163,7 @@ describe('get_forward_msg / cache lifetime', () => {
|
||||
|
||||
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 = '';
|
||||
nameless.responseHead!.grp!.memberCard = new Uint8Array();
|
||||
const downloads = new Map([
|
||||
['enrich-outer', nestedResult('enrich-inner', 'enrich-key', nameless)],
|
||||
]);
|
||||
@@ -220,7 +220,7 @@ describe('get_forward_msg / cache lifetime', () => {
|
||||
|
||||
it('does not resurrect evicted nested results when enrichment finishes late', async () => {
|
||||
const nameless = message({ text: { str: 'late sender' } });
|
||||
nameless.responseHead!.grp!.memberCard = '';
|
||||
nameless.responseHead!.grp!.memberCard = new Uint8Array();
|
||||
const downloads = new Map([
|
||||
['late-outer', nestedResult('late-inner', 'late-key', nameless)],
|
||||
]);
|
||||
|
||||
@@ -43,7 +43,7 @@ function message(...elems: Elem[]): PushMsgBody {
|
||||
responseHead: {
|
||||
fromUin: 20002,
|
||||
fromUid: 'sender-uid',
|
||||
grp: { groupUin: 12345, memberCard: 'alice' },
|
||||
grp: { groupUin: 12345, memberCard: Buffer.from('alice') },
|
||||
},
|
||||
contentHead: { msgType: 82, sequence: 10, timestamp: 1700000000 },
|
||||
body: { richText: { elems } },
|
||||
|
||||
@@ -71,7 +71,7 @@ function setup(id: string) {
|
||||
responseHead: {
|
||||
fromUin: 20002,
|
||||
fromUid: 'sender-uid',
|
||||
grp: { groupUin: 12345, memberCard: 'alice' },
|
||||
grp: { groupUin: 12345, memberCard: Buffer.from('alice') },
|
||||
},
|
||||
contentHead: { msgType: 82, sequence: 10, timestamp: 1700000000 },
|
||||
body: {
|
||||
|
||||
@@ -190,7 +190,7 @@ describe('actions/forward', () => {
|
||||
responseHead: {
|
||||
fromUin: 1787882683,
|
||||
fromUid: 'u_x',
|
||||
grp: { groupUin: 284840486, memberCard: '墨梓柒' },
|
||||
grp: { groupUin: 284840486, memberCard: Buffer.from('墨梓柒') },
|
||||
},
|
||||
contentHead: { msgType: 82, sequence: 1, timestamp: 100 }, // 82 = PkgType.GroupMessage
|
||||
body: { richText: { elems: [{ text: { str: 'hi' } }] } },
|
||||
|
||||
@@ -26,6 +26,7 @@ const bridges: Bridge[] = [];
|
||||
afterEach(async () => {
|
||||
await Promise.all(bridges.splice(0).map((bridge) => bridge.dispose()));
|
||||
vi.restoreAllMocks();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
function friend(uin: number, name = 'Roster'): OidbFriend {
|
||||
@@ -118,6 +119,40 @@ function setup(roster: () => OidbFriend[], load: (uin: number) => Promise<void>
|
||||
}
|
||||
|
||||
describe('explicit friend profile enrichment', () => {
|
||||
it('releases profile cache timers when its Bridge is disposed', async () => {
|
||||
vi.useFakeTimers();
|
||||
const { api, bridge, profileCalls } = setup(() => [friend(10001)]);
|
||||
await api.fetchFriendList({ withProfile: true });
|
||||
expect(profileCalls).toEqual([10001]);
|
||||
expect(vi.getTimerCount()).toBe(1);
|
||||
|
||||
await bridge.dispose();
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
});
|
||||
|
||||
it('does not start profile cache loads when a roster response arrives after disposal', async () => {
|
||||
vi.useFakeTimers();
|
||||
const { api, bridge, send, profileCalls } = setup(() => [friend(10001)]);
|
||||
const response = await send.getMockImplementation()!(
|
||||
'OidbSvcTrpcTcp.0xfd4_1',
|
||||
new Uint8Array(),
|
||||
);
|
||||
let resolve!: (value: typeof response) => void;
|
||||
send.mockReturnValueOnce(
|
||||
new Promise((yes) => {
|
||||
resolve = yes;
|
||||
}),
|
||||
);
|
||||
const pending = api.fetchFriendList({ withProfile: true });
|
||||
const checked = expect(pending).rejects.toThrow('friend profile enrichment failed');
|
||||
await bridge.dispose();
|
||||
|
||||
resolve(response);
|
||||
await checked;
|
||||
expect(profileCalls).toEqual([]);
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
});
|
||||
|
||||
it('does not fan out on a cold 160-friend ordinary or categorized list', async () => {
|
||||
const { api, profileCalls, send } = setup(() =>
|
||||
Array.from({ length: 160 }, (_, i) => friend(10000 + i)),
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
import { describe, it, expect, vi, beforeEach, beforeAll, afterAll } from 'vitest';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import type { OidbBase } from '@snowluma/proto-defs/oidb';
|
||||
import type { FileUploadExt } from '@snowluma/proto-defs/highway';
|
||||
import type {
|
||||
OidbGroupFileCountViewResp,
|
||||
OidbGroupFileReq,
|
||||
OidbGroupFileResp,
|
||||
OidbGroupFileUploadResp,
|
||||
OidbGroupFileViewResp,
|
||||
OidbGroupFileFolderResp,
|
||||
OidbGroupSendFileReq,
|
||||
@@ -70,6 +72,10 @@ function packResponse(body: Uint8Array) {
|
||||
};
|
||||
}
|
||||
|
||||
function uploadResponse(upload: OidbGroupFileUploadResp) {
|
||||
return packResponse(protobuf_encode<OidbBase<OidbGroupFileResp>>({ body: { upload } }));
|
||||
}
|
||||
|
||||
let STAGED_FILE: string;
|
||||
|
||||
describe('apis/group-file', () => {
|
||||
@@ -138,7 +144,7 @@ describe('apis/group-file', () => {
|
||||
const api = new GroupFileApi(bridge as any);
|
||||
vi.spyOn(api, 'publish').mockResolvedValue();
|
||||
const out = await api.upload(12345, '/path/file.bin');
|
||||
expect(out).toEqual({ fileId: 'fid-xyz' });
|
||||
expect(out).toEqual({ fileId: 'fid-xyz', busId: 102 });
|
||||
expect(highwayClient.fetchHighwaySession).not.toHaveBeenCalled();
|
||||
expect(highwayClient.uploadHighwayHttp).not.toHaveBeenCalled();
|
||||
});
|
||||
@@ -224,8 +230,180 @@ describe('apis/group-file', () => {
|
||||
await expect(
|
||||
new GroupFileApi(bridge as any).upload(12345, '/path/file.bin'),
|
||||
).rejects.toThrow(/code=999/);
|
||||
expect(bridge.sendRawPacket).toHaveBeenCalledOnce();
|
||||
expect(highwayClient.uploadHighwayHttp).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([-403, -9801, -98090])(
|
||||
'retries capacity error %s as a temporary group file',
|
||||
async (retCode) => {
|
||||
const bridge = mockBridge();
|
||||
bridge.sendRawPacket
|
||||
.mockResolvedValueOnce(
|
||||
uploadResponse({ retCode, retMsg: 'permanent storage full' }),
|
||||
)
|
||||
.mockResolvedValueOnce(
|
||||
uploadResponse({ fileId: 'temporary-file', busId: 104, boolFileExist: true }),
|
||||
);
|
||||
const api = new GroupFileApi(bridge as any);
|
||||
const result = await api.upload(12345, '/path/file.bin', 'doc.bin', '/folder');
|
||||
expect(result).toMatchObject({ fileId: 'temporary-file', busId: 104 });
|
||||
expect(bridge.sendRawPacket).toHaveBeenCalledTimes(3);
|
||||
const requests = bridge.sendRawPacket.mock.calls
|
||||
.slice(0, 2)
|
||||
.map(([, bytes]) => protobuf_decode<OidbBase<OidbGroupFileReq>>(bytes).body?.file);
|
||||
expect(requests[0]).toMatchObject({ busId: 102, targetDirectory: '/folder' });
|
||||
expect(requests[1]).toEqual({ ...requests[0], busId: 104 });
|
||||
const publish = protobuf_decode<OidbBase<OidbGroupSendFileReq>>(
|
||||
bridge.sendRawPacket.mock.calls[2]![1],
|
||||
);
|
||||
expect(publish.body?.body?.info).toMatchObject({
|
||||
fileId: 'temporary-file',
|
||||
busiType: 104,
|
||||
});
|
||||
expect(bridge.rememberUploadedFile).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ busId: 104, groupId: 12345 }),
|
||||
);
|
||||
expect(highwayClient.uploadHighwayHttp).not.toHaveBeenCalled();
|
||||
},
|
||||
);
|
||||
|
||||
it('carries the server-selected storage type through bytes, publication and cached reuse', async () => {
|
||||
const bridge = mockBridge();
|
||||
bridge.sendRawPacket.mockResolvedValueOnce(
|
||||
uploadResponse({
|
||||
fileId: 'temporary-file',
|
||||
busId: 104,
|
||||
uploadIp: '127.0.0.1',
|
||||
uploadPort: 8080,
|
||||
fileKey: new Uint8Array([7]),
|
||||
checkKey: new Uint8Array([8]),
|
||||
}),
|
||||
);
|
||||
bridge.recallUploadedFile.mockImplementation(
|
||||
() => bridge.rememberUploadedFile.mock.calls.at(-1)?.[0],
|
||||
);
|
||||
const api = new GroupFileApi(bridge as any);
|
||||
await api.upload(12345, '/path/file.bin');
|
||||
const ext = protobuf_decode<FileUploadExt>(
|
||||
vi.mocked(highwayClient.uploadHighwayHttp).mock.calls[0]![5],
|
||||
);
|
||||
expect(ext.entry?.busiBuff?.busId).toBe(104);
|
||||
await api.publish(12345, 'temporary-file');
|
||||
|
||||
for (const [, bytes] of bridge.sendRawPacket.mock.calls.slice(1)) {
|
||||
expect(
|
||||
protobuf_decode<OidbBase<OidbGroupSendFileReq>>(bytes).body?.body?.info?.busiType,
|
||||
).toBe(104);
|
||||
}
|
||||
});
|
||||
|
||||
it('stops after a failed temporary attempt and releases the staged file', async () => {
|
||||
const bridge = mockBridge();
|
||||
bridge.sendRawPacket
|
||||
.mockResolvedValueOnce(uploadResponse({ retCode: -403 }))
|
||||
.mockResolvedValueOnce(
|
||||
uploadResponse({ retCode: -9801, retMsg: 'temporary storage rejected' }),
|
||||
);
|
||||
await expect(
|
||||
new GroupFileApi(bridge as any).upload(12345, '/path/file.bin'),
|
||||
).rejects.toThrow(/code=-9801/);
|
||||
expect(bridge.sendRawPacket).toHaveBeenCalledTimes(2);
|
||||
expect(bridge.rememberUploadedFile).not.toHaveBeenCalled();
|
||||
expect(highwayClient.uploadHighwayHttp).not.toHaveBeenCalled();
|
||||
const staged = await vi.mocked(stageMod.stageSourceToDisk).mock.results.at(-1)!.value;
|
||||
expect(staged.cleanup).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('retains temporary mode when the successful retry omits its storage type', async () => {
|
||||
const bridge = mockBridge();
|
||||
bridge.sendRawPacket
|
||||
.mockResolvedValueOnce(uploadResponse({ retCode: -403 }))
|
||||
.mockResolvedValueOnce(uploadResponse({ fileId: 'temp', boolFileExist: true }));
|
||||
const api = new GroupFileApi(bridge as any);
|
||||
const publish = vi.spyOn(api, 'publish').mockResolvedValue();
|
||||
await expect(api.upload(12345, '/path/file.bin')).resolves.toEqual({
|
||||
fileId: 'temp',
|
||||
busId: 104,
|
||||
});
|
||||
expect(publish).toHaveBeenCalledExactlyOnceWith(12345, 'temp', 104);
|
||||
});
|
||||
|
||||
it('rejects an unknown server storage type before bytes or publication', async () => {
|
||||
const bridge = mockBridge();
|
||||
bridge.sendRawPacket.mockResolvedValueOnce(
|
||||
uploadResponse({ fileId: 'bad', busId: 777, boolFileExist: true }),
|
||||
);
|
||||
await expect(
|
||||
new GroupFileApi(bridge as any).upload(12345, '/path/file.bin'),
|
||||
).rejects.toThrow(/unsupported storage type: 777/);
|
||||
expect(bridge.sendRawPacket).toHaveBeenCalledOnce();
|
||||
expect(bridge.rememberUploadedFile).not.toHaveBeenCalled();
|
||||
expect(highwayClient.uploadHighwayHttp).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ scope: 'group', groupId: 12345, expected: 104 },
|
||||
{ scope: 'group', groupId: 54321, expected: 102 },
|
||||
{ scope: 'private', groupId: undefined, expected: 102 },
|
||||
] as const)(
|
||||
'scopes cached storage to the target group for download and reuse (%j)',
|
||||
async ({ scope, groupId, expected }) => {
|
||||
const bridge = mockBridge();
|
||||
bridge.recallUploadedFile.mockReturnValue({
|
||||
fileId: 'temp',
|
||||
scope,
|
||||
groupId,
|
||||
busId: 104,
|
||||
});
|
||||
bridge.sendRawPacket.mockResolvedValueOnce(
|
||||
packResponse(
|
||||
protobuf_encode<OidbBase<OidbGroupFileResp>>({
|
||||
body: {
|
||||
download: {
|
||||
downloadDns: 'download.example.com',
|
||||
downloadUrl: new Uint8Array([1]),
|
||||
},
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
const api = new GroupFileApi(bridge as any);
|
||||
await api.getUrl(12345, 'temp');
|
||||
await api.publish(12345, 'temp');
|
||||
const requests = bridge.sendRawPacket.mock.calls;
|
||||
expect(
|
||||
protobuf_decode<OidbBase<OidbGroupFileReq>>(requests[0]![1]).body?.download?.busId,
|
||||
).toBe(expected);
|
||||
expect(
|
||||
protobuf_decode<OidbBase<OidbGroupSendFileReq>>(requests[1]![1]).body?.body?.info
|
||||
?.busiType,
|
||||
).toBe(expected);
|
||||
},
|
||||
);
|
||||
|
||||
it.each([{ retCode: -403 }, { fileId: 'temp', busId: 104, boolFileExist: true }])(
|
||||
'rejects a disallowed temporary upload before transferring bytes or publishing (%j)',
|
||||
async (response) => {
|
||||
const bridge = mockBridge();
|
||||
bridge.sendRawPacket.mockResolvedValueOnce(uploadResponse(response));
|
||||
await expect(
|
||||
new GroupFileApi(bridge as any).upload(
|
||||
12345,
|
||||
'/path/file.bin',
|
||||
'',
|
||||
'/',
|
||||
true,
|
||||
false,
|
||||
{ allowTemporary: false },
|
||||
),
|
||||
).rejects.toThrow(/temporary group files.*only file or image/i);
|
||||
expect(bridge.sendRawPacket).toHaveBeenCalledOnce();
|
||||
expect(bridge.rememberUploadedFile).not.toHaveBeenCalled();
|
||||
expect(highwayClient.uploadHighwayHttp).not.toHaveBeenCalled();
|
||||
},
|
||||
);
|
||||
|
||||
it('upload publishes the file via OIDB 0x6d9_4 after upload (the "empty message" regression)', async () => {
|
||||
// Reproduces the bug report: OIDB upload + highway PUT alone only
|
||||
// stage the bytes on QQ's side; without the trailing 0x6d9_4 OIDB
|
||||
@@ -341,11 +519,12 @@ describe('apis/group-file', () => {
|
||||
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');
|
||||
await expect(upload).resolves.toEqual({ fileId: 'fid-confirm', busId: 102 });
|
||||
expect(publishSpy).toHaveBeenCalledExactlyOnceWith(12345, 'fid-confirm', 102);
|
||||
} else {
|
||||
await expect(upload).rejects.toBe(failure);
|
||||
expect(publishSpy).not.toHaveBeenCalled();
|
||||
expect(bridge.rememberUploadedFile).not.toHaveBeenCalled();
|
||||
}
|
||||
|
||||
expect(highwayClient.uploadHighwayHttp).toHaveBeenCalledOnce();
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { IdentityService } from '@snowluma/protocol/identity-service';
|
||||
import { FetchGroupMemberListPage } from '@snowluma/protocol/oidb-services/contacts/fetch-group-member-list-page';
|
||||
import { FetchRobotUinRanges } from '@snowluma/protocol/oidb-services/contacts/fetch-robot-uin-ranges';
|
||||
import { Bridge } from '../src/bridge/bridge';
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
describe('Bridge contact cache lifecycle', () => {
|
||||
it('keeps contact lookups available to packets already draining during shutdown', async () => {
|
||||
vi.useFakeTimers();
|
||||
const bridge = new Bridge(IdentityService.memory('10001'));
|
||||
vi.spyOn(FetchRobotUinRanges, 'invoke').mockResolvedValue({ version: 1, ranges: [] });
|
||||
const load = vi
|
||||
.spyOn(FetchGroupMemberListPage, 'invoke')
|
||||
.mockResolvedValue({ members: [], token: '' });
|
||||
await bridge.apis.contacts.fetchGroupMemberList(42);
|
||||
let memberRead: Promise<unknown> | undefined;
|
||||
bridge.registerCmd('test.contact-cache', () => {
|
||||
memberRead = bridge.apis.contacts.fetchGroupMemberList(42);
|
||||
return [];
|
||||
});
|
||||
const packet = bridge.onPacket({
|
||||
pid: 1,
|
||||
uin: '10001',
|
||||
serviceCmd: 'test.contact-cache',
|
||||
seqId: 1,
|
||||
retCode: 0,
|
||||
fromClient: false,
|
||||
body: new Uint8Array(),
|
||||
});
|
||||
const closing = bridge.dispose();
|
||||
await packet;
|
||||
await expect(memberRead).resolves.toEqual([]);
|
||||
await closing;
|
||||
expect(load).toHaveBeenCalledOnce();
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
});
|
||||
|
||||
it.each([false, true])(
|
||||
'releases member caches before identity closes, close failure=%s',
|
||||
async (fails) => {
|
||||
vi.useFakeTimers();
|
||||
const identity = IdentityService.memory('10001');
|
||||
const bridge = new Bridge(identity);
|
||||
vi.spyOn(FetchRobotUinRanges, 'invoke').mockResolvedValue({ version: 1, ranges: [] });
|
||||
const load = vi
|
||||
.spyOn(FetchGroupMemberListPage, 'invoke')
|
||||
.mockResolvedValue({ members: [], token: '' });
|
||||
await bridge.apis.contacts.fetchGroupMemberList(42);
|
||||
await bridge.apis.contacts.fetchGroupMemberList(42);
|
||||
expect(load).toHaveBeenCalledOnce();
|
||||
expect(vi.getTimerCount()).toBe(1);
|
||||
|
||||
const originalClose = identity.close.bind(identity);
|
||||
vi.spyOn(identity, 'close').mockImplementation(async () => {
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
await originalClose();
|
||||
|
||||
if (fails) {
|
||||
throw new Error('identity close failed');
|
||||
}
|
||||
});
|
||||
const closing = bridge.dispose();
|
||||
expect(bridge.dispose()).toBe(closing);
|
||||
|
||||
if (fails) {
|
||||
await expect(closing).rejects.toThrow('identity close failed');
|
||||
} else {
|
||||
await closing;
|
||||
}
|
||||
|
||||
await expect(bridge.apis.contacts.fetchGroupMemberList(42)).rejects.toThrow('disposed');
|
||||
expect(load).toHaveBeenCalledOnce();
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -30,7 +30,7 @@ vi.mock('@snowluma/protocol/highway/video-upload', () => ({
|
||||
}));
|
||||
|
||||
import { type bytes, type pb, protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import type { MsgInfo } from '@snowluma/proto-defs/element';
|
||||
import type { GroupFileExtra, MsgInfo } from '@snowluma/proto-defs/element';
|
||||
import { buildSendElems, encodePrivateRichText } from '@snowluma/protocol/element-builder';
|
||||
import { uploadPtt } from '@snowluma/protocol/highway/ptt-upload';
|
||||
import { MessageElementValidationError } from '@snowluma/protocol/element-manifest';
|
||||
@@ -374,6 +374,27 @@ describe('element-builder / all-message validation preflight', () => {
|
||||
});
|
||||
|
||||
describe('element-builder / file element is no longer carried in elems[]', () => {
|
||||
it.each([12345, 54321])(
|
||||
'preserves temporary storage only in a matching group forward (%s)',
|
||||
async (cachedGroupId) => {
|
||||
const bridge = {
|
||||
recallUploadedFile: vi.fn(() => ({
|
||||
scope: 'group',
|
||||
groupId: cachedGroupId,
|
||||
busId: 104,
|
||||
fileName: 'doc.pdf',
|
||||
fileSize: 3,
|
||||
})),
|
||||
} as any;
|
||||
const [elem] = await buildSendElems([{ type: 'file', fileId: 'temp' }], {
|
||||
bridge,
|
||||
groupId: 12345,
|
||||
forwardFake: true,
|
||||
});
|
||||
const extra = protobuf_decode<GroupFileExtra>(elem!.transElem!.elemValue!.subarray(3));
|
||||
expect(extra.inner?.info?.busId).toBe(cachedGroupId === 12345 ? 104 : 102);
|
||||
},
|
||||
);
|
||||
// Regression for the `result=79` class: previously the element-builder
|
||||
// emitted a `transElem(elemType=24, ...)` for `{type:'file'}` segments
|
||||
// and the QQ-NT server rejected the outgoing PbSendMsg with that wire
|
||||
|
||||
@@ -82,8 +82,12 @@ class FakeSocket extends EventEmitter {
|
||||
headers: string[] = [];
|
||||
frames: Buffer[] = [];
|
||||
closeBeforeResponse = false;
|
||||
idleBeforeResponse = false;
|
||||
stallWrites = false;
|
||||
responseDelayMs = 0;
|
||||
connectFailure?: Error | 'timeout';
|
||||
private connectTimer?: ReturnType<typeof setTimeout>;
|
||||
private responseTimer?: ReturnType<typeof setTimeout>;
|
||||
private buf = Buffer.alloc(0);
|
||||
constructor(
|
||||
private readonly responseFrame: Buffer,
|
||||
@@ -105,6 +109,10 @@ class FakeSocket extends EventEmitter {
|
||||
}
|
||||
|
||||
write(data: unknown, cb?: (err?: Error) => void): boolean {
|
||||
if (this.stallWrites) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (this.destroyed || !this.writable) {
|
||||
const err = new Error('write after socket end');
|
||||
|
||||
@@ -148,11 +156,16 @@ class FakeSocket extends EventEmitter {
|
||||
this.buf = this.buf.subarray(total);
|
||||
this.posts += 1;
|
||||
const thisPost = this.posts;
|
||||
setImmediate(() => {
|
||||
|
||||
const respond = () => {
|
||||
if (this.destroyed) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.idleBeforeResponse) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (thisPost === this.failOnPost) {
|
||||
this.writable = false;
|
||||
this.readableEnded = true;
|
||||
@@ -199,12 +212,19 @@ class FakeSocket extends EventEmitter {
|
||||
this.emit('end');
|
||||
this.emit('close');
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
if (this.responseDelayMs > 0) {
|
||||
this.responseTimer = setTimeout(respond, this.responseDelayMs);
|
||||
} else {
|
||||
setImmediate(respond);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
destroy() {
|
||||
clearTimeout(this.connectTimer);
|
||||
clearTimeout(this.responseTimer);
|
||||
this.destroyed = true;
|
||||
this.writable = false;
|
||||
}
|
||||
@@ -239,8 +259,8 @@ function highwayTrace(entries: LogEntry[]): LogEntry[] {
|
||||
return entries.filter((entry) => entry.level === 'trace' && entry.scope === 'Highway');
|
||||
}
|
||||
|
||||
function makeBridge(): BridgeContext {
|
||||
return { identity: { uin: '10001' } as unknown } as unknown as BridgeContext;
|
||||
function makeBridge(uin = '10001'): BridgeContext {
|
||||
return { identity: { uin } as unknown } as unknown as BridgeContext;
|
||||
}
|
||||
|
||||
function makeSession(): HighwaySession {
|
||||
@@ -459,6 +479,7 @@ describe('Highway connection selection', () => {
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
vi.restoreAllMocks();
|
||||
vi.unstubAllEnvs();
|
||||
setLogLevel(previousLogLevel);
|
||||
});
|
||||
|
||||
@@ -472,6 +493,201 @@ describe('Highway connection selection', () => {
|
||||
};
|
||||
}
|
||||
|
||||
it.each([1003, 1004])(
|
||||
'reaches the fourth candidate after three idle peers for command %i (#637)',
|
||||
async (commandId) => {
|
||||
vi.useFakeTimers();
|
||||
vi.stubEnv('SNOWLUMA_HIGHWAY_UPLOAD_IDLE_TIMEOUT_MS', '100');
|
||||
vi.stubEnv('SNOWLUMA_HIGHWAY_UPLOAD_TIMEOUT_MS', '5000');
|
||||
installFactory(() => {
|
||||
const socket = new FakeSocket(buildEmptyHighwayResponseFrame(), 'keepalive');
|
||||
socket.idleBeforeResponse =
|
||||
createConnectionMock.mock.lastCall?.[0].host !== '192.0.2.4';
|
||||
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 completed = expect(
|
||||
uploadHighwayHttp(
|
||||
makeBridge(),
|
||||
session,
|
||||
commandId,
|
||||
source,
|
||||
new Uint8Array(16),
|
||||
new Uint8Array(),
|
||||
),
|
||||
).resolves.toBeUndefined();
|
||||
await Promise.all([completed, vi.runAllTimersAsync()]);
|
||||
expect(createConnectionMock.mock.calls.map(([options]) => options)).toEqual(
|
||||
session.servers,
|
||||
);
|
||||
expect(source.reads).toEqual([{ offset: 0, length: 80 }]);
|
||||
expect(source.closeCount).toBe(1);
|
||||
expect((createdSockets as FakeSocket[]).every((socket) => socket.destroyed)).toBe(true);
|
||||
},
|
||||
);
|
||||
|
||||
it('uses recent successful host and port only for the same account and upload type', async () => {
|
||||
vi.useFakeTimers();
|
||||
vi.stubEnv('SNOWLUMA_HIGHWAY_UPLOAD_IDLE_TIMEOUT_MS', '100');
|
||||
const session = {
|
||||
...makeSession(),
|
||||
servers: [
|
||||
{ host: '192.0.2.1', port: 14000 },
|
||||
{ host: '192.0.2.1', port: 80 },
|
||||
],
|
||||
};
|
||||
const bridge = makeBridge();
|
||||
|
||||
const send = async (owner: BridgeContext, commandId = 1004, candidates = session) => {
|
||||
installFactory(() => {
|
||||
const socket = new FakeSocket(buildEmptyHighwayResponseFrame(), 'keepalive');
|
||||
socket.idleBeforeResponse = createConnectionMock.mock.lastCall?.[0].port === 14000;
|
||||
return socket;
|
||||
});
|
||||
await Promise.all([
|
||||
expect(
|
||||
uploadHighwayHttp(
|
||||
owner,
|
||||
candidates,
|
||||
commandId,
|
||||
new RecordingChunkSource(80),
|
||||
new Uint8Array(16),
|
||||
new Uint8Array(),
|
||||
),
|
||||
).resolves.toBeUndefined(),
|
||||
vi.runAllTimersAsync(),
|
||||
]);
|
||||
return createConnectionMock.mock.calls.map(([options]) => options);
|
||||
};
|
||||
|
||||
expect(await send(bridge)).toEqual(session.servers);
|
||||
expect(await send(bridge)).toEqual([session.servers[1]]);
|
||||
expect(await send(makeBridge('10002'))).toEqual(session.servers);
|
||||
expect(await send(bridge, 1003)).toEqual(session.servers);
|
||||
const replacement = { ...session, servers: [{ host: '192.0.2.2', port: 80 }] };
|
||||
expect(await send(bridge, 1004, replacement)).toEqual(replacement.servers);
|
||||
await vi.advanceTimersByTimeAsync(5 * 60_000);
|
||||
expect(await send(bridge)).toEqual(session.servers);
|
||||
});
|
||||
|
||||
it.each(['response', 'write', 'retry'])(
|
||||
'stops a pending %s at the shared upload deadline and releases resources',
|
||||
async (phase) => {
|
||||
vi.useFakeTimers();
|
||||
vi.stubEnv('SNOWLUMA_HIGHWAY_UPLOAD_TIMEOUT_MS', '150');
|
||||
vi.stubEnv(
|
||||
'SNOWLUMA_HIGHWAY_UPLOAD_IDLE_TIMEOUT_MS',
|
||||
phase === 'retry' ? '50' : '1000',
|
||||
);
|
||||
installFactory(() => {
|
||||
const socket = new FakeSocket(buildEmptyHighwayResponseFrame(), 'keepalive');
|
||||
socket.idleBeforeResponse = true;
|
||||
socket.stallWrites = phase === 'write';
|
||||
return socket;
|
||||
});
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
const source = new RecordingChunkSource(80);
|
||||
const start = Date.now();
|
||||
|
||||
try {
|
||||
const failed = expect(
|
||||
uploadHighwayHttp(
|
||||
makeBridge(),
|
||||
sessionWithCandidates(),
|
||||
1004,
|
||||
source,
|
||||
new Uint8Array(16),
|
||||
new Uint8Array(),
|
||||
),
|
||||
).rejects.toThrow('timed out after 150ms');
|
||||
await Promise.all([failed, vi.runAllTimersAsync()]);
|
||||
expect(Date.now() - start).toBe(150);
|
||||
expect(createConnectionMock).toHaveBeenCalledTimes(1);
|
||||
expect(source.closeCount).toBe(1);
|
||||
expect(
|
||||
(createdSockets as FakeSocket[]).every(
|
||||
(socket) =>
|
||||
socket.destroyed &&
|
||||
socket.listenerCount('data') === 0 &&
|
||||
socket.listenerCount('close') === 0,
|
||||
),
|
||||
).toBe(true);
|
||||
const terminal = highwayTrace(entries).filter((entry) =>
|
||||
entry.message.startsWith('highway_put_terminal '),
|
||||
);
|
||||
expect(terminal).toHaveLength(1);
|
||||
expect(terminal[0]!.message).toContain('reason=upload_timeout');
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
|
||||
if (phase === 'retry') {
|
||||
expect(
|
||||
entries.some(
|
||||
(entry) =>
|
||||
entry.message.includes('phase=read_response') &&
|
||||
entry.message.includes('received=0B'),
|
||||
),
|
||||
).toBe(true);
|
||||
}
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it('does not renew the total deadline when a chunk succeeds', async () => {
|
||||
vi.useFakeTimers();
|
||||
vi.stubEnv('SNOWLUMA_HIGHWAY_UPLOAD_TIMEOUT_MS', '250');
|
||||
vi.stubEnv('SNOWLUMA_HIGHWAY_UPLOAD_IDLE_TIMEOUT_MS', '200');
|
||||
installFactory(() => {
|
||||
const socket = new FakeSocket(buildEmptyHighwayResponseFrame(), 'keepalive');
|
||||
socket.responseDelayMs = 100;
|
||||
return socket;
|
||||
});
|
||||
const source = new RecordingChunkSource(2 * HIGHWAY_BLOCK_SIZE + 80);
|
||||
const start = Date.now();
|
||||
const failed = expect(
|
||||
uploadHighwayHttp(
|
||||
makeBridge(),
|
||||
makeSession(),
|
||||
1004,
|
||||
source,
|
||||
new Uint8Array(16),
|
||||
new Uint8Array(),
|
||||
),
|
||||
).rejects.toThrow('acknowledgedBytes=2097152/2097232');
|
||||
await Promise.all([failed, vi.runAllTimersAsync()]);
|
||||
expect(Date.now() - start).toBe(250);
|
||||
expect(source.closeCount).toBe(1);
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
});
|
||||
|
||||
it('rejects invalid timeout configuration before connecting and closes the source', async () => {
|
||||
vi.stubEnv('SNOWLUMA_HIGHWAY_UPLOAD_TIMEOUT_MS', '0');
|
||||
installFactory(() => new FakeSocket(buildEmptyHighwayResponseFrame(), 'keepalive'));
|
||||
const source = new RecordingChunkSource(80);
|
||||
await expect(
|
||||
uploadHighwayHttp(
|
||||
makeBridge(),
|
||||
makeSession(),
|
||||
1004,
|
||||
source,
|
||||
new Uint8Array(16),
|
||||
new Uint8Array(),
|
||||
),
|
||||
).rejects.toThrow('SNOWLUMA_HIGHWAY_UPLOAD_TIMEOUT_MS');
|
||||
expect(createConnectionMock).not.toHaveBeenCalled();
|
||||
expect(source.closeCount).toBe(1);
|
||||
});
|
||||
|
||||
it.each(['timeout', 'ECONNREFUSED', 'ENETUNREACH'])(
|
||||
'switches on %s and uploads over the successful connection',
|
||||
async (failure) => {
|
||||
@@ -515,8 +731,9 @@ describe('Highway connection selection', () => {
|
||||
},
|
||||
);
|
||||
|
||||
it('bounds initial selection to ten seconds without repeating exhausted candidates', async () => {
|
||||
it('bounds initial selection by the configured total deadline without repeating candidates', async () => {
|
||||
vi.useFakeTimers();
|
||||
vi.stubEnv('SNOWLUMA_HIGHWAY_UPLOAD_TIMEOUT_MS', '10000');
|
||||
installFactory(() => {
|
||||
const socket = new FakeSocket(buildEmptyHighwayResponseFrame(), 'keepalive');
|
||||
socket.connectFailure = 'timeout';
|
||||
@@ -544,7 +761,7 @@ describe('Highway connection selection', () => {
|
||||
new Uint8Array(16),
|
||||
new Uint8Array(),
|
||||
);
|
||||
const failed = expect(upload).rejects.toThrow(/connection failed.*TCP connect timeout/);
|
||||
const failed = expect(upload).rejects.toThrow('timed out after 10000ms');
|
||||
await vi.runAllTimersAsync();
|
||||
await failed;
|
||||
expect(Date.now() - start).toBe(10000);
|
||||
@@ -561,7 +778,7 @@ describe('Highway connection selection', () => {
|
||||
entry.message.startsWith('highway_put_terminal '),
|
||||
);
|
||||
expect(terminals).toHaveLength(1);
|
||||
expect(terminals[0]!.message).toContain('reason=connect_exhausted');
|
||||
expect(terminals[0]!.message).toContain('reason=upload_timeout');
|
||||
expect(terminals[0]!.message).toContain('connections=0');
|
||||
} finally {
|
||||
unsubscribe();
|
||||
|
||||
@@ -177,6 +177,8 @@ beforeEach(() => {
|
||||
});
|
||||
afterEach(() => {
|
||||
setLogLevel(level);
|
||||
vi.unstubAllEnvs();
|
||||
vi.useRealTimers();
|
||||
|
||||
for (const socket of sockets) {
|
||||
socket.destroy();
|
||||
@@ -184,6 +186,64 @@ afterEach(() => {
|
||||
});
|
||||
|
||||
describe('bounded parallel highway uploads', () => {
|
||||
it('does not let trickled response bytes extend the whole-file deadline', async () => {
|
||||
vi.useFakeTimers();
|
||||
vi.stubEnv('SNOWLUMA_HIGHWAY_UPLOAD_TIMEOUT_MS', '100');
|
||||
vi.stubEnv('SNOWLUMA_HIGHWAY_UPLOAD_IDLE_TIMEOUT_MS', '30');
|
||||
|
||||
onRequest = ({ socket }) => {
|
||||
const timer = setInterval(() => socket.emit('data', Buffer.from('x')), 10);
|
||||
socket.once('close', () => clearInterval(timer));
|
||||
};
|
||||
|
||||
const source = new Source(80);
|
||||
const start = Date.now();
|
||||
const failed = expect(upload(source, 1)).rejects.toThrow('timed out after 100ms');
|
||||
await Promise.all([failed, vi.runAllTimersAsync()]);
|
||||
expect(Date.now() - start).toBe(100);
|
||||
expect(source.closes).toBe(1);
|
||||
expect(active.size).toBe(0);
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
});
|
||||
|
||||
it('drains a pending source read after the deadline without sending its bytes', async () => {
|
||||
vi.useFakeTimers();
|
||||
vi.stubEnv('SNOWLUMA_HIGHWAY_UPLOAD_TIMEOUT_MS', '50');
|
||||
const source = new Source(80);
|
||||
let reading = false;
|
||||
const read = source.read.bind(source);
|
||||
|
||||
source.read = async (offset, length) => {
|
||||
reading = true;
|
||||
await new Promise<void>((resolve) => setTimeout(resolve, 100));
|
||||
reading = false;
|
||||
return read(offset, length);
|
||||
};
|
||||
|
||||
const close = vi.spyOn(source, 'close').mockImplementation(async () => {
|
||||
expect(reading).toBe(false);
|
||||
});
|
||||
const failed = expect(upload(source, 1)).rejects.toThrow('timed out after 50ms');
|
||||
await Promise.all([failed, vi.runAllTimersAsync()]);
|
||||
expect(connect).not.toHaveBeenCalled();
|
||||
expect(close).toHaveBeenCalledTimes(1);
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
});
|
||||
|
||||
it('aborts all parallel requests at one whole-file deadline', async () => {
|
||||
vi.useFakeTimers();
|
||||
vi.stubEnv('SNOWLUMA_HIGHWAY_UPLOAD_TIMEOUT_MS', '1000');
|
||||
const source = new Source(6 * BLOCK);
|
||||
const start = Date.now();
|
||||
const failed = expect(upload(source, 3)).rejects.toThrow('timed out after 1000ms');
|
||||
await Promise.all([failed, vi.runAllTimersAsync()]);
|
||||
expect(Date.now() - start).toBe(1000);
|
||||
expect(requests).toHaveLength(3);
|
||||
expect(sockets.every((socket) => socket.destroyed)).toBe(true);
|
||||
expect(active.size).toBe(0);
|
||||
expect(source.closes).toBe(1);
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
});
|
||||
it.each([2, 3, 4])(
|
||||
'uses %i connections, accepts out-of-order acknowledgements and sends the tail last',
|
||||
async (concurrency) => {
|
||||
|
||||
@@ -6,7 +6,9 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
|
||||
vi.mock('@snowluma/protocol/highway/pipeline', () => ({
|
||||
runNtv2Upload: vi.fn(async () => ({ msgInfo: { msgInfoBody: [], extBizInfo: {} } })),
|
||||
runNtv2Upload: vi.fn(async () => ({
|
||||
msgInfo: { msgInfoBody: [{ index: { fileUuid: 'uploaded-image' } }], extBizInfo: {} },
|
||||
})),
|
||||
finalizeMediaMsgInfo: vi.fn(() => new Uint8Array([0xca, 0xfe])),
|
||||
hexToBytes: vi.fn((hex: string) => new Uint8Array(hex.length / 2)),
|
||||
}));
|
||||
|
||||
@@ -39,11 +39,12 @@ describe('ptt-upload', () => {
|
||||
vi.mocked(pipeline.runNtv2Upload).mockResolvedValueOnce({
|
||||
msgInfo: { msgInfoBody: [{ index: node }] },
|
||||
} as any);
|
||||
const element = { ...FINGERPRINT };
|
||||
const element = { ...FINGERPRINT, isNtv2: false };
|
||||
await uploadPttMsgInfo({} as any, true, 12345, element);
|
||||
expect(element).toMatchObject({
|
||||
fileId: 'uploaded-resource',
|
||||
mediaNode: node,
|
||||
isNtv2: true,
|
||||
md5Hex: 'aa',
|
||||
sha1Hex: 'bb',
|
||||
});
|
||||
|
||||
@@ -141,6 +141,73 @@ describe('IdentityService', () => {
|
||||
}
|
||||
});
|
||||
|
||||
it('retains legacy member identities and refreshes only damaged cards across restarts', async () => {
|
||||
const dbPath = tempDbPath('legacy-card');
|
||||
const member = makeMember(33333, 'u_member', 'placeholder');
|
||||
const other = makeMember(44444, 'u_other', 'ordinary');
|
||||
const seed = new IdentityService(SELF_UIN, dbPath);
|
||||
seed.rememberGroups([makeGroup()]);
|
||||
seed.rememberGroupMembers(GROUP_ID, [member, other]);
|
||||
await seed.close();
|
||||
// Persisted bytes from #646 after the old text normalization stripped the envelope prefix.
|
||||
const damaged = Buffer.concat([
|
||||
Buffer.from('1209', 'hex'),
|
||||
Buffer.from('三字名'),
|
||||
Buffer.from('0a090a0724c3bfc48011221000', 'hex'),
|
||||
]);
|
||||
const sql = new DatabaseSync(dbPath);
|
||||
|
||||
try {
|
||||
sql.prepare('UPDATE group_members SET card = CAST(? AS TEXT) WHERE uin = ?').run(
|
||||
damaged,
|
||||
member.uin,
|
||||
);
|
||||
} finally {
|
||||
sql.close();
|
||||
}
|
||||
|
||||
const stale = new IdentityService(SELF_UIN, dbPath);
|
||||
|
||||
try {
|
||||
await stale.initialization;
|
||||
const cached = stale.findGroupMember(GROUP_ID, member.uin)!;
|
||||
expect(cached).toMatchObject({ card: undefined, uid: member.uid, isRobot: false });
|
||||
expect(stale.findGroupMember(GROUP_ID, other.uin)?.card).toBe('ordinary');
|
||||
stale.updateGroupMember(GROUP_ID, { ...cached, role: 'admin' });
|
||||
} finally {
|
||||
await stale.close();
|
||||
}
|
||||
|
||||
const refreshed = new IdentityService(SELF_UIN, dbPath);
|
||||
|
||||
try {
|
||||
await refreshed.initialization;
|
||||
expect(refreshed.findGroupMember(GROUP_ID, member.uin)).toMatchObject({
|
||||
card: undefined,
|
||||
role: 'admin',
|
||||
});
|
||||
refreshed.rememberGroupMembers(GROUP_ID, [
|
||||
{ ...member, role: 'admin', card: ' 三字名 ' },
|
||||
other,
|
||||
]);
|
||||
} finally {
|
||||
await refreshed.close();
|
||||
}
|
||||
|
||||
const restored = new IdentityService(SELF_UIN, dbPath);
|
||||
|
||||
try {
|
||||
await restored.initialization;
|
||||
expect(restored.findGroupMember(GROUP_ID, member.uin)).toMatchObject({
|
||||
card: ' 三字名 ',
|
||||
role: 'admin',
|
||||
});
|
||||
expect(restored.findGroupMember(GROUP_ID, other.uin)?.card).toBe('ordinary');
|
||||
} finally {
|
||||
await restored.close();
|
||||
}
|
||||
});
|
||||
|
||||
it('persists group member robot classification across restarts', async () => {
|
||||
const dbPath = tempDbPath('persist-robot');
|
||||
|
||||
@@ -160,11 +227,13 @@ describe('IdentityService', () => {
|
||||
}
|
||||
});
|
||||
|
||||
it('migrates legacy member caches without inventing a robot classification', async () => {
|
||||
const dbPath = tempDbPath('migrate-robot');
|
||||
fs.mkdirSync(path.dirname(dbPath), { recursive: true });
|
||||
const legacy = new DatabaseSync(dbPath);
|
||||
legacy.exec(`
|
||||
it.each([false, true])(
|
||||
'migrates legacy member cards and retries after failure=%s',
|
||||
async (failMigration) => {
|
||||
const dbPath = tempDbPath('migrate-robot');
|
||||
fs.mkdirSync(path.dirname(dbPath), { recursive: true });
|
||||
const legacy = new DatabaseSync(dbPath);
|
||||
legacy.exec(`
|
||||
CREATE TABLE users (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
uid TEXT UNIQUE,
|
||||
@@ -197,6 +266,7 @@ describe('IdentityService', () => {
|
||||
join_time INTEGER NOT NULL DEFAULT 0,
|
||||
last_sent_time INTEGER NOT NULL DEFAULT 0,
|
||||
shut_up_time INTEGER NOT NULL DEFAULT 0,
|
||||
${failMigration ? 'is_robot INTEGER,' : ''}
|
||||
active INTEGER NOT NULL DEFAULT 1,
|
||||
updated_at INTEGER NOT NULL,
|
||||
UNIQUE(group_id, uid),
|
||||
@@ -207,19 +277,96 @@ describe('IdentityService', () => {
|
||||
INSERT INTO group_members (group_id, uid, uin, nickname, updated_at)
|
||||
VALUES (${GROUP_ID}, 'u_legacy', 33333, 'legacy-member', 1);
|
||||
`);
|
||||
legacy.close();
|
||||
legacy.close();
|
||||
|
||||
const identity = new IdentityService(SELF_UIN, dbPath);
|
||||
await identity.initialization;
|
||||
expect(identity.findGroupMember(GROUP_ID, 33333)?.isRobot).toBeUndefined();
|
||||
await identity.close();
|
||||
if (failMigration) {
|
||||
const originalExec = SqliteDatabase.prototype.exec;
|
||||
const fault = vi
|
||||
.spyOn(SqliteDatabase.prototype, 'exec')
|
||||
.mockImplementation(function (this: SqliteDatabase, sql) {
|
||||
if (sql.includes('ADD COLUMN card_known')) {
|
||||
return Promise.reject(new Error('injected card migration failure'));
|
||||
}
|
||||
|
||||
const migrated = new DatabaseSync(dbPath);
|
||||
const columns = migrated.prepare('PRAGMA table_info(group_members)').all() as Array<{
|
||||
name: string;
|
||||
}>;
|
||||
expect(columns.map((column) => column.name)).toContain('is_robot');
|
||||
migrated.close();
|
||||
return originalExec.call(this, sql);
|
||||
});
|
||||
const failed = new IdentityService(SELF_UIN, dbPath);
|
||||
|
||||
try {
|
||||
await expect(failed.initialization).rejects.toThrow(
|
||||
'injected card migration failure',
|
||||
);
|
||||
await expect(failed.close()).rejects.toThrow('injected card migration failure');
|
||||
} finally {
|
||||
fault.mockRestore();
|
||||
await failed.close();
|
||||
}
|
||||
}
|
||||
|
||||
const identity = new IdentityService(SELF_UIN, dbPath);
|
||||
await identity.initialization;
|
||||
expect(identity.findGroupMember(GROUP_ID, 33333)?.isRobot).toBeUndefined();
|
||||
expect(identity.findGroupMember(GROUP_ID, 33333)?.card).toBe('');
|
||||
await identity.close();
|
||||
|
||||
const migrated = new DatabaseSync(dbPath);
|
||||
const columns = migrated.prepare('PRAGMA table_info(group_members)').all() as Array<{
|
||||
name: string;
|
||||
}>;
|
||||
expect(columns.map((column) => column.name)).toContain('is_robot');
|
||||
expect(columns.map((column) => column.name)).toContain('card_known');
|
||||
migrated.close();
|
||||
|
||||
const reopened = new IdentityService(SELF_UIN, dbPath);
|
||||
await reopened.initialization;
|
||||
expect(reopened.findGroupMember(GROUP_ID, 33333)?.card).toBe('');
|
||||
await reopened.close();
|
||||
},
|
||||
);
|
||||
|
||||
it('preserves valid cards when an unreadable roster arrives during initialization', async () => {
|
||||
const dbPath = tempDbPath('pending-card-roster');
|
||||
const member = makeMember(33333, 'u_member', 'valid card');
|
||||
const seed = new IdentityService(SELF_UIN, dbPath);
|
||||
seed.rememberGroups([makeGroup()]);
|
||||
seed.rememberGroupMembers(GROUP_ID, [member]);
|
||||
await seed.close();
|
||||
let release!: () => void;
|
||||
const loading = new Promise<void>((resolve) => {
|
||||
release = resolve;
|
||||
});
|
||||
const identity = new IdentityService(SELF_UIN, dbPath, loading);
|
||||
const unreadable = { ...member, card: undefined, role: 'admin' };
|
||||
identity.rememberGroupMembers(GROUP_ID, [unreadable]);
|
||||
release();
|
||||
|
||||
try {
|
||||
await identity.initialization;
|
||||
expect(identity.findGroupMember(GROUP_ID, member.uin)).toMatchObject({
|
||||
card: 'valid card',
|
||||
role: 'admin',
|
||||
});
|
||||
identity.updateGroupMember(GROUP_ID, { ...unreadable, level: 9 });
|
||||
expect(identity.findGroupMember(GROUP_ID, member.uin)).toMatchObject({
|
||||
card: 'valid card',
|
||||
level: 9,
|
||||
});
|
||||
} finally {
|
||||
await identity.close();
|
||||
}
|
||||
|
||||
const reopened = new IdentityService(SELF_UIN, dbPath);
|
||||
|
||||
try {
|
||||
await reopened.initialization;
|
||||
expect(reopened.findGroupMember(GROUP_ID, member.uin)).toMatchObject({
|
||||
card: 'valid card',
|
||||
role: 'admin',
|
||||
level: 9,
|
||||
});
|
||||
} finally {
|
||||
await reopened.close();
|
||||
}
|
||||
});
|
||||
|
||||
it('keeps updateGroupMember changes after reopening the persistent cache', async () => {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "@snowluma/mcp",
|
||||
"version": "2.4.0",
|
||||
"version": "2.4.2",
|
||||
"description": "MCP server exposing the SnowLuma OneBot action catalog (docs + JSON Schemas) and optional execution to LLM clients.",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
|
||||
@@ -6521,6 +6521,10 @@
|
||||
}
|
||||
},
|
||||
"additionalProperties": true
|
||||
},
|
||||
"auto_reply": {
|
||||
"const": true,
|
||||
"description": "仅当 QQ 标记该私聊消息为自动回复时提供"
|
||||
}
|
||||
},
|
||||
"additionalProperties": true
|
||||
@@ -9999,7 +10003,7 @@
|
||||
"name": "get_group_system_msg",
|
||||
"aliases": [],
|
||||
"summary": "获取群系统消息",
|
||||
"returns": "群系统消息数组,可按群号或未处理状态过滤。",
|
||||
"returns": "群系统消息数组,分别提供入群者、邀请人和处理者,可按群号或未处理状态过滤。身份为 0 时须查看状态;未知不代表不存在邀请人。",
|
||||
"returnsSchema": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
@@ -10019,20 +10023,60 @@
|
||||
},
|
||||
"requester_uin": {
|
||||
"type": "integer",
|
||||
"description": "申请人 QQ 号"
|
||||
"description": "请求发起人 QQ 号;邀请登录账号入群时表示邀请人"
|
||||
},
|
||||
"requester_nick": {
|
||||
"type": "string",
|
||||
"description": "申请人昵称"
|
||||
"description": "请求发起人昵称"
|
||||
},
|
||||
"target_uin": {
|
||||
"type": "integer",
|
||||
"description": "申请或被邀请入群者 QQ 号,未知时为 0"
|
||||
},
|
||||
"target_nick": {
|
||||
"type": "string",
|
||||
"description": "入群者昵称"
|
||||
},
|
||||
"target_status": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"known",
|
||||
"unknown"
|
||||
],
|
||||
"description": "入群者 QQ 号是否已知"
|
||||
},
|
||||
"invitor_uin": {
|
||||
"type": "integer",
|
||||
"description": "邀请人 QQ 号,无邀请时为 0"
|
||||
"description": "邀请人 QQ 号,未知时为 0;不能据此认定没有邀请人"
|
||||
},
|
||||
"invitor_nick": {
|
||||
"type": "string",
|
||||
"description": "邀请人昵称"
|
||||
},
|
||||
"invitor_status": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"known",
|
||||
"unknown"
|
||||
],
|
||||
"description": "邀请人 QQ 号是否已知;缺失信息为 unknown"
|
||||
},
|
||||
"operator_uin": {
|
||||
"type": "integer",
|
||||
"description": "处理该申请的操作者 QQ 号,未知时为 0"
|
||||
},
|
||||
"operator_nick": {
|
||||
"type": "string",
|
||||
"description": "处理者昵称"
|
||||
},
|
||||
"operator_status": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"known",
|
||||
"unknown"
|
||||
],
|
||||
"description": "处理者 QQ 号是否已知;已知不代表审批通过"
|
||||
},
|
||||
"message": {
|
||||
"type": "string",
|
||||
"description": "验证留言"
|
||||
@@ -10052,8 +10096,15 @@
|
||||
"request_id",
|
||||
"requester_uin",
|
||||
"requester_nick",
|
||||
"target_uin",
|
||||
"target_nick",
|
||||
"target_status",
|
||||
"invitor_uin",
|
||||
"invitor_nick",
|
||||
"invitor_status",
|
||||
"operator_uin",
|
||||
"operator_nick",
|
||||
"operator_status",
|
||||
"message",
|
||||
"checked",
|
||||
"flag"
|
||||
@@ -10710,6 +10761,10 @@
|
||||
}
|
||||
},
|
||||
"additionalProperties": true
|
||||
},
|
||||
"auto_reply": {
|
||||
"const": true,
|
||||
"description": "仅当 QQ 标记该私聊消息为自动回复时提供"
|
||||
}
|
||||
},
|
||||
"additionalProperties": true
|
||||
|
||||
@@ -6524,6 +6524,10 @@ export const ACTIONS: CatalogAction[] = [
|
||||
}
|
||||
},
|
||||
"additionalProperties": true
|
||||
},
|
||||
"auto_reply": {
|
||||
"const": true,
|
||||
"description": "仅当 QQ 标记该私聊消息为自动回复时提供"
|
||||
}
|
||||
},
|
||||
"additionalProperties": true
|
||||
@@ -10002,7 +10006,7 @@ export const ACTIONS: CatalogAction[] = [
|
||||
"name": "get_group_system_msg",
|
||||
"aliases": [],
|
||||
"summary": "获取群系统消息",
|
||||
"returns": "群系统消息数组,可按群号或未处理状态过滤。",
|
||||
"returns": "群系统消息数组,分别提供入群者、邀请人和处理者,可按群号或未处理状态过滤。身份为 0 时须查看状态;未知不代表不存在邀请人。",
|
||||
"returnsSchema": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
@@ -10022,20 +10026,60 @@ export const ACTIONS: CatalogAction[] = [
|
||||
},
|
||||
"requester_uin": {
|
||||
"type": "integer",
|
||||
"description": "申请人 QQ 号"
|
||||
"description": "请求发起人 QQ 号;邀请登录账号入群时表示邀请人"
|
||||
},
|
||||
"requester_nick": {
|
||||
"type": "string",
|
||||
"description": "申请人昵称"
|
||||
"description": "请求发起人昵称"
|
||||
},
|
||||
"target_uin": {
|
||||
"type": "integer",
|
||||
"description": "申请或被邀请入群者 QQ 号,未知时为 0"
|
||||
},
|
||||
"target_nick": {
|
||||
"type": "string",
|
||||
"description": "入群者昵称"
|
||||
},
|
||||
"target_status": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"known",
|
||||
"unknown"
|
||||
],
|
||||
"description": "入群者 QQ 号是否已知"
|
||||
},
|
||||
"invitor_uin": {
|
||||
"type": "integer",
|
||||
"description": "邀请人 QQ 号,无邀请时为 0"
|
||||
"description": "邀请人 QQ 号,未知时为 0;不能据此认定没有邀请人"
|
||||
},
|
||||
"invitor_nick": {
|
||||
"type": "string",
|
||||
"description": "邀请人昵称"
|
||||
},
|
||||
"invitor_status": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"known",
|
||||
"unknown"
|
||||
],
|
||||
"description": "邀请人 QQ 号是否已知;缺失信息为 unknown"
|
||||
},
|
||||
"operator_uin": {
|
||||
"type": "integer",
|
||||
"description": "处理该申请的操作者 QQ 号,未知时为 0"
|
||||
},
|
||||
"operator_nick": {
|
||||
"type": "string",
|
||||
"description": "处理者昵称"
|
||||
},
|
||||
"operator_status": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"known",
|
||||
"unknown"
|
||||
],
|
||||
"description": "处理者 QQ 号是否已知;已知不代表审批通过"
|
||||
},
|
||||
"message": {
|
||||
"type": "string",
|
||||
"description": "验证留言"
|
||||
@@ -10055,8 +10099,15 @@ export const ACTIONS: CatalogAction[] = [
|
||||
"request_id",
|
||||
"requester_uin",
|
||||
"requester_nick",
|
||||
"target_uin",
|
||||
"target_nick",
|
||||
"target_status",
|
||||
"invitor_uin",
|
||||
"invitor_nick",
|
||||
"invitor_status",
|
||||
"operator_uin",
|
||||
"operator_nick",
|
||||
"operator_status",
|
||||
"message",
|
||||
"checked",
|
||||
"flag"
|
||||
@@ -10713,6 +10764,10 @@ export const ACTIONS: CatalogAction[] = [
|
||||
}
|
||||
},
|
||||
"additionalProperties": true
|
||||
},
|
||||
"auto_reply": {
|
||||
"const": true,
|
||||
"description": "仅当 QQ 标记该私聊消息为自动回复时提供"
|
||||
}
|
||||
},
|
||||
"additionalProperties": true
|
||||
|
||||
@@ -49,3 +49,23 @@ The exported `FriendInfo`, `StrangerInfo`, `PublicProfileFields` and
|
||||
`ProfilePrivilege` types describe these fields. Returned availability depends
|
||||
on QQ and the account's access; requesting enrichment does not guarantee every
|
||||
field is present.
|
||||
|
||||
## Group member cards
|
||||
|
||||
Styled cards are decoded before their text is normalized. Within successfully
|
||||
decoded UTF-8 text, SnowLuma removes C0 control characters (`U+0000`–`U+001F`)
|
||||
except tab, line feed and carriage return, and removes DEL (`U+007F`). Spaces,
|
||||
Unicode formatting characters and emoji sequences are preserved. Raw plain text
|
||||
and explicitly literal display names retain strict control-character validation;
|
||||
invalid UTF-8 is rejected in both formats.
|
||||
|
||||
`get_group_member_list` and `get_group_member_info` keep returning member data
|
||||
when an individual group card cannot be decoded. The last valid card for that
|
||||
member in the same group and account is retained; if none is known, the OneBot
|
||||
`card` field is an empty string. An explicitly empty card from QQ clears a
|
||||
previous value.
|
||||
|
||||
Unreadable cards are logged with the group, member, byte length and decoding
|
||||
reason. The persistent cache distinguishes an unknown card from a confirmed
|
||||
empty one, so later roster refreshes can recover it after restart. The existing
|
||||
60-second roster cache and `no_cache: true` refresh option still apply.
|
||||
@@ -0,0 +1,26 @@
|
||||
# 群文件发送与临时存储
|
||||
|
||||
`upload_group_file` 和 `send_group_msg` 中的文件段默认使用群永久文件空间。
|
||||
当服务器明确返回容量或文件数量限制时,SnowLuma 会尝试一次临时存储,并在日志中记录这次切换。
|
||||
临时申请、文件传输或聊天发布失败仍会报错;权限不足、连接失败等其他错误不会触发切换。
|
||||
临时文件可能过期,不能作为永久保存的替代。
|
||||
|
||||
## 消息内容限制
|
||||
|
||||
进入临时文件路径时,一条消息只能包含文件或图片段。
|
||||
含文字、提及、表情等其他内容的混合消息会被拒绝,需要调用方拆成独立消息后再发送。
|
||||
合并转发按每个节点的内容检查同一规则。
|
||||
|
||||
SnowLuma 会在发布聊天消息前检查附件;发现不允许的组合时,不会先发文字、再丢掉附件或文字。
|
||||
检查之前已完成的其他附件上传不会自动删除。上传成功后如果聊天发布失败,错误仍会保留文件标识。
|
||||
这不是跨多条消息的事务:开始发布后出现的网络或服务端错误仍可能使前面的消息已经送达。
|
||||
|
||||
普通图片加文字仍通过图片消息通道发送,不会因为群永久文件空间不足而转成群文件。
|
||||
永久文件与文字的现有分开发送方式保持兼容。超大视频按原有规则转成文件后,也适用临时文件的内容限制。
|
||||
|
||||
## 文件复用与下载
|
||||
|
||||
运行期间上传过的群文件会按账号、群和文件标识保留其存储类型。
|
||||
同一群中用 `file_id` 再次发送、获取下载链接或生成合并转发时,会使用该存储类型。
|
||||
`get_group_file_url` 显式传入的 `busid` 仍优先;未提供有效值时,使用当前会话记住的类型,否则沿用永久文件默认值。
|
||||
上传记录不是持久化目录;重启后获取临时文件链接,应从群文件列表取得对应的 `busid` 并传入。
|
||||
@@ -0,0 +1,55 @@
|
||||
# 群邀请与入群身份
|
||||
|
||||
成员 A 邀请 B,管理员 C 审批时,邀请人、入群者与处理者是三个独立身份。
|
||||
不要把 `group_increase.operator_id` 当成邀请人,也不要仅凭 `sub_type: invite` 推断两者相同。
|
||||
|
||||
## 入群通知
|
||||
|
||||
`group_increase` 保留原有的 `user_id`、`operator_id` 和 `sub_type`,增加:
|
||||
|
||||
| 字段 | 含义 |
|
||||
| --- | --- |
|
||||
| `invitor_id` | QQ 明确提供的独立邀请人 QQ 号;无法确定时为 `0` |
|
||||
| `invitor_status` | `known` 表示邀请人 QQ 号已知;`unknown` 表示无法确定 |
|
||||
|
||||
部分审批入群推送提供独立邀请人信息,SnowLuma 从该推送读取并解析身份。
|
||||
二维码分享者与邀请人分开处理;旧式推送、自身入群通知或缺少来源信息的通知保留 `unknown`。
|
||||
不会按同群、同成员或时间接近程度猜测邀请关系,也不会用操作者填充邀请人。
|
||||
身份查询失败会留下日志,入群事件仍按现有策略上报,未知邀请人不阻断通知。
|
||||
|
||||
## 群申请列表
|
||||
|
||||
`get_group_system_msg` 返回的每条记录增加以下字段:
|
||||
|
||||
| 字段 | 含义 |
|
||||
| --- | --- |
|
||||
| `target_uin`、`target_nick` | 申请或被邀请入群者,始终表示 B |
|
||||
| `operator_uin`、`operator_nick` | 处理该申请的操作者;审批场景中表示 C |
|
||||
| `target_status`、`invitor_status`、`operator_status` | 对应 QQ 号为 `known` 或 `unknown` |
|
||||
|
||||
原有 `invitor_uin`、`invitor_nick` 表示 A。`requester_uin` 保持兼容:普通申请表示申请人,
|
||||
邀请登录账号入群的记录则表示邀请人。需要区分三方时,应使用 `target_uin`、`invitor_uin`、`operator_uin`。
|
||||
QQ 只提供 UID 时会查询对应 QQ 号,查询去重并限制并发;查询错误会返回接口错误,不伪装成空列表。
|
||||
|
||||
```json
|
||||
{
|
||||
"target_uin": 10002,
|
||||
"target_status": "known",
|
||||
"invitor_uin": 10004,
|
||||
"invitor_status": "known",
|
||||
"operator_uin": 10003,
|
||||
"operator_status": "known",
|
||||
"checked": true
|
||||
}
|
||||
```
|
||||
|
||||
**`0` 或 `unknown` 不代表“没有邀请人”。** QQ 未提供身份、记录不可见、身份尚未解析等情况均不能证明没有邀请人。
|
||||
当前已确认的字段不足以对缺失信息可靠作出“无邀请人”的判断,因此不输出这种推断。
|
||||
同样,`checked: true` 只表示已处理,不代表必然审批通过;`operator_uin` 也可能是拒绝请求的人。
|
||||
|
||||
`count` 限制每个收件箱读取的记录数(最多 100);`group_id` 在读取后过滤,
|
||||
并非查询指定群的完整历史。`only_pending` 默认为 `false`。空数组表示本次读取范围内没有匹配记录,
|
||||
不能证明某次入群没有邀请人。调试日志会分别记录收件箱数量、类型筛选和最终筛选数量。
|
||||
|
||||
SDK 的 `getGroupSystemMessages()` 提供相应类型。新增字段在 SDK 中可选,以兼容旧服务端;
|
||||
连接旧服务端时,缺失的状态也应视为未知。
|
||||
@@ -26,3 +26,17 @@ identifier without logging quoted content. Fetch failures remain visible.
|
||||
Group quotes retain their group-sequence lookup. Forwarded nodes retain their
|
||||
inline quote content, which can be resent even when the original message is not
|
||||
available in the local account's history.
|
||||
|
||||
Image uploads retain their download reference and actual filename in durable
|
||||
message metadata. `get_msg` refreshes each image from that message's own reference,
|
||||
so a reused filename or a restart does not select another upload.
|
||||
|
||||
For older records missing an image reference, `get_msg` requests bounded history
|
||||
for the stored conversation and sequence (or the stored timestamp and client
|
||||
sequence for legacy private records). Only a unique message with matching sender,
|
||||
time and ordered image fingerprints can fill the missing references. The repair
|
||||
is saved under the existing signed `message_id`; it preserves message content
|
||||
and identity metadata and never restores a record removed while the request was pending.
|
||||
Complete images need no history request. If history is unavailable or cannot
|
||||
verify the match, the unverified image data is left intact and a warning is logged;
|
||||
download URLs are not guessed.
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "@snowluma/onebot",
|
||||
"version": "2.4.0",
|
||||
"version": "2.4.2",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "SnowLuma OneBot v11 adapter — the protocol translation layer that maps the public OneBot vocabulary (HTTP / WebSocket actions, message segments, post events) onto @snowluma/core's typed Api hub (`bridge.apis.<area>.method()`). Owns network adapters (HTTP server / HTTP client / WS server / WS client), the registered action handlers, the receive-side event→OneBot converter, message-id hashing, message store (SQLite-backed event history), media store, and the OneBot instance + manager that ties one OneBotConfig to one Bridge. Per-file subpath exports mirror the legacy `core/src/onebot/*` layout 1:1 so the previous `import { … } from '../onebot/<x>'` collapses to `import { … } from '@snowluma/onebot/<x>'`.",
|
||||
|
||||
@@ -62,6 +62,14 @@ export const messageDataSchema = {
|
||||
additionalProperties: true,
|
||||
} satisfies JsonSchema;
|
||||
|
||||
export const messageWithAutoReplySchema = {
|
||||
...messageDataSchema,
|
||||
properties: {
|
||||
...messageDataSchema.properties,
|
||||
auto_reply: { const: true, description: '仅当 QQ 标记该私聊消息为自动回复时提供' },
|
||||
},
|
||||
} satisfies JsonSchema;
|
||||
|
||||
// Forward nodes carry their original identifiers, not locally hashed message IDs.
|
||||
export const forwardNodeSchema: JsonSchema = {
|
||||
...messageDataSchema,
|
||||
|
||||
@@ -3,7 +3,7 @@ import { mapWithConcurrency } from '@snowluma/common/concurrency';
|
||||
import { positiveIntEnv } from '@snowluma/common/env';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { FriendDressError } from '@snowluma/protocol/web/friend-dress';
|
||||
import { formatGroupRequestFlag } from '@snowluma/protocol/qq-info';
|
||||
import { formatGroupRequestFlag, groupRequestSubType } from '@snowluma/protocol/qq-info';
|
||||
import type {
|
||||
GroupEssenceContent,
|
||||
GroupEssenceMessage,
|
||||
@@ -27,6 +27,7 @@ import { GROUP_MESSAGE_EVENT, hashMessageIdInt32 } from '../message-id';
|
||||
import {
|
||||
messageIdSchema,
|
||||
messageDataSchema,
|
||||
messageWithAutoReplySchema,
|
||||
forwardNodeSchema,
|
||||
messageSegmentSchema,
|
||||
mediaInfoSchema,
|
||||
@@ -1039,7 +1040,7 @@ export const actions = [
|
||||
messages: {
|
||||
type: 'array',
|
||||
description: '消息对象数组;去除 post_type/self_id,附带 real_id',
|
||||
items: messageDataSchema,
|
||||
items: messageWithAutoReplySchema,
|
||||
},
|
||||
},
|
||||
required: ['messages'],
|
||||
@@ -5485,7 +5486,8 @@ export const actions = [
|
||||
// 与标准群系统消息共用过滤收件箱,只保留方言动作的返回形状。
|
||||
// 这几个动作只是为实际使用中的 OneBot 方言客户端重命名并投影相同数据。
|
||||
async function fetchFilteredGroupRequests(ctx: ApiActionContext) {
|
||||
return ctx.bridge.apis.contacts.fetchGroupRequests(true);
|
||||
const requests = await ctx.bridge.apis.contacts.fetchGroupRequests(true);
|
||||
return requests.filter((request) => groupRequestSubType(request) !== undefined);
|
||||
}
|
||||
|
||||
function parseDownloadHeaders(headers: unknown): Record<string, string> {
|
||||
|
||||
@@ -4,17 +4,17 @@ import { RETCODE, failedResponse, okResponse } from '../types';
|
||||
// NapCat/LLOneBot omit `busid` from their `get_group_file_url` schema entirely,
|
||||
// so whatever value a client tacks on is silently ignored. Mirror that here:
|
||||
// accept any value, coerce when it's a usable non-negative integer, else fall
|
||||
// back to the canonical 102. Restores the legacy `asNumber(busid) || 102`
|
||||
// back to the uploaded file's known storage type (otherwise 102). Retains the
|
||||
// semantics that a strict `f.int({min:0}).default(102)` regressed (a *present*
|
||||
// non-numeric busid was rejected with `expected an integer`). See issue #147.
|
||||
function busidOr102(raw: unknown): number {
|
||||
function optionalBusId(raw: unknown): number | undefined {
|
||||
const n =
|
||||
typeof raw === 'number' && Number.isFinite(raw)
|
||||
? Math.trunc(raw)
|
||||
: typeof raw === 'string' && raw.trim() !== '' && Number.isFinite(Number(raw))
|
||||
? Math.trunc(Number(raw))
|
||||
: NaN;
|
||||
return Number.isInteger(n) && n >= 0 ? n : 102;
|
||||
return Number.isInteger(n) && n >= 0 ? n : undefined;
|
||||
}
|
||||
|
||||
export const actions = [
|
||||
@@ -159,7 +159,7 @@ export const actions = [
|
||||
properties: { url: { type: 'string', description: '文件下载直链' } },
|
||||
required: ['url'],
|
||||
},
|
||||
// busid is accepted but tolerant (see busidOr102): NapCat/LLBot ignore it,
|
||||
// busid is accepted but tolerant (see optionalBusId): NapCat/LLBot ignore it,
|
||||
// so a present null/empty/non-numeric value must not 400 the request (#147).
|
||||
params: { file_id: f.fileId(), busid: f.raw() },
|
||||
run: async (p, ctx) => {
|
||||
@@ -167,7 +167,7 @@ export const actions = [
|
||||
url: await ctx.bridge.apis.groupFile.getUrl(
|
||||
p.group_id,
|
||||
p.file_id,
|
||||
busidOr102(p.busid),
|
||||
optionalBusId(p.busid),
|
||||
),
|
||||
});
|
||||
},
|
||||
|
||||
@@ -577,7 +577,8 @@ export const actions = [
|
||||
],
|
||||
summary: '获取群系统消息',
|
||||
readOnly: true,
|
||||
returns: '群系统消息数组,可按群号或未处理状态过滤。',
|
||||
returns:
|
||||
'群系统消息数组,分别提供入群者、邀请人和处理者,可按群号或未处理状态过滤。身份为 0 时须查看状态;未知不代表不存在邀请人。',
|
||||
returnsSchema: {
|
||||
type: 'array',
|
||||
items: {
|
||||
@@ -586,10 +587,41 @@ export const actions = [
|
||||
group_id: { type: 'integer', description: '群号' },
|
||||
group_name: { type: 'string', description: '群名称' },
|
||||
request_id: { type: 'integer', description: '请求序列号' },
|
||||
requester_uin: { type: 'integer', description: '申请人 QQ 号' },
|
||||
requester_nick: { type: 'string', description: '申请人昵称' },
|
||||
invitor_uin: { type: 'integer', description: '邀请人 QQ 号,无邀请时为 0' },
|
||||
requester_uin: {
|
||||
type: 'integer',
|
||||
description: '请求发起人 QQ 号;邀请登录账号入群时表示邀请人',
|
||||
},
|
||||
requester_nick: { type: 'string', description: '请求发起人昵称' },
|
||||
target_uin: {
|
||||
type: 'integer',
|
||||
description: '申请或被邀请入群者 QQ 号,未知时为 0',
|
||||
},
|
||||
target_nick: { type: 'string', description: '入群者昵称' },
|
||||
target_status: {
|
||||
type: 'string',
|
||||
enum: ['known', 'unknown'],
|
||||
description: '入群者 QQ 号是否已知',
|
||||
},
|
||||
invitor_uin: {
|
||||
type: 'integer',
|
||||
description: '邀请人 QQ 号,未知时为 0;不能据此认定没有邀请人',
|
||||
},
|
||||
invitor_nick: { type: 'string', description: '邀请人昵称' },
|
||||
invitor_status: {
|
||||
type: 'string',
|
||||
enum: ['known', 'unknown'],
|
||||
description: '邀请人 QQ 号是否已知;缺失信息为 unknown',
|
||||
},
|
||||
operator_uin: {
|
||||
type: 'integer',
|
||||
description: '处理该申请的操作者 QQ 号,未知时为 0',
|
||||
},
|
||||
operator_nick: { type: 'string', description: '处理者昵称' },
|
||||
operator_status: {
|
||||
type: 'string',
|
||||
enum: ['known', 'unknown'],
|
||||
description: '处理者 QQ 号是否已知;已知不代表审批通过',
|
||||
},
|
||||
message: { type: 'string', description: '验证留言' },
|
||||
checked: { type: 'boolean', description: '是否已处理' },
|
||||
flag: { type: 'string', description: '处理请求使用的规范 flag' },
|
||||
@@ -600,8 +632,15 @@ export const actions = [
|
||||
'request_id',
|
||||
'requester_uin',
|
||||
'requester_nick',
|
||||
'target_uin',
|
||||
'target_nick',
|
||||
'target_status',
|
||||
'invitor_uin',
|
||||
'invitor_nick',
|
||||
'invitor_status',
|
||||
'operator_uin',
|
||||
'operator_nick',
|
||||
'operator_status',
|
||||
'message',
|
||||
'checked',
|
||||
'flag',
|
||||
|
||||
@@ -2,7 +2,11 @@ import { createLogger } from '@snowluma/common/logger';
|
||||
import type { JsonObject, JsonValue } from '../types';
|
||||
import { defineAction, groupAction, f, type Field } from '../action-kit';
|
||||
import { RETCODE, failedResponse, okResponse } from '../types';
|
||||
import { messageResultSchema, messageIdSchema, messageDataSchema } from '../action-result-schemas';
|
||||
import {
|
||||
messageResultSchema,
|
||||
messageIdSchema,
|
||||
messageWithAutoReplySchema,
|
||||
} from '../action-result-schemas';
|
||||
|
||||
/** send_msg only (#426). Some clients send `group_id: ""` on private chats.
|
||||
* Treat that exact empty string as absent. Do not change `f.groupId()`. */
|
||||
@@ -210,7 +214,7 @@ export const actions = [
|
||||
],
|
||||
returnsSchema: {
|
||||
allOf: [
|
||||
messageDataSchema,
|
||||
messageWithAutoReplySchema,
|
||||
{
|
||||
type: 'object',
|
||||
properties: {
|
||||
|
||||
@@ -89,6 +89,10 @@ async function convertPrivateMessage(
|
||||
sender,
|
||||
};
|
||||
|
||||
if (event.autoReply) {
|
||||
fields.auto_reply = true;
|
||||
}
|
||||
|
||||
if (isSelf && sessionId > 0 && sessionId !== ctx.selfId) {
|
||||
fields.target_id = sessionId;
|
||||
}
|
||||
|
||||
@@ -35,6 +35,8 @@ export function convertGroupMemberJoin(ctx: ConverterContext, event: GroupMember
|
||||
group_id: event.groupId,
|
||||
operator_id: event.operatorUin,
|
||||
user_id: event.userUin,
|
||||
invitor_id: event.invitorUin ?? 0,
|
||||
invitor_status: (event.invitorUin ?? 0) > 0 ? 'known' : 'unknown',
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ import type { ApiActionContext } from './api-handler';
|
||||
import type { ConverterContext } from './event-converter';
|
||||
import type { MediaStore } from './media-store';
|
||||
import type { MessageStore } from './message-store';
|
||||
import { readMessageWithImageRepair } from './message-image-repair';
|
||||
import type { TempSessionStore } from './temp-session-store';
|
||||
import {
|
||||
getDownloadRKeys,
|
||||
@@ -76,7 +77,7 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
|
||||
getLoginInfo: () => getLoginInfo(ref),
|
||||
isOnline: () => true,
|
||||
getUptimeMs: () => ref.getUptimeMs(),
|
||||
getMessage: async (messageId) => await messageStore.findEvent(messageId),
|
||||
getMessage: (messageId) => readMessageWithImageRepair(ref, messageId),
|
||||
refreshMessageMedia: (messageId, event) => refreshMessageMedia(ref, messageId, event),
|
||||
getMessageMeta: async (messageId) => await messageStore.findMeta(messageId),
|
||||
cacheMessageMetas: async (entries) => await messageStore.storeMetas(entries),
|
||||
|
||||
@@ -22,7 +22,7 @@ export class MediaIndexer {
|
||||
file: file || element.fileId || '',
|
||||
url,
|
||||
fileSize: element.fileSize ?? 0,
|
||||
fileName: element.fileId ?? '',
|
||||
fileName: element.fileName || element.fileId || '',
|
||||
subType: element.subType ?? 0,
|
||||
summary: element.summary ?? '',
|
||||
imageUrl: element.imageUrl ?? '',
|
||||
@@ -52,6 +52,7 @@ export class MediaIndexer {
|
||||
md5Hex: element.md5Hex,
|
||||
sha1Hex: element.sha1Hex,
|
||||
voiceFormat: element.voiceFormat,
|
||||
isNtv2: element.isNtv2,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -35,6 +35,7 @@ export interface CachedRecord {
|
||||
md5Hex?: string;
|
||||
sha1Hex?: string;
|
||||
voiceFormat?: number;
|
||||
isNtv2?: boolean;
|
||||
}
|
||||
|
||||
export interface CachedVideo {
|
||||
|
||||
@@ -0,0 +1,288 @@
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type { FriendMessage, GroupMessage, MessageElementOf } from '@snowluma/protocol/events';
|
||||
import type { OneBotInstanceContext } from './instance-context';
|
||||
import { segmentsToRawMessage } from './helper/cq';
|
||||
import {
|
||||
attachMessageMedia,
|
||||
imageMd5FromFile,
|
||||
isStoredMediaSegment,
|
||||
type MessageMedia,
|
||||
type StoredMediaSegment,
|
||||
} from './message-media';
|
||||
import { PRIVATE_QUOTE_MAX_DRIFT_SECONDS } from './private-quote';
|
||||
import { hasAuthoritativeSequence, type JsonObject, type MessageMeta } from './types';
|
||||
|
||||
const log = createLogger('OneBot');
|
||||
type RepairContext = Pick<OneBotInstanceContext, 'selfId' | 'bridge' | 'messageStore'>;
|
||||
type HistoryMessage = FriendMessage | GroupMessage;
|
||||
|
||||
function remoteUrl(value: unknown): value is string {
|
||||
return typeof value === 'string' && /^https?:\/\//i.test(value);
|
||||
}
|
||||
|
||||
function imageReference(element: MessageMedia | undefined): string {
|
||||
return remoteUrl(element?.imageUrl)
|
||||
? element.imageUrl
|
||||
: remoteUrl(element?.url)
|
||||
? element.url
|
||||
: '';
|
||||
}
|
||||
|
||||
/** Repair only missing image references. Full server events must not replace the
|
||||
* original message body, sender classification, signed id or sequence metadata.
|
||||
*/
|
||||
export async function readMessageWithImageRepair(
|
||||
ref: RepairContext,
|
||||
messageId: number,
|
||||
): Promise<JsonObject | null> {
|
||||
const event = await ref.messageStore.findEvent(messageId);
|
||||
|
||||
if (!event || !Array.isArray(event.message)) {
|
||||
return event;
|
||||
}
|
||||
|
||||
const segments = event.message.filter(isStoredMediaSegment);
|
||||
|
||||
if (!segments.some((segment) => segment.type === 'image' && !remoteUrl(segment.data.url))) {
|
||||
return event;
|
||||
}
|
||||
|
||||
try {
|
||||
const media = await ref.messageStore.findMedia(messageId);
|
||||
|
||||
if (
|
||||
media &&
|
||||
(media.length !== segments.length ||
|
||||
media.some((element, index) => element.type !== segments[index]!.type))
|
||||
) {
|
||||
throw new Error('stored media association is inconsistent');
|
||||
}
|
||||
|
||||
const missing = segments.map(
|
||||
(segment, index) =>
|
||||
segment.type === 'image' &&
|
||||
!remoteUrl(segment.data.url) &&
|
||||
!imageReference(media?.[index]),
|
||||
);
|
||||
|
||||
if (!missing.some(Boolean)) {
|
||||
return event;
|
||||
}
|
||||
|
||||
const storedMeta = await ref.messageStore.findMeta(messageId);
|
||||
// As in private history listing, old self-keyed outgoing rows require
|
||||
// their explicit recipient. This changes lookup scope, never stored identity.
|
||||
const meta =
|
||||
storedMeta &&
|
||||
!storedMeta.isGroup &&
|
||||
storedMeta.targetId === ref.selfId &&
|
||||
event.user_id === ref.selfId &&
|
||||
typeof event.target_id === 'number' &&
|
||||
Number.isSafeInteger(event.target_id) &&
|
||||
event.target_id > 0
|
||||
? { ...storedMeta, targetId: event.target_id }
|
||||
: storedMeta;
|
||||
|
||||
if (
|
||||
!meta ||
|
||||
meta.targetId <= 0 ||
|
||||
meta.timestamp <= 0 ||
|
||||
!Number.isSafeInteger(event.user_id) ||
|
||||
Number(event.user_id) <= 0 ||
|
||||
(event.self_id !== undefined && event.self_id !== ref.selfId) ||
|
||||
event.message_type !== (meta.isGroup ? 'group' : 'private') ||
|
||||
(meta.isGroup ? event.group_id !== meta.targetId : event.sub_type !== 'friend') ||
|
||||
(!meta.isGroup && event.target_id !== undefined && event.target_id !== meta.targetId)
|
||||
) {
|
||||
throw new Error('stored message identity is incomplete');
|
||||
}
|
||||
|
||||
const candidates = (await fetchHistory(ref, meta)).filter((source) =>
|
||||
matchesIdentity(source, event, meta, ref.selfId),
|
||||
);
|
||||
|
||||
if (candidates.length !== 1) {
|
||||
throw new Error(`expected one matching history message, got ${candidates.length}`);
|
||||
}
|
||||
|
||||
const images = candidates[0]!.elements.filter(
|
||||
(element): element is MessageElementOf<'image'> => element.type === 'image',
|
||||
);
|
||||
const storedImages = segments.filter((segment) => segment.type === 'image');
|
||||
|
||||
if (images.length !== storedImages.length) {
|
||||
throw new Error('history image count differs from stored message');
|
||||
}
|
||||
|
||||
const updated = structuredClone(event);
|
||||
const updatedSegments = (updated.message as JsonObject[]).filter(isStoredMediaSegment);
|
||||
// Never create empty placeholders for other media: they would prevent
|
||||
// a later complete history response from filling their real metadata.
|
||||
const attachSnapshots =
|
||||
media !== null || segments.every((segment) => segment.type === 'image');
|
||||
let imageIndex = 0;
|
||||
|
||||
for (const [index, segment] of updatedSegments.entries()) {
|
||||
const old = media?.[index];
|
||||
let element: MessageMedia = old ?? { type: segment.type };
|
||||
|
||||
if (segment.type === 'image') {
|
||||
const image = images[imageIndex++]!;
|
||||
verifyImage(old, segment, image);
|
||||
|
||||
if (missing[index]) {
|
||||
const url = imageReference(image);
|
||||
|
||||
if (!url) {
|
||||
throw new Error('history image has no download reference');
|
||||
}
|
||||
|
||||
element = { ...image, imageUrl: url };
|
||||
segment.data.url = url;
|
||||
} else if (!old) {
|
||||
element = { ...image, imageUrl: String(segment.data.url) };
|
||||
}
|
||||
}
|
||||
|
||||
if (attachSnapshots) {
|
||||
attachMessageMedia(segment, element);
|
||||
}
|
||||
}
|
||||
|
||||
updated.raw_message = segmentsToRawMessage(updated.message as JsonObject[]);
|
||||
|
||||
if (!(await ref.messageStore.updateMedia(messageId, event, updated))) {
|
||||
log.debug(
|
||||
'[get_msg] image history repair skipped after concurrent update message_id=%d',
|
||||
messageId,
|
||||
);
|
||||
return ref.messageStore.findEvent(messageId);
|
||||
}
|
||||
|
||||
log.debug(
|
||||
'[get_msg] image history repair saved message_id=%d images=%d',
|
||||
messageId,
|
||||
missing.filter(Boolean).length,
|
||||
);
|
||||
return updated;
|
||||
} catch (error) {
|
||||
// get_msg retains its documented partial-media behavior; do not invent
|
||||
// a URL or overwrite a record when history cannot prove the association.
|
||||
log.warn(
|
||||
'[get_msg] image history repair failed message_id=%d: %s',
|
||||
messageId,
|
||||
error instanceof Error ? error.message : String(error),
|
||||
);
|
||||
return ref.messageStore.findEvent(messageId);
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchHistory(ref: RepairContext, meta: MessageMeta): Promise<HistoryMessage[]> {
|
||||
if (meta.isGroup) {
|
||||
if (!hasAuthoritativeSequence(meta)) {
|
||||
throw new Error('group message has no verified sequence');
|
||||
}
|
||||
|
||||
const message = await ref.bridge.apis.message.getGroupMessageBySeq(
|
||||
meta.targetId,
|
||||
meta.sequence,
|
||||
ref.selfId,
|
||||
);
|
||||
return message ? [message] : [];
|
||||
}
|
||||
|
||||
const uid = await ref.bridge.resolveUserUid(meta.targetId);
|
||||
|
||||
if (!uid) {
|
||||
throw new Error('private history peer could not be resolved');
|
||||
}
|
||||
|
||||
if (meta.sequenceAuthoritative && Number.isSafeInteger(meta.sequence) && meta.sequence > 0) {
|
||||
const message = await ref.bridge.apis.message.getC2cMessageBySeq(
|
||||
uid,
|
||||
meta.sequence,
|
||||
ref.selfId,
|
||||
);
|
||||
return message ? [message] : [];
|
||||
}
|
||||
|
||||
if (meta.clientSequence <= 0) {
|
||||
throw new Error('private message has no verified client sequence');
|
||||
}
|
||||
|
||||
return ref.bridge.apis.message.getC2cLatestHistory(
|
||||
uid,
|
||||
20,
|
||||
ref.selfId,
|
||||
Math.min(0xffff_ffff, meta.timestamp + 1),
|
||||
);
|
||||
}
|
||||
|
||||
function matchesIdentity(
|
||||
source: HistoryMessage,
|
||||
event: JsonObject,
|
||||
meta: MessageMeta,
|
||||
selfId: number,
|
||||
): boolean {
|
||||
if (
|
||||
source.selfUin !== selfId ||
|
||||
source.senderUin !== event.user_id ||
|
||||
!Number.isSafeInteger(source.time) ||
|
||||
source.time <= 0 ||
|
||||
Math.abs(source.time - meta.timestamp) > PRIVATE_QUOTE_MAX_DRIFT_SECONDS
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (source.kind === 'group_message') {
|
||||
return meta.isGroup && source.groupId === meta.targetId && source.msgSeq === meta.sequence;
|
||||
}
|
||||
|
||||
// These history requests explicitly bind the peer UID. Older outgoing
|
||||
// responses can omit toUin; preserve that binding, never substitute selfId.
|
||||
const peer = source.peerUin ?? (source.senderUin !== selfId ? source.senderUin : meta.targetId);
|
||||
|
||||
if (
|
||||
meta.isGroup ||
|
||||
peer !== meta.targetId ||
|
||||
(meta.privateDirection &&
|
||||
(source.senderUin === selfId) !== (meta.privateDirection === 'outgoing'))
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return meta.sequenceAuthoritative && Number.isSafeInteger(meta.sequence) && meta.sequence > 0
|
||||
? source.sequenceAuthoritative !== false && source.ntMsgSeq === meta.sequence
|
||||
: (source.clientSeq ?? source.msgSeq) === meta.clientSequence;
|
||||
}
|
||||
|
||||
function verifyImage(
|
||||
old: MessageMedia | undefined,
|
||||
segment: StoredMediaSegment,
|
||||
image: MessageElementOf<'image'>,
|
||||
): void {
|
||||
// Older rows lack per-message snapshots but expose the content hash as the
|
||||
// image filename. Arbitrary aliases cannot establish this association.
|
||||
const legacyMd5 = imageMd5FromFile(segment.data.file ?? segment.data.file_id);
|
||||
const fingerprints = { md5Hex: old?.md5Hex || legacyMd5, sha1Hex: old?.sha1Hex };
|
||||
let matched = false;
|
||||
|
||||
for (const field of ['md5Hex', 'sha1Hex'] as const) {
|
||||
const before = fingerprints[field];
|
||||
const after = image[field];
|
||||
|
||||
if (!before || !after) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (before.toLowerCase() !== after.toLowerCase()) {
|
||||
throw new Error('history image fingerprint conflicts with stored message');
|
||||
}
|
||||
|
||||
matched = true;
|
||||
}
|
||||
|
||||
if (!matched) {
|
||||
throw new Error('history image fingerprint cannot be verified');
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,29 @@
|
||||
import type { MessageElement } from '@snowluma/protocol/events';
|
||||
import { serializeMediaInfo } from './media-store';
|
||||
import type { JsonObject } from './types';
|
||||
import type { JsonObject, JsonValue } from './types';
|
||||
|
||||
export type MessageMedia = Extract<MessageElement, { type: 'image' | 'record' | 'video' }>;
|
||||
export type StoredMediaSegment = JsonObject & { type: MessageMedia['type']; data: JsonObject };
|
||||
|
||||
export function isStoredMediaSegment(segment: JsonValue): segment is StoredMediaSegment {
|
||||
return (
|
||||
segment !== null &&
|
||||
typeof segment === 'object' &&
|
||||
!Array.isArray(segment) &&
|
||||
(segment.type === 'image' || segment.type === 'record' || segment.type === 'video') &&
|
||||
segment.data !== null &&
|
||||
typeof segment.data === 'object' &&
|
||||
!Array.isArray(segment.data)
|
||||
);
|
||||
}
|
||||
|
||||
/** Legacy image segments use a content hash filename; arbitrary aliases prove nothing. */
|
||||
export function imageMd5FromFile(file: unknown): string | undefined {
|
||||
return typeof file === 'string'
|
||||
? /^([a-f0-9]{32})\.(?:png|jpe?g|webp|gif|bmp)$/i.exec(file)?.[1]?.toLowerCase()
|
||||
: undefined;
|
||||
}
|
||||
|
||||
const mediaSnapshot = Symbol('message media snapshot');
|
||||
type MediaSegment = JsonObject & { [mediaSnapshot]?: MessageMedia };
|
||||
|
||||
@@ -57,6 +78,7 @@ export function attachMessageMedia(segment: JsonObject, element: MessageElement)
|
||||
picFormat,
|
||||
duration,
|
||||
voiceFormat,
|
||||
isNtv2,
|
||||
videoFormat,
|
||||
fileHash,
|
||||
mediaNode,
|
||||
@@ -79,6 +101,7 @@ export function attachMessageMedia(segment: JsonObject, element: MessageElement)
|
||||
picFormat,
|
||||
duration,
|
||||
voiceFormat,
|
||||
isNtv2,
|
||||
videoFormat,
|
||||
fileHash,
|
||||
mediaNode,
|
||||
@@ -186,7 +209,13 @@ function mergeKnownMediaFields(old: object, next: object): Record<string, unknow
|
||||
for (const [key, value] of Object.entries(next)) {
|
||||
// Zero dimensions, sizes and durations are incomplete observations, not
|
||||
// evidence that known properties of the same resource have changed.
|
||||
if (value === undefined || value === null || value === '' || value === 0) {
|
||||
// Storage region zero is a valid destination and must replace old values.
|
||||
if (
|
||||
value === undefined ||
|
||||
value === null ||
|
||||
value === '' ||
|
||||
(value === 0 && key !== 'storeId')
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
|
||||
|
||||
@@ -45,6 +45,7 @@ export class MessageStore {
|
||||
private stmtStoreMeta!: SqliteStatement;
|
||||
private stmtFindEvent!: SqliteStatement;
|
||||
private stmtFindMedia!: SqliteStatement;
|
||||
private stmtUpdateMedia!: SqliteStatement;
|
||||
private stmtFindMeta!: SqliteStatement;
|
||||
private stmtResolveReplyGroup!: SqliteStatement;
|
||||
private stmtResolveReplyPrivate!: SqliteStatement;
|
||||
@@ -122,6 +123,10 @@ export class MessageStore {
|
||||
this.stmtFindMedia = this.db.prepare(
|
||||
'SELECT media_data FROM messages WHERE message_hash = ?',
|
||||
);
|
||||
this.stmtUpdateMedia = this.db.prepare(
|
||||
`UPDATE messages SET data = ?, media_data = ?
|
||||
WHERE message_hash = ? AND data = ? AND media_data IS ?`,
|
||||
);
|
||||
|
||||
this.stmtFindMeta = this.db.prepare(
|
||||
'SELECT is_group, session_id, sequence, sequence_authoritative, event_name, client_sequence, private_direction, random, timestamp FROM messages WHERE message_hash = ?',
|
||||
@@ -326,6 +331,33 @@ export class MessageStore {
|
||||
});
|
||||
}
|
||||
|
||||
/** Enrich a read record without changing its identity or restoring a removed row. */
|
||||
async updateMedia(
|
||||
messageId: number,
|
||||
expected: JsonObject,
|
||||
updated: JsonObject,
|
||||
): Promise<boolean> {
|
||||
const before = JSON.stringify(expected);
|
||||
updated = snapshotMessageEvent(updated);
|
||||
return this.db.serial(async () => {
|
||||
await this.initialization;
|
||||
const previous = (await this.stmtFindMedia.get(messageId)) as
|
||||
{ media_data: string | null } | undefined;
|
||||
const media = mergeMessageMedia(
|
||||
previous?.media_data ?? null,
|
||||
serializeMessageMedia(updated),
|
||||
);
|
||||
const result = await this.stmtUpdateMedia.run(
|
||||
JSON.stringify(updated),
|
||||
media,
|
||||
messageId,
|
||||
before,
|
||||
previous?.media_data ?? null,
|
||||
);
|
||||
return result.changes === 1;
|
||||
});
|
||||
}
|
||||
|
||||
async findMedia(messageId: number): Promise<MessageMedia[] | null> {
|
||||
return this.db.serial(async () => {
|
||||
await this.initialization;
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
} from '@snowluma/protocol/dataline/device-contacts';
|
||||
import {
|
||||
formatGroupRequestFlag,
|
||||
groupRequestSubType,
|
||||
isSelfGroupInvitation,
|
||||
type GroupMemberInfo,
|
||||
type GroupRequestInfo,
|
||||
@@ -311,7 +312,7 @@ export async function getGroupMemberInfo(
|
||||
): Promise<JsonObject | null> {
|
||||
const cached = bridge.identity.findGroupMember(groupId, userId);
|
||||
|
||||
if (noCache || !cached || cached.isRobot === undefined) {
|
||||
if (noCache || !cached || cached.isRobot === undefined || cached.card === undefined) {
|
||||
await fetchSingleGroupMembers(bridge, groupId, noCache === true);
|
||||
}
|
||||
|
||||
@@ -490,26 +491,46 @@ export async function getStrangerInfo(
|
||||
}
|
||||
}
|
||||
|
||||
async function resolveRequesterUins(
|
||||
async function resolveGroupRequestUins(
|
||||
bridge: BridgeInterface,
|
||||
requests: readonly GroupRequestInfo[],
|
||||
): Promise<Map<string, { uin: number; name: string }>> {
|
||||
const resolved = new Map<string, { uin: number; name: string }>();
|
||||
const unresolved = new Set<string>();
|
||||
const names = new Map<string, string>();
|
||||
const roles = new Map<string, string>();
|
||||
const unresolvedUins = new Set<number>();
|
||||
|
||||
for (const request of requests) {
|
||||
const actor = groupRequestActor(request);
|
||||
const actors = requests.flatMap((request) =>
|
||||
(['target', 'invitor', 'operator'] as const).map((role) => ({
|
||||
...groupRequestPerson(request, role),
|
||||
groupId: request.groupId,
|
||||
role,
|
||||
})),
|
||||
);
|
||||
|
||||
for (const actor of actors) {
|
||||
const uid = actor.uid;
|
||||
|
||||
if (uid) {
|
||||
roles.set(uid, actor.role === 'target' ? 'requester' : actor.role);
|
||||
}
|
||||
|
||||
if (actor.name) {
|
||||
names.set(uid || `uin:${actor.uin}`, actor.name);
|
||||
}
|
||||
|
||||
if (uid && actor.uin > 0 && actor.name) {
|
||||
resolved.set(uid, { uin: actor.uin, name: actor.name });
|
||||
unresolved.delete(uid);
|
||||
if (actor.uin > 0) {
|
||||
resolved.set(uid || `uin:${actor.uin}`, { uin: actor.uin, name: actor.name });
|
||||
|
||||
if (uid) {
|
||||
unresolved.delete(uid);
|
||||
}
|
||||
|
||||
if (!actor.name) {
|
||||
unresolvedUins.add(actor.uin);
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -519,21 +540,21 @@ async function resolveRequesterUins(
|
||||
}
|
||||
|
||||
const cached =
|
||||
bridge.identity.findUinByUid(uid, request.groupId) ??
|
||||
bridge.identity.findUinByUid(uid, actor.groupId) ??
|
||||
bridge.identity.findUinByUid(uid);
|
||||
|
||||
if (cached && cached > 0 && actor.name) {
|
||||
if (cached && cached > 0) {
|
||||
resolved.set(uid, { uin: cached, name: actor.name });
|
||||
|
||||
if (!actor.name) {
|
||||
unresolvedUins.add(cached);
|
||||
}
|
||||
} else {
|
||||
unresolved.add(uid);
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (actor.uin > 0 && !actor.name) {
|
||||
unresolvedUins.add(actor.uin);
|
||||
}
|
||||
}
|
||||
|
||||
const profiles = await mapWithConcurrency(
|
||||
@@ -546,13 +567,16 @@ async function resolveRequesterUins(
|
||||
profile = await bridge.apis.contacts.fetchUserProfileByUid(uid);
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
throw new Error(`failed to resolve requester UIN for UID ${uid}: ${message}`, {
|
||||
cause: error,
|
||||
});
|
||||
throw new Error(
|
||||
`failed to resolve ${roles.get(uid)} UIN for UID ${uid}: ${message}`,
|
||||
{
|
||||
cause: error,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
if (!Number.isSafeInteger(profile.uin) || profile.uin <= 0) {
|
||||
throw new Error(`failed to resolve requester UIN for UID ${uid}`);
|
||||
throw new Error(`failed to resolve ${roles.get(uid)} UIN for UID ${uid}`);
|
||||
}
|
||||
|
||||
return [uid, profile] as const;
|
||||
@@ -572,7 +596,12 @@ async function resolveRequesterUins(
|
||||
async (uin) => {
|
||||
try {
|
||||
return [uin, await bridge.apis.contacts.fetchUserProfile(uin)] as const;
|
||||
} catch {
|
||||
} catch (error) {
|
||||
log.warn(
|
||||
'group request actor nickname unavailable: uin=%d error=%s',
|
||||
uin,
|
||||
error instanceof Error ? error.message : String(error),
|
||||
);
|
||||
return [uin, undefined] as const;
|
||||
}
|
||||
},
|
||||
@@ -589,35 +618,18 @@ async function resolveRequesterUins(
|
||||
return resolved;
|
||||
}
|
||||
|
||||
/** Join requests, self invitations, and invitations awaiting administrator approval. */
|
||||
function isJoinOrInviteNotify(notifyType: number | undefined): boolean {
|
||||
return (
|
||||
notifyType === undefined ||
|
||||
notifyType === 1 ||
|
||||
notifyType === 2 ||
|
||||
notifyType === 5 ||
|
||||
notifyType === 7 ||
|
||||
notifyType === 22
|
||||
);
|
||||
}
|
||||
|
||||
function groupRequestActor(request: GroupRequestInfo): {
|
||||
function groupRequestPerson(
|
||||
request: GroupRequestInfo,
|
||||
role: 'target' | 'invitor' | 'operator',
|
||||
): {
|
||||
uid: string;
|
||||
uin: number;
|
||||
name: string;
|
||||
} {
|
||||
if (isSelfGroupInvitation(request)) {
|
||||
return {
|
||||
uid: request.invitorUid,
|
||||
uin: request.invitorUin,
|
||||
name: request.invitorName,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
uid: request.targetUid,
|
||||
uin: request.targetUin,
|
||||
name: request.targetName,
|
||||
uid: request[`${role}Uid`],
|
||||
uin: request[`${role}Uin`],
|
||||
name: request[`${role}Name`],
|
||||
};
|
||||
}
|
||||
|
||||
@@ -638,11 +650,7 @@ export async function getGroupSystemMessages(
|
||||
const unique = new Map<string, GroupRequestInfo>();
|
||||
|
||||
for (const request of [...main, ...filtered]) {
|
||||
if (!isJoinOrInviteNotify(request.notifyType)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (request.eventType <= 0) {
|
||||
if (!groupRequestSubType(request)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -664,21 +672,47 @@ export async function getGroupSystemMessages(
|
||||
|
||||
return true;
|
||||
});
|
||||
const requesterUins = await resolveRequesterUins(bridge, requests);
|
||||
log.debug(
|
||||
'group request list: main=%d filtered=%d relevant=%d selected=%d group=%s onlyPending=%s',
|
||||
main.length,
|
||||
filtered.length,
|
||||
unique.size,
|
||||
requests.length,
|
||||
query.groupId ?? 'all',
|
||||
Boolean(query.onlyPending),
|
||||
);
|
||||
const actorUins = await resolveGroupRequestUins(bridge, requests);
|
||||
|
||||
return requests.map((request) => {
|
||||
const actor = groupRequestActor(request);
|
||||
const resolved =
|
||||
(actor.uid ? requesterUins.get(actor.uid) : undefined) ??
|
||||
(actor.uin > 0 ? requesterUins.get(`uin:${actor.uin}`) : undefined);
|
||||
const person = (role: 'target' | 'invitor' | 'operator') => {
|
||||
const actor = groupRequestPerson(request, role);
|
||||
const resolved =
|
||||
(actor.uid ? actorUins.get(actor.uid) : undefined) ??
|
||||
(actor.uin > 0 ? actorUins.get(`uin:${actor.uin}`) : undefined);
|
||||
const uin = actor.uin || resolved?.uin || 0;
|
||||
const name = actor.name || actorUins.get(`uin:${uin}`)?.name || resolved?.name || '';
|
||||
return { uin, name, status: uin > 0 ? 'known' : 'unknown' };
|
||||
};
|
||||
|
||||
const target = person('target');
|
||||
const invitor = person('invitor');
|
||||
const operator = person('operator');
|
||||
const requester = isSelfGroupInvitation(request) ? invitor : target;
|
||||
return {
|
||||
group_id: request.groupId,
|
||||
group_name: request.groupName,
|
||||
request_id: request.sequence,
|
||||
requester_uin: resolved?.uin ?? actor.uin,
|
||||
requester_nick: resolved?.name || actor.name,
|
||||
invitor_uin: request.invitorUin,
|
||||
invitor_nick: request.invitorName,
|
||||
requester_uin: requester.uin,
|
||||
requester_nick: requester.name,
|
||||
target_uin: target.uin,
|
||||
target_nick: target.name,
|
||||
target_status: target.status,
|
||||
invitor_uin: invitor.uin,
|
||||
invitor_nick: invitor.name,
|
||||
invitor_status: invitor.status,
|
||||
operator_uin: operator.uin,
|
||||
operator_nick: operator.name,
|
||||
operator_status: operator.status,
|
||||
message: request.comment,
|
||||
checked: request.state !== 1,
|
||||
flag: formatGroupRequestFlag(request),
|
||||
@@ -732,7 +766,8 @@ function formatGroupMember(
|
||||
group_id: groupId,
|
||||
user_id: member.uin,
|
||||
nickname: member.nickname,
|
||||
card: member.card,
|
||||
// OneBot requires a string; keep the unknown state in the identity store.
|
||||
card: member.card ?? '',
|
||||
is_robot: member.isRobot,
|
||||
sex: 'unknown',
|
||||
age: 0,
|
||||
|
||||
@@ -1,30 +1,18 @@
|
||||
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
|
||||
import type { MessageElementOf } from '@snowluma/protocol/events';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type { ImageUrlResolver } from '../event-converter';
|
||||
import type { CachedImage, MediaStore } from '../media-store';
|
||||
import type { MessageStore } from '../message-store';
|
||||
import type { OneBotInstanceContext } from '../instance-context';
|
||||
import { resolveRemoteMediaUrl } from '../media-url-resolver';
|
||||
import { imageMd5FromFile, isStoredMediaSegment } from '../message-media';
|
||||
import { segmentsToRawMessage } from '../helper/cq';
|
||||
import { pttTransKey, requestPttTransText } from './ptt-trans-waiter';
|
||||
import type { JsonObject, JsonValue } from '../types';
|
||||
import type { JsonObject } from '../types';
|
||||
|
||||
const log = createLogger('OneBot');
|
||||
|
||||
type StoredMediaSegment = JsonObject & { type: 'image' | 'record' | 'video'; data: JsonObject };
|
||||
|
||||
function isStoredMediaSegment(segment: JsonValue): segment is StoredMediaSegment {
|
||||
return (
|
||||
segment !== null &&
|
||||
typeof segment === 'object' &&
|
||||
!Array.isArray(segment) &&
|
||||
(segment.type === 'image' || segment.type === 'record' || segment.type === 'video') &&
|
||||
segment.data !== null &&
|
||||
typeof segment.data === 'object' &&
|
||||
!Array.isArray(segment.data)
|
||||
);
|
||||
}
|
||||
|
||||
export async function refreshMessageMedia(
|
||||
ref: Pick<OneBotInstanceContext, 'bridge' | 'messageStore' | 'mediaStore' | 'converterCtx'>,
|
||||
messageId: number,
|
||||
@@ -36,13 +24,17 @@ export async function refreshMessageMedia(
|
||||
|
||||
const segments = event.message.filter(isStoredMediaSegment);
|
||||
const voiceVideoSegments = segments.filter((segment) => segment.type !== 'image');
|
||||
const media =
|
||||
voiceVideoSegments.length > 0
|
||||
? (await ref.messageStore.findMedia(messageId))?.filter(
|
||||
(element) => element.type !== 'image',
|
||||
)
|
||||
: null;
|
||||
const meta = voiceVideoSegments.length > 0 ? await ref.messageStore.findMeta(messageId) : null;
|
||||
const snapshots = segments.length > 0 ? await ref.messageStore.findMedia(messageId) : null;
|
||||
const meta = segments.length > 0 ? await ref.messageStore.findMeta(messageId) : null;
|
||||
const media = snapshots?.filter((element) => element.type !== 'image');
|
||||
const aligned =
|
||||
snapshots?.length === segments.length &&
|
||||
snapshots.every((element, index) => element.type === segments[index]!.type);
|
||||
|
||||
if (snapshots && !aligned && segments.some((segment) => segment.type === 'image')) {
|
||||
log.warn('[get_msg] image metadata association inconsistent message_id=%d', messageId);
|
||||
}
|
||||
|
||||
// Validate the ordered association once; a filename lookup can select another upload.
|
||||
const voiceVideo =
|
||||
meta &&
|
||||
@@ -64,19 +56,58 @@ export async function refreshMessageMedia(
|
||||
let url: string | null;
|
||||
|
||||
if (segment.type === 'image') {
|
||||
const file =
|
||||
typeof segment.data.file === 'string'
|
||||
? segment.data.file
|
||||
: segment.data.file_id;
|
||||
const snapshot = aligned ? snapshots?.[index] : undefined;
|
||||
const ownUrl =
|
||||
typeof segment.data.url === 'string' && /^https?:\/\//i.test(segment.data.url)
|
||||
? segment.data.url
|
||||
: '';
|
||||
|
||||
if (typeof file !== 'string' || !file) {
|
||||
continue;
|
||||
if (meta && (snapshot?.type === 'image' || ownUrl)) {
|
||||
const element: MessageElementOf<'image'> =
|
||||
snapshot?.type === 'image'
|
||||
? snapshot
|
||||
: {
|
||||
type: 'image' as const,
|
||||
subType:
|
||||
typeof segment.data.sub_type === 'number'
|
||||
? segment.data.sub_type
|
||||
: 0,
|
||||
};
|
||||
const source = element.imageUrl || element.url || ownUrl;
|
||||
|
||||
if (typeof source === 'string' && /^https?:\/\//i.test(source)) {
|
||||
url = ref.converterCtx.imageUrlResolver
|
||||
? await ref.converterCtx.imageUrlResolver(
|
||||
{ ...element, imageUrl: source },
|
||||
meta.isGroup,
|
||||
)
|
||||
: source;
|
||||
} else {
|
||||
url = null;
|
||||
}
|
||||
} else if (!snapshots) {
|
||||
const file =
|
||||
typeof segment.data.file === 'string'
|
||||
? segment.data.file
|
||||
: segment.data.file_id;
|
||||
|
||||
if (typeof file !== 'string' || !file) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const cached = await ref.mediaStore.findImage(file);
|
||||
const md5 = imageMd5FromFile(file);
|
||||
url =
|
||||
cached &&
|
||||
meta &&
|
||||
cached.isGroup === meta.isGroup &&
|
||||
cached.sessionId === meta.targetId &&
|
||||
(!md5 || cached.md5Hex?.toLowerCase() === md5)
|
||||
? await resolveImageUrl(cached, ref.converterCtx.imageUrlResolver)
|
||||
: null;
|
||||
} else {
|
||||
url = null;
|
||||
}
|
||||
|
||||
url = await resolveImageUrl(
|
||||
await ref.mediaStore.findImage(file),
|
||||
ref.converterCtx.imageUrlResolver,
|
||||
);
|
||||
} else {
|
||||
if (!voiceVideo) {
|
||||
continue;
|
||||
@@ -191,10 +222,17 @@ export async function fetchPttText(
|
||||
const senderUin = Number(event.user_id) || 0;
|
||||
// c2c: receiver is self (inbound voice); group: the group uin.
|
||||
const peerUin = isGroup ? Number(event.group_id) || cached.sessionId : selfId;
|
||||
// Before the explicit marker was persisted, only NT records carried a
|
||||
// storage region. Legacy records also have mediaNode, but no storeId.
|
||||
// Old decoded NT records can store null for the default region as well.
|
||||
const isNtv2 = cached.isNtv2 ?? cached.mediaNode?.storeId !== undefined;
|
||||
const storeRegion = isNtv2 ? (cached.mediaNode?.storeId ?? 0) : 0;
|
||||
|
||||
const text = await requestPttTransText(pttTransKey(selfId, messageId), 20_000, () =>
|
||||
bridge.apis.extras.translatePttToText({
|
||||
isGroup,
|
||||
isNtv2,
|
||||
storeRegion,
|
||||
msgId: messageId,
|
||||
senderUin,
|
||||
peerUin,
|
||||
|
||||
@@ -1409,9 +1409,8 @@ export async function sendGroupMessage(
|
||||
throw new Error('message is empty');
|
||||
}
|
||||
|
||||
// Two sub-paths for group file segments:
|
||||
// a) has url/path but no file_id → upload() which internally calls publish()
|
||||
// b) has file_id from a prior upload_group_file → publish() only
|
||||
// Prepare all file uploads before publishing any part of the message.
|
||||
// Whether storage is temporary is only known after the upload preflight.
|
||||
let allFileElements = elements.filter((e) => e.type === 'file');
|
||||
let nonFileElements = elements.filter((e) => e.type !== 'file');
|
||||
|
||||
@@ -1426,6 +1425,73 @@ export async function sendGroupMessage(
|
||||
}
|
||||
}
|
||||
|
||||
let allowTemporary = nonFileElements.every((element) => element.type === 'image');
|
||||
|
||||
const assertStorageAllowed = (busId: number | undefined) => {
|
||||
if (busId === 104 && !allowTemporary) {
|
||||
throw new MessageElementValidationError(
|
||||
'UNSENDABLE_TYPE',
|
||||
'temporary group files require only file or image segments; remove text and other content before retrying',
|
||||
'file',
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const preparedFiles: Array<{
|
||||
element: MessageElementOf<'file'>;
|
||||
fileId: string;
|
||||
busId?: number;
|
||||
}> = [];
|
||||
|
||||
const prepareFiles = async (files: Array<MessageElementOf<'file'>>) => {
|
||||
// Check known temporary ids first, even if preceded by a new upload.
|
||||
const candidates = files.map((element) => {
|
||||
const cached = element.fileId
|
||||
? ref.bridge.recallUploadedFile(element.fileId)
|
||||
: undefined;
|
||||
const busId =
|
||||
cached?.scope === 'group' && cached.groupId === groupId ? cached.busId : undefined;
|
||||
assertStorageAllowed(busId);
|
||||
return { element, fileId: element.fileId, busId };
|
||||
});
|
||||
|
||||
for (const candidate of candidates) {
|
||||
const { element } = candidate;
|
||||
|
||||
if (!candidate.fileId) {
|
||||
if (!element.url) {
|
||||
throw new MessageElementValidationError(
|
||||
'MISSING_FIELD',
|
||||
'group file segment requires file_id or url',
|
||||
'file',
|
||||
);
|
||||
}
|
||||
|
||||
const name = element.fileName || guessFileNameFromUrl(element.url) || 'file';
|
||||
const uploaded = await ref.bridge.apis.groupFile.upload(
|
||||
groupId,
|
||||
element.url,
|
||||
name,
|
||||
'/',
|
||||
true,
|
||||
false,
|
||||
{ allowTemporary },
|
||||
);
|
||||
candidate.fileId = uploaded.fileId;
|
||||
candidate.busId = uploaded.busId;
|
||||
assertStorageAllowed(candidate.busId);
|
||||
}
|
||||
|
||||
if (!candidate.fileId) {
|
||||
throw new Error('group file auto-upload returned no file_id');
|
||||
}
|
||||
|
||||
preparedFiles.push({ element, fileId: candidate.fileId, busId: candidate.busId });
|
||||
}
|
||||
};
|
||||
|
||||
await prepareFiles(allFileElements);
|
||||
|
||||
let lastReceipt: Awaited<ReturnType<typeof ref.bridge.apis.message.sendGroup>> | undefined;
|
||||
|
||||
if (nonFileElements.length > 0) {
|
||||
@@ -1447,8 +1513,9 @@ export async function sendGroupMessage(
|
||||
err instanceof Error ? err.message : String(err),
|
||||
);
|
||||
const { fileEls, remaining } = splitVideoFileFallback(nonFileElements, isSizeErr);
|
||||
allFileElements = [...allFileElements, ...fileEls];
|
||||
nonFileElements = remaining;
|
||||
allowTemporary = remaining.every((element) => element.type === 'image');
|
||||
await prepareFiles(fileEls);
|
||||
|
||||
if (nonFileElements.length > 0) {
|
||||
lastReceipt = await ref.bridge.apis.message.sendGroup(groupId, nonFileElements);
|
||||
@@ -1457,34 +1524,14 @@ export async function sendGroupMessage(
|
||||
}
|
||||
}
|
||||
|
||||
for (const fileEl of allFileElements) {
|
||||
let fileId: string;
|
||||
|
||||
if (fileEl.url && !fileEl.fileId) {
|
||||
// upload() already calls publish() internally — do NOT call publish() again.
|
||||
const name = fileEl.fileName || guessFileNameFromUrl(fileEl.url) || 'file';
|
||||
const result = await ref.bridge.apis.groupFile.upload(
|
||||
groupId,
|
||||
fileEl.url,
|
||||
name,
|
||||
'/',
|
||||
true,
|
||||
for (const { element: fileEl, fileId, busId } of preparedFiles) {
|
||||
try {
|
||||
await ref.bridge.apis.groupFile.publish(groupId, fileId, busId);
|
||||
} catch (err) {
|
||||
throw new Error(
|
||||
`group file chat post failed (fileId=${fileId}): ${err instanceof Error ? err.message : String(err)}`,
|
||||
{ cause: err },
|
||||
);
|
||||
fileId = result.fileId ?? '';
|
||||
|
||||
if (!fileId) {
|
||||
throw new Error('group file auto-upload returned no file_id');
|
||||
}
|
||||
} else if (fileEl.fileId) {
|
||||
fileId = fileEl.fileId;
|
||||
await ref.bridge.apis.groupFile.publish(groupId, fileId);
|
||||
} else {
|
||||
throw new MessageElementValidationError(
|
||||
'MISSING_FIELD',
|
||||
'group file segment requires file_id or url',
|
||||
'file',
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
logSentMessage(true, groupId, [fileEl]);
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
|
||||
import {
|
||||
groupRequestSubType,
|
||||
isSelfGroupInvitation,
|
||||
type GroupRequestHandle,
|
||||
type GroupRequestInfo,
|
||||
@@ -141,10 +142,7 @@ async function resolveLiveGroupRequest(
|
||||
|
||||
const lookup = await fetchRequestInboxes(bridge, 'uin');
|
||||
const live = lookup.requests.find(
|
||||
(request) =>
|
||||
request.groupId === handle.groupId &&
|
||||
request.sequence === handle.sequence &&
|
||||
request.eventType > 0,
|
||||
(request) => request.groupId === handle.groupId && request.sequence === handle.sequence,
|
||||
);
|
||||
|
||||
if (!live) {
|
||||
@@ -168,6 +166,13 @@ async function applyGroupRequest(
|
||||
knownLive?: GroupRequestInfo,
|
||||
): Promise<void> {
|
||||
const live = knownLive ?? (await resolveLiveGroupRequest(bridge, handle));
|
||||
|
||||
if (!groupRequestSubType(live)) {
|
||||
throw new Error(
|
||||
`unsupported group request type: group=${live.groupId} sequence=${live.sequence} type=${live.eventType}`,
|
||||
);
|
||||
}
|
||||
|
||||
log.debug(
|
||||
'handling group request: group=%d sequence=%d eventType=%d filtered=%s approve=%s',
|
||||
live.groupId,
|
||||
@@ -263,7 +268,11 @@ export async function handleGroupAddRequest(
|
||||
|
||||
const lookup = await fetchRequestInboxes(bridge, 'uid');
|
||||
const candidates = lookup.requests.filter((request) => {
|
||||
if (request.groupId !== parsed.groupId || request.state !== 1 || request.eventType <= 0) {
|
||||
if (
|
||||
request.groupId !== parsed.groupId ||
|
||||
request.state !== 1 ||
|
||||
groupRequestSubType(request) !== parsed.requestType
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import type { ApiActionContext } from '../src/api-handler';
|
||||
import { actions } from '../src/actions/group-file';
|
||||
|
||||
describe('get_group_file_url storage selection', () => {
|
||||
it.each([
|
||||
{ busid: undefined, expected: undefined },
|
||||
{ busid: null, expected: undefined },
|
||||
{ busid: '', expected: undefined },
|
||||
{ busid: 'invalid', expected: undefined },
|
||||
{ busid: -1, expected: undefined },
|
||||
{ busid: 102, expected: 102 },
|
||||
{ busid: '104', expected: 104 },
|
||||
{ busid: 0, expected: 0 },
|
||||
])(
|
||||
'passes an explicit valid type, otherwise lets the file cache select it (%j)',
|
||||
async ({ busid, expected }) => {
|
||||
const getUrl = vi.fn(async () => 'https://download.example.com/file');
|
||||
const ctx = {
|
||||
bridge: { apis: { groupFile: { getUrl } } },
|
||||
} as unknown as ApiActionContext;
|
||||
const action = actions.find((entry) => entry.names[0] === 'get_group_file_url')!;
|
||||
const result = await action.toHandler(ctx)({ group_id: 12345, file_id: 'temp', busid });
|
||||
expect(result).toMatchObject({ status: 'ok' });
|
||||
expect(getUrl).toHaveBeenCalledExactlyOnceWith(12345, 'temp', expected);
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -708,6 +708,29 @@ describe('onebot/contact-actions / getGroupMemberInfo', () => {
|
||||
expect(out).toMatchObject({ user_id: 55, nickname: 'eve' });
|
||||
});
|
||||
|
||||
it('retries a failed legacy card refresh and then reuses the confirmed empty card', async () => {
|
||||
const fresh = makeMember(66, 'legacy', '');
|
||||
let member: GroupMemberInfo = { ...fresh, card: undefined };
|
||||
const fetchGroupMemberList = vi
|
||||
.fn(async () => {
|
||||
member = fresh;
|
||||
return [fresh];
|
||||
})
|
||||
.mockRejectedValueOnce(new Error('roster offline'));
|
||||
const bridge = fakeBridge({
|
||||
fetchGroupMemberList,
|
||||
identity: fakeIdentity({ findGroupMember: () => member }),
|
||||
});
|
||||
await expect(getGroupMemberInfo(bridge, 1200, 66)).rejects.toThrow('roster offline');
|
||||
expect(await getGroupMemberInfo(bridge, 1200, 66)).toMatchObject({
|
||||
nickname: 'legacy',
|
||||
card: '',
|
||||
});
|
||||
expect(await getGroupMemberInfo(bridge, 1200, 66)).toMatchObject({ card: '' });
|
||||
expect(fetchGroupMemberList).toHaveBeenCalledTimes(2);
|
||||
expect(fetchGroupMemberList).toHaveBeenCalledWith(1200, { force: false });
|
||||
});
|
||||
|
||||
it('refreshes a persisted member whose robot classification is unknown', async () => {
|
||||
let member: GroupMemberInfo = { ...makeMember(66, 'legacy'), isRobot: undefined };
|
||||
const fetchGroupMemberList = vi.fn(async () => {
|
||||
@@ -1033,6 +1056,98 @@ describe('onebot/contact-actions / getStrangerInfo', () => {
|
||||
});
|
||||
|
||||
describe('onebot/contact-actions / getGroupSystemMessages', () => {
|
||||
it('reports the invitee, inviter and reviewing operator independently (#643)', async () => {
|
||||
const bridge = fakeBridge({
|
||||
fetchGroupRequests: vi.fn(async (filtered: boolean) =>
|
||||
filtered ? [] : [makeGroupRequest({ state: 2 })],
|
||||
),
|
||||
});
|
||||
expect(await getGroupSystemMessages(bridge)).toEqual([
|
||||
expect.objectContaining({
|
||||
requester_uin: 123,
|
||||
target_uin: 123,
|
||||
target_nick: 'target',
|
||||
target_status: 'known',
|
||||
invitor_uin: 456,
|
||||
invitor_nick: 'inviter',
|
||||
invitor_status: 'known',
|
||||
operator_uin: 789,
|
||||
operator_nick: 'operator',
|
||||
operator_status: 'known',
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
it('marks omitted actors unknown rather than claiming there was no inviter', async () => {
|
||||
const bridge = fakeBridge({
|
||||
fetchGroupRequests: vi.fn(async (filtered: boolean) =>
|
||||
filtered
|
||||
? []
|
||||
: [
|
||||
makeGroupRequest({
|
||||
invitorUid: '',
|
||||
invitorUin: 0,
|
||||
invitorName: '',
|
||||
operatorUid: '',
|
||||
operatorUin: 0,
|
||||
operatorName: '',
|
||||
}),
|
||||
],
|
||||
),
|
||||
});
|
||||
expect(await getGroupSystemMessages(bridge)).toEqual([
|
||||
expect.objectContaining({
|
||||
invitor_uin: 0,
|
||||
invitor_status: 'unknown',
|
||||
operator_uin: 0,
|
||||
operator_status: 'unknown',
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
it('resolves UID-only inviters and operators as well as the requester', async () => {
|
||||
const fetchUserProfileByUid = vi.fn(async (uid: string) =>
|
||||
makeProfile(uid === 'u_inviter' ? 456 : 789, uid),
|
||||
);
|
||||
const bridge = fakeBridge({
|
||||
fetchGroupRequests: vi.fn(async (filtered: boolean) =>
|
||||
filtered ? [] : [makeGroupRequest({ invitorUin: 0, operatorUin: 0 })],
|
||||
),
|
||||
fetchUserProfileByUid,
|
||||
identity: fakeIdentity({ findUinByUid: () => null }),
|
||||
});
|
||||
expect(await getGroupSystemMessages(bridge)).toEqual([
|
||||
expect.objectContaining({
|
||||
invitor_uin: 456,
|
||||
invitor_status: 'known',
|
||||
operator_uin: 789,
|
||||
operator_status: 'known',
|
||||
}),
|
||||
]);
|
||||
expect(fetchUserProfileByUid.mock.calls.map(([uid]) => uid).sort()).toEqual([
|
||||
'u_inviter',
|
||||
'u_operator',
|
||||
]);
|
||||
});
|
||||
|
||||
it.each(['invitor', 'operator'] as const)(
|
||||
'propagates %s lookup failures instead of reporting absence',
|
||||
async (role) => {
|
||||
const bridge = fakeBridge({
|
||||
fetchGroupRequests: vi.fn(async (filtered: boolean) =>
|
||||
filtered ? [] : [makeGroupRequest({ [`${role}Uin`]: 0 })],
|
||||
),
|
||||
fetchUserProfileByUid: vi.fn(async () => {
|
||||
throw new Error('profile offline');
|
||||
}),
|
||||
identity: fakeIdentity({ findUinByUid: () => null }),
|
||||
});
|
||||
await expect(getGroupSystemMessages(bridge)).rejects.toThrow(
|
||||
`failed to resolve ${role} UIN`,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it('reads both request inboxes with the requested per-inbox count', async () => {
|
||||
const fetchGroupRequests = vi.fn(async (filtered: boolean) =>
|
||||
filtered
|
||||
@@ -1127,6 +1242,8 @@ describe('onebot/contact-actions / getGroupSystemMessages', () => {
|
||||
expect.objectContaining({
|
||||
requester_uin: 45_678,
|
||||
requester_nick: 'inviter',
|
||||
target_uin: 10_001,
|
||||
target_nick: 'bot',
|
||||
invitor_uin: 45_678,
|
||||
invitor_nick: 'inviter',
|
||||
}),
|
||||
|
||||
@@ -112,6 +112,28 @@ describe('convertEvent — message kinds', () => {
|
||||
expect(out!.message_id).toBe(PEER_UIN + 1);
|
||||
});
|
||||
|
||||
it.each([makeFriendMessage(PEER_UIN), makeTempMessage(PEER_UIN)])(
|
||||
'exposes only QQ-marked auto replies in $kind',
|
||||
async (event) => {
|
||||
const manual = await convertEvent(bareCtx(), {
|
||||
...event,
|
||||
elements: [{ type: 'text', text: '[自动回复] 稍后联系' }],
|
||||
});
|
||||
const automatic = await convertEvent(bareCtx(), { ...event, autoReply: true });
|
||||
|
||||
expect(manual).toMatchObject({
|
||||
message: [{ type: 'text', data: { text: '[自动回复] 稍后联系' } }],
|
||||
raw_message: '[自动回复] 稍后联系',
|
||||
});
|
||||
expect(manual).not.toHaveProperty('auto_reply');
|
||||
expect(automatic).toMatchObject({
|
||||
auto_reply: true,
|
||||
message: [{ type: 'text', data: { text: 'hi' } }],
|
||||
raw_message: 'hi',
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it('group_message peer → post_type "message", sub_type "normal", group_id set', async () => {
|
||||
const out = await convertEvent(bareCtx(), makeGroupMessage(PEER_UIN));
|
||||
expect(out!.post_type).toBe('message');
|
||||
|
||||
@@ -343,7 +343,11 @@ describe('registerEventPipeline', () => {
|
||||
message: {
|
||||
responseHead: {
|
||||
fromUin: SELF_ID,
|
||||
grp: { groupUin: GROUP_ID, memberCard: 'self', groupName: 'test group' },
|
||||
grp: {
|
||||
groupUin: GROUP_ID,
|
||||
memberCard: Buffer.from('self'),
|
||||
groupName: 'test group',
|
||||
},
|
||||
},
|
||||
contentHead: {
|
||||
msgType: 82,
|
||||
|
||||
@@ -1300,7 +1300,7 @@ function fakeFilteredRequest(overrides: Partial<GroupRequestInfo> = {}): GroupRe
|
||||
operatorName: 'op',
|
||||
sequence: 42,
|
||||
state: 1,
|
||||
eventType: 7,
|
||||
eventType: 1,
|
||||
comment: 'pls',
|
||||
filtered: true,
|
||||
...overrides,
|
||||
@@ -1310,7 +1310,9 @@ function fakeFilteredRequest(overrides: Partial<GroupRequestInfo> = {}): GroupRe
|
||||
describe('extended-actions / get_group_ignored_notifies', () => {
|
||||
it('maps filtered fetchGroupRequests(true) into the napcat shape', async () => {
|
||||
const fetchGroupRequests = vi.fn(async (filtered: boolean) =>
|
||||
filtered ? [fakeFilteredRequest()] : [],
|
||||
filtered
|
||||
? [fakeFilteredRequest(), fakeFilteredRequest({ sequence: 43, eventType: 7 })]
|
||||
: [],
|
||||
);
|
||||
const bridge = fakeBridge({ fetchGroupRequests: fetchGroupRequests as any });
|
||||
const h = makeHandler(fakeCtx(bridge));
|
||||
@@ -1329,7 +1331,7 @@ describe('extended-actions / get_group_ignored_notifies', () => {
|
||||
actor: 8888,
|
||||
invitor_uin: 7777,
|
||||
invitor_nick: 'inviter',
|
||||
flag: 'slreq:1:42:999:7:1',
|
||||
flag: 'slreq:1:42:999:1:1',
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
@@ -1,12 +1,18 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { Bridge } from '@snowluma/core/bridge';
|
||||
import { IdentityService } from '@snowluma/protocol/identity-service';
|
||||
import type { GroupInviteEvent } from '@snowluma/protocol/events';
|
||||
import { MSG_PUSH_CMD } from '@snowluma/protocol/msg-push';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import type { PushMsg } from '@snowluma/proto-defs/message';
|
||||
import type { GroupInvite } from '@snowluma/proto-defs/notify';
|
||||
import type { OidbBase, OidbSvcTrpcTcp0x10C0Response } from '@snowluma/proto-defs/oidb';
|
||||
import type { GroupInvitation, GroupInvite, GroupJoin } from '@snowluma/proto-defs/notify';
|
||||
import type {
|
||||
OidbBase,
|
||||
OidbSvcTrpcTcp0x10C0Response,
|
||||
OidbSvcTrpcTcp0x10C0ResponseRequest,
|
||||
} from '@snowluma/proto-defs/oidb';
|
||||
import type { OidbGroupRequestAction } from '@snowluma/proto-defs/oidb-actions/base';
|
||||
import { convertEvent } from '../src/event-converter';
|
||||
import { getGroupSystemMessages } from '../src/modules/contact-actions';
|
||||
import { handleGroupAddRequest } from '../src/modules/request-actions';
|
||||
|
||||
@@ -16,7 +22,7 @@ afterEach(async () => {
|
||||
await Promise.all(bridges.splice(0).map((bridge) => bridge.dispose()));
|
||||
});
|
||||
|
||||
function setup(filtered = false, overrides: { targetUid?: string; state?: number } = {}) {
|
||||
function setup(filtered = false, overrides: OidbSvcTrpcTcp0x10C0ResponseRequest = {}) {
|
||||
const bridge = new Bridge(IdentityService.memory('10001'));
|
||||
bridges.push(bridge);
|
||||
bridge.identity.setSelfProfile({
|
||||
@@ -36,15 +42,15 @@ function setup(filtered = false, overrides: { targetUid?: string; state?: number
|
||||
});
|
||||
bridge.identity.rememberRequestIdentity({ groupId: 999, uid: 'u_self', uin: 10001 });
|
||||
bridge.identity.rememberRequestIdentity({ groupId: 999, uid: 'u_inviter', uin: 456 });
|
||||
const operateTransInfo = Uint8Array.from([8, 42, 16, 231, 7, 24, 2]);
|
||||
const record = {
|
||||
sequence: 42n,
|
||||
eventType: 2,
|
||||
state: overrides.state ?? 1,
|
||||
state: 1,
|
||||
group: { groupUin: 999, groupName: 'group' },
|
||||
target: { uid: overrides.targetUid ?? 'u_self', name: 'bot' },
|
||||
target: { uid: 'u_self', name: 'bot' },
|
||||
invitor: { uid: 'u_inviter', name: 'inviter' },
|
||||
operateTransInfo,
|
||||
operateTransInfo: Uint8Array.from([8, 42, 16, 231, 7, 24, 2]),
|
||||
...overrides,
|
||||
};
|
||||
const send = vi.spyOn(bridge, 'sendRawPacket').mockImplementation(async (cmd) => {
|
||||
let responseData = Buffer.alloc(0);
|
||||
@@ -61,9 +67,12 @@ function setup(filtered = false, overrides: { targetUid?: string; state?: number
|
||||
|
||||
return { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData };
|
||||
});
|
||||
const flags: string[] = [];
|
||||
bridge.events.on('group_invite', (event) => flags.push(event.flag));
|
||||
const notice = () =>
|
||||
const events: GroupInviteEvent[] = [];
|
||||
bridge.events.on('group_invite', (event) => events.push(event));
|
||||
const notice = (
|
||||
msgType = 87,
|
||||
msgContent = protobuf_encode<GroupInvite>({ groupUin: 999, invitorUid: 'u_inviter' }),
|
||||
) =>
|
||||
bridge.onPacket({
|
||||
pid: 1,
|
||||
uin: '10001',
|
||||
@@ -74,36 +83,108 @@ function setup(filtered = false, overrides: { targetUid?: string; state?: number
|
||||
body: Buffer.from(
|
||||
protobuf_encode<PushMsg>({
|
||||
message: {
|
||||
contentHead: { msgType: 87, timestamp: 1 },
|
||||
body: {
|
||||
msgContent: protobuf_encode<GroupInvite>({
|
||||
groupUin: 999,
|
||||
invitorUid: 'u_inviter',
|
||||
}),
|
||||
},
|
||||
contentHead: { msgType, timestamp: 1 },
|
||||
body: { msgContent },
|
||||
},
|
||||
status: 0,
|
||||
}),
|
||||
),
|
||||
});
|
||||
return { bridge, send, flags, notice, operateTransInfo };
|
||||
return { bridge, send, events, notice, operateTransInfo: record.operateTransInfo };
|
||||
}
|
||||
|
||||
describe('group join requests', () => {
|
||||
it.each([false, true])(
|
||||
'reports and handles a join from the inbox (filtered=%s)',
|
||||
async (filtered) => {
|
||||
const { bridge, send, events, notice, operateTransInfo } = setup(filtered, {
|
||||
eventType: 1,
|
||||
target: { uid: 'u_applicant', name: 'applicant' },
|
||||
invitor: undefined,
|
||||
comment: 'please let me in',
|
||||
operateTransInfo: Uint8Array.from([8, 42, 16, 231, 7, 24, 1]),
|
||||
});
|
||||
bridge.identity.rememberRequestIdentity({ groupId: 999, uid: 'u_applicant', uin: 123 });
|
||||
await notice(
|
||||
84,
|
||||
protobuf_encode<GroupJoin>({ groupUin: 999, targetUid: 'u_applicant' }),
|
||||
);
|
||||
|
||||
expect(events).toHaveLength(1);
|
||||
const flag = `slreq:1:42:999:1:${filtered ? 1 : 0}`;
|
||||
const event = await convertEvent(
|
||||
{
|
||||
selfId: 10001,
|
||||
imageUrlResolver: null,
|
||||
mediaUrlResolver: null,
|
||||
messageIdResolver: null,
|
||||
mediaSegmentSink: null,
|
||||
},
|
||||
events[0]!,
|
||||
);
|
||||
expect(event).toMatchObject({
|
||||
post_type: 'request',
|
||||
request_type: 'group',
|
||||
sub_type: 'add',
|
||||
group_id: 999,
|
||||
user_id: 123,
|
||||
comment: 'please let me in',
|
||||
flag,
|
||||
});
|
||||
expect(await getGroupSystemMessages(bridge, { onlyPending: true })).toEqual([
|
||||
expect.objectContaining({ requester_uin: 123, requester_nick: 'applicant', flag }),
|
||||
]);
|
||||
|
||||
await handleGroupAddRequest(bridge, events[0]!.flag, true, '');
|
||||
const approvals = send.mock.calls.filter(([cmd]) =>
|
||||
cmd.startsWith('OidbSvcTrpcTcp.0x10c8_'),
|
||||
);
|
||||
expect(approvals).toHaveLength(1);
|
||||
const [cmd, bytes] = approvals[0]!;
|
||||
expect(cmd).toBe(`OidbSvcTrpcTcp.0x10c8_${filtered ? 2 : 1}`);
|
||||
expect(protobuf_decode<OidbBase<OidbGroupRequestAction>>(bytes).body).toMatchObject({
|
||||
accept: 1,
|
||||
body: { sequence: 42n, groupUin: 999, eventType: 1, operateTransInfo },
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it.each([7, 10, 5])('does not report another wire type (%i) as a join', async (eventType) => {
|
||||
const { bridge, events, notice } = setup(false, { eventType });
|
||||
await notice(84, protobuf_encode<GroupJoin>({ groupUin: 999, targetUid: 'u_self' }));
|
||||
expect(events).toEqual([]);
|
||||
expect(await getGroupSystemMessages(bridge)).toEqual([]);
|
||||
});
|
||||
|
||||
it.each(['42', 'slreq:1:42:999:1:0'])(
|
||||
'refuses an unknown inbox type for flag %s',
|
||||
async (flag) => {
|
||||
const { bridge, send } = setup(false, { eventType: 5 });
|
||||
await expect(handleGroupAddRequest(bridge, flag, true, '')).rejects.toThrow(
|
||||
'unsupported group request type',
|
||||
);
|
||||
expect(send.mock.calls.some(([cmd]) => cmd.startsWith('OidbSvcTrpcTcp.0x10c8_'))).toBe(
|
||||
false,
|
||||
);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe('non-friend group invitations', () => {
|
||||
it.each([
|
||||
{ approve: true, filtered: false },
|
||||
{ approve: false, filtered: true },
|
||||
])('handles an emitted flag through the real codecs: %j', async ({ approve, filtered }) => {
|
||||
const { bridge, send, flags, notice, operateTransInfo } = setup(filtered);
|
||||
const { bridge, send, events, notice, operateTransInfo } = setup(filtered);
|
||||
await notice();
|
||||
expect(flags).toEqual(['invite:999:u_inviter']);
|
||||
await handleGroupAddRequest(bridge, flags[0]!, approve, '');
|
||||
expect(events).toEqual([expect.objectContaining({ flag: 'invite:999:u_inviter' })]);
|
||||
await handleGroupAddRequest(bridge, events[0]!.flag, approve, '');
|
||||
const approval = send.mock.calls.find(([cmd]) => cmd.startsWith('OidbSvcTrpcTcp.0x10c8_'))!;
|
||||
expect(approval[0]).toBe(`OidbSvcTrpcTcp.0x10c8_${filtered ? 2 : 1}`);
|
||||
const wire = protobuf_decode<OidbBase<OidbGroupRequestAction>>(approval[1]);
|
||||
expect(wire.body).toMatchObject({
|
||||
accept: approve ? 1 : 2,
|
||||
body: { sequence: 42n, groupUin: 999, eventType: 10, message: ' ', operateTransInfo },
|
||||
body: { sequence: 42n, groupUin: 999, eventType: 2, message: ' ', operateTransInfo },
|
||||
});
|
||||
expect(
|
||||
await bridge.apis.contacts.resolveGroupJoinRequest(
|
||||
@@ -112,7 +193,7 @@ describe('non-friend group invitations', () => {
|
||||
'invite',
|
||||
'u_self',
|
||||
),
|
||||
).toMatchObject({ notifyType: 2, eventType: 10 });
|
||||
).toMatchObject({ notifyType: 1, eventType: 2 });
|
||||
});
|
||||
|
||||
it('lists the inviter and returns a flag that can approve the same invitation', async () => {
|
||||
@@ -124,21 +205,38 @@ describe('non-friend group invitations', () => {
|
||||
requester_uin: 456,
|
||||
requester_nick: 'inviter',
|
||||
checked: false,
|
||||
flag: 'slreq:1:42:999:10:0',
|
||||
flag: 'slreq:1:42:999:2:0',
|
||||
}),
|
||||
]);
|
||||
await handleGroupAddRequest(bridge, String(rows[0]!.flag), true, '');
|
||||
const approval = send.mock.calls.find(([cmd]) => cmd.startsWith('OidbSvcTrpcTcp.0x10c8_'))!;
|
||||
const wire = protobuf_decode<OidbBase<OidbGroupRequestAction>>(approval[1]);
|
||||
expect(wire.body?.body).toMatchObject({ eventType: 10, operateTransInfo });
|
||||
expect(wire.body?.body).toMatchObject({ eventType: 2, operateTransInfo });
|
||||
});
|
||||
|
||||
it.each([{ targetUid: 'u_other' }, { state: 2 }])(
|
||||
'rejects a mismatched or processed invitation: %j',
|
||||
it('corrects the type in an older invitation flag from the current inbox', async () => {
|
||||
const { bridge, send, operateTransInfo } = setup(true);
|
||||
await handleGroupAddRequest(bridge, 'slreq:1:42:999:10:0', true, '');
|
||||
const approvals = send.mock.calls.filter(([cmd]) =>
|
||||
cmd.startsWith('OidbSvcTrpcTcp.0x10c8_'),
|
||||
);
|
||||
expect(approvals).toHaveLength(1);
|
||||
const [cmd, bytes] = approvals[0]!;
|
||||
expect(cmd).toBe('OidbSvcTrpcTcp.0x10c8_2');
|
||||
expect(protobuf_decode<OidbBase<OidbGroupRequestAction>>(bytes).body?.body).toMatchObject({
|
||||
sequence: 42n,
|
||||
groupUin: 999,
|
||||
eventType: 2,
|
||||
operateTransInfo,
|
||||
});
|
||||
});
|
||||
|
||||
it.each([{ target: { uid: 'u_other' } }, { state: 2 }, { eventType: 10 }])(
|
||||
'requires a pending invitation to this account: %j',
|
||||
async (overrides) => {
|
||||
const { bridge, send, flags, notice } = setup(false, overrides);
|
||||
const { bridge, send, events, notice } = setup(false, overrides);
|
||||
await notice();
|
||||
await expect(handleGroupAddRequest(bridge, flags[0]!, true, '')).rejects.toThrow(
|
||||
await expect(handleGroupAddRequest(bridge, events[0]!.flag, true, '')).rejects.toThrow(
|
||||
'matching group request not found',
|
||||
);
|
||||
expect(send.mock.calls.some(([cmd]) => cmd.startsWith('OidbSvcTrpcTcp.0x10c8_'))).toBe(
|
||||
@@ -147,3 +245,56 @@ describe('non-friend group invitations', () => {
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe('invitations awaiting administrator approval', () => {
|
||||
it('keeps the applicant, inviter and approval type through the real codecs', async () => {
|
||||
const { bridge, send, events, notice, operateTransInfo } = setup(true, {
|
||||
eventType: 22,
|
||||
target: { uid: 'u_applicant', name: 'applicant' },
|
||||
comment: 'invited to join',
|
||||
operateTransInfo: Uint8Array.from([8, 42, 16, 231, 7, 24, 22]),
|
||||
});
|
||||
bridge.identity.rememberRequestIdentity({ groupId: 999, uid: 'u_applicant', uin: 123 });
|
||||
await notice(
|
||||
525,
|
||||
protobuf_encode<GroupInvitation>({
|
||||
cmd: 87,
|
||||
info: {
|
||||
inner: { groupUin: 999, invitorUid: 'u_inviter', targetUid: 'u_applicant' },
|
||||
},
|
||||
}),
|
||||
);
|
||||
expect(events).toEqual([
|
||||
expect.objectContaining({
|
||||
subType: 'invite',
|
||||
fromUin: 456,
|
||||
invitedUin: 123,
|
||||
flag: 'slreq:1:42:999:22:1',
|
||||
}),
|
||||
]);
|
||||
expect(await getGroupSystemMessages(bridge)).toEqual([
|
||||
expect.objectContaining({
|
||||
requester_uin: 123,
|
||||
invitor_uin: 456,
|
||||
flag: events[0]!.flag,
|
||||
}),
|
||||
]);
|
||||
await handleGroupAddRequest(bridge, events[0]!.flag, false, 'declined');
|
||||
const approvals = send.mock.calls.filter(([cmd]) =>
|
||||
cmd.startsWith('OidbSvcTrpcTcp.0x10c8_'),
|
||||
);
|
||||
expect(approvals).toHaveLength(1);
|
||||
const [cmd, bytes] = approvals[0]!;
|
||||
expect(cmd).toBe('OidbSvcTrpcTcp.0x10c8_2');
|
||||
expect(protobuf_decode<OidbBase<OidbGroupRequestAction>>(bytes).body).toMatchObject({
|
||||
accept: 2,
|
||||
body: {
|
||||
sequence: 42n,
|
||||
groupUin: 999,
|
||||
eventType: 22,
|
||||
message: 'declined',
|
||||
operateTransInfo,
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,183 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { protobuf_encode, type pb, type uint_32, type bytes } from '@snowluma/proton';
|
||||
import { IdentityService } from '@snowluma/protocol/identity-service';
|
||||
import { parseMsgPush, parseMsgPushOrThrow } from '@snowluma/protocol/msg-push';
|
||||
import type { PacketInfo } from '@snowluma/common/protocol-types';
|
||||
import { convertEvent } from '../src/event-converter';
|
||||
|
||||
// Independent wire fixture: routing header 1.8.8.4.1 contains the join
|
||||
// origin. The member-change body has its own operator, not the inviter.
|
||||
interface ObservedOrigin {
|
||||
type?: pb<1, uint_32>;
|
||||
uid?: pb<3, bytes>;
|
||||
}
|
||||
interface ObservedJoinInfo {
|
||||
origin?: pb<1, ObservedOrigin>;
|
||||
}
|
||||
interface ObservedGroupKey {
|
||||
extra?: pb<4, ObservedJoinInfo>;
|
||||
}
|
||||
interface ObservedGroupRoute {
|
||||
key?: pb<8, ObservedGroupKey>;
|
||||
}
|
||||
interface ObservedRoute {
|
||||
from?: pb<1, uint_32>;
|
||||
group?: pb<8, ObservedGroupRoute>;
|
||||
}
|
||||
interface ObservedHead {
|
||||
type?: pb<1, uint_32>;
|
||||
time?: pb<6, uint_32>;
|
||||
}
|
||||
interface ObservedBody {
|
||||
content?: pb<2, bytes>;
|
||||
}
|
||||
interface ObservedMessage {
|
||||
route?: pb<1, ObservedRoute>;
|
||||
head?: pb<2, ObservedHead>;
|
||||
body?: pb<3, ObservedBody>;
|
||||
}
|
||||
interface ObservedPush {
|
||||
message?: pb<1, ObservedMessage>;
|
||||
}
|
||||
interface ObservedChange {
|
||||
group?: pb<1, uint_32>;
|
||||
member?: pb<3, string>;
|
||||
operation?: pb<4, uint_32>;
|
||||
operator?: pb<5, bytes>;
|
||||
}
|
||||
|
||||
function packet(operation: number, origin?: ObservedOrigin): PacketInfo {
|
||||
return {
|
||||
pid: 0,
|
||||
uin: '10001',
|
||||
seqId: 1,
|
||||
retCode: 0,
|
||||
fromClient: false,
|
||||
serviceCmd: 'trpc.msg.olpush.OlPushService.MsgPush',
|
||||
body: protobuf_encode<ObservedPush>({
|
||||
message: {
|
||||
route: { from: 90001, group: { key: { extra: { origin } } } },
|
||||
head: { type: 33, time: 1_700_000_000 },
|
||||
body: {
|
||||
content: protobuf_encode<ObservedChange>({
|
||||
group: 90001,
|
||||
member: 'u_member',
|
||||
operation,
|
||||
operator: Buffer.from('u_admin'),
|
||||
}),
|
||||
},
|
||||
},
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
function identity() {
|
||||
const result = IdentityService.memory('10001');
|
||||
|
||||
for (const [uid, uin] of [
|
||||
['u_member', 10002],
|
||||
['u_admin', 10003],
|
||||
['u_inviter', 10004],
|
||||
] as const) {
|
||||
result.rememberRequestIdentity({ uid, uin, source: 'group_request' });
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
async function notice(pkt: PacketInfo, identities = identity()) {
|
||||
const events = parseMsgPush(pkt, identities);
|
||||
expect(events).toHaveLength(1);
|
||||
return convertEvent(
|
||||
{
|
||||
selfId: 10001,
|
||||
imageUrlResolver: null,
|
||||
mediaUrlResolver: null,
|
||||
messageIdResolver: null,
|
||||
mediaSegmentSink: null,
|
||||
},
|
||||
events[0]!,
|
||||
);
|
||||
}
|
||||
|
||||
describe('group join identities (#643)', () => {
|
||||
it.each([2, 130])('keeps all three actors distinct for operation %d', async (operation) => {
|
||||
expect(
|
||||
await notice(packet(operation, { type: 0, uid: Buffer.from('u_inviter') })),
|
||||
).toMatchObject({
|
||||
notice_type: 'group_increase',
|
||||
sub_type: 'approve',
|
||||
group_id: 90001,
|
||||
user_id: 10002,
|
||||
operator_id: 10003,
|
||||
invitor_id: 10004,
|
||||
invitor_status: 'known',
|
||||
});
|
||||
});
|
||||
|
||||
it.each([3, 131, 0x102, 0x103])(
|
||||
'does not guess the inviter from operation %d',
|
||||
async (operation) => {
|
||||
expect(
|
||||
await notice(packet(operation, { type: 0, uid: Buffer.from('u_inviter') })),
|
||||
).toMatchObject({
|
||||
user_id: 10002,
|
||||
operator_id: 10003,
|
||||
invitor_id: 0,
|
||||
invitor_status: 'unknown',
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it('does not label a QR-code sharer as an inviter', async () => {
|
||||
expect(await notice(packet(130, { type: 1, uid: Buffer.from('u_inviter') }))).toMatchObject(
|
||||
{
|
||||
operator_id: 10003,
|
||||
invitor_id: 0,
|
||||
invitor_status: 'unknown',
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
it.each([undefined, {}, { type: 0, uid: new Uint8Array() }])(
|
||||
'reports missing origin as unknown',
|
||||
async (origin) => {
|
||||
expect(await notice(packet(130, origin))).toMatchObject({
|
||||
invitor_id: 0,
|
||||
invitor_status: 'unknown',
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it('keeps an unresolved inviter unknown without substituting the administrator', async () => {
|
||||
expect(
|
||||
await notice(packet(130, { type: 0, uid: Buffer.from('u_unresolved') })),
|
||||
).toMatchObject({
|
||||
operator_id: 10003,
|
||||
invitor_id: 0,
|
||||
invitor_status: 'unknown',
|
||||
});
|
||||
});
|
||||
|
||||
it.each([Buffer.from([0xff]), Buffer.from('u_bad\nuid')])(
|
||||
'rejects malformed inviter identities',
|
||||
(uid) => {
|
||||
expect(() => parseMsgPushOrThrow(packet(130, { type: 0, uid }), identity())).toThrow(
|
||||
/invitation origin/,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it("does not reuse another account's identity cache", async () => {
|
||||
identity();
|
||||
expect(
|
||||
await notice(
|
||||
packet(130, { type: 0, uid: Buffer.from('u_inviter') }),
|
||||
IdentityService.memory('20001'),
|
||||
),
|
||||
).toMatchObject({
|
||||
invitor_id: 0,
|
||||
invitor_status: 'unknown',
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,253 @@
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { Bridge } from '@snowluma/core/bridge';
|
||||
import { IdentityService } from '@snowluma/protocol/identity-service';
|
||||
import type { GroupMemberInfo, QQGroupInfo } from '@snowluma/protocol/qq-info';
|
||||
import type { SendPacketResult } from '@snowluma/common/packet-sender';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import type {
|
||||
OidbBase,
|
||||
OidbRobotUinRangeResponse,
|
||||
OidbSvcTrpcTcp0xFE7_3Response,
|
||||
} from '@snowluma/proto-defs/oidb';
|
||||
import type { OidbGroupMemberListRequest } from '@snowluma/proto-defs/oidb-actions/base';
|
||||
import { getGroupMemberInfo, getGroupMemberList } from '../src/modules/contact-actions';
|
||||
|
||||
const groupId = 680;
|
||||
const cleanups: Array<() => void | Promise<void>> = [];
|
||||
|
||||
afterEach(async () => {
|
||||
for (const cleanup of cleanups.splice(0).reverse()) {
|
||||
await cleanup();
|
||||
}
|
||||
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
function member(uin: number, card: string): GroupMemberInfo {
|
||||
return {
|
||||
uin,
|
||||
uid: `u_${uin}`,
|
||||
nickname: `old-${uin}`,
|
||||
card,
|
||||
isRobot: false,
|
||||
role: 'member',
|
||||
level: 1,
|
||||
title: '',
|
||||
joinTime: 10,
|
||||
lastSentTime: 20,
|
||||
shutUpTime: 0,
|
||||
};
|
||||
}
|
||||
|
||||
function group(id = groupId): QQGroupInfo {
|
||||
return {
|
||||
groupId: id,
|
||||
groupName: 'test group',
|
||||
remark: '',
|
||||
memberCount: 0,
|
||||
memberMax: 100,
|
||||
members: new Map(),
|
||||
};
|
||||
}
|
||||
|
||||
function packet(responseData: Uint8Array): SendPacketResult {
|
||||
return {
|
||||
success: true,
|
||||
gotResponse: true,
|
||||
errorCode: 0,
|
||||
errorMessage: '',
|
||||
responseData: Buffer.from(responseData),
|
||||
};
|
||||
}
|
||||
|
||||
async function openBridge(dbPath: string) {
|
||||
const identity = new IdentityService('10001', dbPath);
|
||||
const bridge = new Bridge(identity);
|
||||
cleanups.push(() => bridge.dispose());
|
||||
await identity.initialization;
|
||||
// Profile enrichment is independent of the roster and card decoding.
|
||||
vi.spyOn(bridge.apis.contacts, 'fetchUserProfile').mockImplementation(async (uin) => ({
|
||||
uin,
|
||||
uid: `u_${uin}`,
|
||||
nickname: 'profile',
|
||||
remark: '',
|
||||
qid: '',
|
||||
sex: 'unknown',
|
||||
age: 0,
|
||||
sign: '',
|
||||
avatar: '',
|
||||
level: 0,
|
||||
qidianMasterFlag: 0,
|
||||
qidianCrewFlag: 0,
|
||||
qidianCrewFlag2: 0,
|
||||
}));
|
||||
return bridge;
|
||||
}
|
||||
|
||||
function sendPages(bridge: Bridge, pages: OidbSvcTrpcTcp0xFE7_3Response[]) {
|
||||
const tokens: string[] = [];
|
||||
const send = vi.spyOn(bridge, 'sendRawPacket').mockImplementation(async (command, bytes) => {
|
||||
if (command === 'OidbSvcTrpcTcp.0x496_0') {
|
||||
return packet(
|
||||
protobuf_encode<OidbBase<OidbRobotUinRangeResponse>>({
|
||||
body: { robotConfig: { version: 1, ranges: [{ minUin: 66n, maxUin: 66n }] } },
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
if (command !== 'OidbSvcTrpcTcp.0xfe7_3') {
|
||||
throw new Error(`unexpected command: ${command}`);
|
||||
}
|
||||
|
||||
const request = protobuf_decode<OidbBase<OidbGroupMemberListRequest>>(bytes);
|
||||
expect(request.body?.groupUin).toBe(groupId);
|
||||
tokens.push(request.body?.token ?? '');
|
||||
const page = pages[tokens.length - 1];
|
||||
|
||||
if (!page) {
|
||||
throw new Error('roster unavailable');
|
||||
}
|
||||
|
||||
return packet(protobuf_encode<OidbBase<OidbSvcTrpcTcp0xFE7_3Response>>({ body: page }));
|
||||
});
|
||||
return { send, tokens };
|
||||
}
|
||||
|
||||
describe('group card failures through roster, cache and OneBot output', () => {
|
||||
it.each([false, true])(
|
||||
'returns every page and preserves valid cards with no_cache=%s',
|
||||
async (noCache) => {
|
||||
const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'group-card-'));
|
||||
cleanups.push(() => fs.rmSync(directory, { recursive: true, force: true }));
|
||||
const dbPath = path.join(directory, 'identity.db');
|
||||
const bridge = await openBridge(dbPath);
|
||||
bridge.identity.rememberGroups([group(), group(681)]);
|
||||
bridge.identity.rememberGroupMembers(groupId, [
|
||||
member(11, 'last valid card'),
|
||||
member(44, 'removed card'),
|
||||
member(55, ''),
|
||||
]);
|
||||
bridge.identity.rememberGroupMembers(681, [member(22, 'another group card')]);
|
||||
const damaged = Buffer.from('616207', 'hex');
|
||||
const firstPage: OidbSvcTrpcTcp0xFE7_3Response = {
|
||||
token: 'page-2',
|
||||
members: [11, 22, 33, 44, 55].map((uin) => ({
|
||||
uin: { uin, uid: `u_${uin}` },
|
||||
memberName: `fresh-${uin}`,
|
||||
permission: 2,
|
||||
memberCard: {
|
||||
memberCard:
|
||||
uin === 33
|
||||
? Buffer.from('fresh card')
|
||||
: uin === 44
|
||||
? Buffer.alloc(0)
|
||||
: damaged,
|
||||
},
|
||||
})),
|
||||
};
|
||||
const transport = sendPages(bridge, [
|
||||
firstPage,
|
||||
{
|
||||
members: [
|
||||
{ uin: { uin: 66, uid: 'u_66' } },
|
||||
{
|
||||
uin: { uin: 77, uid: 'u_77' },
|
||||
memberName: 'styled member',
|
||||
memberCard: {
|
||||
memberCard: Buffer.from(
|
||||
'0a090a0724c7bfc480440e0a071205202014c6951000',
|
||||
'hex',
|
||||
),
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
]);
|
||||
|
||||
const output = await getGroupMemberList(bridge, groupId, noCache);
|
||||
expect(output.map((entry) => [entry.user_id, entry.card])).toEqual([
|
||||
[11, 'last valid card'],
|
||||
[22, ''],
|
||||
[33, 'fresh card'],
|
||||
[44, ''],
|
||||
[55, ''],
|
||||
[66, ''],
|
||||
[77, ' ƕ'],
|
||||
]);
|
||||
expect(output[0]).toMatchObject({ nickname: 'fresh-11', role: 'admin' });
|
||||
expect(output[5]).toMatchObject({ is_robot: true });
|
||||
expect(transport.tokens).toEqual(['', 'page-2']);
|
||||
expect(bridge.identity.findGroupMember(groupId, 22)?.card).toBeUndefined();
|
||||
expect(bridge.identity.findGroupMember(681, 22)?.card).toBe('another group card');
|
||||
|
||||
expect(await getGroupMemberList(bridge, groupId)).toEqual(output);
|
||||
expect(await getGroupMemberInfo(bridge, groupId, 22)).toMatchObject({
|
||||
user_id: 22,
|
||||
card: '',
|
||||
role: 'admin',
|
||||
});
|
||||
expect(await getGroupMemberInfo(bridge, groupId, 11)).toMatchObject({
|
||||
card: 'last valid card',
|
||||
});
|
||||
expect(await getGroupMemberInfo(bridge, groupId, 77)).toMatchObject({
|
||||
card: ' ƕ',
|
||||
});
|
||||
expect(transport.tokens).toEqual(['', 'page-2']);
|
||||
await bridge.dispose();
|
||||
|
||||
const restarted = await openBridge(dbPath);
|
||||
const offline = sendPages(restarted, []);
|
||||
expect(restarted.identity.findGroupMember(groupId, 22)?.card).toBeUndefined();
|
||||
expect(restarted.identity.findGroupMember(groupId, 55)?.card).toBe('');
|
||||
const cachedOutput = await getGroupMemberList(restarted, groupId);
|
||||
expect(cachedOutput).toHaveLength(output.length);
|
||||
expect(cachedOutput).toEqual(expect.arrayContaining(output));
|
||||
expect(offline.tokens).toEqual(['']);
|
||||
|
||||
sendPages(restarted, [
|
||||
{
|
||||
members: [
|
||||
{
|
||||
uin: { uin: 22, uid: 'u_22' },
|
||||
memberName: 'recovered',
|
||||
memberCard: { memberCard: Buffer.from('decoded card') },
|
||||
},
|
||||
],
|
||||
},
|
||||
]);
|
||||
expect(await getGroupMemberInfo(restarted, groupId, 22, true)).toMatchObject({
|
||||
nickname: 'recovered',
|
||||
card: 'decoded card',
|
||||
});
|
||||
await restarted.dispose();
|
||||
const recovered = await openBridge(dbPath);
|
||||
expect(recovered.identity.findGroupMember(groupId, 22)?.card).toBe('decoded card');
|
||||
},
|
||||
);
|
||||
|
||||
it('still rejects a forced refresh when a later page fails and keeps the previous roster', async () => {
|
||||
const bridge = new Bridge(IdentityService.memory('10001'));
|
||||
cleanups.push(() => bridge.dispose());
|
||||
bridge.identity.rememberGroups([group()]);
|
||||
bridge.identity.rememberGroupMembers(groupId, [member(11, 'existing')]);
|
||||
sendPages(bridge, [
|
||||
{
|
||||
token: 'missing-page',
|
||||
members: [
|
||||
{
|
||||
uin: { uin: 22 },
|
||||
memberCard: { memberCard: Buffer.from('616207', 'hex') },
|
||||
},
|
||||
],
|
||||
},
|
||||
]);
|
||||
await expect(getGroupMemberList(bridge, groupId, true)).rejects.toThrow(
|
||||
'roster unavailable',
|
||||
);
|
||||
expect(bridge.identity.findGroupMember(groupId, 11)?.card).toBe('existing');
|
||||
expect(bridge.identity.findGroupMember(groupId, 22)).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -137,7 +137,7 @@ describe('history direction plumbing', () => {
|
||||
it('uses C2C roaming for an unanchored latest page and ignores a stale local sequence', async () => {
|
||||
const fetchRangeHistory = vi.fn(async () => [friendMessage(99999, FRIEND_ID)]);
|
||||
const fetchLatestHistory = vi.fn(async () => [
|
||||
friendMessage(63213, FRIEND_ID, 32742),
|
||||
{ ...friendMessage(63213, FRIEND_ID, 32742), autoReply: true },
|
||||
friendMessage(63214, SELF_ID, 32743),
|
||||
]);
|
||||
await messageStore.storeMeta(-222222222, {
|
||||
@@ -169,6 +169,12 @@ describe('history direction plumbing', () => {
|
||||
|
||||
expect(fetchLatestHistory).toHaveBeenCalledWith('u_friend', 20, SELF_ID);
|
||||
expect(fetchRangeHistory).not.toHaveBeenCalled();
|
||||
expect(messages[0]).toMatchObject({ auto_reply: true, raw_message: '63213' });
|
||||
expect(messages[1]).not.toHaveProperty('auto_reply');
|
||||
expect(await messageStore.findEvent(Number(messages[0]!.message_id))).toMatchObject({
|
||||
auto_reply: true,
|
||||
raw_message: '63213',
|
||||
});
|
||||
expect(
|
||||
messages.map((message) => ({
|
||||
sender: message.user_id,
|
||||
|
||||
@@ -0,0 +1,735 @@
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import type { OidbBase } from '@snowluma/proto-defs/oidb';
|
||||
import type { EncodableMediaMsgInfo, NTV2UploadRichMediaResp } from '@snowluma/proto-defs/highway';
|
||||
import type { BridgeContext } from '@snowluma/protocol/bridge-context';
|
||||
import type { FriendMessage, GroupMessage, MessageElement } from '@snowluma/protocol/events';
|
||||
import { uploadImageMsgInfo } from '@snowluma/protocol/highway/image-upload';
|
||||
import { subscribeLogs, type LogEntry } from '@snowluma/common/logger';
|
||||
import { ApiHandler } from '../src/api-handler';
|
||||
import { elementsToOneBotSegments } from '../src/event-converter';
|
||||
import { buildApiContext, type OneBotInstanceContext } from '../src/instance-context';
|
||||
import { MediaIndexer } from '../src/media-indexer';
|
||||
import { MediaStore } from '../src/media-store';
|
||||
import { MessageStore } from '../src/message-store';
|
||||
import {
|
||||
backfillReplyTarget,
|
||||
sendGroupMessage,
|
||||
sendPrivateMessage,
|
||||
} from '../src/modules/message-actions';
|
||||
import { GROUP_MESSAGE_EVENT, privateMessageEventName } from '../src/message-id';
|
||||
import { createMessageIdResolver } from '../src/message-id-resolver';
|
||||
import { segmentsToRawMessage } from '../src/helper/cq';
|
||||
import type { JsonObject } from '../src/types';
|
||||
|
||||
const png =
|
||||
'base64://iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jFZkAAAAASUVORK5CYII=';
|
||||
const self = 10001;
|
||||
const peer = 20002;
|
||||
const time = 1700000000;
|
||||
const legacyId = -659;
|
||||
const md5 = 'aa'.repeat(16);
|
||||
const sha1 = 'bb'.repeat(20);
|
||||
const cleanups: Array<() => void | Promise<void>> = [];
|
||||
|
||||
afterEach(async () => {
|
||||
for (const cleanup of cleanups.splice(0).reverse()) {
|
||||
await cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
function fixture(isGroup: boolean) {
|
||||
const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'image-history-'));
|
||||
cleanups.push(() => fs.rmSync(directory, { recursive: true, force: true }));
|
||||
const dbPath = path.join(directory, 'messages.db');
|
||||
const url = `https://multimedia.nt.qq.com.cn/download?appid=${isGroup ? 1407 : 1406}&fileid=original-resource`;
|
||||
const remoteImage = {
|
||||
type: 'image',
|
||||
fileId: `${md5}.webp`,
|
||||
imageUrl: url,
|
||||
md5Hex: md5,
|
||||
sha1Hex: sha1,
|
||||
} satisfies MessageElement;
|
||||
const historyMessage: FriendMessage | GroupMessage = {
|
||||
selfUin: self,
|
||||
senderUin: self,
|
||||
senderNick: 'self',
|
||||
time,
|
||||
msgId: 456,
|
||||
elements: [remoteImage, { type: 'text', text: 'server representation' }],
|
||||
...(isGroup
|
||||
? {
|
||||
kind: 'group_message',
|
||||
groupId: peer,
|
||||
groupName: '',
|
||||
senderCard: '',
|
||||
senderRole: 'member',
|
||||
msgSeq: 42,
|
||||
}
|
||||
: {
|
||||
kind: 'friend_message',
|
||||
peerUin: peer,
|
||||
msgSeq: 123,
|
||||
clientSeq: 123,
|
||||
ntMsgSeq: 42,
|
||||
sequenceAuthoritative: true,
|
||||
}),
|
||||
};
|
||||
const getGroupMessageBySeq = vi.fn(async (): Promise<GroupMessage | null> =>
|
||||
isGroup ? (historyMessage as GroupMessage) : null,
|
||||
);
|
||||
const getC2cMessageBySeq = vi.fn(async (): Promise<FriendMessage | null> =>
|
||||
isGroup ? null : (historyMessage as FriendMessage),
|
||||
);
|
||||
const getC2cLatestHistory = vi.fn(async (): Promise<FriendMessage[]> =>
|
||||
isGroup ? [] : [historyMessage as FriendMessage],
|
||||
);
|
||||
const resolver = vi.fn(async (element: MessageElement) => `${element.imageUrl}&rkey=fresh`);
|
||||
const uploads: EncodableMediaMsgInfo[] = [];
|
||||
const protocolBridge = {
|
||||
identity: { uin: String(self) },
|
||||
sendRawPacket: vi.fn(async () => ({
|
||||
success: true,
|
||||
gotResponse: true,
|
||||
errorCode: 0,
|
||||
responseData: protobuf_encode<OidbBase<NTV2UploadRichMediaResp>>({
|
||||
body: {
|
||||
upload: {
|
||||
msgInfo: {
|
||||
msgInfoBody: [
|
||||
{
|
||||
index: { fileUuid: 'original-resource' },
|
||||
picture: {
|
||||
domain: 'multimedia.nt.qq.com.cn',
|
||||
urlPath: url.slice(
|
||||
'https://multimedia.nt.qq.com.cn'.length,
|
||||
),
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
})),
|
||||
} as unknown as BridgeContext;
|
||||
|
||||
const send = async (_target: number, elements: MessageElement[]) => {
|
||||
for (const element of elements) {
|
||||
if (element.type === 'image') {
|
||||
uploads.push(
|
||||
protobuf_decode<EncodableMediaMsgInfo>(
|
||||
await uploadImageMsgInfo(
|
||||
protocolBridge,
|
||||
isGroup,
|
||||
isGroup ? peer : 'u_peer',
|
||||
element,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return { sequence: 42, clientSequence: 123, random: 456, timestamp: time };
|
||||
};
|
||||
|
||||
async function open() {
|
||||
const messageStore = new MessageStore(dbPath);
|
||||
await messageStore.initialization;
|
||||
const mediaStore = new MediaStore(dbPath);
|
||||
await mediaStore.initialization;
|
||||
const indexer = new MediaIndexer(mediaStore);
|
||||
|
||||
const close = async () => {
|
||||
await mediaStore.close();
|
||||
await messageStore.close();
|
||||
};
|
||||
|
||||
cleanups.push(close);
|
||||
const ref = {
|
||||
selfId: self,
|
||||
uin: String(self),
|
||||
messageStore,
|
||||
mediaStore,
|
||||
bridge: {
|
||||
identity: { nickname: 'self' },
|
||||
resolveUserUid: vi.fn(async () => 'u_peer'),
|
||||
apis: {
|
||||
message: {
|
||||
sendPrivate: send,
|
||||
sendGroup: send,
|
||||
getGroupMessageBySeq,
|
||||
getC2cMessageBySeq,
|
||||
getC2cLatestHistory,
|
||||
},
|
||||
},
|
||||
},
|
||||
converterCtx: {
|
||||
selfId: self,
|
||||
imageUrlResolver: resolver,
|
||||
mediaUrlResolver: null,
|
||||
messageIdResolver: createMessageIdResolver(messageStore),
|
||||
mediaSegmentSink: (...args: Parameters<MediaIndexer['remember']>) =>
|
||||
indexer.remember(...args),
|
||||
},
|
||||
cacheMessageMeta: messageStore.storeMeta.bind(messageStore),
|
||||
} as unknown as OneBotInstanceContext;
|
||||
return {
|
||||
ref,
|
||||
handler: new ApiHandler(buildApiContext(ref)),
|
||||
close: async () => {
|
||||
cleanups.splice(cleanups.indexOf(close), 1);
|
||||
await close();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
open,
|
||||
resolver,
|
||||
url,
|
||||
uploads,
|
||||
historyMessage,
|
||||
getGroupMessageBySeq,
|
||||
getC2cMessageBySeq,
|
||||
getC2cLatestHistory,
|
||||
};
|
||||
}
|
||||
|
||||
async function saveIncomplete(
|
||||
ref: OneBotInstanceContext,
|
||||
isGroup: boolean,
|
||||
authoritative = true,
|
||||
snapshot = true,
|
||||
elements?: MessageElement[],
|
||||
) {
|
||||
const eventName = isGroup ? GROUP_MESSAGE_EVENT : privateMessageEventName(true, authoritative);
|
||||
await ref.messageStore.storeMeta(legacyId, {
|
||||
isGroup,
|
||||
targetId: peer,
|
||||
sequence: authoritative ? 42 : 123,
|
||||
sequenceAuthoritative: authoritative,
|
||||
eventName,
|
||||
clientSequence: 123,
|
||||
...(isGroup ? {} : { privateDirection: 'outgoing' as const }),
|
||||
random: 456,
|
||||
timestamp: time,
|
||||
});
|
||||
const message = await elementsToOneBotSegments(
|
||||
{ ...ref.converterCtx, imageUrlResolver: null },
|
||||
elements ?? [
|
||||
{
|
||||
type: 'image',
|
||||
url: png,
|
||||
fileName: `${md5}.webp`,
|
||||
md5Hex: md5,
|
||||
sha1Hex: sha1,
|
||||
picFormat: 1002,
|
||||
},
|
||||
{ type: 'text', text: 'original caption' },
|
||||
],
|
||||
isGroup,
|
||||
peer,
|
||||
);
|
||||
const event: JsonObject = {
|
||||
message_id: legacyId,
|
||||
self_id: self,
|
||||
post_type: 'message_sent',
|
||||
message_type: isGroup ? 'group' : 'private',
|
||||
sub_type: isGroup ? 'normal' : 'friend',
|
||||
user_id: self,
|
||||
target_id: peer,
|
||||
...(isGroup ? { group_id: peer } : {}),
|
||||
time,
|
||||
message_seq: isGroup ? 42 : 123,
|
||||
message: snapshot ? message : structuredClone(message),
|
||||
raw_message: segmentsToRawMessage(message),
|
||||
};
|
||||
await ref.messageStore.storeEvent(
|
||||
legacyId,
|
||||
isGroup,
|
||||
peer,
|
||||
authoritative ? 42 : 123,
|
||||
eventName,
|
||||
event,
|
||||
{ sequenceAuthoritative: authoritative },
|
||||
);
|
||||
return ref.messageStore.findEvent(legacyId);
|
||||
}
|
||||
|
||||
describe('image history (#659)', () => {
|
||||
it('accepts an omitted outgoing peer only within the explicitly requested history conversation', async () => {
|
||||
const f = fixture(false);
|
||||
const { ref, handler } = await f.open();
|
||||
await saveIncomplete(ref, false);
|
||||
delete (f.historyMessage as FriendMessage).peerUin;
|
||||
expect(await handler.handle('get_msg', { message_id: legacyId })).toMatchObject({
|
||||
status: 'ok',
|
||||
data: { message: [{ data: { url: `${f.url}&rkey=fresh` } }, {}] },
|
||||
});
|
||||
expect(f.getC2cMessageBySeq).toHaveBeenCalledExactlyOnceWith('u_peer', 42, self);
|
||||
});
|
||||
|
||||
it('uses the explicit recipient on older self-keyed private records without rewriting their identity', async () => {
|
||||
const f = fixture(false);
|
||||
const { ref, handler } = await f.open();
|
||||
await saveIncomplete(ref, false);
|
||||
const meta = { ...(await ref.messageStore.findMeta(legacyId))!, targetId: self };
|
||||
await ref.messageStore.storeMeta(legacyId, meta);
|
||||
expect(await handler.handle('get_msg', { message_id: legacyId })).toMatchObject({
|
||||
status: 'ok',
|
||||
data: { message_id: legacyId, message: [{ data: { url: `${f.url}&rkey=fresh` } }, {}] },
|
||||
});
|
||||
expect(ref.bridge.resolveUserUid).toHaveBeenCalledExactlyOnceWith(peer);
|
||||
expect(await ref.messageStore.findMeta(legacyId)).toEqual(meta);
|
||||
});
|
||||
|
||||
it.each([false, true])(
|
||||
'never restores a private message recalled while its history request is in flight (failed=%s)',
|
||||
async (failed) => {
|
||||
const f = fixture(false);
|
||||
const { ref, handler } = await f.open();
|
||||
await saveIncomplete(ref, false);
|
||||
f.getC2cMessageBySeq.mockImplementationOnce(async () => {
|
||||
expect(await ref.messageStore.recordPrivateRecall(peer, 123, true, time + 1)).toBe(
|
||||
legacyId,
|
||||
);
|
||||
|
||||
if (failed) {
|
||||
throw new Error('history request failed after recall');
|
||||
}
|
||||
|
||||
return f.historyMessage as FriendMessage;
|
||||
});
|
||||
expect(await handler.handle('get_msg', { message_id: legacyId })).toMatchObject({
|
||||
status: 'failed',
|
||||
});
|
||||
expect(await ref.messageStore.findEvent(legacyId)).toBeNull();
|
||||
expect(await ref.messageStore.findMeta(legacyId)).toBeNull();
|
||||
},
|
||||
);
|
||||
|
||||
it('keeps a newer stored body when history completes after an update', async () => {
|
||||
const f = fixture(false);
|
||||
const { ref, handler } = await f.open();
|
||||
await saveIncomplete(ref, false);
|
||||
f.getC2cMessageBySeq.mockImplementationOnce(async () => {
|
||||
await saveIncomplete(ref, false, true, true, [
|
||||
{
|
||||
type: 'image',
|
||||
imageUrl: 'https://new.example/image',
|
||||
md5Hex: md5,
|
||||
sha1Hex: sha1,
|
||||
},
|
||||
{ type: 'text', text: 'newer caption' },
|
||||
]);
|
||||
return f.historyMessage as FriendMessage;
|
||||
});
|
||||
expect(await handler.handle('get_msg', { message_id: legacyId })).toMatchObject({
|
||||
status: 'ok',
|
||||
data: {
|
||||
message_id: legacyId,
|
||||
message: [
|
||||
{ data: { url: 'https://new.example/image&rkey=fresh' } },
|
||||
{ data: { text: 'newer caption' } },
|
||||
],
|
||||
},
|
||||
});
|
||||
expect((await ref.messageStore.findMedia(legacyId))![0]!.imageUrl).toBe(
|
||||
'https://new.example/image',
|
||||
);
|
||||
});
|
||||
|
||||
it('refuses an ambiguous sender-local sequence instead of choosing the first history item', async () => {
|
||||
const f = fixture(false);
|
||||
const { ref, handler } = await f.open();
|
||||
const before = await saveIncomplete(ref, false, false);
|
||||
f.getC2cLatestHistory.mockResolvedValue([
|
||||
f.historyMessage as FriendMessage,
|
||||
{ ...(f.historyMessage as FriendMessage), ntMsgSeq: 43 },
|
||||
]);
|
||||
expect(await handler.handle('get_msg', { message_id: legacyId })).toMatchObject({
|
||||
status: 'ok',
|
||||
data: { message: [{ data: { url: '' } }, {}] },
|
||||
});
|
||||
expect(await ref.messageStore.findEvent(legacyId)).toEqual(before);
|
||||
});
|
||||
|
||||
it.each([false, true])(
|
||||
'repairs only the missing image in a mixed message and preserves ordered metadata (group=%s)',
|
||||
async (isGroup) => {
|
||||
const f = fixture(isGroup);
|
||||
const { ref, handler } = await f.open();
|
||||
const first: MessageElement = { type: 'image', md5Hex: md5, sha1Hex: sha1, url: png };
|
||||
const second: MessageElement = {
|
||||
type: 'image',
|
||||
md5Hex: 'cc'.repeat(16),
|
||||
sha1Hex: 'dd'.repeat(20),
|
||||
imageUrl: 'https://existing.example/second',
|
||||
fileName: 'second.webp',
|
||||
};
|
||||
await saveIncomplete(ref, isGroup, true, true, [
|
||||
first,
|
||||
{ type: 'text', text: 'between images' },
|
||||
second,
|
||||
]);
|
||||
const before = await ref.messageStore.findMedia(legacyId);
|
||||
f.historyMessage.elements = [
|
||||
{ ...first, imageUrl: f.url },
|
||||
{ ...second, imageUrl: 'https://history.example/second' },
|
||||
];
|
||||
expect(await handler.handle('get_msg', { message_id: legacyId })).toMatchObject({
|
||||
status: 'ok',
|
||||
data: {
|
||||
message_id: legacyId,
|
||||
message: [
|
||||
{ data: { url: `${f.url}&rkey=fresh` } },
|
||||
{ data: { text: 'between images' } },
|
||||
{ data: { url: 'https://existing.example/second&rkey=fresh' } },
|
||||
],
|
||||
},
|
||||
});
|
||||
expect((await ref.messageStore.findMedia(legacyId))![1]).toEqual(before![1]);
|
||||
},
|
||||
);
|
||||
|
||||
it('rejects reordered images atomically without saving a partial repair', async () => {
|
||||
const f = fixture(true);
|
||||
const { ref, handler } = await f.open();
|
||||
const first: MessageElement = { type: 'image', md5Hex: md5, sha1Hex: sha1, url: png };
|
||||
const second: MessageElement = {
|
||||
type: 'image',
|
||||
md5Hex: 'cc'.repeat(16),
|
||||
sha1Hex: 'dd'.repeat(20),
|
||||
url: png,
|
||||
};
|
||||
const before = await saveIncomplete(ref, true, true, true, [first, second]);
|
||||
f.historyMessage.elements = [
|
||||
{ ...second, imageUrl: f.url },
|
||||
{ ...first, imageUrl: f.url },
|
||||
];
|
||||
expect(await handler.handle('get_msg', { message_id: legacyId })).toMatchObject({
|
||||
status: 'ok',
|
||||
data: { message: [{ data: { url: '' } }, { data: { url: '' } }] },
|
||||
});
|
||||
expect(await ref.messageStore.findEvent(legacyId)).toEqual(before);
|
||||
});
|
||||
|
||||
it('repairs a legacy image without inventing snapshots for other media', async () => {
|
||||
const f = fixture(true);
|
||||
const { ref, handler } = await f.open();
|
||||
await saveIncomplete(ref, true, true, false, [
|
||||
{ type: 'image', url: png, md5Hex: md5, sha1Hex: sha1 },
|
||||
{ type: 'record', fileName: 'voice.amr', url: 'https://original.example/voice' },
|
||||
]);
|
||||
expect(await handler.handle('get_msg', { message_id: legacyId })).toMatchObject({
|
||||
status: 'ok',
|
||||
data: {
|
||||
message: [
|
||||
{ type: 'image', data: { url: `${f.url}&rkey=fresh` } },
|
||||
{ type: 'record', data: { url: 'https://original.example/voice' } },
|
||||
],
|
||||
},
|
||||
});
|
||||
expect(await ref.messageStore.findMedia(legacyId)).toBeNull();
|
||||
expect(await ref.messageStore.findEvent(legacyId)).toMatchObject({
|
||||
message: [{ data: { url: f.url } }, {}],
|
||||
});
|
||||
});
|
||||
|
||||
it('does not repair a message with an unverified group identity', async () => {
|
||||
const f = fixture(true);
|
||||
const { ref, handler } = await f.open();
|
||||
const before = await saveIncomplete(ref, true);
|
||||
(f.historyMessage as GroupMessage).groupId = 30003;
|
||||
expect(await handler.handle('get_msg', { message_id: legacyId })).toMatchObject({
|
||||
status: 'ok',
|
||||
data: { message: [{ data: { url: '' } }, {}] },
|
||||
});
|
||||
expect(await ref.messageStore.findEvent(legacyId)).toEqual(before);
|
||||
});
|
||||
|
||||
it.each(['conversation', 'fingerprint'] as const)(
|
||||
'does not use a conflicting legacy filename alias (%s)',
|
||||
async (conflict) => {
|
||||
const f = fixture(false);
|
||||
const { ref, handler } = await f.open();
|
||||
const before = await saveIncomplete(ref, false, true, false);
|
||||
f.getC2cMessageBySeq.mockResolvedValue(null);
|
||||
await ref.mediaStore.rememberImage({
|
||||
file: `${md5}.png`,
|
||||
fileName: `${md5}.png`,
|
||||
fileSize: 1,
|
||||
imageUrl: 'https://wrong.example/image',
|
||||
url: '',
|
||||
isGroup: conflict === 'conversation',
|
||||
sessionId: conflict === 'conversation' ? 30003 : peer,
|
||||
md5Hex: 'cc'.repeat(16),
|
||||
subType: 0,
|
||||
summary: '',
|
||||
});
|
||||
expect(await handler.handle('get_msg', { message_id: legacyId })).toMatchObject({
|
||||
status: 'ok',
|
||||
data: { message: [{ data: { url: '' } }, {}] },
|
||||
});
|
||||
expect(f.resolver).not.toHaveBeenCalled();
|
||||
expect(await ref.messageStore.findEvent(legacyId)).toEqual(before);
|
||||
},
|
||||
);
|
||||
|
||||
it('repairs incoming private media under its existing message identity', async () => {
|
||||
const f = fixture(false);
|
||||
const { ref, handler } = await f.open();
|
||||
await saveIncomplete(ref, false);
|
||||
const source = f.historyMessage as FriendMessage;
|
||||
source.senderUin = peer;
|
||||
delete source.peerUin;
|
||||
const meta = (await ref.messageStore.findMeta(legacyId))!;
|
||||
await ref.messageStore.storeMeta(legacyId, { ...meta, privateDirection: 'incoming' });
|
||||
const message = await elementsToOneBotSegments(
|
||||
{ ...ref.converterCtx, imageUrlResolver: null },
|
||||
[{ type: 'image', md5Hex: md5, sha1Hex: sha1 }],
|
||||
false,
|
||||
peer,
|
||||
);
|
||||
const event = {
|
||||
...(await ref.messageStore.findEvent(legacyId))!,
|
||||
user_id: peer,
|
||||
post_type: 'message',
|
||||
message,
|
||||
raw_message: segmentsToRawMessage(message),
|
||||
};
|
||||
await ref.messageStore.storeEvent(legacyId, false, peer, 42, meta.eventName, event);
|
||||
source.elements = [source.elements[0]!];
|
||||
expect(await handler.handle('get_msg', { message_id: legacyId })).toMatchObject({
|
||||
status: 'ok',
|
||||
data: {
|
||||
message_id: legacyId,
|
||||
user_id: peer,
|
||||
message: [{ data: { url: `${f.url}&rkey=fresh` } }],
|
||||
},
|
||||
});
|
||||
expect((await ref.messageStore.findMeta(legacyId))!.privateDirection).toBe('incoming');
|
||||
});
|
||||
|
||||
it('reports an unverifiable image instead of guessing a resource from an arbitrary filename', async () => {
|
||||
const f = fixture(true);
|
||||
const { ref, handler } = await f.open();
|
||||
const before = await saveIncomplete(ref, true, true, false, [
|
||||
{ type: 'image', fileId: 'photo.webp' },
|
||||
]);
|
||||
expect(await handler.handle('get_msg', { message_id: legacyId })).toMatchObject({
|
||||
status: 'ok',
|
||||
data: { message: [{ data: { file: 'photo.webp', url: '' } }] },
|
||||
});
|
||||
expect(await ref.messageStore.findEvent(legacyId)).toEqual(before);
|
||||
});
|
||||
|
||||
it.each([false, true])(
|
||||
'retains a newly uploaded resource through send, cache churn and restart (group=%s)',
|
||||
async (isGroup) => {
|
||||
const f = fixture(isGroup);
|
||||
let account = await f.open();
|
||||
const sent = await (isGroup ? sendGroupMessage : sendPrivateMessage)(
|
||||
account.ref,
|
||||
peer,
|
||||
[{ type: 'image', data: { file: png } }],
|
||||
false,
|
||||
);
|
||||
expect(f.uploads[0]?.msgInfoBody?.[0]?.index?.fileUuid).toBe('original-resource');
|
||||
const media = (await account.ref.messageStore.findMedia(sent.messageId))![0]!;
|
||||
expect(media.imageUrl).toBe(f.url);
|
||||
const saved = await account.ref.messageStore.findEvent(sent.messageId);
|
||||
expect(saved).toMatchObject({
|
||||
message: [{ type: 'image', data: { file: media.fileName, url: f.url } }],
|
||||
});
|
||||
expect(JSON.stringify(media)).not.toContain('base64://');
|
||||
expect(JSON.stringify(saved)).not.toContain('base64://');
|
||||
expect(f.resolver).not.toHaveBeenCalled();
|
||||
await account.close();
|
||||
account = await f.open();
|
||||
// Reused filenames and newer resources cannot replace a message's own reference.
|
||||
await account.ref.mediaStore.rememberImage({
|
||||
file: media.fileName!,
|
||||
fileName: media.fileName!,
|
||||
fileSize: 1,
|
||||
imageUrl: 'https://wrong.example/image',
|
||||
url: '',
|
||||
isGroup: !isGroup,
|
||||
sessionId: 30003,
|
||||
subType: 0,
|
||||
summary: '',
|
||||
});
|
||||
expect(
|
||||
await account.handler.handle('get_msg', { message_id: sent.messageId }),
|
||||
).toMatchObject({
|
||||
status: 'ok',
|
||||
data: {
|
||||
message_id: sent.messageId,
|
||||
real_id: sent.messageId,
|
||||
message: [{ type: 'image', data: { url: `${f.url}&rkey=fresh` } }],
|
||||
},
|
||||
});
|
||||
expect(f.resolver).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ imageUrl: f.url }),
|
||||
isGroup,
|
||||
);
|
||||
expect(f.getC2cMessageBySeq).not.toHaveBeenCalled();
|
||||
expect(f.getC2cLatestHistory).not.toHaveBeenCalled();
|
||||
expect(f.getGroupMessageBySeq).not.toHaveBeenCalled();
|
||||
},
|
||||
);
|
||||
|
||||
it.each([
|
||||
{ isGroup: false, authoritative: true, snapshot: true },
|
||||
{ isGroup: true, authoritative: true, snapshot: true },
|
||||
{ isGroup: false, authoritative: false, snapshot: true },
|
||||
{ isGroup: false, authoritative: true, snapshot: false },
|
||||
{ isGroup: true, authoritative: true, snapshot: false },
|
||||
])(
|
||||
'repairs an incomplete stored image without replacing its identity ($isGroup/$authoritative/$snapshot)',
|
||||
async ({ isGroup, authoritative, snapshot }) => {
|
||||
const f = fixture(isGroup);
|
||||
let account = await f.open();
|
||||
await saveIncomplete(account.ref, isGroup, authoritative, snapshot);
|
||||
const meta = await account.ref.messageStore.findMeta(legacyId);
|
||||
await account.close();
|
||||
account = await f.open();
|
||||
|
||||
if (!isGroup) {
|
||||
const quoted = await backfillReplyTarget(account.ref, {
|
||||
kind: 'friend_message',
|
||||
selfUin: self,
|
||||
senderUin: peer,
|
||||
peerUin: peer,
|
||||
senderNick: 'peer',
|
||||
time: time + 2,
|
||||
msgSeq: 900,
|
||||
clientSeq: 900,
|
||||
ntMsgSeq: 9900,
|
||||
msgId: 55,
|
||||
elements: [
|
||||
{ type: 'reply', replySeq: 777, replySenderUin: self, replyTime: time },
|
||||
],
|
||||
});
|
||||
expect(quoted.elements[0]).toMatchObject({ replyMessageId: legacyId });
|
||||
}
|
||||
|
||||
const expected = {
|
||||
status: 'ok',
|
||||
data: {
|
||||
message_id: legacyId,
|
||||
real_id: legacyId,
|
||||
message: [
|
||||
{ type: 'image', data: { file: `${md5}.png`, url: `${f.url}&rkey=fresh` } },
|
||||
{ type: 'text', data: { text: 'original caption' } },
|
||||
],
|
||||
},
|
||||
};
|
||||
expect(await account.handler.handle('get_msg', { message_id: legacyId })).toMatchObject(
|
||||
expected,
|
||||
);
|
||||
expect(await account.ref.messageStore.findMeta(legacyId)).toEqual(meta);
|
||||
expect(await account.ref.messageStore.findEvent(legacyId)).toMatchObject({
|
||||
message_id: legacyId,
|
||||
message: [{ data: { url: f.url } }, { data: { text: 'original caption' } }],
|
||||
});
|
||||
expect((await account.ref.messageStore.findMedia(legacyId))![0]).toMatchObject({
|
||||
imageUrl: f.url,
|
||||
md5Hex: md5,
|
||||
});
|
||||
|
||||
if (isGroup) {
|
||||
expect(f.getGroupMessageBySeq).toHaveBeenCalledExactlyOnceWith(peer, 42, self);
|
||||
} else if (authoritative) {
|
||||
expect(f.getC2cMessageBySeq).toHaveBeenCalledExactlyOnceWith('u_peer', 42, self);
|
||||
} else {
|
||||
expect(f.getC2cLatestHistory).toHaveBeenCalledExactlyOnceWith(
|
||||
'u_peer',
|
||||
20,
|
||||
self,
|
||||
time + 1,
|
||||
);
|
||||
}
|
||||
|
||||
await account.close();
|
||||
account = await f.open();
|
||||
f.getGroupMessageBySeq.mockClear();
|
||||
f.getC2cMessageBySeq.mockClear();
|
||||
f.getC2cLatestHistory.mockClear();
|
||||
expect(await account.handler.handle('get_msg', { message_id: legacyId })).toMatchObject(
|
||||
expected,
|
||||
);
|
||||
expect(f.getGroupMessageBySeq).not.toHaveBeenCalled();
|
||||
expect(f.getC2cMessageBySeq).not.toHaveBeenCalled();
|
||||
expect(f.getC2cLatestHistory).not.toHaveBeenCalled();
|
||||
},
|
||||
);
|
||||
|
||||
it.each(['sender', 'peer', 'sequence', 'time', 'fingerprint', 'missing', 'request'] as const)(
|
||||
'keeps the original record and reports an unverified repair: %s',
|
||||
async (mismatch) => {
|
||||
const f = fixture(false);
|
||||
const { ref, handler } = await f.open();
|
||||
const original = await saveIncomplete(ref, false);
|
||||
const media = await ref.messageStore.findMedia(legacyId);
|
||||
const source = f.historyMessage as FriendMessage;
|
||||
|
||||
if (mismatch === 'sender') {
|
||||
source.senderUin = peer;
|
||||
}
|
||||
|
||||
if (mismatch === 'peer') {
|
||||
source.peerUin = 30003;
|
||||
}
|
||||
|
||||
if (mismatch === 'sequence') {
|
||||
source.ntMsgSeq = 43;
|
||||
}
|
||||
|
||||
if (mismatch === 'time') {
|
||||
source.time += 60;
|
||||
}
|
||||
|
||||
if (mismatch === 'fingerprint') {
|
||||
source.elements[0]!.md5Hex = 'cc'.repeat(16);
|
||||
}
|
||||
|
||||
if (mismatch === 'missing') {
|
||||
f.getC2cMessageBySeq.mockResolvedValue(null);
|
||||
}
|
||||
|
||||
if (mismatch === 'request') {
|
||||
f.getC2cMessageBySeq.mockRejectedValue(new Error('history unavailable'));
|
||||
}
|
||||
|
||||
const logs: LogEntry[] = [];
|
||||
const unsubscribe = subscribeLogs((entry) => logs.push(entry));
|
||||
|
||||
try {
|
||||
expect(await handler.handle('get_msg', { message_id: legacyId })).toMatchObject({
|
||||
status: 'ok',
|
||||
data: {
|
||||
message_id: legacyId,
|
||||
message: [{ data: { url: '' } }, { data: { text: 'original caption' } }],
|
||||
},
|
||||
});
|
||||
expect(
|
||||
logs.some(
|
||||
(entry) =>
|
||||
entry.level === 'warn' &&
|
||||
entry.message.includes('image history repair'),
|
||||
),
|
||||
).toBe(true);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
|
||||
expect(await ref.messageStore.findEvent(legacyId)).toEqual(original);
|
||||
expect(await ref.messageStore.findMedia(legacyId)).toEqual(media);
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -1013,8 +1013,15 @@ describe('buildApiContext contact reads', () => {
|
||||
request_id: 888,
|
||||
requester_uin: 20002,
|
||||
requester_nick: 'applicant',
|
||||
target_uin: 20002,
|
||||
target_nick: 'applicant',
|
||||
target_status: 'known',
|
||||
invitor_uin: 30003,
|
||||
invitor_nick: 'inviter',
|
||||
invitor_status: 'known',
|
||||
operator_uin: 40004,
|
||||
operator_nick: 'operator',
|
||||
operator_status: 'known',
|
||||
message: 'please add',
|
||||
checked: false,
|
||||
flag: 'slreq:1:888:710010:22:0',
|
||||
@@ -1134,6 +1141,8 @@ describe('buildApiContext media', () => {
|
||||
duration: 2,
|
||||
size: 16,
|
||||
format: 1,
|
||||
isNtv2: false,
|
||||
storeRegion: 0,
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -428,6 +428,8 @@ describe('fetchPttText', () => {
|
||||
duration: 7,
|
||||
size: 4096,
|
||||
format: 1,
|
||||
isNtv2: false,
|
||||
storeRegion: 0,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -461,6 +463,8 @@ describe('fetchPttText', () => {
|
||||
duration: 7,
|
||||
size: 4096,
|
||||
format: 1,
|
||||
isNtv2: false,
|
||||
storeRegion: 0,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -494,6 +498,8 @@ describe('fetchPttText', () => {
|
||||
duration: 7,
|
||||
size: 4096,
|
||||
format: 1,
|
||||
isNtv2: false,
|
||||
storeRegion: 0,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -526,6 +532,8 @@ describe('fetchPttText', () => {
|
||||
duration: 7,
|
||||
size: 4096,
|
||||
format: 1,
|
||||
isNtv2: false,
|
||||
storeRegion: 0,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -564,6 +572,8 @@ describe('fetchPttText', () => {
|
||||
duration: 0,
|
||||
size: 0,
|
||||
format: 0,
|
||||
isNtv2: false,
|
||||
storeRegion: 0,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -591,6 +601,8 @@ describe('fetchPttText', () => {
|
||||
duration: 7,
|
||||
size: 4096,
|
||||
format: 1,
|
||||
isNtv2: false,
|
||||
storeRegion: 0,
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,292 @@
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import type { pb, uint_32 } from '@snowluma/proton';
|
||||
import type { MsgInfo } from '@snowluma/proto-defs/element';
|
||||
import type { MessageBody } from '@snowluma/proto-defs/message';
|
||||
import type { PttTransReq, PttTransResp } from '@snowluma/proto-defs/ptt-trans';
|
||||
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
|
||||
import { ExtrasApi } from '../../core/src/bridge/apis/extras';
|
||||
import { decodeRichBody } from '@snowluma/protocol/msg-push/rich-body-decoder';
|
||||
import { elementsToOneBotSegments, type ConverterContext } from '../src/event-converter';
|
||||
import { MediaIndexer } from '../src/media-indexer';
|
||||
import { MediaStore } from '../src/media-store';
|
||||
import { migrateLegacyMedia } from '../src/media-store-migration';
|
||||
import { MessageStore } from '../src/message-store';
|
||||
import { fetchPttText } from '../src/modules/media-actions';
|
||||
|
||||
// Decode the routing fields independently of the production request schema.
|
||||
interface TranscriptionRouting {
|
||||
isNtv2?: pb<5, uint_32>;
|
||||
storeRegion?: pb<6, uint_32>;
|
||||
}
|
||||
|
||||
const selfId = 10001;
|
||||
const peerId = 20002;
|
||||
const groupId = 30003;
|
||||
const messageId = -607;
|
||||
const md5 = '00112233445566778899aabbccddeeff';
|
||||
const cleanups: Array<() => void | Promise<void>> = [];
|
||||
|
||||
afterEach(async () => {
|
||||
for (const cleanup of cleanups.splice(0).reverse()) {
|
||||
await cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
function location() {
|
||||
const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'ptt-transcription-'));
|
||||
cleanups.push(() => fs.rmSync(directory, { recursive: true, force: true }));
|
||||
return {
|
||||
dbPath: path.join(directory, 'messages.db'),
|
||||
legacyPath: path.join(directory, 'media.db'),
|
||||
};
|
||||
}
|
||||
|
||||
async function openStores(dbPath: string) {
|
||||
const messages = new MessageStore(dbPath);
|
||||
await messages.initialization;
|
||||
const media = new MediaStore(dbPath, 1);
|
||||
let closed = false;
|
||||
|
||||
const close = async () => {
|
||||
if (closed) {
|
||||
return;
|
||||
}
|
||||
|
||||
closed = true;
|
||||
await media.close();
|
||||
await messages.close();
|
||||
};
|
||||
|
||||
cleanups.push(close);
|
||||
await media.initialization;
|
||||
const indexer = new MediaIndexer(media);
|
||||
const converter: ConverterContext = {
|
||||
selfId,
|
||||
imageUrlResolver: null,
|
||||
mediaUrlResolver: null,
|
||||
messageIdResolver: null,
|
||||
mediaSegmentSink: (...args) => indexer.remember(...args),
|
||||
};
|
||||
return { messages, media, converter, close };
|
||||
}
|
||||
|
||||
function voice(isGroup: boolean, ntv2: boolean, storeId?: number) {
|
||||
const body: MessageBody = {
|
||||
richText: ntv2
|
||||
? {
|
||||
elems: [
|
||||
{
|
||||
commonElem: {
|
||||
serviceType: 48,
|
||||
businessType: isGroup ? 12 : 22,
|
||||
pbElem: protobuf_encode<MsgInfo>({
|
||||
msgInfoBody: [
|
||||
{
|
||||
index: {
|
||||
fileUuid: 'voice-resource',
|
||||
storeId,
|
||||
info: {
|
||||
fileName: 'voice.silk',
|
||||
fileSize: 4003,
|
||||
fileHash: md5,
|
||||
time: 2,
|
||||
type: { type: 3, voiceFormat: 1 },
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
}),
|
||||
},
|
||||
},
|
||||
],
|
||||
}
|
||||
: {
|
||||
ptt: {
|
||||
fileName: 'voice.silk',
|
||||
fileUuid: Buffer.from('voice-resource'),
|
||||
fileMd5: Buffer.from(md5, 'hex'),
|
||||
fileSize: 4003,
|
||||
time: 2,
|
||||
format: 1,
|
||||
},
|
||||
},
|
||||
};
|
||||
const elements = decodeRichBody(
|
||||
protobuf_decode<MessageBody>(protobuf_encode<MessageBody>(body)),
|
||||
isGroup,
|
||||
);
|
||||
expect(elements).toHaveLength(1);
|
||||
return elements;
|
||||
}
|
||||
|
||||
async function saveVoice(
|
||||
stores: Awaited<ReturnType<typeof openStores>>,
|
||||
isGroup: boolean,
|
||||
elements: ReturnType<typeof voice>,
|
||||
withSnapshot = true,
|
||||
) {
|
||||
const segments = await elementsToOneBotSegments(
|
||||
stores.converter,
|
||||
elements,
|
||||
isGroup,
|
||||
isGroup ? groupId : peerId,
|
||||
);
|
||||
await stores.messages.storeEvent(
|
||||
messageId,
|
||||
isGroup,
|
||||
isGroup ? groupId : peerId,
|
||||
42,
|
||||
isGroup ? 'GroupMessage' : 'PrivateMessage',
|
||||
{
|
||||
message_id: messageId,
|
||||
message_type: isGroup ? 'group' : 'private',
|
||||
user_id: peerId,
|
||||
...(isGroup ? { group_id: groupId } : {}),
|
||||
message: withSnapshot ? segments : JSON.parse(JSON.stringify(segments)),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
function transport(isGroup: boolean, errCode = 0) {
|
||||
const sendRawPacket = vi.fn(async (_cmd: string, _bytes: Uint8Array) => ({
|
||||
success: true,
|
||||
gotResponse: true,
|
||||
errorCode: 0,
|
||||
errorMessage: '',
|
||||
responseData: protobuf_encode<PttTransResp>(
|
||||
isGroup
|
||||
? { type: 1, groupResult: { errCode, text: errCode ? '' : '测试转写结果' } }
|
||||
: { type: 2, c2cResult: { errCode, text: errCode ? '' : '测试转写结果' } },
|
||||
),
|
||||
}));
|
||||
const extras = new ExtrasApi({ sendRawPacket } as unknown as ConstructorParameters<
|
||||
typeof ExtrasApi
|
||||
>[0]);
|
||||
const bridge = { apis: { extras } } as unknown as BridgeInterface;
|
||||
return { sendRawPacket, bridge };
|
||||
}
|
||||
|
||||
async function checkRequest(
|
||||
stores: Awaited<ReturnType<typeof openStores>>,
|
||||
isGroup: boolean,
|
||||
ntv2: boolean,
|
||||
storeRegion = 0,
|
||||
) {
|
||||
const { sendRawPacket, bridge } = transport(isGroup);
|
||||
await expect(
|
||||
fetchPttText(stores.messages, stores.media, bridge, selfId, messageId),
|
||||
).resolves.toEqual({ text: '测试转写结果' });
|
||||
expect(sendRawPacket).toHaveBeenCalledTimes(1);
|
||||
const [cmd, bytes] = sendRawPacket.mock.calls[0]!;
|
||||
expect(cmd).toBe(isGroup ? 'pttTrans.TransGroupPttReq' : 'pttTrans.TransC2CPttReq');
|
||||
const routing = protobuf_decode<TranscriptionRouting>(bytes);
|
||||
expect(routing.isNtv2 ?? 0).toBe(ntv2 ? 1 : 0);
|
||||
expect(routing.storeRegion ?? 0).toBe(storeRegion);
|
||||
const request = protobuf_decode<PttTransReq>(bytes);
|
||||
expect(isGroup ? request.groupItem : request.c2cItem).toMatchObject({
|
||||
msgId: BigInt.asUintN(64, BigInt(messageId)),
|
||||
senderUin: BigInt(peerId),
|
||||
uuid: 'voice-resource',
|
||||
md5,
|
||||
duration: 2,
|
||||
size: 4003,
|
||||
format: 1,
|
||||
...(isGroup ? { groupUin: BigInt(groupId) } : { receiverUin: BigInt(selfId) }),
|
||||
});
|
||||
}
|
||||
|
||||
describe.each([false, true])('voice transcription (isGroup=%s)', (isGroup) => {
|
||||
it.each([
|
||||
{ name: 'NT voice', ntv2: true, storeId: 1 },
|
||||
{ name: 'NT voice in region zero', ntv2: true, storeId: 0 },
|
||||
{ name: 'NT voice without a region', ntv2: true, storeId: undefined },
|
||||
{ name: 'legacy voice', ntv2: false, storeId: undefined },
|
||||
])('preserves $name routing through storage and reopening', async ({ ntv2, storeId }) => {
|
||||
const { dbPath } = location();
|
||||
let stores = await openStores(dbPath);
|
||||
await saveVoice(stores, isGroup, voice(isGroup, ntv2, storeId));
|
||||
await checkRequest(stores, isGroup, ntv2, storeId);
|
||||
await stores.close();
|
||||
stores = await openStores(dbPath);
|
||||
await checkRequest(stores, isGroup, ntv2, storeId);
|
||||
expect((await stores.messages.findMedia(messageId))?.[0]).toMatchObject({ isNtv2: ntv2 });
|
||||
expect(await stores.media.findRecord('voice.silk')).toMatchObject({ isNtv2: ntv2 });
|
||||
const event = await stores.messages.findEvent(messageId);
|
||||
expect(event?.message_id).toBe(messageId);
|
||||
expect(JSON.stringify(event)).not.toMatch(/isNtv2|storeId|storeRegion/);
|
||||
});
|
||||
|
||||
it.each([true, false])('reads pre-marker snapshots (ntv2=%s)', async (ntv2) => {
|
||||
const { dbPath } = location();
|
||||
let stores = await openStores(dbPath);
|
||||
const elements = voice(isGroup, ntv2, ntv2 ? 1 : undefined);
|
||||
Reflect.deleteProperty(elements[0]!, 'isNtv2');
|
||||
await saveVoice(stores, isGroup, elements);
|
||||
await stores.close();
|
||||
stores = await openStores(dbPath);
|
||||
await checkRequest(stores, isGroup, ntv2, ntv2 ? 1 : 0);
|
||||
});
|
||||
|
||||
it('recognizes pre-marker NT snapshots with a null default region', async () => {
|
||||
const { dbPath } = location();
|
||||
let stores = await openStores(dbPath);
|
||||
const elements = voice(isGroup, true);
|
||||
Reflect.deleteProperty(elements[0]!, 'isNtv2');
|
||||
Reflect.set(elements[0]!.mediaNode!, 'storeId', null);
|
||||
await saveVoice(stores, isGroup, elements);
|
||||
await stores.close();
|
||||
stores = await openStores(dbPath);
|
||||
await checkRequest(stores, isGroup, true);
|
||||
});
|
||||
|
||||
it('retains an explicit zero region when updating the same voice', async () => {
|
||||
const { dbPath } = location();
|
||||
let stores = await openStores(dbPath);
|
||||
await saveVoice(stores, isGroup, voice(isGroup, true, 1));
|
||||
await saveVoice(stores, isGroup, voice(isGroup, true, 0));
|
||||
await stores.close();
|
||||
stores = await openStores(dbPath);
|
||||
await checkRequest(stores, isGroup, true, 0);
|
||||
});
|
||||
|
||||
it.each([true, false])(
|
||||
'reads migrated media without a message snapshot (ntv2=%s)',
|
||||
async (ntv2) => {
|
||||
const { dbPath, legacyPath } = location();
|
||||
const old = await openStores(legacyPath);
|
||||
const elements = voice(isGroup, ntv2, ntv2 ? 1 : undefined);
|
||||
Reflect.deleteProperty(elements[0]!, 'isNtv2');
|
||||
await saveVoice(old, isGroup, elements);
|
||||
await old.close();
|
||||
let stores = await openStores(dbPath);
|
||||
await saveVoice(stores, isGroup, elements, false);
|
||||
await stores.close();
|
||||
await migrateLegacyMedia(dbPath);
|
||||
stores = await openStores(dbPath);
|
||||
// A same-named current entry must not replace the migrated source.
|
||||
await elementsToOneBotSegments(
|
||||
stores.converter,
|
||||
voice(isGroup, true, 9),
|
||||
isGroup,
|
||||
peerId,
|
||||
);
|
||||
expect(await stores.messages.findMedia(messageId)).toBeNull();
|
||||
await checkRequest(stores, isGroup, ntv2, ntv2 ? 1 : 0);
|
||||
},
|
||||
);
|
||||
|
||||
it('preserves the server failure without retrying', async () => {
|
||||
const { dbPath } = location();
|
||||
const stores = await openStores(dbPath);
|
||||
await saveVoice(stores, isGroup, voice(isGroup, true, 1));
|
||||
const { sendRawPacket, bridge } = transport(isGroup, 9);
|
||||
await expect(
|
||||
fetchPttText(stores.messages, stores.media, bridge, selfId, messageId),
|
||||
).rejects.toThrow('ptt translate failed: error=9');
|
||||
expect(sendRawPacket).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -58,7 +58,7 @@ function fakeRequest(overrides: Partial<GroupRequestInfo> = {}): GroupRequestInf
|
||||
operatorName: 'op',
|
||||
sequence: 42,
|
||||
state: 1,
|
||||
eventType: 7,
|
||||
eventType: 2,
|
||||
comment: 'pls',
|
||||
filtered: false,
|
||||
...overrides,
|
||||
@@ -118,7 +118,7 @@ describe('onebot/modules/request-actions / handleGroupAddRequest', () => {
|
||||
fakeRequest({
|
||||
groupId: 999,
|
||||
sequence: 261237407,
|
||||
eventType: 7,
|
||||
eventType: 1,
|
||||
filtered: false,
|
||||
}),
|
||||
],
|
||||
@@ -131,7 +131,7 @@ describe('onebot/modules/request-actions / handleGroupAddRequest', () => {
|
||||
expect(setAddRequest).toHaveBeenCalledWith(
|
||||
999,
|
||||
261237407,
|
||||
7,
|
||||
1,
|
||||
false,
|
||||
'no',
|
||||
false,
|
||||
@@ -172,11 +172,12 @@ describe('onebot/modules/request-actions / handleGroupAddRequest', () => {
|
||||
it('matches add requests by groupId and targetUid', async () => {
|
||||
const setAddRequest = vi.fn(async () => {});
|
||||
const fetchGroupRequestsByUid = vi.fn(async () => [
|
||||
fakeRequest({ sequence: 41, targetUid: 'u_t', eventType: 2 }),
|
||||
fakeRequest({
|
||||
groupId: 999,
|
||||
targetUid: 'u_t',
|
||||
sequence: 42,
|
||||
eventType: 7,
|
||||
eventType: 1,
|
||||
filtered: false,
|
||||
}),
|
||||
]);
|
||||
@@ -188,7 +189,7 @@ describe('onebot/modules/request-actions / handleGroupAddRequest', () => {
|
||||
await handleGroupAddRequest(bridge, 'add:999:u_t', true, 'ok');
|
||||
|
||||
expect(setAddRequest).toHaveBeenCalledOnce();
|
||||
expect(setAddRequest).toHaveBeenCalledWith(999, 42, 7, true, 'ok', false, undefined);
|
||||
expect(setAddRequest).toHaveBeenCalledWith(999, 42, 1, true, 'ok', false, undefined);
|
||||
expect(fetchGroupRequestsByUid).toHaveBeenCalledWith(false, 100);
|
||||
expect(fetchGroupRequestsByUid).toHaveBeenCalledWith(true, 100);
|
||||
});
|
||||
@@ -197,11 +198,12 @@ describe('onebot/modules/request-actions / handleGroupAddRequest', () => {
|
||||
const setAddRequest = vi.fn(async () => {});
|
||||
const bridge = fakeBridge({
|
||||
fetchGroupRequestsByUid: vi.fn(async () => [
|
||||
fakeRequest({ sequence: 96, invitorUid: 'u_i', eventType: 1 }),
|
||||
fakeRequest({
|
||||
groupId: 999,
|
||||
invitorUid: 'u_i',
|
||||
sequence: 97,
|
||||
eventType: 8,
|
||||
eventType: 22,
|
||||
filtered: false,
|
||||
}),
|
||||
]),
|
||||
@@ -212,7 +214,7 @@ describe('onebot/modules/request-actions / handleGroupAddRequest', () => {
|
||||
await handleGroupAddRequest(bridge, 'invite:999:u_i', false, 'no');
|
||||
|
||||
expect(setAddRequest).toHaveBeenCalledOnce();
|
||||
expect(setAddRequest).toHaveBeenCalledWith(999, 97, 8, false, 'no', false, undefined);
|
||||
expect(setAddRequest).toHaveBeenCalledWith(999, 97, 22, false, 'no', false, undefined);
|
||||
});
|
||||
|
||||
it('finds a request that only lives in the filtered inbox (#197)', async () => {
|
||||
@@ -284,7 +286,7 @@ describe('onebot/modules/request-actions / handleGroupAddRequest', () => {
|
||||
expect(setAddRequest).toHaveBeenCalledExactlyOnceWith(
|
||||
999,
|
||||
124,
|
||||
7,
|
||||
2,
|
||||
true,
|
||||
'',
|
||||
false,
|
||||
|
||||
@@ -167,7 +167,12 @@ describe('self-sent remote media', () => {
|
||||
raw_message: `[CQ:image,file=failed.jpg,url=${originalUrl}][CQ:image,file=,url=https://fresh.example/fresh.jpg][CQ:image,file=missing.jpg,url=https://original.example/missing.jpg]`,
|
||||
},
|
||||
});
|
||||
expect(resolver).toHaveBeenCalledTimes(2);
|
||||
// URLs already on the message remain refreshable without a global alias.
|
||||
expect(resolver).toHaveBeenCalledTimes(3);
|
||||
expect(resolver).toHaveBeenLastCalledWith(
|
||||
expect.objectContaining({ imageUrl: 'https://original.example/missing.jpg' }),
|
||||
true,
|
||||
);
|
||||
expect(await ref.messageStore.findEvent(42)).toEqual(original);
|
||||
},
|
||||
);
|
||||
|
||||
@@ -22,15 +22,22 @@ import { MessageStore } from '../src/message-store';
|
||||
import { sendGroupMessage } from '../src/modules/message-actions';
|
||||
|
||||
function fakeBridge(overrides: Partial<BridgeInterface> = {}): BridgeInterface {
|
||||
return new Proxy({ identity: { nickname: 'SnowLuma' }, ...overrides } as BridgeInterface, {
|
||||
get(target, prop) {
|
||||
if (prop in target) {
|
||||
return (target as any)[prop];
|
||||
}
|
||||
return new Proxy(
|
||||
{
|
||||
identity: { nickname: 'SnowLuma' },
|
||||
recallUploadedFile: vi.fn(),
|
||||
...overrides,
|
||||
} as BridgeInterface,
|
||||
{
|
||||
get(target, prop) {
|
||||
if (prop in target) {
|
||||
return (target as any)[prop];
|
||||
}
|
||||
|
||||
throw new Error(`fakeBridge: '${String(prop)}' was not stubbed for this test`);
|
||||
throw new Error(`fakeBridge: '${String(prop)}' was not stubbed for this test`);
|
||||
},
|
||||
},
|
||||
});
|
||||
);
|
||||
}
|
||||
|
||||
function makeCtx(bridge: BridgeInterface, messageStore?: MessageStore): OneBotInstanceContext {
|
||||
@@ -345,10 +352,214 @@ describe('send_group_msg with {type:"file"} segment', () => {
|
||||
expect(upload).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('file segment with url (no file_id) auto-uploads via groupFile.upload (not publish)', async () => {
|
||||
it('rejects text + image + temporary file before any chat publication', async () => {
|
||||
const sendGroup = vi.fn(async () => goodReceipt);
|
||||
const publish = vi.fn();
|
||||
const upload = vi.fn(async () => ({ fileId: 'temp', busId: 104 }));
|
||||
const ctx = makeCtx(
|
||||
fakeBridge({
|
||||
apis: { message: { sendGroup }, groupFile: { upload, publish } } as any,
|
||||
}),
|
||||
);
|
||||
await expect(
|
||||
sendGroupMessage(
|
||||
ctx,
|
||||
12345,
|
||||
[
|
||||
{ type: 'text', data: { text: 'caption' } },
|
||||
{ type: 'image', data: { file: 'base64://AQID' } },
|
||||
{ type: 'file', data: { file: '/tmp/report.pdf' } },
|
||||
],
|
||||
false,
|
||||
),
|
||||
).rejects.toThrow(/temporary group files.*only file or image/i);
|
||||
expect(sendGroup).not.toHaveBeenCalled();
|
||||
expect(publish).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects cached temporary file + text before publishing an earlier permanent file', async () => {
|
||||
const sendGroup = vi.fn(async () => goodReceipt);
|
||||
const publish = vi.fn();
|
||||
const ctx = makeCtx(
|
||||
fakeBridge({
|
||||
apis: { message: { sendGroup }, groupFile: { publish } } as any,
|
||||
recallUploadedFile: vi.fn((id) =>
|
||||
id === 'temp'
|
||||
? {
|
||||
fileId: id,
|
||||
scope: 'group',
|
||||
groupId: 12345,
|
||||
busId: 104,
|
||||
}
|
||||
: undefined,
|
||||
),
|
||||
} as any),
|
||||
);
|
||||
await expect(
|
||||
sendGroupMessage(
|
||||
ctx,
|
||||
12345,
|
||||
[
|
||||
{ type: 'file', data: { file_id: 'permanent' } },
|
||||
{ type: 'text', data: { text: 'caption' } },
|
||||
{ type: 'file', data: { file_id: 'temp' } },
|
||||
],
|
||||
false,
|
||||
),
|
||||
).rejects.toThrow(/temporary group files.*only file or image/i);
|
||||
expect(sendGroup).not.toHaveBeenCalled();
|
||||
expect(publish).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([false, true])(
|
||||
'allows temporary files with only file/image content (image=%s)',
|
||||
async (withImage) => {
|
||||
const sendGroup = vi.fn(async () => goodReceipt);
|
||||
const publish = vi.fn();
|
||||
const upload = vi.fn(async () => {
|
||||
expect(sendGroup).not.toHaveBeenCalled();
|
||||
expect(publish).not.toHaveBeenCalled();
|
||||
return { fileId: 'temp', busId: 104 };
|
||||
});
|
||||
const ctx = makeCtx(
|
||||
fakeBridge({
|
||||
apis: { message: { sendGroup }, groupFile: { upload, publish } } as any,
|
||||
}),
|
||||
);
|
||||
const message = [
|
||||
{ type: 'file', data: { file: '/tmp/report.pdf' } },
|
||||
...(withImage ? [{ type: 'image', data: { file: 'base64://AQID' } }] : []),
|
||||
];
|
||||
await sendGroupMessage(ctx, 12345, message, false);
|
||||
expect(upload).toHaveBeenCalledWith(
|
||||
12345,
|
||||
'/tmp/report.pdf',
|
||||
'report.pdf',
|
||||
'/',
|
||||
true,
|
||||
false,
|
||||
{ allowTemporary: true },
|
||||
);
|
||||
expect(publish).toHaveBeenCalledExactlyOnceWith(12345, 'temp', 104);
|
||||
expect(sendGroup).toHaveBeenCalledTimes(withImage ? 1 : 0);
|
||||
},
|
||||
);
|
||||
|
||||
it('preserves ordinary image + text without entering the group-file path', async () => {
|
||||
const sendGroup = vi.fn(async () => goodReceipt);
|
||||
const upload = vi.fn();
|
||||
const publish = vi.fn();
|
||||
const ctx = makeCtx(
|
||||
fakeBridge({ apis: { message: { sendGroup }, groupFile: { upload, publish } } as any }),
|
||||
);
|
||||
await sendGroupMessage(
|
||||
ctx,
|
||||
12345,
|
||||
[
|
||||
{ type: 'image', data: { file: 'base64://AQID' } },
|
||||
{ type: 'text', data: { text: 'caption' } },
|
||||
],
|
||||
false,
|
||||
);
|
||||
expect(sendGroup).toHaveBeenCalledOnce();
|
||||
expect(sendGroup.mock.calls[0]).toMatchObject([
|
||||
12345,
|
||||
[
|
||||
{ type: 'image', url: 'base64://AQID' },
|
||||
{ type: 'text', text: 'caption' },
|
||||
],
|
||||
]);
|
||||
expect(upload).not.toHaveBeenCalled();
|
||||
expect(publish).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('keeps permanent file + text sends, but checks uploads before sending the text', async () => {
|
||||
const sendGroup = vi.fn(async () => goodReceipt);
|
||||
const publish = vi.fn();
|
||||
const upload = vi.fn(async () => {
|
||||
expect(sendGroup).not.toHaveBeenCalled();
|
||||
return { fileId: 'permanent', busId: 102 };
|
||||
});
|
||||
const ctx = makeCtx(
|
||||
fakeBridge({ apis: { message: { sendGroup }, groupFile: { upload, publish } } as any }),
|
||||
);
|
||||
await sendGroupMessage(
|
||||
ctx,
|
||||
12345,
|
||||
[
|
||||
{ type: 'text', data: { text: 'caption' } },
|
||||
{ type: 'file', data: { file: '/tmp/report.pdf' } },
|
||||
],
|
||||
false,
|
||||
);
|
||||
expect(upload).toHaveBeenCalledWith(
|
||||
12345,
|
||||
'/tmp/report.pdf',
|
||||
'report.pdf',
|
||||
'/',
|
||||
true,
|
||||
false,
|
||||
{ allowTemporary: false },
|
||||
);
|
||||
expect(sendGroup).toHaveBeenCalledOnce();
|
||||
expect(publish).toHaveBeenCalledExactlyOnceWith(12345, 'permanent', 102);
|
||||
});
|
||||
|
||||
it('does not publish the first file or text if a later upload fails', async () => {
|
||||
const sendGroup = vi.fn();
|
||||
const publish = vi.fn();
|
||||
const upload = vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce({ fileId: 'first', busId: 102 })
|
||||
.mockRejectedValueOnce(
|
||||
new Error('temporary group files require only file or image segments'),
|
||||
);
|
||||
const ctx = makeCtx(
|
||||
fakeBridge({ apis: { message: { sendGroup }, groupFile: { upload, publish } } as any }),
|
||||
);
|
||||
await expect(
|
||||
sendGroupMessage(
|
||||
ctx,
|
||||
12345,
|
||||
[
|
||||
{ type: 'text', data: { text: 'caption' } },
|
||||
{ type: 'file', data: { file: '/tmp/one.pdf' } },
|
||||
{ type: 'file', data: { file: '/tmp/two.pdf' } },
|
||||
],
|
||||
false,
|
||||
),
|
||||
).rejects.toThrow(/temporary group files/);
|
||||
expect(sendGroup).not.toHaveBeenCalled();
|
||||
expect(publish).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('reports a failed file publication with its identity and never retries the send', async () => {
|
||||
const cause = new Error('chat post rejected');
|
||||
const publish = vi.fn().mockRejectedValueOnce(cause);
|
||||
const upload = vi.fn(async () => ({ fileId: 'temp', busId: 104 }));
|
||||
const ctx = makeCtx(
|
||||
fakeBridge({
|
||||
apis: { message: { sendGroup: vi.fn() }, groupFile: { upload, publish } } as any,
|
||||
}),
|
||||
);
|
||||
await expect(
|
||||
sendGroupMessage(
|
||||
ctx,
|
||||
12345,
|
||||
[{ type: 'file', data: { file: '/tmp/report.pdf' } }],
|
||||
false,
|
||||
),
|
||||
).rejects.toMatchObject({
|
||||
message: 'group file chat post failed (fileId=temp): chat post rejected',
|
||||
cause,
|
||||
});
|
||||
expect(upload).toHaveBeenCalledOnce();
|
||||
expect(publish).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('uploads a file source without publishing, then publishes it exactly once', async () => {
|
||||
// Happy path for inline file sending: the bot passes a local path
|
||||
// directly. upload() internally calls publish(), so we must NOT
|
||||
// call publish() a second time.
|
||||
// directly. Delay chat publication until all uploads are checked.
|
||||
const upload = vi.fn(
|
||||
async (
|
||||
_gid: number,
|
||||
@@ -387,8 +598,16 @@ describe('send_group_msg with {type:"file"} segment', () => {
|
||||
expect(name).toBe('audio.wav');
|
||||
expect(folder).toBe('/');
|
||||
expect(doUpload).toBe(true);
|
||||
// publish must NOT be called — upload() already handles it internally
|
||||
expect(publish).not.toHaveBeenCalled();
|
||||
expect(upload).toHaveBeenCalledWith(
|
||||
12345,
|
||||
'/tmp/audio.wav',
|
||||
'audio.wav',
|
||||
'/',
|
||||
true,
|
||||
false,
|
||||
{ allowTemporary: true },
|
||||
);
|
||||
expect(publish).toHaveBeenCalledExactlyOnceWith(12345, 'auto-fid', undefined);
|
||||
});
|
||||
|
||||
it('percent-decodes a file:// URL basename when name is omitted (#354)', async () => {
|
||||
|
||||
@@ -95,8 +95,7 @@ describe('send_group_msg large-video fallback', () => {
|
||||
expect(gid).toBe(12345);
|
||||
expect(src).toBe('http://example.com/big.mp4');
|
||||
expect(name).toBe('video.mp4');
|
||||
// upload() publishes internally — no second publish().
|
||||
expect(publish).not.toHaveBeenCalled();
|
||||
expect(publish).toHaveBeenCalledExactlyOnceWith(12345, 'auto-fid', undefined);
|
||||
});
|
||||
|
||||
it('rethrows (no fallback) when a remote video fails with a non-size error', async () => {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "@snowluma/proto-defs",
|
||||
"version": "2.4.0",
|
||||
"version": "2.4.2",
|
||||
"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).",
|
||||
|
||||
@@ -1,6 +1,30 @@
|
||||
import type { pb, pb_repeated, int_32, uint_32, uint_64, bytes } from '@snowluma/proton';
|
||||
import type { Elem } from './element';
|
||||
|
||||
export interface GroupCardPart {
|
||||
control?: pb<1, bytes>;
|
||||
text?: pb<2, bytes>;
|
||||
}
|
||||
|
||||
export interface RichGroupCard {
|
||||
parts?: pb_repeated<1, GroupCardPart>;
|
||||
}
|
||||
|
||||
/** Join-origin metadata used by QQ's member-add notification handler. */
|
||||
export interface GroupJoinOrigin {
|
||||
/** 1 names a QR-code sharer rather than an inviter. */
|
||||
type?: pb<1, uint_32>;
|
||||
uid?: pb<3, bytes>;
|
||||
}
|
||||
|
||||
export interface GroupJoinExtra {
|
||||
origin?: pb<1, GroupJoinOrigin>;
|
||||
}
|
||||
|
||||
export interface GroupMessageKey {
|
||||
joinExtra?: pb<4, GroupJoinExtra>;
|
||||
}
|
||||
|
||||
// ResponseHead.Grp
|
||||
export interface ResponseGrp {
|
||||
groupUin?: pb<1, uint_32>;
|
||||
@@ -13,9 +37,12 @@ export interface ResponseGrp {
|
||||
* message shows "星屿"/"墨梓柒111" (the card) here while field 2 is empty, and
|
||||
* forward nodes carry per-node sender names here. Lagrange labels this
|
||||
* `MemberName`; we keep `memberName` for the field-2 group-history slot. */
|
||||
memberCard?: pb<4, string>;
|
||||
memberCard?: pb<4, bytes>;
|
||||
/** Type 2 carries the literal sender nickname. Other values may carry a RichGroupCard. */
|
||||
memberCardType?: pb<5, uint_32>;
|
||||
/** The real group name (Lagrange: GroupName). "测试123" on-target. */
|
||||
groupName?: pb<7, string>;
|
||||
messageKey?: pb<8, GroupMessageKey>;
|
||||
}
|
||||
|
||||
export interface ResponseForward {
|
||||
@@ -49,6 +76,8 @@ export interface ContentHead {
|
||||
sequence?: pb<5, uint_32>;
|
||||
timestamp?: pb<6, uint_32>;
|
||||
field7?: pb<7, uint_64>;
|
||||
/** QQ sets a nonzero value for automatic replies. */
|
||||
autoReply?: pb<10, uint_32>;
|
||||
/** Conversation-wide C2C sequence. Unlike field 5, this advances across
|
||||
* messages sent by either participant and is the sequence accepted by
|
||||
* SsoGetC2cMsg. It is absent on group messages. */
|
||||
|
||||
@@ -156,7 +156,8 @@ export interface OidbSvcTrpcTcp0xFE7_3Uin {
|
||||
}
|
||||
|
||||
export interface OidbSvcTrpcTcp0xFE7_3Card {
|
||||
memberCard?: pb<2, string>;
|
||||
/** Plain UTF-8 or a serialized RichGroupCard. */
|
||||
memberCard?: pb<2, bytes>;
|
||||
}
|
||||
|
||||
export interface OidbSvcTrpcTcp0xFE7_3Level {
|
||||
|
||||
@@ -4,14 +4,6 @@ import type { pb, uint_32, uint_64 } from '@snowluma/proton';
|
||||
* Voice-to-text (语音转文字) request/response protobufs for the
|
||||
* `pttTrans.TransC2CPttReq` / `pttTrans.TransGroupPttReq` SSO commands.
|
||||
*
|
||||
* Reverse-engineered from QQ-NT `wrapper.node` (macOS 9.9.x) —
|
||||
* `im_core/msg/ptt/ptt_trans_worker.cc` (`EncodeC2CPtt` / `EncodeTroopPtt`
|
||||
* build the request, `OnTranslateResp` decodes the response). The wire shape
|
||||
* here is RE-derived and NOT yet verified against a live server: the numeric
|
||||
* field tags are read straight from the encoder, but the length-delimited
|
||||
* fields (uuid / md5) and the response `text` tag should be confirmed with a
|
||||
* single live capture before relying on them.
|
||||
*
|
||||
* Flow: the response can carry completed text inline. Otherwise, the caller
|
||||
* waits for an asynchronous result correlated with the original message ID.
|
||||
*/
|
||||
@@ -55,6 +47,9 @@ export interface PttTransReq {
|
||||
type?: pb<1, uint_32>;
|
||||
groupItem?: pb<2, GroupPttTransItem>;
|
||||
c2cItem?: pb<3, C2CPttTransItem>;
|
||||
/** 1 for NT media, 0 for legacy media; not the audio codec. */
|
||||
isNtv2?: pb<5, uint_32>;
|
||||
storeRegion?: pb<6, uint_32>;
|
||||
}
|
||||
|
||||
/** Per-scene result. `errCode` 0 = ok; `text` carries the recognised speech. */
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
# Video upload connections
|
||||
# Media transfer settings
|
||||
|
||||
## Video upload connections
|
||||
|
||||
Video uploads use one connection by default. In **Settings → Global configuration →
|
||||
Video upload connections**, choose 1, 2, 3 or 4 connections. The equivalent setting
|
||||
@@ -36,6 +38,54 @@ Regression tests use isolated transports and cover concurrency bounds,
|
||||
out-of-order acknowledgements, a stalled early chunk, retry exhaustion, backpressure
|
||||
and cleanup. They do not establish real QQ delivery or upload throughput.
|
||||
|
||||
## Upload timeouts and node selection
|
||||
|
||||
All Highway HTTP uploads (including images, voice, video and files) snapshot
|
||||
these deployment-wide environment variables when each file starts transferring:
|
||||
|
||||
| Variable | Default | Meaning |
|
||||
| --- | --- | --- |
|
||||
| `SNOWLUMA_HIGHWAY_UPLOAD_IDLE_TIMEOUT_MS` | `30000` | Maximum wait without response bytes during one request, in milliseconds. Resets when response bytes arrive. |
|
||||
| `SNOWLUMA_HIGHWAY_UPLOAD_TIMEOUT_MS` | `1800000` | Total transfer budget for one file, in milliseconds (30 minutes). Shared by all chunks, connections, writes, response waits and retry delays. |
|
||||
|
||||
For example, a deployment sending small images can use:
|
||||
|
||||
```sh
|
||||
SNOWLUMA_HIGHWAY_UPLOAD_IDLE_TIMEOUT_MS=5000
|
||||
SNOWLUMA_HIGHWAY_UPLOAD_TIMEOUT_MS=120000
|
||||
```
|
||||
|
||||
Restart the process/container with these variables. Both values must be integers
|
||||
from 1 to 2147483647; invalid values fail the upload visibly rather than silently
|
||||
using a default. The total budget does not reset after a successful chunk, after
|
||||
incoming bytes, or on a different node. The idle timer starts when the HTTP request
|
||||
begins, including writes; slow connections may need a larger value. Source downloads,
|
||||
hashing and QQ upload preparation precede this transfer budget. Video bodies and
|
||||
their covers are separate files with separate budgets.
|
||||
|
||||
Transport failures retry only the unconfirmed chunk. Each chunk allows at least
|
||||
three attempts, or enough attempts to cover all distinct supplied candidates when
|
||||
there are more than three, subject to the file's total budget. Each connection has
|
||||
a three-second handshake limit. An expired total budget aborts all workers and
|
||||
closes their connections; outstanding filesystem reads are drained before closing
|
||||
the source, so cleanup can finish after that deadline. Explicit server rejection
|
||||
and invalid acknowledgements still fail immediately. Backpressure retries remain
|
||||
bounded separately and share the same file deadline.
|
||||
|
||||
Node observations belong to the account session and upload type, keyed by the
|
||||
complete host and port. A validated successful upload acknowledgement is preferred
|
||||
for five minutes; a transport failure lowers that endpoint's priority for thirty
|
||||
seconds. Unknown endpoints remain eligible ahead of recent failures, and failures
|
||||
never permanently exclude a candidate. Only destinations supplied for the current
|
||||
upload can be selected. The history holds at most 128 observations per account
|
||||
session, contains no tickets or payloads, and is released when that account's
|
||||
identity object is discarded. A process restart clears it.
|
||||
|
||||
TRACE logs show the effective timeouts and candidate order. Read timeouts include
|
||||
the current write/read phase, completed write byte count, received byte count and
|
||||
whether response headers were seen. Total-budget exhaustion is reported separately
|
||||
as `upload_timeout`; failed transfers remain failed OneBot actions.
|
||||
|
||||
## Media download limits
|
||||
|
||||
Two deployment-wide knobs bound HTTP media downloads in `highway/utils.ts`. They are
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "@snowluma/protocol",
|
||||
"version": "2.4.0",
|
||||
"version": "2.4.2",
|
||||
"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>'`.",
|
||||
|
||||
@@ -31,6 +31,8 @@ export interface UploadedFileMeta {
|
||||
scope: 'group' | 'private';
|
||||
/** Group id if scope='group', else `undefined`. */
|
||||
groupId?: number;
|
||||
/** Server-selected group storage type: 102 permanent, 104 temporary. */
|
||||
busId?: number;
|
||||
/** Friend uin if scope='private', else `undefined`. */
|
||||
userId?: number;
|
||||
fileName: string;
|
||||
|
||||
@@ -607,6 +607,8 @@ function makeGroupFileElem(element: MessageElement, ctx?: SendContext): ProtoEle
|
||||
}
|
||||
|
||||
const cached = ctx?.bridge.recallUploadedFile(element.fileId);
|
||||
const busId =
|
||||
cached?.scope === 'group' && cached.groupId === ctx?.groupId ? (cached.busId ?? 102) : 102;
|
||||
const fileSize = element.fileSize ?? cached?.fileSize ?? 0;
|
||||
const fileName = element.fileName ?? cached?.fileName ?? '';
|
||||
const md5 = element.md5Hex
|
||||
@@ -618,13 +620,13 @@ function makeGroupFileElem(element: MessageElement, ctx?: SendContext): ProtoEle
|
||||
|
||||
// Outer field1 is hardcoded to 6 in NapCat's encoder
|
||||
// (`packet/message/element.ts:589`). Inner GroupFileExtraInfo carries
|
||||
// busId=102 + the file_id + name + size + sha1/md5 hashes.
|
||||
// the storage type + file_id + name + size + sha1/md5 hashes.
|
||||
const extraBytes = protobuf_encode<GroupFileExtra>({
|
||||
field1: 6,
|
||||
fileName,
|
||||
inner: {
|
||||
info: {
|
||||
busId: 102,
|
||||
busId,
|
||||
fileId: element.fileId,
|
||||
fileSize: BigInt(fileSize),
|
||||
fileName,
|
||||
|
||||
@@ -215,6 +215,7 @@ export const ELEMENT_MANIFEST = {
|
||||
'md5Hex',
|
||||
'sha1Hex',
|
||||
'voiceFormat',
|
||||
'isNtv2',
|
||||
'noByteFallback',
|
||||
'mediaNode',
|
||||
]),
|
||||
@@ -353,7 +354,7 @@ const NUMBER_FIELDS: ReadonlySet<string> = new Set([
|
||||
'videoFormat',
|
||||
'voiceFormat',
|
||||
]);
|
||||
const BOOLEAN_FIELDS: ReadonlySet<string> = new Set(['flash', 'noByteFallback', 'large']);
|
||||
const BOOLEAN_FIELDS: ReadonlySet<string> = new Set(['flash', 'noByteFallback', 'large', 'isNtv2']);
|
||||
|
||||
function throwValidation(
|
||||
code: MessageElementValidationCode,
|
||||
|
||||
@@ -145,6 +145,8 @@ export interface RecordElement extends FingerprintFields {
|
||||
url?: string;
|
||||
duration?: number;
|
||||
voiceFormat?: number;
|
||||
/** Media protocol generation; independent of the audio codec. */
|
||||
isNtv2?: boolean;
|
||||
mediaNode?: MediaNode;
|
||||
}
|
||||
|
||||
@@ -283,6 +285,7 @@ export interface QQEvent {
|
||||
|
||||
export interface FriendMessage extends QQEvent {
|
||||
kind: 'friend_message';
|
||||
autoReply?: true;
|
||||
senderUin: number;
|
||||
/** The other participant in this private conversation. Differs from
|
||||
* senderUin for messages sent by the logged-in account. */
|
||||
@@ -326,6 +329,7 @@ export interface GroupMessage extends QQEvent {
|
||||
|
||||
export interface TempMessage extends QQEvent {
|
||||
kind: 'temp_message';
|
||||
autoReply?: true;
|
||||
senderUin: number;
|
||||
/** Source group of the temp session (from responseHead.forward), or 0. */
|
||||
groupId: number;
|
||||
@@ -344,6 +348,9 @@ export interface GroupMemberJoin extends QQEvent {
|
||||
operatorUin: number;
|
||||
userUid?: string;
|
||||
operatorUid?: string;
|
||||
/** Independent invitation origin; never inferred from the operator. */
|
||||
invitorUid?: string;
|
||||
invitorUin?: number;
|
||||
/**
|
||||
* Admission mode derived from GroupChange field 4. This is deliberately
|
||||
* separate from QQ's nested invitation-source enum, which has different
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type { ResponseGrp, RichGroupCard } from '@snowluma/proto-defs/message';
|
||||
import { protobuf_decode } from '@snowluma/proton';
|
||||
|
||||
const log = createLogger('Protocol.GroupMemberCard');
|
||||
const utf8 = new TextDecoder('utf-8', { fatal: true });
|
||||
// eslint-disable-next-line no-control-regex -- C0 controls except tab/LF/CR, plus DEL.
|
||||
const cardControls = /[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g;
|
||||
|
||||
/** Keep ordinary text whitespace, but never publish binary framing as a name. */
|
||||
export function isBinaryCardText(text: string): boolean {
|
||||
return text.search(cardControls) !== -1;
|
||||
}
|
||||
|
||||
function utf8Text(bytes: Uint8Array): string {
|
||||
try {
|
||||
return utf8.decode(bytes);
|
||||
} catch (cause) {
|
||||
throw new Error('group card contains invalid UTF-8', { cause });
|
||||
}
|
||||
}
|
||||
|
||||
function displayText(bytes: Uint8Array): string {
|
||||
const text = utf8Text(bytes);
|
||||
|
||||
if (isBinaryCardText(text)) {
|
||||
throw new Error('group card text contains binary control characters');
|
||||
}
|
||||
|
||||
return text;
|
||||
}
|
||||
|
||||
export function decodeGroupMemberCard(bytes?: Uint8Array): string {
|
||||
if (!bytes?.length) {
|
||||
return '';
|
||||
}
|
||||
|
||||
// Each part has tag 0x0a, but version/unknown fields can precede the parts.
|
||||
if (!bytes.includes(0x0a)) {
|
||||
return displayText(bytes);
|
||||
}
|
||||
|
||||
let parts: RichGroupCard['parts'];
|
||||
|
||||
try {
|
||||
parts = protobuf_decode<RichGroupCard>(bytes).parts;
|
||||
} catch {
|
||||
// Both formats occupy the same wire field. A newline in a plain name
|
||||
// is also 0x0a; accept it only if the entire value is valid display text.
|
||||
return displayText(bytes);
|
||||
}
|
||||
|
||||
if (!parts?.length) {
|
||||
return displayText(bytes);
|
||||
}
|
||||
|
||||
// A control field, even an empty one, takes precedence over text in the same part.
|
||||
const text = parts.flatMap((part) =>
|
||||
part.control == null && part.text != null ? [part.text] : [],
|
||||
);
|
||||
// Structured text can contain display controls (#680). Normalize the whole
|
||||
// control set after strict UTF-8 decoding, preserving whitespace and Unicode formatting.
|
||||
return utf8Text(Buffer.concat(text)).replace(cardControls, '');
|
||||
}
|
||||
|
||||
/** A malformed optional display name must not discard the message itself. */
|
||||
export function decodeGroupDisplayName(group?: ResponseGrp): string | undefined {
|
||||
if (!group?.memberCard?.length) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const bytes = group.memberCard;
|
||||
|
||||
try {
|
||||
return group.memberCardType === 2 ? displayText(bytes) : decodeGroupMemberCard(bytes);
|
||||
} catch (error) {
|
||||
log.warn(
|
||||
'invalid group message display name: group=%d bytes=%d reason=%s',
|
||||
group.groupUin ?? 0,
|
||||
bytes.length,
|
||||
error instanceof Error ? error.message : String(error),
|
||||
);
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
@@ -18,14 +18,18 @@ import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import net from 'net';
|
||||
import { promises as fsp } from 'fs';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
import { validateUploadConcurrency } from './upload-settings';
|
||||
import {
|
||||
highwayUploadTimeouts,
|
||||
validateUploadConcurrency,
|
||||
type HighwayUploadTimeouts,
|
||||
} from './upload-settings';
|
||||
import { uploadNodeHistory } from './upload-nodes';
|
||||
import { computeMd5, packHighwayFrame, unpackHighwayFrame } from './utils';
|
||||
|
||||
const log = createLogger('Highway');
|
||||
const HIGHWAY_APP_ID = 1600001604;
|
||||
const HIGHWAY_BLOCK_SIZE = 1024 * 1024;
|
||||
const HIGHWAY_CONNECT_TIMEOUT_MS = 3000;
|
||||
const HIGHWAY_CONNECT_BUDGET_MS = 10000;
|
||||
|
||||
// Per-chunk transport retry: a transient connection failure retries only
|
||||
// the unconfirmed offset, preserving acknowledged data (issue #118).
|
||||
@@ -44,14 +48,6 @@ const HIGHWAY_DELAY_RETRY_CODES = new Set([102902, 302902]);
|
||||
const HIGHWAY_DELAY_RETRY_MS = 250;
|
||||
const HIGHWAY_MAX_DELAY_RETRIES = 8;
|
||||
|
||||
// Idle read timeout for a highway response. tcpConnect() clears the socket's
|
||||
// own timeout once connected, so a peer that accepts the connection but then
|
||||
// neither responds nor FINs would hang the whole upload forever. The single
|
||||
// persistent connection (issue #211) keeps a socket alive across the whole
|
||||
// file, widening that exposure, so the response reader arms its own idle timer
|
||||
// and treats a stall as a retryable transport failure.
|
||||
const HIGHWAY_READ_IDLE_MS = 30000;
|
||||
|
||||
function sleepMs(ms: number, signal: AbortSignal): Promise<void> {
|
||||
signal.throwIfAborted();
|
||||
return new Promise((resolve, reject) => {
|
||||
@@ -95,6 +91,7 @@ type HighwayPutFailureReason =
|
||||
| 'server_rejected'
|
||||
| 'source_close_failed'
|
||||
| 'source_read_failed'
|
||||
| 'upload_timeout'
|
||||
| 'transport_exhausted';
|
||||
|
||||
interface HighwayPutTraceState {
|
||||
@@ -359,29 +356,25 @@ async function connectHighway(
|
||||
servers: HighwayServer[],
|
||||
startIndex: number,
|
||||
signal: AbortSignal,
|
||||
onFailure: (server: HighwayServer) => void,
|
||||
): Promise<{ socket: net.Socket; server: HighwayServer; serverIndex: number }> {
|
||||
const deadline = Date.now() + HIGHWAY_CONNECT_BUDGET_MS;
|
||||
const errors: Error[] = [];
|
||||
|
||||
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) {
|
||||
break;
|
||||
}
|
||||
|
||||
try {
|
||||
const socket = await tcpConnect(
|
||||
server.host,
|
||||
server.port,
|
||||
Math.min(HIGHWAY_CONNECT_TIMEOUT_MS, remaining),
|
||||
HIGHWAY_CONNECT_TIMEOUT_MS,
|
||||
signal,
|
||||
);
|
||||
return { socket, server, serverIndex };
|
||||
} catch (cause) {
|
||||
signal.throwIfAborted();
|
||||
onFailure(server);
|
||||
const error = new Error(`${server.host}:${server.port}: ${highwayErrorText(cause)}`, {
|
||||
cause,
|
||||
});
|
||||
@@ -396,13 +389,41 @@ async function connectHighway(
|
||||
);
|
||||
}
|
||||
|
||||
function socketWrite(socket: net.Socket, data: Uint8Array): Promise<void> {
|
||||
function socketWrite(socket: net.Socket, data: Uint8Array, signal: AbortSignal): Promise<void> {
|
||||
signal.throwIfAborted();
|
||||
return new Promise((resolve, reject) => {
|
||||
socket.write(data, (err) => (err ? reject(err) : resolve()));
|
||||
const finish = (error?: unknown) => {
|
||||
signal.removeEventListener('abort', onAbort);
|
||||
|
||||
if (error !== undefined) {
|
||||
reject(error);
|
||||
} else {
|
||||
resolve();
|
||||
}
|
||||
};
|
||||
|
||||
const onAbort = () => finish(signal.reason);
|
||||
signal.addEventListener('abort', onAbort, { once: true });
|
||||
|
||||
try {
|
||||
socket.write(data, (error) => finish(error ?? undefined));
|
||||
} catch (error) {
|
||||
finish(error);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function readHttpResponseBody(socket: net.Socket, signal: AbortSignal): Promise<Uint8Array> {
|
||||
interface RequestProgress {
|
||||
phase: 'write_headers' | 'write_body' | 'read_response';
|
||||
writtenBytes: number;
|
||||
}
|
||||
|
||||
function readHttpResponseBody(
|
||||
socket: net.Socket,
|
||||
signal: AbortSignal,
|
||||
idleMs: number,
|
||||
progress: RequestProgress,
|
||||
): Promise<Uint8Array> {
|
||||
signal.throwIfAborted();
|
||||
return new Promise((resolve, reject) => {
|
||||
const chunks: Buffer[] = [];
|
||||
@@ -410,6 +431,7 @@ function readHttpResponseBody(socket: net.Socket, signal: AbortSignal): Promise<
|
||||
let contentLength = 0;
|
||||
let totalNeeded = 0;
|
||||
let settled = false;
|
||||
let receivedBytes = 0;
|
||||
|
||||
const partialResponseBody = (): Uint8Array | undefined => {
|
||||
if (headerEnd < 0 || getLogLevel() !== 'trace') {
|
||||
@@ -433,12 +455,12 @@ function readHttpResponseBody(socket: net.Socket, signal: AbortSignal): Promise<
|
||||
finish(() =>
|
||||
reject(
|
||||
new HighwayResponseReadError(
|
||||
'highway response read timeout (peer idle)',
|
||||
`highway response read timeout (peer idle; phase=${progress.phase}, written=${progress.writtenBytes}B, received=${receivedBytes}B, headerSeen=${headerEnd >= 0}, expected=${totalNeeded}B)`,
|
||||
partialResponseBody(),
|
||||
),
|
||||
),
|
||||
),
|
||||
HIGHWAY_READ_IDLE_MS,
|
||||
idleMs,
|
||||
);
|
||||
};
|
||||
|
||||
@@ -467,6 +489,7 @@ function readHttpResponseBody(socket: net.Socket, signal: AbortSignal): Promise<
|
||||
const onData = (chunk: Buffer) => {
|
||||
armIdle();
|
||||
chunks.push(chunk);
|
||||
receivedBytes += chunk.length;
|
||||
const buf = Buffer.concat(chunks);
|
||||
|
||||
if (headerEnd < 0) {
|
||||
@@ -542,6 +565,7 @@ async function httpPostFrame(
|
||||
path: string,
|
||||
body: Uint8Array,
|
||||
signal: AbortSignal,
|
||||
idleMs: number,
|
||||
): Promise<Uint8Array> {
|
||||
const header = `POST ${path} HTTP/1.1\r\nHost: ${host}\r\nConnection: keep-alive\r\nAccept-Encoding: identity\r\nUser-Agent: Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2)\r\nContent-Length: ${body.length}\r\n\r\n`;
|
||||
const responseAbort = new AbortController();
|
||||
@@ -554,14 +578,20 @@ async function httpPostFrame(
|
||||
signal.throwIfAborted();
|
||||
signal.addEventListener('abort', onAbort, { once: true });
|
||||
// Arm the reader before writing: a fast peer may reply before write callbacks.
|
||||
const response = readHttpResponseBody(socket, responseAbort.signal);
|
||||
const progress: RequestProgress = { phase: 'write_headers', writtenBytes: 0 };
|
||||
const response = readHttpResponseBody(socket, responseAbort.signal, idleMs, progress);
|
||||
const write = (async () => {
|
||||
await socketWrite(socket, Buffer.from(header, 'ascii'));
|
||||
await socketWrite(socket, Buffer.from(header, 'ascii'), responseAbort.signal);
|
||||
progress.writtenBytes += Buffer.byteLength(header, 'ascii');
|
||||
signal.throwIfAborted();
|
||||
|
||||
if (body.length > 0) {
|
||||
await socketWrite(socket, body);
|
||||
progress.phase = 'write_body';
|
||||
await socketWrite(socket, body, responseAbort.signal);
|
||||
progress.writtenBytes += body.byteLength;
|
||||
}
|
||||
|
||||
progress.phase = 'read_response';
|
||||
})();
|
||||
|
||||
try {
|
||||
@@ -739,13 +769,16 @@ async function uploadHighwayHttpOperation(
|
||||
|
||||
signal.addEventListener('abort', wake, { once: true });
|
||||
|
||||
const fail = (reason: HighwayPutFailureReason, error: unknown): never => {
|
||||
const abortUpload = (reason: HighwayPutFailureReason, error: unknown): void => {
|
||||
if (!signal.aborted) {
|
||||
trace.failureReason = reason;
|
||||
trace.error = error;
|
||||
abort.abort(error);
|
||||
}
|
||||
};
|
||||
|
||||
const fail = (reason: HighwayPutFailureReason, error: unknown): never => {
|
||||
abortUpload(reason, error);
|
||||
throw signal.reason;
|
||||
};
|
||||
|
||||
@@ -766,6 +799,11 @@ async function uploadHighwayHttpOperation(
|
||||
let retries = 0;
|
||||
let contiguous = 0;
|
||||
const confirmed = new Set<number>();
|
||||
const history = uploadNodeHistory(bridge.identity);
|
||||
const servers = history.order(commandId, session.servers);
|
||||
const maxAttempts = Math.max(HIGHWAY_MAX_CHUNK_ATTEMPTS, servers.length);
|
||||
let timeouts: HighwayUploadTimeouts;
|
||||
let deadlineTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
|
||||
const dropSocket = (worker: Worker) => {
|
||||
worker.socket?.destroy();
|
||||
@@ -854,9 +892,10 @@ async function uploadHighwayHttpOperation(
|
||||
|
||||
if (!worker.socket) {
|
||||
const connected = await connectHighway(
|
||||
session.servers,
|
||||
servers,
|
||||
worker.serverIndex,
|
||||
signal,
|
||||
(server) => history.record(commandId, server, false),
|
||||
);
|
||||
worker.socket = connected.socket;
|
||||
worker.serverIndex = connected.serverIndex;
|
||||
@@ -896,10 +935,11 @@ async function uploadHighwayHttpOperation(
|
||||
);
|
||||
body = await httpPostFrame(
|
||||
worker.socket,
|
||||
session.servers[worker.serverIndex]!.host,
|
||||
servers[worker.serverIndex]!.host,
|
||||
pathStr,
|
||||
packHighwayFrame(head, chunk),
|
||||
signal,
|
||||
timeouts.idleMs,
|
||||
);
|
||||
} catch (error) {
|
||||
signal.throwIfAborted();
|
||||
@@ -919,9 +959,10 @@ async function uploadHighwayHttpOperation(
|
||||
}
|
||||
|
||||
dropSocket(worker);
|
||||
history.record(commandId, servers[worker.serverIndex]!, false);
|
||||
transportAttempts += 1;
|
||||
|
||||
if (transportAttempts >= HIGHWAY_MAX_CHUNK_ATTEMPTS) {
|
||||
if (transportAttempts >= maxAttempts) {
|
||||
return fail(
|
||||
'transport_exhausted',
|
||||
new Error(
|
||||
@@ -932,13 +973,13 @@ async function uploadHighwayHttpOperation(
|
||||
}
|
||||
|
||||
retries += 1;
|
||||
worker.serverIndex = (worker.serverIndex + 1) % session.servers.length;
|
||||
worker.serverIndex = (worker.serverIndex + 1) % servers.length;
|
||||
log.trace(
|
||||
'highway_put_branch branch=chunk_retry offset=%d bytes=%d attempt=%d nextServer=%j error=%j',
|
||||
offset,
|
||||
chunkSize,
|
||||
transportAttempts,
|
||||
session.servers[worker.serverIndex],
|
||||
servers[worker.serverIndex],
|
||||
highwayErrorText(error),
|
||||
);
|
||||
await sleepMs(HIGHWAY_RETRY_BASE_MS * transportAttempts, signal);
|
||||
@@ -991,7 +1032,7 @@ async function uploadHighwayHttpOperation(
|
||||
effectiveConcurrency = 1;
|
||||
}
|
||||
|
||||
worker.serverIndex = (worker.serverIndex + 1) % session.servers.length;
|
||||
worker.serverIndex = (worker.serverIndex + 1) % servers.length;
|
||||
const delayMs = HIGHWAY_DELAY_RETRY_MS;
|
||||
log.trace(
|
||||
'highway_put_branch branch=chunk_delay_retry offset=%d bytes=%d attempt=%d errorCode=%d delayMs=%d',
|
||||
@@ -1029,6 +1070,7 @@ async function uploadHighwayHttpOperation(
|
||||
);
|
||||
}
|
||||
|
||||
history.record(commandId, servers[worker.serverIndex]!, true);
|
||||
break;
|
||||
} finally {
|
||||
activeRequests -= 1;
|
||||
@@ -1063,13 +1105,30 @@ async function uploadHighwayHttpOperation(
|
||||
|
||||
try {
|
||||
try {
|
||||
timeouts = highwayUploadTimeouts();
|
||||
concurrency = validateUploadConcurrency(
|
||||
options.concurrency === undefined ? 1 : options.concurrency,
|
||||
);
|
||||
} catch (error) {
|
||||
fail('invalid_options', error);
|
||||
return fail('invalid_options', error);
|
||||
}
|
||||
|
||||
deadlineTimer = setTimeout(() => {
|
||||
abortUpload(
|
||||
'upload_timeout',
|
||||
new Error(
|
||||
`highway upload timed out after ${timeouts.totalMs}ms (cmdId=${commandId} acknowledgedBytes=${trace.uploadedBytes}/${totalSize})`,
|
||||
),
|
||||
);
|
||||
}, timeouts.totalMs);
|
||||
log.trace(
|
||||
'highway_put_policy idleTimeoutMs=%d totalTimeoutMs=%d maxAttempts=%d servers=%j',
|
||||
timeouts.idleMs,
|
||||
timeouts.totalMs,
|
||||
maxAttempts,
|
||||
servers,
|
||||
);
|
||||
|
||||
const pieces = Math.ceil(totalSize / HIGHWAY_BLOCK_SIZE);
|
||||
// The final piece commits the file only after every preceding piece is
|
||||
// acknowledged. One/two-piece files therefore need just one connection.
|
||||
@@ -1142,6 +1201,7 @@ async function uploadHighwayHttpOperation(
|
||||
Date.now() - trace.startedAt,
|
||||
);
|
||||
} finally {
|
||||
clearTimeout(deadlineTimer);
|
||||
abort.abort(new Error('highway upload stopped'));
|
||||
|
||||
for (const worker of workers) {
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
type MediaSubFileUpload,
|
||||
} from './pipeline';
|
||||
import { computeHashes, detectImageFormat, loadBinarySource } from './utils';
|
||||
import { ntImageUrlFromMsgInfo } from '../msg-push/helpers';
|
||||
|
||||
const moduleLog = createLogger('Highway.Image');
|
||||
|
||||
@@ -208,8 +209,16 @@ export async function uploadImageMsgInfo(
|
||||
});
|
||||
|
||||
const encoded = finalizeMediaMsgInfo(upload, pic);
|
||||
const imageUrl = ntImageUrlFromMsgInfo(upload.msgInfo?.msgInfoBody?.[0], isGroup);
|
||||
|
||||
if (!imageUrl) {
|
||||
throw new Error('image upload response is missing a download reference');
|
||||
}
|
||||
|
||||
// Retain successful upload metadata for the caller's self-sent history.
|
||||
Object.assign(element, {
|
||||
imageUrl,
|
||||
fileId: image.fileName,
|
||||
md5Hex: image.md5Hex,
|
||||
sha1Hex: image.sha1Hex,
|
||||
fileSize: image.fileSize,
|
||||
|
||||
@@ -310,6 +310,7 @@ export async function uploadPtt(
|
||||
fileName: ptt.fileName,
|
||||
duration: ptt.duration,
|
||||
voiceFormat: ptt.voiceFormat,
|
||||
isNtv2: true,
|
||||
fileId: mediaNode?.fileUuid,
|
||||
mediaNode,
|
||||
});
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
import type { HighwayServer } from './highway-client';
|
||||
|
||||
const SUCCESS_TTL_MS = 5 * 60_000;
|
||||
const FAILURE_TTL_MS = 30_000;
|
||||
const MAX_OBSERVATIONS = 128;
|
||||
|
||||
interface Observation {
|
||||
succeeded: boolean;
|
||||
expiresAt: number;
|
||||
}
|
||||
|
||||
/** Short-lived scheduling evidence, never credentials or additional upload destinations. */
|
||||
export class UploadNodeHistory {
|
||||
private readonly observations = new Map<string, Observation>();
|
||||
|
||||
private key(commandId: number, server: HighwayServer): string {
|
||||
return JSON.stringify([commandId, server.host, server.port]);
|
||||
}
|
||||
|
||||
private prune(now: number): void {
|
||||
for (const [key, observation] of this.observations) {
|
||||
if (observation.expiresAt <= now) {
|
||||
this.observations.delete(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
order(commandId: number, candidates: readonly HighwayServer[]): HighwayServer[] {
|
||||
this.prune(Date.now());
|
||||
const unique = new Map(candidates.map((server) => [this.key(commandId, server), server]));
|
||||
|
||||
const rank = (server: HighwayServer): number => {
|
||||
const observation = this.observations.get(this.key(commandId, server));
|
||||
return observation ? (observation.succeeded ? 0 : 2) : 1;
|
||||
};
|
||||
|
||||
// Stable ties retain server-provided order. Failed endpoints remain eligible:
|
||||
// a temporary observation must not permanently exclude the only working node.
|
||||
return [...unique.values()].sort((a, b) => rank(a) - rank(b));
|
||||
}
|
||||
|
||||
record(commandId: number, server: HighwayServer, succeeded: boolean): void {
|
||||
const now = Date.now();
|
||||
this.prune(now);
|
||||
const key = this.key(commandId, server);
|
||||
this.observations.delete(key);
|
||||
this.observations.set(key, {
|
||||
succeeded,
|
||||
expiresAt: now + (succeeded ? SUCCESS_TTL_MS : FAILURE_TTL_MS),
|
||||
});
|
||||
|
||||
if (this.observations.size > MAX_OBSERVATIONS) {
|
||||
const oldest = this.observations.keys().next();
|
||||
|
||||
if (!oldest.done) {
|
||||
this.observations.delete(oldest.value);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// IdentityService belongs to one account's Bridge. Weak ownership also releases
|
||||
// observations when that account session is discarded, without a global UIN registry.
|
||||
const histories = new WeakMap<
|
||||
BridgeContext['identity'],
|
||||
{ uin: string; history: UploadNodeHistory }
|
||||
>();
|
||||
|
||||
export function uploadNodeHistory(identity: BridgeContext['identity']): UploadNodeHistory {
|
||||
let entry = histories.get(identity);
|
||||
|
||||
if (!entry || entry.uin !== identity.uin) {
|
||||
entry = { uin: identity.uin, history: new UploadNodeHistory() };
|
||||
histories.set(identity, entry);
|
||||
}
|
||||
|
||||
return entry.history;
|
||||
}
|
||||
@@ -1,6 +1,36 @@
|
||||
/** Deployment-wide policy. Each video snapshots it before preparing its bytes. */
|
||||
let videoUploadConcurrency = 1;
|
||||
|
||||
export interface HighwayUploadTimeouts {
|
||||
idleMs: number;
|
||||
totalMs: number;
|
||||
}
|
||||
|
||||
/** Snapshot once per file; a deployment change must not alter an in-flight upload. */
|
||||
export function highwayUploadTimeouts(env: NodeJS.ProcessEnv = process.env): HighwayUploadTimeouts {
|
||||
const read = (name: string, defaultMs: number): number => {
|
||||
const raw = env[name];
|
||||
|
||||
if (raw === undefined) {
|
||||
return defaultMs;
|
||||
}
|
||||
|
||||
const value = raw.trim();
|
||||
const parsed = /^[1-9]\d*$/.test(value) ? Number(value) : Number.NaN;
|
||||
|
||||
if (!Number.isSafeInteger(parsed) || parsed > 2_147_483_647) {
|
||||
throw new RangeError(`${name} must be an integer from 1 to 2147483647 milliseconds`);
|
||||
}
|
||||
|
||||
return parsed;
|
||||
};
|
||||
|
||||
return {
|
||||
idleMs: read('SNOWLUMA_HIGHWAY_UPLOAD_IDLE_TIMEOUT_MS', 30_000),
|
||||
totalMs: read('SNOWLUMA_HIGHWAY_UPLOAD_TIMEOUT_MS', 30 * 60_000),
|
||||
};
|
||||
}
|
||||
|
||||
export function validateUploadConcurrency(value: unknown): number {
|
||||
if (typeof value !== 'number' || !Number.isInteger(value) || value < 1 || value > 4) {
|
||||
throw new RangeError('videoUploadConcurrency must be an integer from 1 to 4');
|
||||
|
||||
@@ -2,6 +2,7 @@ import { SqliteDatabase } from '@snowluma/sqlite';
|
||||
import path from 'path';
|
||||
|
||||
import { createLogger, type Logger } from '@snowluma/common/logger';
|
||||
import { isBinaryCardText } from './group-member-card';
|
||||
import type {
|
||||
FriendInfo,
|
||||
GroupMemberInfo,
|
||||
@@ -390,7 +391,7 @@ export class IdentityService {
|
||||
}
|
||||
|
||||
this.assertPersistenceCapacity('group member update');
|
||||
const observed = { ...member };
|
||||
const observed = this.retainGroupMemberCard(groupId, member);
|
||||
const persisted: MemberInput = { groupId, ...observed, active: true };
|
||||
g.members.set(observed.uin, observed);
|
||||
this.rememberUidUin(observed.uid, observed.uin);
|
||||
@@ -779,7 +780,8 @@ export class IdentityService {
|
||||
});
|
||||
}
|
||||
|
||||
rememberGroupMembers(groupId: number, members: GroupMemberInfo[]): void {
|
||||
/** Returns the refreshed roster with previously known cards retained when unreadable. */
|
||||
rememberGroupMembers(groupId: number, members: GroupMemberInfo[]): GroupMemberInfo[] {
|
||||
this.beginObservation('group members');
|
||||
|
||||
if (!this.loaded_) {
|
||||
@@ -789,7 +791,7 @@ export class IdentityService {
|
||||
});
|
||||
}
|
||||
|
||||
const observed = members.map((member) => ({ ...member }));
|
||||
const observed = members.map((member) => this.retainGroupMemberCard(groupId, member));
|
||||
const persisted = observed.map((member): MemberInput => ({
|
||||
groupId,
|
||||
...member,
|
||||
@@ -815,6 +817,7 @@ export class IdentityService {
|
||||
}
|
||||
}),
|
||||
);
|
||||
return observed;
|
||||
}
|
||||
|
||||
rememberUserProfile(info: UserProfileInfo): void {
|
||||
@@ -1119,6 +1122,16 @@ export class IdentityService {
|
||||
}
|
||||
}
|
||||
|
||||
private retainGroupMemberCard(groupId: number, member: GroupMemberInfo): GroupMemberInfo {
|
||||
const previous = this.findGroupMember(groupId, member.uin)?.card;
|
||||
return {
|
||||
...member,
|
||||
card:
|
||||
member.card ??
|
||||
(previous !== undefined && !isBinaryCardText(previous) ? previous : undefined),
|
||||
};
|
||||
}
|
||||
|
||||
private setGroupMembersInMemory(groupId: number, members: GroupMemberInfo[]): void {
|
||||
const g = this.groups_.get(groupId);
|
||||
|
||||
@@ -1181,6 +1194,7 @@ export class IdentityService {
|
||||
uin INTEGER,
|
||||
nickname TEXT NOT NULL DEFAULT '',
|
||||
card TEXT NOT NULL DEFAULT '',
|
||||
card_known INTEGER NOT NULL DEFAULT 1,
|
||||
role TEXT NOT NULL DEFAULT 'member',
|
||||
level INTEGER NOT NULL DEFAULT 0,
|
||||
title TEXT NOT NULL DEFAULT '',
|
||||
@@ -1207,12 +1221,17 @@ export class IdentityService {
|
||||
'PRAGMA table_info(group_members)',
|
||||
).all()) as Array<{ name: string }>;
|
||||
|
||||
if (columns.some((column) => column.name === 'is_robot')) {
|
||||
return;
|
||||
if (!columns.some((column) => column.name === 'is_robot')) {
|
||||
await this.db!.exec('ALTER TABLE group_members ADD COLUMN is_robot INTEGER');
|
||||
this.log.info('identity schema migrated: added group_members.is_robot');
|
||||
}
|
||||
|
||||
await this.db!.exec('ALTER TABLE group_members ADD COLUMN is_robot INTEGER');
|
||||
this.log.info('identity schema migrated: added group_members.is_robot');
|
||||
if (!columns.some((column) => column.name === 'card_known')) {
|
||||
await this.db!.exec(
|
||||
'ALTER TABLE group_members ADD COLUMN card_known INTEGER NOT NULL DEFAULT 1',
|
||||
);
|
||||
this.log.info('identity schema migrated: added group_members.card_known');
|
||||
}
|
||||
}
|
||||
|
||||
private async loadSnapshot(): Promise<void> {
|
||||
@@ -1307,7 +1326,8 @@ export class IdentityService {
|
||||
}
|
||||
|
||||
const select = this.db!.prepare(
|
||||
`SELECT group_id, uid, uin, nickname, card, role, level, title,
|
||||
`SELECT group_id, uid, uin, nickname,
|
||||
CASE WHEN card_known = 1 AND instr(card, char(0)) = 0 THEN card END AS card, role, level, title,
|
||||
join_time, last_sent_time, shut_up_time, is_robot
|
||||
FROM group_members
|
||||
WHERE group_id = ? AND active = 1`,
|
||||
@@ -1319,7 +1339,7 @@ export class IdentityService {
|
||||
uid: string | null;
|
||||
uin: number | null;
|
||||
nickname: string;
|
||||
card: string;
|
||||
card: string | null;
|
||||
role: string;
|
||||
level: number;
|
||||
title: string;
|
||||
@@ -1329,6 +1349,16 @@ export class IdentityService {
|
||||
is_robot: number | null;
|
||||
}>;
|
||||
const members = rows.map(rowToMemberInfo);
|
||||
const staleCards = members.filter((member) => member.card === undefined).length;
|
||||
|
||||
if (staleCards > 0) {
|
||||
this.log.warn(
|
||||
'cached member cards require refresh: group=%d count=%d',
|
||||
groupId,
|
||||
staleCards,
|
||||
);
|
||||
}
|
||||
|
||||
this.setGroupMembersInMemory(groupId, members);
|
||||
|
||||
for (const m of members) {
|
||||
@@ -1459,7 +1489,6 @@ export class IdentityService {
|
||||
uid: uid || primary?.uid || null,
|
||||
uin: uin ?? primary?.uin ?? null,
|
||||
nickname: mergeOptionalText(input.nickname, primary?.nickname ?? ''),
|
||||
card: mergeOptionalText(input.card, primary?.card ?? ''),
|
||||
role: mergeOptionalText(input.role, primary?.role ?? 'member'),
|
||||
level: normalizeNonNegative(input.level, primary?.level ?? 0),
|
||||
title: mergeOptionalText(input.title, primary?.title ?? ''),
|
||||
@@ -1479,14 +1508,15 @@ export class IdentityService {
|
||||
|
||||
await this.db!.prepare(
|
||||
`UPDATE group_members
|
||||
SET uid = ?, uin = ?, nickname = ?, card = ?, role = ?, level = ?, title = ?,
|
||||
join_time = ?, last_sent_time = ?, shut_up_time = ?, is_robot = ?, active = ?, updated_at = ?
|
||||
SET uid = ?, uin = ?, nickname = ?, card = COALESCE(?, card), role = ?, level = ?, title = ?,
|
||||
join_time = ?, last_sent_time = ?, shut_up_time = ?, is_robot = ?, active = ?, updated_at = ?,
|
||||
card_known = CASE WHEN ? IS NULL THEN card_known ELSE 1 END
|
||||
WHERE id = ?`,
|
||||
).run(
|
||||
merged.uid,
|
||||
merged.uin,
|
||||
merged.nickname,
|
||||
merged.card,
|
||||
input.card ?? null,
|
||||
merged.role,
|
||||
merged.level,
|
||||
merged.title,
|
||||
@@ -1496,6 +1526,7 @@ export class IdentityService {
|
||||
merged.isRobot,
|
||||
merged.active,
|
||||
merged.updatedAt,
|
||||
input.card ?? null,
|
||||
primary.id,
|
||||
);
|
||||
return;
|
||||
@@ -1504,14 +1535,14 @@ export class IdentityService {
|
||||
await this.db!.prepare(
|
||||
`INSERT INTO group_members
|
||||
(group_id, uid, uin, nickname, card, role, level, title,
|
||||
join_time, last_sent_time, shut_up_time, is_robot, active, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
join_time, last_sent_time, shut_up_time, is_robot, active, updated_at, card_known)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
).run(
|
||||
input.groupId,
|
||||
merged.uid,
|
||||
merged.uin,
|
||||
merged.nickname,
|
||||
merged.card,
|
||||
input.card ?? '',
|
||||
merged.role,
|
||||
merged.level,
|
||||
merged.title,
|
||||
@@ -1521,6 +1552,7 @@ export class IdentityService {
|
||||
merged.isRobot,
|
||||
merged.active,
|
||||
merged.updatedAt,
|
||||
input.card === undefined ? 0 : 1,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1879,7 +1911,7 @@ function rowToMemberInfo(row: {
|
||||
uid: string | null;
|
||||
uin: number | null;
|
||||
nickname: string;
|
||||
card: string;
|
||||
card: string | null;
|
||||
role: string;
|
||||
level: number;
|
||||
title: string;
|
||||
@@ -1892,7 +1924,7 @@ function rowToMemberInfo(row: {
|
||||
uid: row.uid ?? '',
|
||||
uin: row.uin ?? 0,
|
||||
nickname: row.nickname,
|
||||
card: row.card,
|
||||
card: row.card !== null && !isBinaryCardText(row.card) ? row.card : undefined,
|
||||
role: row.role || 'member',
|
||||
level: row.level,
|
||||
title: row.title,
|
||||
|
||||
@@ -21,6 +21,7 @@ export interface MsgPushHead {
|
||||
readonly c2cCmd: number;
|
||||
/** Sender-local C2C client sequence (field 5), or the group sequence. */
|
||||
readonly sequence: number;
|
||||
readonly autoReply?: true;
|
||||
/** Bidirectional C2C sequence (field 11); zero on groups/legacy packets. */
|
||||
readonly ntMsgSeq: number;
|
||||
readonly timestamp: number;
|
||||
@@ -94,6 +95,7 @@ export function buildContextFromMessage(
|
||||
subType: msg.contentHead.subType ?? 0,
|
||||
c2cCmd: msg.contentHead.c2cCmd ?? 0,
|
||||
sequence: msg.contentHead.sequence ?? 0,
|
||||
autoReply: msg.contentHead.autoReply ? true : undefined,
|
||||
ntMsgSeq: msg.contentHead.ntMsgSeq ?? 0,
|
||||
timestamp: msg.contentHead.timestamp ?? 0,
|
||||
msgId: msg.contentHead.msgId ?? 0,
|
||||
|
||||
@@ -80,6 +80,7 @@ export const decodeFriendMessage: MsgPushDecoder = (ctx) => {
|
||||
|
||||
const ev: FriendMessage = {
|
||||
kind: 'friend_message',
|
||||
autoReply: ctx.head.autoReply,
|
||||
time: ctx.head.timestamp,
|
||||
selfUin: ctx.selfUin,
|
||||
senderUin: ctx.fromUin,
|
||||
|
||||
@@ -1,9 +1,17 @@
|
||||
import { protobuf_decode } from '@snowluma/proton';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type { GroupMemberJoin, GroupMemberLeave } from '../../events';
|
||||
import type { GroupChange, SelfJoinInGroup } from '@snowluma/proto-defs/notify';
|
||||
import { decodeGroupChangeOperatorUid, decodeNestedOperatorUid, resolveUidToUin } from '../helpers';
|
||||
import {
|
||||
decodeGroupChangeOperatorUid,
|
||||
decodeNestedOperatorUid,
|
||||
decodeRawOperatorUid,
|
||||
resolveUidToUin,
|
||||
} from '../helpers';
|
||||
import type { MsgPushDecoder } from '../registry';
|
||||
|
||||
const log = createLogger('MsgPush.GroupJoin');
|
||||
|
||||
function joinTypeFromOperationType(raw: number): NonNullable<GroupMemberJoin['joinType']> {
|
||||
// QQ uses bit 0x80 as a flag on the PkgType=33 operation code. Clear only
|
||||
// that bit: other high bits remain significant in the native handler. The
|
||||
@@ -26,6 +34,22 @@ export const decodeGroupMemberJoin: MsgPushDecoder = (ctx) => {
|
||||
change.operatorBytes ?? new Uint8Array(0),
|
||||
'group member increase',
|
||||
);
|
||||
const operation = (change.decreaseType ?? 0) - ((change.decreaseType ?? 0) & 0x80);
|
||||
const origin = ctx.responseHead?.grp?.messageKey?.joinExtra?.origin;
|
||||
// QQ consumes this independent origin only for operation 2. Type 1
|
||||
// identifies a QR-code sharer; neither that person nor the approving
|
||||
// operator is evidence of an invitation.
|
||||
const invitorUid =
|
||||
operation === 2 && origin?.type !== 1 && origin?.uid?.length
|
||||
? decodeRawOperatorUid(origin.uid, 'group member invitation origin')
|
||||
: '';
|
||||
log.trace(
|
||||
'join identity: group=%d operation=%d originType=%s inviterProvided=%s',
|
||||
groupId,
|
||||
operation,
|
||||
origin?.type === undefined ? 'absent' : String(origin.type),
|
||||
Boolean(invitorUid),
|
||||
);
|
||||
const ev: GroupMemberJoin = {
|
||||
kind: 'group_member_join',
|
||||
time: ctx.head.timestamp,
|
||||
@@ -35,6 +59,9 @@ export const decodeGroupMemberJoin: MsgPushDecoder = (ctx) => {
|
||||
operatorUin: resolveUidToUin(ctx.identity, groupId, operatorUid),
|
||||
userUid,
|
||||
operatorUid,
|
||||
...(invitorUid
|
||||
? { invitorUid, invitorUin: resolveUidToUin(ctx.identity, groupId, invitorUid) }
|
||||
: {}),
|
||||
joinType: joinTypeFromOperationType(change.decreaseType ?? 0),
|
||||
};
|
||||
return [ev];
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { GroupMessage } from '../../events';
|
||||
import { decodeGroupDisplayName } from '../../group-member-card';
|
||||
import type { MsgPushDecoder } from '../registry';
|
||||
import { decodeRichBody } from '../rich-body-decoder';
|
||||
|
||||
@@ -18,38 +19,27 @@ export const decodeGroupMessage: MsgPushDecoder = (ctx) => {
|
||||
senderRole: '',
|
||||
};
|
||||
const grp = ctx.responseHead?.grp;
|
||||
const displayName = decodeGroupDisplayName(grp);
|
||||
const isNickname = grp?.memberCardType === 2;
|
||||
|
||||
if (grp) {
|
||||
ev.groupId = grp.groupUin ?? 0;
|
||||
// Sender name priority (#201): the group-history fetch fills `memberName`
|
||||
// (field 2); the local member cache gives a clean nickname/card split; and
|
||||
// live pushes + merged-forward nodes carry the display name in `memberCard`
|
||||
// (field 4). Prefer the explicit field-2 name, then the cache, then field 4
|
||||
// — the last is what lets a forward node from a group the bot isn't in keep
|
||||
// its per-node sender name without a member-list lookup.
|
||||
ev.senderNick = grp.memberName ?? '';
|
||||
}
|
||||
|
||||
ev.groupId = grp?.groupUin ?? 0;
|
||||
const member = ctx.identity.findGroupMember(ev.groupId, ctx.fromUin);
|
||||
// History supplies an explicit nickname. Live type 2 is also a nickname;
|
||||
// a card from an unknown group doubles as a forward node's display name (#201).
|
||||
ev.senderNick =
|
||||
grp?.memberName ||
|
||||
(isNickname ? displayName : undefined) ||
|
||||
(member ? member.nickname : displayName) ||
|
||||
'';
|
||||
|
||||
if (member) {
|
||||
if (!ev.senderNick) {
|
||||
ev.senderNick = member.nickname;
|
||||
}
|
||||
|
||||
ev.senderCard = member.card;
|
||||
ev.senderCard = member.card ?? '';
|
||||
ev.senderRole = member.role;
|
||||
|
||||
// [#1] field 4 (memberCard) is the sender's CURRENT display name (group card
|
||||
// if set, else base nickname). When it differs from the base nickname it's an
|
||||
// up-to-date group card — fresher than the cache, which nothing refreshes on
|
||||
// a card change (no push; a quiet group can freeze at warmup for months).
|
||||
// Prefer it. (Self-healed back into the cache in packet-pipeline side effects.)
|
||||
if (grp?.memberCard && grp.memberCard !== ev.senderNick) {
|
||||
ev.senderCard = grp.memberCard;
|
||||
// A fresh card supersedes the cache, which can otherwise survive a rename (#1).
|
||||
if (!isNickname && displayName !== undefined && displayName !== ev.senderNick) {
|
||||
ev.senderCard = displayName;
|
||||
}
|
||||
} else if (!ev.senderNick && grp?.memberCard) {
|
||||
ev.senderNick = grp.memberCard;
|
||||
}
|
||||
|
||||
// Group name: prefer the message's own wire field (ResponseGrp field 7 —
|
||||
|
||||
@@ -6,6 +6,7 @@ export const decodeTempMessage: MsgPushDecoder = (ctx) => {
|
||||
const sequenceAuthoritative = ctx.head.ntMsgSeq > 0;
|
||||
const ev: TempMessage = {
|
||||
kind: 'temp_message',
|
||||
autoReply: ctx.head.autoReply,
|
||||
time: ctx.head.timestamp,
|
||||
selfUin: ctx.selfUin,
|
||||
senderUin: ctx.fromUin,
|
||||
|
||||
@@ -3,6 +3,7 @@ import { hexPreview } from '@snowluma/common/hex';
|
||||
import { inflateSync } from 'zlib';
|
||||
import type { IdentityService } from '../identity-service';
|
||||
import type { OperatorInfo } from '@snowluma/proto-defs/notify';
|
||||
import type { MsgInfoBody } from '@snowluma/proto-defs/element';
|
||||
|
||||
export const MAX_RICH_CARD_OUTPUT_BYTES = 4 * 1024 * 1024;
|
||||
export const MAX_RICH_CARD_MESSAGE_OUTPUT_BYTES = 8 * 1024 * 1024;
|
||||
@@ -51,6 +52,16 @@ export function ntImageUrlFromFileId(fileId: string, isGroup: boolean): string {
|
||||
return `https://multimedia.nt.qq.com.cn/download?appid=${appid}&fileid=${encodeURIComponent(fileId)}`;
|
||||
}
|
||||
|
||||
/** Upload receipts and received messages carry the same NT image reference. */
|
||||
export function ntImageUrlFromMsgInfo(body: MsgInfoBody | undefined, isGroup: boolean): string {
|
||||
if (body?.picture?.urlPath) {
|
||||
const { domain, urlPath, ext } = body.picture;
|
||||
return `https://${domain ?? 'multimedia.nt.qq.com.cn'}${urlPath}${ext?.originalParameter ?? ''}`;
|
||||
}
|
||||
|
||||
return ntImageUrlFromFileId(body?.index?.fileUuid ?? '', isGroup);
|
||||
}
|
||||
|
||||
export function decompressData(
|
||||
data: Uint8Array,
|
||||
maxOutputBytes = MAX_RICH_CARD_OUTPUT_BYTES,
|
||||
|
||||
Loaded 100 of 146 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user