refactor(packages): rename @snowluma/bridge → @snowluma/protocol

The package previously named "bridge" houses the protocol-byte layer
(OIDB cmds, msg-push decoders, highway uploaders, element-builder,
event bus). The name "bridge" suggested transport/lifecycle, which it
isn't — that role lives in core/hook and core/bridge/manager. Rename
to match what's actually inside.

This is a pure rename: zero logic changes, all 73 import sites updated
mechanically and TS-verified. core/onebot dependencies key updated.
ESLint override path adjusted for the moved oidb-services directory.

Rename detection threshold: git log --find-renames=20% recommended
when following history across this commit — content-replacement
(@snowluma/bridge → @snowluma/protocol) dropped per-file similarity
below git's default 50% on import-heavy files.
This commit is contained in:
DrSmoothl committed 2026-05-23 23:31:03 +08:00
1 parent 98296fcec5
commit c16064d7e3
238 files changed
+247 -284

No files matched your search

@@ -0,0 +1,123 @@
// Receive-side decode for `com.tencent.multimsg` LightApp — verifies
// the inverse of element-builder.makeForwardElem so a forward sent by
// SnowLuma (or any QQ-NT / Lagrange / NapCat client) round-trips
// back to `{type: 'forward', resId, forwardUuid}` on the receiver.
//
// Without this the receiver-side decoder sees `lightApp` and falls
// back to a generic `{type: 'json', text: <json>}` element, which
// means the OneBot layer can't surface a forward bubble OR walk into
// the nested forward via fetch(resId).
import { describe, expect, it } from 'vitest';
import { deflateSync } from 'zlib';
import { decodeRichBody } from '../../src/msg-push/rich-body-decoder';
import type { MessageBody } from '@snowluma/proto-defs/message';
function lightAppBytes(json: unknown): Uint8Array {
const buf = deflateSync(Buffer.from(JSON.stringify(json), 'utf8'));
const out = new Uint8Array(buf.length + 1);
out[0] = 0x01; // deflate prefix
out.set(buf, 1);
return out;
}
describe('decodeRichBody / forward LightApp', () => {
it('emits {type:"forward", resId, forwardUuid} for com.tencent.multimsg', () => {
const body: MessageBody = {
richText: {
elems: [
{
lightApp: {
data: lightAppBytes({
app: 'com.tencent.multimsg',
meta: { detail: { resid: 'inner-res-1', uniseq: 'uuid-1' } },
}),
},
} as any,
],
},
};
const out = decodeRichBody(body, true);
expect(out).toEqual([{ type: 'forward', resId: 'inner-res-1', forwardUuid: 'uuid-1' }]);
});
it('omits forwardUuid when the sender did not set uniseq (XML-era forwards)', () => {
const body: MessageBody = {
richText: {
elems: [
{
lightApp: {
data: lightAppBytes({
app: 'com.tencent.multimsg',
meta: { detail: { resid: 'only-resid' } },
}),
},
} as any,
],
},
};
const out = decodeRichBody(body, true);
expect(out).toEqual([{ type: 'forward', resId: 'only-resid' }]);
});
it('falls back to {type:"json"} for non-multimsg LightApp (e.g. mini-app card)', () => {
const body: MessageBody = {
richText: {
elems: [
{
lightApp: {
data: lightAppBytes({ app: 'com.tencent.miniapp_01', meta: {} }),
},
} as any,
],
},
};
const out = decodeRichBody(body, true);
expect(out).toHaveLength(1);
expect(out[0]!.type).toBe('json');
expect(typeof (out[0] as any).text).toBe('string');
});
it('falls back to {type:"json"} when com.tencent.multimsg is missing resid (malformed)', () => {
const body: MessageBody = {
richText: {
elems: [
{
lightApp: {
data: lightAppBytes({
app: 'com.tencent.multimsg',
meta: { detail: {} },
}),
},
} as any,
],
},
};
const out = decodeRichBody(body, true);
expect(out).toHaveLength(1);
expect(out[0]!.type).toBe('json');
});
it('still decodes the legacy richMsg serviceID=35 path (backward compat with mobile QQ)', () => {
// Older clients (and some bridges) still emit the m_resid XML
// shape. The decoder must keep treating it as a forward element
// so SnowLuma can fetch the resid downstream.
const xml = '<?xml version="1.0"?><msg m_resid="legacy-res" />';
const xmlBuf = new Uint8Array(xml.length + 1);
xmlBuf[0] = 0x00;
xmlBuf.set(new TextEncoder().encode(xml), 1);
const body: MessageBody = {
richText: {
elems: [
{
richMsg: { serviceId: 35, template1: xmlBuf },
} as any,
],
},
};
const out = decodeRichBody(body, true);
expect(out).toHaveLength(1);
expect(out[0]).toMatchObject({ type: 'forward', resId: 'legacy-res' });
});
});
@@ -0,0 +1,291 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase, OidbEmpty } from '@snowluma/proto-defs/oidb';
import type { OidbGroupReaction } from '@snowluma/proto-defs/oidb-actions/base';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import {
buildOidbRequest,
invokeOidb,
OidbError,
parseOidbResponse,
type OidbCallSpec,
type OidbSender,
} from '../src/oidb-service';
// Reused minimal spec — encodes a group-reaction-shaped request and
// reads back a void result. Exercises every spec branch.
const reactionSpec: OidbCallSpec<
OidbSender, OidbGroupReaction, OidbEmpty,
{ groupId: number; sequence: number; code: string; isSet: boolean }, void
> = {
command: 0x9082,
resolveSubCommand: p => p.isSet ? 1 : 2,
serialize: (_ctx, p) => ({
groupUin: p.groupId,
sequence: p.sequence,
code: p.code,
type: p.code.length > 3 ? 2 : 1,
field6: false,
field7: false,
}),
deserialize: () => {},
encode: env => protobuf_encode<OidbBase<OidbGroupReaction>>(env),
decode: bytes => protobuf_decode<OidbBase<OidbEmpty>>(bytes),
};
// Static-subCommand variant for the branch test.
const staticSubSpec: OidbCallSpec<OidbSender, OidbGroupReaction, OidbEmpty, { groupId: number }, void> = {
command: 0xEAC,
subCommand: 1,
serialize: (_ctx, p) => ({ groupUin: p.groupId, sequence: 0, code: '', type: 1, field6: false, field7: false }),
deserialize: () => {},
encode: env => protobuf_encode<OidbBase<OidbGroupReaction>>(env),
decode: bytes => protobuf_decode<OidbBase<OidbEmpty>>(bytes),
};
function makeSender(resp: Partial<SendPacketResult> = {}): OidbSender & { sendRawPacket: ReturnType<typeof vi.fn> } {
const defaultResp: SendPacketResult = {
success: true, gotResponse: true, errorCode: 0, errorMessage: '',
responseData: Buffer.alloc(0),
};
return {
sendRawPacket: vi.fn(async () => ({ ...defaultResp, ...resp })),
};
}
describe('invokeOidb', () => {
it('uses resolveSubCommand when present and computes the wire name', async () => {
const sender = makeSender();
await invokeOidb(sender, reactionSpec, { groupId: 12345, sequence: 99, code: '76', isSet: true });
expect(sender.sendRawPacket).toHaveBeenCalledOnce();
const [wireName] = sender.sendRawPacket.mock.calls[0]!;
expect(wireName).toBe('OidbSvcTrpcTcp.0x9082_1');
});
it('flips wire name when resolveSubCommand returns a different subcmd', async () => {
const sender = makeSender();
await invokeOidb(sender, reactionSpec, { groupId: 1, sequence: 1, code: '76', isSet: false });
const [wireName] = sender.sendRawPacket.mock.calls[0]!;
expect(wireName).toBe('OidbSvcTrpcTcp.0x9082_2');
});
it('uses static subCommand when resolveSubCommand is absent', async () => {
const sender = makeSender();
await invokeOidb(sender, staticSubSpec, { groupId: 12345 });
const [wireName] = sender.sendRawPacket.mock.calls[0]!;
expect(wireName).toBe('OidbSvcTrpcTcp.0xeac_1');
});
it('encodes serialize() output into an OIDB envelope (cmd + subcmd land in fields 1/2)', async () => {
const sender = makeSender();
await invokeOidb(sender, reactionSpec, { groupId: 12345, sequence: 99, code: '76', isSet: true });
const [, bytes] = sender.sendRawPacket.mock.calls[0]!;
const env = protobuf_decode<OidbBase<OidbGroupReaction>>(bytes);
expect(env.command).toBe(0x9082);
expect(env.subCommand).toBe(1);
expect(env.body).toMatchObject({
groupUin: 12345, sequence: 99, code: '76', type: 1,
});
});
it('passes the body through deserialize for transformation', async () => {
type Echo = { tag: number };
const spec: OidbCallSpec<OidbSender, OidbGroupReaction, OidbGroupReaction, { code: string }, Echo> = {
command: 0x9082,
subCommand: 1,
serialize: (_ctx, p) => ({ code: p.code }),
deserialize: (_ctx, b) => ({ tag: b.type ?? 99 }),
encode: env => protobuf_encode<OidbBase<OidbGroupReaction>>(env),
decode: bytes => protobuf_decode<OidbBase<OidbGroupReaction>>(bytes),
};
const responseEnvelope = protobuf_encode<OidbBase<OidbGroupReaction>>({
command: 0x9082, subCommand: 1,
body: { type: 5 } as OidbGroupReaction,
});
const sender = makeSender({ responseData: Buffer.from(responseEnvelope) });
const result = await invokeOidb(sender, spec, { code: 'x' });
expect(result).toEqual({ tag: 5 });
});
it('substitutes an empty body when the envelope has no field 4', async () => {
const envBytes = protobuf_encode<OidbBase<OidbEmpty>>({ command: 0x9082, subCommand: 1 });
const sender = makeSender({ responseData: Buffer.from(envBytes) });
const deserialize = vi.fn(() => undefined);
const spec: OidbCallSpec<OidbSender, OidbGroupReaction, OidbEmpty, { code: string }, void> = {
command: 0x9082, subCommand: 1,
serialize: (_ctx, p) => ({ code: p.code }),
deserialize,
encode: env => protobuf_encode<OidbBase<OidbGroupReaction>>(env),
decode: bytes => protobuf_decode<OidbBase<OidbEmpty>>(bytes),
};
await invokeOidb(sender, spec, { code: 'x' });
expect(deserialize).toHaveBeenCalledOnce();
// deserialize now receives (ctx, body) — body is the second arg.
expect(deserialize.mock.calls[0]![1]).toEqual({});
});
it('awaits async serialize before sending', async () => {
// ctx-aware serialize may need to resolve a uid first; invokeOidb
// must await it before encoding the envelope.
const sender = makeSender();
const spec: OidbCallSpec<OidbSender, OidbGroupReaction, OidbEmpty, { code: string }, void> = {
command: 0x9082, subCommand: 1,
serialize: async (_ctx, p) => {
await new Promise(r => setTimeout(r, 5));
return { code: p.code, sequence: 42 };
},
deserialize: () => {},
encode: env => protobuf_encode<OidbBase<OidbGroupReaction>>(env),
decode: bytes => protobuf_decode<OidbBase<OidbEmpty>>(bytes),
};
await invokeOidb(sender, spec, { code: 'async' });
const [, bytes] = sender.sendRawPacket.mock.calls[0]!;
const env = protobuf_decode<OidbBase<OidbGroupReaction>>(bytes);
expect(env.body?.code).toBe('async');
expect(env.body?.sequence).toBe(42);
});
it('threads ctx into serialize so namespaces can read identity / resolve uids in place', async () => {
const sender = makeSender();
// Extend the ctx with an arbitrary capability the spec uses.
type Ctx = OidbSender & { tag: string };
const ctx: Ctx = { ...sender, tag: 'from-ctx' };
const spec: OidbCallSpec<Ctx, OidbGroupReaction, OidbEmpty, { code: string }, void> = {
command: 0x9082, subCommand: 1,
serialize: (c, p) => ({ code: `${c.tag}/${p.code}` }),
deserialize: () => {},
encode: env => protobuf_encode<OidbBase<OidbGroupReaction>>(env),
decode: bytes => protobuf_decode<OidbBase<OidbEmpty>>(bytes),
};
await invokeOidb(ctx, spec, { code: 'x' });
const [, bytes] = sender.sendRawPacket.mock.calls[0]!;
const env = protobuf_decode<OidbBase<OidbGroupReaction>>(bytes);
expect(env.body?.code).toBe('from-ctx/x');
});
it('propagates timeoutMs to sendRawPacket', async () => {
const sender = makeSender();
await invokeOidb(sender, staticSubSpec, { groupId: 1 }, 5000);
expect(sender.sendRawPacket.mock.calls[0]![2]).toBe(5000);
});
it('rethrows the sender errorMessage when success=false', async () => {
const sender = makeSender({ success: false, errorMessage: 'boom' });
await expect(invokeOidb(sender, staticSubSpec, { groupId: 1 })).rejects.toThrow('boom');
});
it('falls back to "packet send failed" when success=false and errorMessage is empty', async () => {
const sender = makeSender({ success: false, errorMessage: '' });
await expect(invokeOidb(sender, staticSubSpec, { groupId: 1 })).rejects.toThrow('packet send failed');
});
it('rethrows when sender returns success=true but gotResponse=false', async () => {
const sender = makeSender({ success: true, gotResponse: false, errorMessage: 'timeout' });
await expect(invokeOidb(sender, staticSubSpec, { groupId: 1 })).rejects.toThrow('timeout');
});
it('falls back to "no response" when gotResponse=false and errorMessage is empty', async () => {
const sender = makeSender({ success: true, gotResponse: false, errorMessage: '' });
await expect(invokeOidb(sender, staticSubSpec, { groupId: 1 })).rejects.toThrow('no response');
});
it('raises OidbError when envelope errorCode != 0', async () => {
const errBytes = protobuf_encode<OidbBase<OidbEmpty>>({
command: 0x9082, subCommand: 1, errorCode: 42, errorMsg: 'no privilege',
});
const sender = makeSender({ responseData: Buffer.from(errBytes) });
let caught: unknown;
try { await invokeOidb(sender, staticSubSpec, { groupId: 1 }); }
catch (e) { caught = e; }
expect(caught).toBeInstanceOf(OidbError);
expect((caught as OidbError).code).toBe(42);
expect((caught as OidbError).serverMsg).toBe('no privilege');
expect((caught as OidbError).command).toBe(0xEAC);
expect((caught as OidbError).subCommand).toBe(1);
expect((caught as OidbError).message).toContain('OIDB error 42');
expect((caught as OidbError).message).toContain('0xeac_1');
});
it('skips OidbError check when response payload is empty', async () => {
const sender = makeSender({ responseData: Buffer.alloc(0) });
await expect(invokeOidb(sender, staticSubSpec, { groupId: 1 })).resolves.toBeUndefined();
});
it('honours uinForm=true by flipping OIDB envelope reserved to 1', async () => {
const spec: OidbCallSpec<OidbSender, OidbGroupReaction, OidbEmpty, { groupId: number }, void> = {
...staticSubSpec,
uinForm: true,
};
const sender = makeSender();
await invokeOidb(sender, spec, { groupId: 1 });
const [, bytes] = sender.sendRawPacket.mock.calls[0]!;
const env = protobuf_decode<OidbBase<OidbGroupReaction>>(bytes);
expect(env.reserved).toBe(1);
});
it('uses uinForm=false by default (envelope reserved=0)', async () => {
const sender = makeSender();
await invokeOidb(sender, staticSubSpec, { groupId: 1 });
const [, bytes] = sender.sendRawPacket.mock.calls[0]!;
const env = protobuf_decode<OidbBase<OidbGroupReaction>>(bytes);
expect(env.reserved ?? 0).toBe(0);
});
});
describe('buildOidbRequest', () => {
it('returns the same wire name + bytes that invokeOidb would send', async () => {
const sender = makeSender();
await invokeOidb(sender, reactionSpec, { groupId: 12345, sequence: 99, code: '128516', isSet: true });
const sentBytes = sender.sendRawPacket.mock.calls[0]![1];
const built = await buildOidbRequest(sender, reactionSpec, { groupId: 12345, sequence: 99, code: '128516', isSet: true });
expect(built.wireName).toBe('OidbSvcTrpcTcp.0x9082_1');
expect(Buffer.from(built.bytes).equals(Buffer.from(sentBytes))).toBe(true);
});
it('uses static subCommand when resolveSubCommand is absent', async () => {
const sender = makeSender();
const built = await buildOidbRequest(sender, staticSubSpec, { groupId: 1 });
expect(built.wireName).toBe('OidbSvcTrpcTcp.0xeac_1');
});
});
describe('parseOidbResponse', () => {
it('decodes wire bytes via spec.decode and runs spec.deserialize on the body', () => {
const sender = makeSender();
const envBytes = protobuf_encode<OidbBase<OidbGroupReaction>>({
command: 0x9082, subCommand: 1, body: { type: 7 } as OidbGroupReaction,
});
type Echo = { type: number };
const spec: OidbCallSpec<OidbSender, OidbGroupReaction, OidbGroupReaction, void, Echo> = {
command: 0x9082, subCommand: 1,
serialize: () => ({} as OidbGroupReaction),
deserialize: (_ctx, b) => ({ type: b.type ?? 0 }),
encode: env => protobuf_encode<OidbBase<OidbGroupReaction>>(env),
decode: bytes => protobuf_decode<OidbBase<OidbGroupReaction>>(bytes),
};
expect(parseOidbResponse(sender, spec, envBytes)).toEqual({ type: 7 });
});
it('substitutes empty body when the envelope lacks one', () => {
const sender = makeSender();
const envBytes = protobuf_encode<OidbBase<OidbEmpty>>({ command: 0x9082, subCommand: 1 });
const deserialize = vi.fn(() => ({ ok: true }));
parseOidbResponse(sender, { ...staticSubSpec, deserialize } as any, envBytes);
// deserialize now receives (ctx, body) — body is the second arg.
expect(deserialize.mock.calls[0]![1]).toEqual({});
});
});
describe('OidbError', () => {
it('formats message with hex cmd and decimal subcmd', () => {
const e = new OidbError(123, 'denied', 0x9084, 2);
expect(e.message).toBe('OIDB error 123 on 0x9084_2: denied');
expect(e.name).toBe('OidbError');
expect(e.code).toBe(123);
expect(e.serverMsg).toBe('denied');
expect(e.command).toBe(0x9084);
expect(e.subCommand).toBe(2);
});
});
@@ -0,0 +1,69 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { NTV2RichMediaReq, NTV2RichMediaResp } from '@snowluma/proto-defs/oidb-actions/media';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { FetchDownloadRkeys } from '../../../src/oidb-services/contacts/fetch-download-rkeys';
function makeSender(body?: NTV2RichMediaResp) {
const responseData = body !== undefined
? Buffer.from(protobuf_encode<OidbBase<NTV2RichMediaResp>>({ body }))
: Buffer.alloc(0);
const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData };
return { sendRawPacket: vi.fn(async () => r) };
}
describe('FetchDownloadRkeys namespace', () => {
it('declares 0x9067_202 with uinForm=true', () => {
expect(FetchDownloadRkeys.command).toBe(0x9067);
expect(FetchDownloadRkeys.subCommand).toBe(202);
expect(FetchDownloadRkeys.uinForm).toBe(true);
});
describe('serialize', () => {
it('requests the (private=10, group=20, fallback=2) image scopes', () => {
const out = FetchDownloadRkeys.serialize({} as any, {});
expect(out.downloadRkey?.types).toEqual([10, 20, 2]);
});
it('packages the fixed reqHead { common, scene, client }', () => {
const out = FetchDownloadRkeys.serialize({} as any, {});
expect(out.reqHead).toEqual({
common: { requestId: 1, command: 202 },
scene: { requestType: 2, businessType: 1, sceneType: 0 },
client: { agentType: 2 },
});
});
});
describe('deserialize', () => {
it('throws when respHead.retCode is non-zero', () => {
expect(() => FetchDownloadRkeys.deserialize({} as any, {
respHead: { retCode: 42, message: 'bad' },
} as any)).toThrow('bad');
});
it('passes through on retCode = 0', () => {
const body = { respHead: { retCode: 0 }, downloadRkey: { rkeys: [] } };
expect(FetchDownloadRkeys.deserialize({} as any, body as any)).toBe(body);
});
it('falls back to a generic message when none is provided', () => {
expect(() => FetchDownloadRkeys.deserialize({} as any, {
respHead: { retCode: 1 },
} as any)).toThrow('fetch download rkey failed');
});
});
describe('invoke (e2e)', () => {
it('routes to OidbSvcTrpcTcp.0x9067_202 with reserved=1', async () => {
const sender = makeSender({ respHead: { retCode: 0 }, downloadRkey: { rkeys: [] } } as any);
await FetchDownloadRkeys.invoke(sender);
const [wireName, bytes] = sender.sendRawPacket.mock.calls[0]!;
expect(wireName).toBe('OidbSvcTrpcTcp.0x9067_202');
const env = protobuf_decode<OidbBase<NTV2RichMediaReq>>(bytes);
expect(env.reserved).toBe(1);
});
});
});
@@ -0,0 +1,68 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase, OidbSvcTrpcTcp0xFD4_1Response } from '@snowluma/proto-defs/oidb';
import type { OidbFriendListRequest } from '@snowluma/proto-defs/oidb-actions/base';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { FetchFriendListPage } from '../../../src/oidb-services/contacts/fetch-friend-list-page';
function makeSender(body?: OidbSvcTrpcTcp0xFD4_1Response) {
const responseData = body !== undefined
? Buffer.from(protobuf_encode<OidbBase<OidbSvcTrpcTcp0xFD4_1Response>>({ body }))
: Buffer.alloc(0);
const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData };
return { sendRawPacket: vi.fn(async () => r) };
}
describe('FetchFriendListPage namespace', () => {
it('declares 0xFD4_1', () => {
expect(FetchFriendListPage.command).toBe(0xFD4);
expect(FetchFriendListPage.subCommand).toBe(1);
});
describe('serialize', () => {
it('omits nextUin on the first page', () => {
const out = FetchFriendListPage.serialize({} as any, { nextUin: null }) as any;
expect(out.nextUin).toBeUndefined();
expect(out.friendCount).toBe(300);
expect(out.field4).toBe(0);
});
it('includes nextUin sub-message on follow-up pages', () => {
const out = FetchFriendListPage.serialize({} as any, { nextUin: 10001 }) as any;
expect(out.nextUin).toEqual({ uin: 10001 });
});
it('emits the verbatim property request list (codes 100/101/102/103/20002/27394)', () => {
const out = FetchFriendListPage.serialize({} as any, { nextUin: null }) as any;
expect(out.body).toEqual([
{ type: 1, number: { numbers: [103, 102, 20002, 27394] } },
{ type: 4, number: { numbers: [100, 101, 102] } },
]);
});
});
describe('invoke (e2e)', () => {
it('routes to OidbSvcTrpcTcp.0xfd4_1', async () => {
const sender = makeSender({ friends: [] });
await FetchFriendListPage.invoke(sender, { nextUin: null });
expect(sender.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0xfd4_1');
});
it('returns the wire body verbatim (facade does the FriendInfo mapping)', async () => {
const body = { friends: [{ uin: 10001, uid: 'u', additional: [] }], next: { uin: 0 } };
const sender = makeSender(body as any);
const out = await FetchFriendListPage.invoke(sender, { nextUin: null });
expect(out.friends).toBeDefined();
expect(out.next?.uin ?? 0).toBe(0);
});
it('encodes envelope body correctly', async () => {
const sender = makeSender({ friends: [] });
await FetchFriendListPage.invoke(sender, { nextUin: 10001 });
const [, bytes] = sender.sendRawPacket.mock.calls[0]!;
const env = protobuf_decode<OidbBase<OidbFriendListRequest>>(bytes);
expect(env.body?.nextUin).toEqual({ uin: 10001 });
});
});
});
@@ -0,0 +1,43 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_decode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { OidbGroupListRequest } from '@snowluma/proto-defs/oidb-actions/base';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { FetchGroupList } from '../../../src/oidb-services/contacts/fetch-group-list';
function makeSender() {
const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: Buffer.alloc(0) };
return { sendRawPacket: vi.fn(async () => r) };
}
describe('FetchGroupList namespace', () => {
it('declares 0xFE5_2 with uinForm=true', () => {
expect(FetchGroupList.command).toBe(0xFE5);
expect(FetchGroupList.subCommand).toBe(2);
expect(FetchGroupList.uinForm).toBe(true);
});
describe('invoke (e2e)', () => {
it('routes to OidbSvcTrpcTcp.0xfe5_2 with envelope reserved=1', async () => {
const sender = makeSender();
await FetchGroupList.invoke(sender);
const [wireName, bytes] = sender.sendRawPacket.mock.calls[0]!;
expect(wireName).toBe('OidbSvcTrpcTcp.0xfe5_2');
const env = protobuf_decode<OidbBase<OidbGroupListRequest>>(bytes);
expect(env.reserved).toBe(1);
});
it('sends the verbatim config blob (field5002/5003 OFF to avoid EPIPE on big rosters)', async () => {
const sender = makeSender();
await FetchGroupList.invoke(sender);
const [, bytes] = sender.sendRawPacket.mock.calls[0]!;
const env = protobuf_decode<OidbBase<OidbGroupListRequest>>(bytes);
expect(env.body?.config?.config1?.groupName).toBe(true);
expect(env.body?.config?.config1?.memberCount).toBe(true);
// proto3 default false — omitted on wire, decoded as null.
expect(env.body?.config?.config1?.field5002 ?? false).toBe(false);
expect(env.body?.config?.config1?.field5003 ?? false).toBe(false);
});
});
});
@@ -0,0 +1,57 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_decode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { OidbGroupMemberListRequest } from '@snowluma/proto-defs/oidb-actions/base';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { FetchGroupMemberListPage } from '../../../src/oidb-services/contacts/fetch-group-member-list-page';
function makeSender() {
const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: Buffer.alloc(0) };
return { sendRawPacket: vi.fn(async () => r) };
}
describe('FetchGroupMemberListPage namespace', () => {
it('declares 0xFE7_3', () => {
expect(FetchGroupMemberListPage.command).toBe(0xFE7);
expect(FetchGroupMemberListPage.subCommand).toBe(3);
});
describe('serialize', () => {
it('omits the token on the first page', () => {
const out = FetchGroupMemberListPage.serialize({} as any, { groupId: 12345, token: '' }) as any;
expect(out.token).toBeUndefined();
expect(out.groupUin).toBe(12345);
});
it('threads the server-issued token into follow-up pages', () => {
const out = FetchGroupMemberListPage.serialize({} as any, { groupId: 12345, token: 'next-cursor' }) as any;
expect(out.token).toBe('next-cursor');
});
it('always requests the full member-field projection', () => {
const out = FetchGroupMemberListPage.serialize({} as any, { groupId: 1, token: '' }) as any;
expect(out.body).toMatchObject({
memberName: true, memberCard: true, level: true,
joinTimestamp: true, lastMsgTimestamp: true, shutUpTimestamp: true,
permission: true,
});
});
});
describe('invoke (e2e)', () => {
it('routes to OidbSvcTrpcTcp.0xfe7_3', async () => {
const sender = makeSender();
await FetchGroupMemberListPage.invoke(sender, { groupId: 1, token: '' });
expect(sender.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0xfe7_3');
});
it('encodes envelope body with the groupId', async () => {
const sender = makeSender();
await FetchGroupMemberListPage.invoke(sender, { groupId: 12345, token: '' });
const [, bytes] = sender.sendRawPacket.mock.calls[0]!;
const env = protobuf_decode<OidbBase<OidbGroupMemberListRequest>>(bytes);
expect(env.body?.groupUin).toBe(12345);
});
});
});
@@ -0,0 +1,56 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_decode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { OidbGroupRequestList } from '@snowluma/proto-defs/oidb-actions/base';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { FetchGroupRequests } from '../../../src/oidb-services/contacts/fetch-group-requests';
function makeSender() {
const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: Buffer.alloc(0) };
return { sendRawPacket: vi.fn(async () => r) };
}
describe('FetchGroupRequests namespace', () => {
it('declares 0x10C0', () => {
expect(FetchGroupRequests.command).toBe(0x10C0);
});
describe('resolveSubCommand', () => {
it('returns 1 when filtered=false (main inbox)', () => {
expect(FetchGroupRequests.resolveSubCommand({ filtered: false })).toBe(1);
});
it('returns 2 when filtered=true (low-priority inbox)', () => {
expect(FetchGroupRequests.resolveSubCommand({ filtered: true })).toBe(2);
});
});
describe('serialize', () => {
it('always sends count=20 / field2=0', () => {
expect(FetchGroupRequests.serialize({} as any, { filtered: false })).toEqual({ count: 20, field2: 0 });
expect(FetchGroupRequests.serialize({} as any, { filtered: true })).toEqual({ count: 20, field2: 0 });
});
});
describe('invoke (e2e)', () => {
it('routes to 0x10c0_1 for the main inbox', async () => {
const sender = makeSender();
await FetchGroupRequests.invoke(sender, { filtered: false });
expect(sender.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0x10c0_1');
});
it('routes to 0x10c0_2 for the filtered inbox', async () => {
const sender = makeSender();
await FetchGroupRequests.invoke(sender, { filtered: true });
expect(sender.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0x10c0_2');
});
it('encodes envelope body with count=20', async () => {
const sender = makeSender();
await FetchGroupRequests.invoke(sender, { filtered: false });
const [, bytes] = sender.sendRawPacket.mock.calls[0]!;
const env = protobuf_decode<OidbBase<OidbGroupRequestList>>(bytes);
expect(env.body?.count).toBe(20);
});
});
});
@@ -0,0 +1,75 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
OidbUserInfoByUidRequest, OidbUserInfoResponse,
} from '@snowluma/proto-defs/oidb-actions/base';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { FetchUserProfileByUid } from '../../../src/oidb-services/contacts/fetch-user-profile-by-uid';
function makeSender(body?: OidbUserInfoResponse) {
const responseData = body !== undefined
? Buffer.from(protobuf_encode<OidbBase<OidbUserInfoResponse>>({ body }))
: Buffer.alloc(0);
const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData };
return { sendRawPacket: vi.fn(async () => r) };
}
describe('FetchUserProfileByUid namespace (UID form)', () => {
it('declares 0xFE1_2 WITHOUT uinForm (reserved stays 0)', () => {
expect(FetchUserProfileByUid.command).toBe(0xFE1);
expect(FetchUserProfileByUid.subCommand).toBe(2);
// No `uinForm` exposed — matches Lagrange's isUid=false path on
// the UID variant. Important because the server distinguishes
// UIN vs UID requests via the envelope's `reserved` field.
expect((FetchUserProfileByUid as any).uinForm).toBeUndefined();
});
it('packages the uid as field 1 (string), routes to OidbSvcTrpcTcp.0xfe1_2', async () => {
const sender = makeSender({ body: { uin: 950929451, uid: 'u_abc' } as any });
await FetchUserProfileByUid.invoke(sender, { uid: 'u_abc' });
const [wireName, bytes] = sender.sendRawPacket.mock.calls[0]!;
expect(wireName).toBe('OidbSvcTrpcTcp.0xfe1_2');
const env = protobuf_decode<OidbBase<OidbUserInfoByUidRequest>>(bytes);
expect(env.body?.uid).toBe('u_abc');
// reserved=0 (default, omitted on wire) because this is the UID
// variant — Lagrange's `OidbSvcTrpcTcp0xFE1_2.cs:9` does the same.
expect(env.reserved ?? 0).toBe(0);
});
it('requests the same property key catalogue as the UIN variant', async () => {
const sender = makeSender({ body: { uin: 1, uid: 'u' } as any });
await FetchUserProfileByUid.invoke(sender, { uid: 'u' });
const [, bytes] = sender.sendRawPacket.mock.calls[0]!;
const env = protobuf_decode<OidbBase<OidbUserInfoByUidRequest>>(bytes);
const keys = env.body?.keys?.map(k => k.key);
expect(keys).toContain(20002); // nickname — the whole point
expect(keys).toContain(105); // QQ level
});
it('decodes nickname + uin from the response so the pipeline can fill them into the event', async () => {
// This is the actual point of the namespace — the stranger's
// nickname + uin lands here so the pipeline can patch them onto
// the in-flight group_invite event.
const enc = (s: string) => new TextEncoder().encode(s);
const sender = makeSender({
body: {
uin: 950929451, uid: 'u_abc',
properties: {
bytesProperties: [{ code: 20002, value: enc('小明') }],
numberProperties: [],
},
} as any,
});
const out = await FetchUserProfileByUid.invoke(sender, { uid: 'u_abc' });
expect(out.uin).toBe(950929451);
expect(out.nickname).toBe('小明');
});
it('throws when the response body is missing entirely', async () => {
const sender = makeSender({});
await expect(FetchUserProfileByUid.invoke(sender, { uid: 'u_abc' }))
.rejects.toThrow('user info response body missing');
});
});
@@ -0,0 +1,124 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
AvatarInfo, OidbUserInfoRequest, OidbUserInfoResponse,
} from '@snowluma/proto-defs/oidb-actions/base';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { FetchUserProfile } from '../../../src/oidb-services/contacts/fetch-user-profile';
function makeSender(body?: OidbUserInfoResponse) {
const responseData = body !== undefined
? Buffer.from(protobuf_encode<OidbBase<OidbUserInfoResponse>>({ body }))
: Buffer.alloc(0);
const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData };
return { sendRawPacket: vi.fn(async () => r) };
}
describe('FetchUserProfile namespace', () => {
it('declares 0xFE1_2 with uinForm=true', () => {
expect(FetchUserProfile.command).toBe(0xFE1);
expect(FetchUserProfile.subCommand).toBe(2);
expect(FetchUserProfile.uinForm).toBe(true);
});
describe('invoke (e2e)', () => {
it('routes to OidbSvcTrpcTcp.0xfe1_2 with reserved=1', async () => {
const sender = makeSender({ body: { uin: 10001, uid: 'u' } as any });
await FetchUserProfile.invoke(sender, { uin: 10001 });
const [wireName, bytes] = sender.sendRawPacket.mock.calls[0]!;
expect(wireName).toBe('OidbSvcTrpcTcp.0xfe1_2');
const env = protobuf_decode<OidbBase<OidbUserInfoRequest>>(bytes);
expect(env.reserved).toBe(1);
});
it('requests every property key in the catalogue (nickname, level, …)', async () => {
const sender = makeSender({ body: { uin: 10001, uid: 'u' } as any });
await FetchUserProfile.invoke(sender, { uin: 10001 });
const [, bytes] = sender.sendRawPacket.mock.calls[0]!;
const env = protobuf_decode<OidbBase<OidbUserInfoRequest>>(bytes);
const keys = env.body?.keys?.map(k => k.key);
expect(keys).toContain(20002); // nickname
expect(keys).toContain(105); // level
expect(keys).toContain(101); // avatar
expect(keys).toContain(102); // sign
expect(keys).toContain(103); // remark
});
it('decodes nickname / remark / qid / sign from bytes-properties', async () => {
const enc = (s: string) => new TextEncoder().encode(s);
const sender = makeSender({
body: {
uin: 10001, uid: 'u',
properties: {
bytesProperties: [
{ code: 20002, value: enc('Nick') },
{ code: 103, value: enc('Bestie') },
{ code: 27394, value: enc('myqid') },
{ code: 102, value: enc('Hello') },
],
numberProperties: [],
},
} as any,
});
const out = await FetchUserProfile.invoke(sender, { uin: 10001 });
expect(out.nickname).toBe('Nick');
expect(out.remark).toBe('Bestie');
expect(out.qid).toBe('myqid');
expect(out.sign).toBe('Hello');
});
it('decodes sex / age / level from number-properties (sex enum)', async () => {
const cases: Array<[number, string]> = [
[1, 'male'], [2, 'female'], [255, 'unknown'], [0, 'unknown'],
];
for (const [sexNum, expected] of cases) {
const sender = makeSender({
body: {
uin: 1, uid: 'u',
properties: {
bytesProperties: [],
numberProperties: [
{ number1: 20009, number2: sexNum },
{ number1: 20037, number2: 25 },
{ number1: 105, number2: 7 },
],
},
} as any,
});
const out = await FetchUserProfile.invoke(sender, { uin: 1 });
expect(out.sex).toBe(expected);
expect(out.age).toBe(25);
expect(out.level).toBe(7);
}
});
it('decodes the avatar URL with the "640" size suffix appended', async () => {
const avatarBytes = protobuf_encode<AvatarInfo>({ url: 'https://q.qlogo.cn/abc/' });
const sender = makeSender({
body: {
uin: 10001, uid: 'u',
properties: {
bytesProperties: [{ code: 101, value: avatarBytes }],
numberProperties: [],
},
} as any,
});
const out = await FetchUserProfile.invoke(sender, { uin: 10001 });
expect(out.avatar).toBe('https://q.qlogo.cn/abc/640');
});
it('defaults uin to the requested value when the server omits its echo', async () => {
const sender = makeSender({ body: { uid: 'u' } as any });
const out = await FetchUserProfile.invoke(sender, { uin: 99999 });
expect(out.uin).toBe(99999);
});
it('throws when body is entirely missing from the envelope', async () => {
const sender = makeSender({});
await expect(FetchUserProfile.invoke(sender, { uin: 1 }))
.rejects.toThrow('user info response body missing');
});
});
});
@@ -0,0 +1,63 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { OidbAiVoiceListReq, OidbAiVoiceListResp } from '@snowluma/proto-defs/oidb-actions/media';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { FetchAiVoiceList } from '../../../src/oidb-services/extras/fetch-ai-voice-list';
function makeSender(body?: OidbAiVoiceListResp) {
const responseData = body !== undefined
? Buffer.from(protobuf_encode<OidbBase<OidbAiVoiceListResp>>({ body }))
: Buffer.alloc(0);
const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData };
return { sendRawPacket: vi.fn(async () => r) };
}
describe('FetchAiVoiceList namespace', () => {
it('declares 0x929D_0', () => {
expect(FetchAiVoiceList.command).toBe(0x929D);
expect(FetchAiVoiceList.subCommand).toBe(0);
});
describe('serialize', () => {
it('passes groupUin / chatType verbatim', () => {
expect(FetchAiVoiceList.serialize({} as any, { groupId: 4242, chatType: 1 })).toEqual({
groupUin: 4242, chatType: 1,
});
});
});
describe('deserialize', () => {
it('returns content array verbatim', () => {
const out = FetchAiVoiceList.deserialize({} as any, {
content: [
{ category: 'cute', voices: [{ voiceId: 'v1', voiceDisplayName: 'V1', voiceExampleUrl: 'http://x' }] },
],
});
expect(out).toEqual([
{ category: 'cute', voices: [{ voiceId: 'v1', voiceDisplayName: 'V1', voiceExampleUrl: 'http://x' }] },
]);
});
it('returns [] when content is omitted', () => {
expect(FetchAiVoiceList.deserialize({} as any, {})).toEqual([]);
});
});
describe('invoke (e2e)', () => {
it('routes to OidbSvcTrpcTcp.0x929d_0', async () => {
const sender = makeSender({ content: [] });
await FetchAiVoiceList.invoke(sender, { groupId: 100, chatType: 1 });
expect(sender.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0x929d_0');
});
it('encodes envelope body correctly', async () => {
const sender = makeSender({ content: [] });
await FetchAiVoiceList.invoke(sender, { groupId: 4242, chatType: 2 });
const [, bytes] = sender.sendRawPacket.mock.calls[0]!;
const env = protobuf_decode<OidbBase<OidbAiVoiceListReq>>(bytes);
expect(env.body).toMatchObject({ groupUin: 4242, chatType: 2 });
});
});
});
@@ -0,0 +1,78 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { OidbAiVoiceReq, OidbAiVoiceResp } from '@snowluma/proto-defs/oidb-actions/media';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { FetchAiVoice } from '../../../src/oidb-services/extras/fetch-ai-voice';
function makeSender(body?: OidbAiVoiceResp) {
const responseData = body !== undefined
? Buffer.from(protobuf_encode<OidbBase<OidbAiVoiceResp>>({ body }))
: Buffer.alloc(0);
const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData };
return { sendRawPacket: vi.fn(async () => r) };
}
describe('FetchAiVoice namespace', () => {
it('declares 0x929B_0', () => {
expect(FetchAiVoice.command).toBe(0x929B);
expect(FetchAiVoice.subCommand).toBe(0);
});
describe('serialize', () => {
it('packages every field including sessionId into session sub-message', () => {
const out = FetchAiVoice.serialize({} as any, {
groupId: 100, voiceId: 'v', text: 'hi', chatType: 1, sessionId: 0xCAFE,
});
expect(out).toEqual({
groupUin: 100, voiceId: 'v', text: 'hi', chatType: 1,
session: { sessionId: 0xCAFE },
});
});
});
describe('deserialize', () => {
it('returns the first msgInfoBody index when present', () => {
const node = { fileUuid: 'uuid', subType: 1 };
expect(FetchAiVoice.deserialize({} as any, {
msgInfo: { msgInfoBody: [{ index: node }] },
} as any)).toMatchObject(node);
});
it('returns null when msgInfo is empty / missing', () => {
expect(FetchAiVoice.deserialize({} as any, {} as any)).toBeNull();
expect(FetchAiVoice.deserialize({} as any, { msgInfo: {} } as any)).toBeNull();
expect(FetchAiVoice.deserialize({} as any, { msgInfo: { msgInfoBody: [] } } as any)).toBeNull();
});
});
describe('invoke (e2e)', () => {
it('routes to OidbSvcTrpcTcp.0x929b_0', async () => {
const sender = makeSender({ msgInfo: { msgInfoBody: [{ index: { fileUuid: 'u' } }] } } as any);
await FetchAiVoice.invoke(sender, { groupId: 1, voiceId: 'v', text: 't', chatType: 1, sessionId: 1 });
expect(sender.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0x929b_0');
});
it('returns the parsed index node', async () => {
const node = { fileUuid: 'uuid', subType: 1 };
const sender = makeSender({ msgInfo: { msgInfoBody: [{ index: node }] } } as any);
const out = await FetchAiVoice.invoke(sender, { groupId: 1, voiceId: 'v', text: 't', chatType: 1, sessionId: 1 });
expect(out).toMatchObject(node);
});
it('returns null when server polls back empty msgInfo (in-flight)', async () => {
const sender = makeSender({} as any);
const out = await FetchAiVoice.invoke(sender, { groupId: 1, voiceId: 'v', text: 't', chatType: 1, sessionId: 1 });
expect(out).toBeNull();
});
it('passes the sessionId through to the wire envelope verbatim', async () => {
const sender = makeSender({} as any);
await FetchAiVoice.invoke(sender, { groupId: 1, voiceId: 'v', text: 't', chatType: 1, sessionId: 0xCAFEBABE });
const [, bytes] = sender.sendRawPacket.mock.calls[0]!;
const env = protobuf_decode<OidbBase<OidbAiVoiceReq>>(bytes);
expect(env.body?.session?.sessionId).toBe(0xCAFEBABE);
});
});
});
@@ -0,0 +1,66 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { OidbStrangerStatusReq, OidbStrangerStatusResp } from '@snowluma/proto-defs/oidb-actions/base';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { GetStrangerStatus } from '../../../src/oidb-services/extras/get-stranger-status';
function makeSender(body?: OidbStrangerStatusResp) {
const responseData = body !== undefined
? Buffer.from(protobuf_encode<OidbBase<OidbStrangerStatusResp>>({ body }))
: Buffer.alloc(0);
const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData };
return { sendRawPacket: vi.fn(async () => r) };
}
describe('GetStrangerStatus namespace', () => {
it('declares 0xFE1_2 with uinForm=true', () => {
expect(GetStrangerStatus.command).toBe(0xFE1);
expect(GetStrangerStatus.subCommand).toBe(2);
expect(GetStrangerStatus.uinForm).toBe(true);
});
describe('serialize', () => {
it('always queries only key 27372 (status property)', () => {
const out = GetStrangerStatus.serialize({} as any, { uin: 100200 });
expect(out).toEqual({ uin: 100200, key: [{ key: 27372 }] });
});
});
describe('deserialize', () => {
it('low-band (≤10) values map to (value*10, 0)', () => {
expect(GetStrangerStatus.deserialize({} as any, { data: { status: { value: 7n } } })).toEqual({ status: 70, ext_status: 0 });
expect(GetStrangerStatus.deserialize({} as any, { data: { status: { value: 10n } } })).toEqual({ status: 100, ext_status: 0 });
});
it('high-band values decompose into (0xff00 + (>>16 & 0xff)) ext_status', () => {
// 0x42F100 → bits 8..15 = 0xF1<<8 = 0xF100, bits 16..23 = 0x42 → 0xF142
expect(GetStrangerStatus.deserialize({} as any, { data: { status: { value: 0x42F100n } } }))
.toEqual({ status: 10, ext_status: 0xF142 });
});
it('returns null when status field is missing', () => {
expect(GetStrangerStatus.deserialize({} as any, {})).toBeNull();
expect(GetStrangerStatus.deserialize({} as any, { data: {} })).toBeNull();
expect(GetStrangerStatus.deserialize({} as any, { data: { status: {} } })).toBeNull();
});
});
describe('invoke (e2e)', () => {
it('routes to OidbSvcTrpcTcp.0xfe1_2 with uinForm=true (envelope reserved=1)', async () => {
const sender = makeSender({ data: { status: { value: 5n } } });
await GetStrangerStatus.invoke(sender, { uin: 100200 });
const [wireName, bytes] = sender.sendRawPacket.mock.calls[0]!;
expect(wireName).toBe('OidbSvcTrpcTcp.0xfe1_2');
const env = protobuf_decode<OidbBase<OidbStrangerStatusReq>>(bytes);
expect(env.reserved).toBe(1);
});
it('returns the decoded status object', async () => {
const sender = makeSender({ data: { status: { value: 5n } } });
const out = await GetStrangerStatus.invoke(sender, { uin: 1 });
expect(out).toEqual({ status: 50, ext_status: 0 });
});
});
});
@@ -0,0 +1,59 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_decode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { OidbGroupTodo } from '@snowluma/proto-defs/oidb-actions/base';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { GroupTodo } from '../../../src/oidb-services/extras/group-todo';
function makeSender() {
const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: Buffer.alloc(0) };
return { sendRawPacket: vi.fn(async () => r) };
}
describe('GroupTodo namespace', () => {
it('declares 0xF90', () => {
expect(GroupTodo.command).toBe(0xF90);
});
describe('resolveSubCommand', () => {
it('maps set → 1', () => {
expect(GroupTodo.resolveSubCommand({ groupId: 1, msgSeq: 1n, action: 'set' })).toBe(1);
});
it('maps complete → 2', () => {
expect(GroupTodo.resolveSubCommand({ groupId: 1, msgSeq: 1n, action: 'complete' })).toBe(2);
});
it('maps cancel → 3', () => {
expect(GroupTodo.resolveSubCommand({ groupId: 1, msgSeq: 1n, action: 'cancel' })).toBe(3);
});
});
describe('serialize', () => {
it('packages groupUin + msgSeq verbatim regardless of action', () => {
for (const action of ['set', 'complete', 'cancel'] as const) {
const out = GroupTodo.serialize({} as any, { groupId: 12345, msgSeq: 9876543210n, action });
expect(out).toEqual({ groupUin: 12345, msgSeq: 9876543210n });
}
});
});
describe('invoke (e2e)', () => {
it.each([
['set', 'OidbSvcTrpcTcp.0xf90_1'] as const,
['complete', 'OidbSvcTrpcTcp.0xf90_2'] as const,
['cancel', 'OidbSvcTrpcTcp.0xf90_3'] as const,
])('action %s routes to %s', async (action, expectedWire) => {
const sender = makeSender();
await GroupTodo.invoke(sender, { groupId: 12345, msgSeq: 100n, action });
expect(sender.sendRawPacket.mock.calls[0]![0]).toBe(expectedWire);
});
it('encodes envelope body correctly', async () => {
const sender = makeSender();
await GroupTodo.invoke(sender, { groupId: 100, msgSeq: 999n, action: 'set' });
const [, bytes] = sender.sendRawPacket.mock.calls[0]!;
const env = protobuf_decode<OidbBase<OidbGroupTodo>>(bytes);
expect(env.body).toEqual({ groupUin: 100, msgSeq: 999n });
});
});
});
@@ -0,0 +1,61 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_decode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { OidbDeleteFriend } from '@snowluma/proto-defs/oidb-actions/base';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { DeleteFriend } from '../../../src/oidb-services/friend/delete-friend';
function makeDeps() {
const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: Buffer.alloc(0) };
return {
sendRawPacket: vi.fn(async () => r),
resolveUserUid: vi.fn(async () => 'resolved-uid'),
};
}
describe('DeleteFriend namespace', () => {
it('declares 0x126B_0', () => {
expect(DeleteFriend.command).toBe(0x126B);
expect(DeleteFriend.subCommand).toBe(0);
});
describe('invoke', () => {
it('routes to OidbSvcTrpcTcp.0x126b_0', async () => {
const deps = makeDeps();
await DeleteFriend.invoke(deps, { userId: 10001 });
expect(deps.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0x126b_0');
});
it('resolves the target uid before encoding', async () => {
const deps = makeDeps();
await DeleteFriend.invoke(deps, { userId: 10001 });
expect(deps.resolveUserUid).toHaveBeenCalledWith(10001);
});
it('packages the nested envelope with verbatim magic constants', async () => {
const deps = makeDeps();
await DeleteFriend.invoke(deps, { userId: 10001, block: true });
const [, bytes] = deps.sendRawPacket.mock.calls[0]!;
const env = protobuf_decode<OidbBase<OidbDeleteFriend>>(bytes);
expect(env.body?.field1).toMatchObject({
targetUid: 'resolved-uid',
block: true,
field2: {
field1: 130,
field2: 109,
field3: { field1: 8, field2: 8, field3: 50 },
},
});
});
it('defaults block to false (no block flag)', async () => {
const deps = makeDeps();
await DeleteFriend.invoke(deps, { userId: 10001 });
const [, bytes] = deps.sendRawPacket.mock.calls[0]!;
const env = protobuf_decode<OidbBase<OidbDeleteFriend>>(bytes);
// proto3 false omitted on wire — decoded as null/undefined.
expect(env.body?.field1?.block ?? false).toBe(false);
});
});
});
@@ -0,0 +1,64 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_decode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { OidbFriendRequestAction } from '@snowluma/proto-defs/oidb-actions/base';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { HandleFriendRequest } from '../../../src/oidb-services/friend/handle-friend-request';
function makeDeps(resolvedUid = 'resolved-uid') {
const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: Buffer.alloc(0) };
return {
sendRawPacket: vi.fn(async () => r),
resolveUserUid: vi.fn(async () => resolvedUid),
};
}
describe('HandleFriendRequest namespace', () => {
it('declares 0xB5D_44', () => {
expect(HandleFriendRequest.command).toBe(0xB5D);
expect(HandleFriendRequest.subCommand).toBe(44);
});
describe('invoke', () => {
it('routes to OidbSvcTrpcTcp.0xb5d_44', async () => {
const deps = makeDeps();
await HandleFriendRequest.invoke(deps, { uidOrFlag: 'uid', approve: true });
expect(deps.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0xb5d_44');
});
it('detects digit-only flag → resolves via resolveUserUid', async () => {
const deps = makeDeps('resolved-from-uin');
await HandleFriendRequest.invoke(deps, { uidOrFlag: '10001', approve: true });
expect(deps.resolveUserUid).toHaveBeenCalledWith(10001);
const [, bytes] = deps.sendRawPacket.mock.calls[0]!;
const env = protobuf_decode<OidbBase<OidbFriendRequestAction>>(bytes);
expect(env.body?.targetUid).toBe('resolved-from-uin');
});
it('passes non-numeric flag through verbatim (no resolveUserUid call)', async () => {
const deps = makeDeps();
await HandleFriendRequest.invoke(deps, { uidOrFlag: 'flag-abc', approve: false });
expect(deps.resolveUserUid).not.toHaveBeenCalled();
const [, bytes] = deps.sendRawPacket.mock.calls[0]!;
const env = protobuf_decode<OidbBase<OidbFriendRequestAction>>(bytes);
expect(env.body?.targetUid).toBe('flag-abc');
});
it('encodes accept=3 when approve=true', async () => {
const deps = makeDeps();
await HandleFriendRequest.invoke(deps, { uidOrFlag: 'u', approve: true });
const [, bytes] = deps.sendRawPacket.mock.calls[0]!;
const env = protobuf_decode<OidbBase<OidbFriendRequestAction>>(bytes);
expect(env.body?.accept).toBe(3);
});
it('encodes accept=5 when approve=false', async () => {
const deps = makeDeps();
await HandleFriendRequest.invoke(deps, { uidOrFlag: 'u', approve: false });
const [, bytes] = deps.sendRawPacket.mock.calls[0]!;
const env = protobuf_decode<OidbBase<OidbFriendRequestAction>>(bytes);
expect(env.body?.accept).toBe(5);
});
});
});
@@ -0,0 +1,44 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_decode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { OidbSetFriendRemark } from '@snowluma/proto-defs/oidb-actions/base';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { SetFriendRemark } from '../../../src/oidb-services/friend/set-friend-remark';
function makeDeps() {
const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: Buffer.alloc(0) };
return {
sendRawPacket: vi.fn(async () => r),
resolveUserUid: vi.fn(async () => 'resolved-uid'),
};
}
describe('SetFriendRemark namespace', () => {
it('declares 0xB6E_2', () => {
expect(SetFriendRemark.command).toBe(0xB6E);
expect(SetFriendRemark.subCommand).toBe(2);
});
describe('invoke', () => {
it('routes to OidbSvcTrpcTcp.0xb6e_2', async () => {
const deps = makeDeps();
await SetFriendRemark.invoke(deps, { userId: 10001, remark: 'x' });
expect(deps.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0xb6e_2');
});
it('resolves the target uid before encoding', async () => {
const deps = makeDeps();
await SetFriendRemark.invoke(deps, { userId: 10001, remark: 'best-friend' });
expect(deps.resolveUserUid).toHaveBeenCalledWith(10001);
});
it('packages uid + remark in body', async () => {
const deps = makeDeps();
await SetFriendRemark.invoke(deps, { userId: 10001, remark: 'best-friend' });
const [, bytes] = deps.sendRawPacket.mock.calls[0]!;
const env = protobuf_decode<OidbBase<OidbSetFriendRemark>>(bytes);
expect(env.body).toMatchObject({ targetUid: 'resolved-uid', remark: 'best-friend' });
});
});
});
@@ -0,0 +1,58 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { Oidb0x8a7Req, Oidb0x8a7Resp } from '@snowluma/proto-defs/oidb-actions/base';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { GetAtAllRemain } from '../../../src/oidb-services/group-admin/get-at-all-remain';
function makeDeps(body?: Oidb0x8a7Resp) {
const responseData = body !== undefined
? Buffer.from(protobuf_encode<OidbBase<Oidb0x8a7Resp>>({ body }))
: Buffer.alloc(0);
const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData };
return {
sendRawPacket: vi.fn(async () => r),
identity: { uin: '10001' } as any,
};
}
describe('GetAtAllRemain namespace', () => {
it('declares 0x8A7_0', () => {
expect(GetAtAllRemain.command).toBe(0x8A7);
expect(GetAtAllRemain.subCommand).toBe(0);
});
it('emits the basic{1,2,3}=1,2,1 cookie + bot uin + groupId, routes to 0x8a7_0', async () => {
const deps = makeDeps({ canAtAll: true, groupRemain: 12, uinRemain: 5 });
await GetAtAllRemain.invoke(deps, { groupId: 12345 });
const [wire, bytes] = deps.sendRawPacket.mock.calls[0]!;
expect(wire).toBe('OidbSvcTrpcTcp.0x8a7_0');
const env = protobuf_decode<OidbBase<Oidb0x8a7Req>>(bytes);
expect(env.body).toMatchObject({
basic1: 1, basic2: 2, basic3: 1,
uin: 10001n,
groupId: 12345n,
});
});
it('decodes canAtAll + groupRemain + uinRemain as plain numbers / boolean', async () => {
const deps = makeDeps({ canAtAll: true, groupRemain: 12, uinRemain: 5 });
const out = await GetAtAllRemain.invoke(deps, { groupId: 12345 });
expect(out).toEqual({
can_at_all: true,
remain_at_all_count_for_group: 12,
remain_at_all_count_for_uin: 5,
});
});
it('falls back to false / 0 when the response body is empty', async () => {
const deps = makeDeps({} as any);
const out = await GetAtAllRemain.invoke(deps, { groupId: 1 });
expect(out).toEqual({
can_at_all: false,
remain_at_all_count_for_group: 0,
remain_at_all_count_for_uin: 0,
});
});
});
@@ -0,0 +1,43 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_decode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { OidbKickMember } from '@snowluma/proto-defs/oidb-actions/base';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { KickMember } from '../../../src/oidb-services/group-admin/kick-member';
function makeDeps() {
const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: Buffer.alloc(0) };
return {
sendRawPacket: vi.fn(async () => r),
resolveUserUid: vi.fn(async () => 'resolved-uid'),
};
}
describe('KickMember namespace', () => {
it('declares 0x8A0_1', () => {
expect(KickMember.command).toBe(0x8A0);
expect(KickMember.subCommand).toBe(1);
});
it('resolves uid per-group and forwards reject + reason', async () => {
const deps = makeDeps();
await KickMember.invoke(deps, { groupId: 12345, userId: 67890, reject: true, reason: 'bye' });
expect(deps.resolveUserUid).toHaveBeenCalledWith(67890, 12345);
const [wire, bytes] = deps.sendRawPacket.mock.calls[0]!;
expect(wire).toBe('OidbSvcTrpcTcp.0x8a0_1');
const env = protobuf_decode<OidbBase<OidbKickMember>>(bytes);
expect(env.body).toMatchObject({
groupUin: 12345, targetUid: 'resolved-uid', rejectAddRequest: true, reason: 'bye',
});
});
it('defaults reason to empty string', async () => {
const deps = makeDeps();
await KickMember.invoke(deps, { groupId: 1, userId: 2, reject: false });
const [, bytes] = deps.sendRawPacket.mock.calls[0]!;
const env = protobuf_decode<OidbBase<OidbKickMember>>(bytes);
expect(env.body?.reason ?? '').toBe('');
expect(env.body?.rejectAddRequest ?? false).toBe(false);
});
});
@@ -0,0 +1,44 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_decode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { Oidb0x8a0Req } from '@snowluma/proto-defs/oidb-actions/base';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { KickMembers } from '../../../src/oidb-services/group-admin/kick-members';
function makeDeps(resolveSequence: string[] = ['uid-a', 'uid-b']) {
const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: Buffer.alloc(0) };
const resolveUserUid = vi.fn();
for (const uid of resolveSequence) resolveUserUid.mockResolvedValueOnce(uid);
return {
sendRawPacket: vi.fn(async () => r),
resolveUserUid,
};
}
describe('KickMembers namespace', () => {
it('declares 0x8A0_1 (same as KickMember; disambiguated by proto body)', () => {
expect(KickMembers.command).toBe(0x8A0);
expect(KickMembers.subCommand).toBe(1);
});
it('resolves each uid in parallel and packages targetUids[]', async () => {
const deps = makeDeps(['uid-a', 'uid-b']);
await KickMembers.invoke(deps, { groupId: 12345, userIds: [11, 22], reject: false });
expect(deps.resolveUserUid).toHaveBeenCalledTimes(2);
const [wire, bytes] = deps.sendRawPacket.mock.calls[0]!;
expect(wire).toBe('OidbSvcTrpcTcp.0x8a0_1');
const env = protobuf_decode<OidbBase<Oidb0x8a0Req>>(bytes);
expect(env.body?.targetUids).toEqual(['uid-a', 'uid-b']);
expect(env.body?.groupId).toBe(12345n);
expect(env.body?.rejectAddRequest ?? 0).toBe(0);
});
it('reject=true => rejectAddRequest=1', async () => {
const deps = makeDeps(['u']);
await KickMembers.invoke(deps, { groupId: 1, userIds: [2], reject: true });
const [, bytes] = deps.sendRawPacket.mock.calls[0]!;
const env = protobuf_decode<OidbBase<Oidb0x8a0Req>>(bytes);
expect(env.body?.rejectAddRequest).toBe(1);
});
});
@@ -0,0 +1,28 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_decode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { OidbLeaveGroup } from '@snowluma/proto-defs/oidb-actions/base';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { LeaveGroup } from '../../../src/oidb-services/group-admin/leave-group';
function makeDeps() {
const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: Buffer.alloc(0) };
return { sendRawPacket: vi.fn(async () => r) };
}
describe('LeaveGroup namespace', () => {
it('declares 0x1097_1', () => {
expect(LeaveGroup.command).toBe(0x1097);
expect(LeaveGroup.subCommand).toBe(1);
});
it('routes to 0x1097_1 with groupUin only', async () => {
const deps = makeDeps();
await LeaveGroup.invoke(deps, { groupId: 12345 });
const [wire, bytes] = deps.sendRawPacket.mock.calls[0]!;
expect(wire).toBe('OidbSvcTrpcTcp.0x1097_1');
const env = protobuf_decode<OidbBase<OidbLeaveGroup>>(bytes);
expect(env.body).toMatchObject({ groupUin: 12345 });
});
});
@@ -0,0 +1,37 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_decode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { OidbMuteAll } from '@snowluma/proto-defs/oidb-actions/base';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { MuteAll } from '../../../src/oidb-services/group-admin/mute-all';
function makeDeps() {
const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: Buffer.alloc(0) };
return { sendRawPacket: vi.fn(async () => r) };
}
describe('MuteAll namespace', () => {
it('declares 0x89A_0', () => {
expect(MuteAll.command).toBe(0x89A);
expect(MuteAll.subCommand).toBe(0);
});
it('enable=true emits the 0xFFFFFFFF "permanent" state', async () => {
const deps = makeDeps();
await MuteAll.invoke(deps, { groupId: 12345, enable: true });
const [wire, bytes] = deps.sendRawPacket.mock.calls[0]!;
expect(wire).toBe('OidbSvcTrpcTcp.0x89a_0');
const env = protobuf_decode<OidbBase<OidbMuteAll>>(bytes);
expect(env.body).toMatchObject({ groupUin: 12345, muteState: { state: 0xFFFFFFFF } });
});
it('enable=false emits state=0', async () => {
const deps = makeDeps();
await MuteAll.invoke(deps, { groupId: 12345, enable: false });
const [, bytes] = deps.sendRawPacket.mock.calls[0]!;
const env = protobuf_decode<OidbBase<OidbMuteAll>>(bytes);
// proto3 default 0 fields are omitted on the wire.
expect(env.body?.muteState?.state ?? 0).toBe(0);
});
});
@@ -0,0 +1,44 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_decode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { OidbMuteMember } from '@snowluma/proto-defs/oidb-actions/base';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { MuteMember } from '../../../src/oidb-services/group-admin/mute-member';
function makeDeps() {
const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: Buffer.alloc(0) };
return {
sendRawPacket: vi.fn(async () => r),
resolveUserUid: vi.fn(async () => 'resolved-uid'),
};
}
describe('MuteMember namespace', () => {
it('declares 0x1253_1', () => {
expect(MuteMember.command).toBe(0x1253);
expect(MuteMember.subCommand).toBe(1);
});
it('resolves uid before encoding and routes to 0x1253_1', async () => {
const deps = makeDeps();
await MuteMember.invoke(deps, { groupId: 12345, userId: 67890, duration: 600 });
expect(deps.resolveUserUid).toHaveBeenCalledWith(67890, 12345);
const [wire, bytes] = deps.sendRawPacket.mock.calls[0]!;
expect(wire).toBe('OidbSvcTrpcTcp.0x1253_1');
const env = protobuf_decode<OidbBase<OidbMuteMember>>(bytes);
expect(env.body).toMatchObject({
groupUin: 12345, type: 1,
body: { targetUid: 'resolved-uid', duration: 600 },
});
});
it('duration = 0 acts as unmute', async () => {
const deps = makeDeps();
await MuteMember.invoke(deps, { groupId: 1, userId: 2, duration: 0 });
const [, bytes] = deps.sendRawPacket.mock.calls[0]!;
const env = protobuf_decode<OidbBase<OidbMuteMember>>(bytes);
// duration=0 is the proto3 default and is omitted on the wire.
expect(env.body?.body?.duration ?? 0).toBe(0);
});
});
@@ -0,0 +1,28 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_decode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { Oidb0x89a_0AddOption } from '@snowluma/proto-defs/oidb-actions/base';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { SetAddOption } from '../../../src/oidb-services/group-admin/set-add-option';
function makeDeps() {
const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: Buffer.alloc(0) };
return { sendRawPacket: vi.fn(async () => r) };
}
describe('SetAddOption namespace', () => {
it('declares 0x89A_0 (shared cmd with MuteAll / SetSearch / SetGroupName)', () => {
expect(SetAddOption.command).toBe(0x89A);
expect(SetAddOption.subCommand).toBe(0);
});
it('packages settings.addType and routes to 0x89a_0', async () => {
const deps = makeDeps();
await SetAddOption.invoke(deps, { groupId: 12345, addType: 2 });
const [wire, bytes] = deps.sendRawPacket.mock.calls[0]!;
expect(wire).toBe('OidbSvcTrpcTcp.0x89a_0');
const env = protobuf_decode<OidbBase<Oidb0x89a_0AddOption>>(bytes);
expect(env.body).toMatchObject({ groupUin: 12345n, settings: { addType: 2 } });
});
});
@@ -0,0 +1,52 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_decode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { OidbGroupRequestAction } from '@snowluma/proto-defs/oidb-actions/base';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { SetAddRequest } from '../../../src/oidb-services/group-admin/set-add-request';
function makeDeps() {
const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: Buffer.alloc(0) };
return { sendRawPacket: vi.fn(async () => r) };
}
describe('SetAddRequest namespace', () => {
it('declares 0x10C8 with uinForm=true and dynamic subCommand', () => {
expect(SetAddRequest.command).toBe(0x10C8);
expect(SetAddRequest.uinForm).toBe(true);
expect(SetAddRequest.resolveSubCommand({ groupId: 1, sequence: 1, eventType: 0, approve: true, filtered: false })).toBe(1);
expect(SetAddRequest.resolveSubCommand({ groupId: 1, sequence: 1, eventType: 0, approve: true, filtered: true })).toBe(2);
});
it('approve=true => accept=1, filtered=false => 0x10c8_1, reserved=1 (uinForm)', async () => {
const deps = makeDeps();
await SetAddRequest.invoke(deps, { groupId: 12345, sequence: 5, eventType: 1, approve: true, reason: 'ok' });
const [wire, bytes] = deps.sendRawPacket.mock.calls[0]!;
expect(wire).toBe('OidbSvcTrpcTcp.0x10c8_1');
const env = protobuf_decode<OidbBase<OidbGroupRequestAction>>(bytes);
expect(env.reserved).toBe(1);
expect(env.body?.accept).toBe(1);
expect(env.body?.body).toMatchObject({
sequence: 5n, eventType: 1, groupUin: 12345, message: 'ok',
});
});
it('approve=false + filtered=true => accept=2, 0x10c8_2', async () => {
const deps = makeDeps();
await SetAddRequest.invoke(deps, { groupId: 12345, sequence: 5, eventType: 1, approve: false, reason: 'no', filtered: true });
const [wire, bytes] = deps.sendRawPacket.mock.calls[0]!;
expect(wire).toBe('OidbSvcTrpcTcp.0x10c8_2');
const env = protobuf_decode<OidbBase<OidbGroupRequestAction>>(bytes);
expect(env.body?.accept).toBe(2);
});
it('defaults reason to empty string', async () => {
const deps = makeDeps();
await SetAddRequest.invoke(deps, { groupId: 1, sequence: 1, eventType: 0, approve: true });
const [, bytes] = deps.sendRawPacket.mock.calls[0]!;
const env = protobuf_decode<OidbBase<OidbGroupRequestAction>>(bytes);
// proto3 empty string omitted on the wire.
expect(env.body?.body?.message ?? '').toBe('');
});
});
@@ -0,0 +1,40 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_decode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { OidbSetAdmin } from '@snowluma/proto-defs/oidb-actions/base';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { SetAdmin } from '../../../src/oidb-services/group-admin/set-admin';
function makeDeps() {
const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: Buffer.alloc(0) };
return {
sendRawPacket: vi.fn(async () => r),
resolveUserUid: vi.fn(async () => 'resolved-uid'),
};
}
describe('SetAdmin namespace', () => {
it('declares 0x1096_1', () => {
expect(SetAdmin.command).toBe(0x1096);
expect(SetAdmin.subCommand).toBe(1);
});
it('enable=true promotes (isAdmin=true)', async () => {
const deps = makeDeps();
await SetAdmin.invoke(deps, { groupId: 12345, userId: 67890, enable: true });
expect(deps.resolveUserUid).toHaveBeenCalledWith(67890, 12345);
const [wire, bytes] = deps.sendRawPacket.mock.calls[0]!;
expect(wire).toBe('OidbSvcTrpcTcp.0x1096_1');
const env = protobuf_decode<OidbBase<OidbSetAdmin>>(bytes);
expect(env.body).toMatchObject({ groupUin: 12345, uid: 'resolved-uid', isAdmin: true });
});
it('enable=false demotes (isAdmin omitted on the wire)', async () => {
const deps = makeDeps();
await SetAdmin.invoke(deps, { groupId: 1, userId: 2, enable: false });
const [, bytes] = deps.sendRawPacket.mock.calls[0]!;
const env = protobuf_decode<OidbBase<OidbSetAdmin>>(bytes);
expect(env.body?.isAdmin ?? false).toBe(false);
});
});
@@ -0,0 +1,28 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_decode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { OidbRenameGroup } from '@snowluma/proto-defs/oidb-actions/base';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { SetGroupName } from '../../../src/oidb-services/group-admin/set-group-name';
function makeDeps() {
const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: Buffer.alloc(0) };
return { sendRawPacket: vi.fn(async () => r) };
}
describe('SetGroupName namespace', () => {
it('declares 0x89A_15', () => {
expect(SetGroupName.command).toBe(0x89A);
expect(SetGroupName.subCommand).toBe(15);
});
it('routes to 0x89a_15 with the new name', async () => {
const deps = makeDeps();
await SetGroupName.invoke(deps, { groupId: 12345, name: 'newName' });
const [wire, bytes] = deps.sendRawPacket.mock.calls[0]!;
expect(wire).toBe('OidbSvcTrpcTcp.0x89a_15');
const env = protobuf_decode<OidbBase<OidbRenameGroup>>(bytes);
expect(env.body).toMatchObject({ groupUin: 12345, body: { targetName: 'newName' } });
});
});
@@ -0,0 +1,28 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_decode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { Oidb0xf16Req } from '@snowluma/proto-defs/oidb-actions/base';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { SetGroupRemark } from '../../../src/oidb-services/group-admin/set-group-remark';
function makeDeps() {
const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: Buffer.alloc(0) };
return { sendRawPacket: vi.fn(async () => r) };
}
describe('SetGroupRemark namespace', () => {
it('declares 0xF16_1', () => {
expect(SetGroupRemark.command).toBe(0xF16);
expect(SetGroupRemark.subCommand).toBe(1);
});
it('routes to 0xf16_1 with groupId + remark wrapped in inner', async () => {
const deps = makeDeps();
await SetGroupRemark.invoke(deps, { groupId: 12345, remark: 'my group' });
const [wire, bytes] = deps.sendRawPacket.mock.calls[0]!;
expect(wire).toBe('OidbSvcTrpcTcp.0xf16_1');
const env = protobuf_decode<OidbBase<Oidb0xf16Req>>(bytes);
expect(env.body?.inner).toMatchObject({ groupId: 12345n, remark: 'my group' });
});
});
@@ -0,0 +1,35 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_decode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { OidbRenameMember } from '@snowluma/proto-defs/oidb-actions/base';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { SetMemberCard } from '../../../src/oidb-services/group-admin/set-member-card';
function makeDeps() {
const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: Buffer.alloc(0) };
return {
sendRawPacket: vi.fn(async () => r),
resolveUserUid: vi.fn(async () => 'resolved-uid'),
};
}
describe('SetMemberCard namespace', () => {
it('declares 0x8FC_3', () => {
expect(SetMemberCard.command).toBe(0x8FC);
expect(SetMemberCard.subCommand).toBe(3);
});
it('routes to 0x8fc_3 with targetUid + targetName', async () => {
const deps = makeDeps();
await SetMemberCard.invoke(deps, { groupId: 12345, userId: 67890, card: 'newCard' });
expect(deps.resolveUserUid).toHaveBeenCalledWith(67890, 12345);
const [wire, bytes] = deps.sendRawPacket.mock.calls[0]!;
expect(wire).toBe('OidbSvcTrpcTcp.0x8fc_3');
const env = protobuf_decode<OidbBase<OidbRenameMember>>(bytes);
expect(env.body).toMatchObject({
groupUin: 12345,
body: { targetUid: 'resolved-uid', targetName: 'newCard' },
});
});
});
@@ -0,0 +1,28 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_decode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { Oidb0x89a_0Search } from '@snowluma/proto-defs/oidb-actions/base';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { SetSearch } from '../../../src/oidb-services/group-admin/set-search';
function makeDeps() {
const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: Buffer.alloc(0) };
return { sendRawPacket: vi.fn(async () => r) };
}
describe('SetSearch namespace', () => {
it('declares 0x89A_0 (shared cmd shape with other 0x89a_0 cmds)', () => {
expect(SetSearch.command).toBe(0x89A);
expect(SetSearch.subCommand).toBe(0);
});
it('emits an empty settings byte string and routes to 0x89a_0', async () => {
const deps = makeDeps();
await SetSearch.invoke(deps, { groupId: 12345 });
const [wire, bytes] = deps.sendRawPacket.mock.calls[0]!;
expect(wire).toBe('OidbSvcTrpcTcp.0x89a_0');
const env = protobuf_decode<OidbBase<Oidb0x89a_0Search>>(bytes);
expect(env.body?.groupUin).toBe(12345n);
});
});
@@ -0,0 +1,36 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_decode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { OidbSpecialTitle } from '@snowluma/proto-defs/oidb-actions/base';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { SetSpecialTitle } from '../../../src/oidb-services/group-admin/set-special-title';
function makeDeps() {
const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: Buffer.alloc(0) };
return {
sendRawPacket: vi.fn(async () => r),
resolveUserUid: vi.fn(async () => 'resolved-uid'),
};
}
describe('SetSpecialTitle namespace', () => {
it('declares 0x8FC_2', () => {
expect(SetSpecialTitle.command).toBe(0x8FC);
expect(SetSpecialTitle.subCommand).toBe(2);
});
it('routes to 0x8fc_2 with -1 (permanent) expireTime sentinel', async () => {
const deps = makeDeps();
await SetSpecialTitle.invoke(deps, { groupId: 12345, userId: 67890, title: 'crown' });
expect(deps.resolveUserUid).toHaveBeenCalledWith(67890, 12345);
const [wire, bytes] = deps.sendRawPacket.mock.calls[0]!;
expect(wire).toBe('OidbSvcTrpcTcp.0x8fc_2');
const env = protobuf_decode<OidbBase<OidbSpecialTitle>>(bytes);
expect(env.body?.groupUin).toBe(12345);
expect(env.body?.body?.targetUid).toBe('resolved-uid');
expect(env.body?.body?.specialTitle).toBe('crown');
// -1 (int_32) round-trips as 0xFFFFFFFF after the proton decoder reinterprets.
expect(env.body?.body?.expireTime).toBe(0xFFFFFFFF);
});
});
@@ -0,0 +1,40 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
OidbGroupFileFolderReq, OidbGroupFileFolderResp,
} from '@snowluma/proto-defs/oidb-actions/group-file';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { CreateGroupFolder } from '../../../src/oidb-services/group-file/create-group-folder';
function makeDeps(body?: OidbGroupFileFolderResp) {
const responseData = body !== undefined
? Buffer.from(protobuf_encode<OidbBase<OidbGroupFileFolderResp>>({ body }))
: Buffer.alloc(0);
const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData };
return { sendRawPacket: vi.fn(async () => r) };
}
describe('CreateGroupFolder namespace', () => {
it('declares 0x6D7_0 with uinForm=true', () => {
expect(CreateGroupFolder.command).toBe(0x6D7);
expect(CreateGroupFolder.subCommand).toBe(0);
expect(CreateGroupFolder.uinForm).toBe(true);
});
it('packages create.{groupUin, rootDirectory, folderName}', async () => {
const deps = makeDeps({ create: {} as any });
await CreateGroupFolder.invoke(deps, { groupId: 12345, parentId: '/', folderName: 'docs' });
const env = protobuf_decode<OidbBase<OidbGroupFileFolderReq>>(deps.sendRawPacket.mock.calls[0]![1]);
expect(env.body?.create).toMatchObject({
groupUin: 12345, rootDirectory: '/', folderName: 'docs',
});
});
it('throws on retcode != 0 (note: lower-case retcode in this proto)', async () => {
const deps = makeDeps({ create: { retcode: 7, retMsg: 'denied' } as any });
await expect(CreateGroupFolder.invoke(deps, { groupId: 1, parentId: '/', folderName: 'f' }))
.rejects.toThrow(/code=7/);
});
});
@@ -0,0 +1,46 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
OidbGroupFileReq, OidbGroupFileResp,
} from '@snowluma/proto-defs/oidb-actions/group-file';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { DeleteGroupFile } from '../../../src/oidb-services/group-file/delete-group-file';
function makeDeps(body?: OidbGroupFileResp) {
const responseData = body !== undefined
? Buffer.from(protobuf_encode<OidbBase<OidbGroupFileResp>>({ body }))
: Buffer.alloc(0);
const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData };
return { sendRawPacket: vi.fn(async () => r) };
}
describe('DeleteGroupFile namespace', () => {
it('declares 0x6D6_3 with uinForm=true', () => {
expect(DeleteGroupFile.command).toBe(0x6D6);
expect(DeleteGroupFile.subCommand).toBe(3);
expect(DeleteGroupFile.uinForm).toBe(true);
});
it('packages busId=102 and routes to 0x6d6_3', async () => {
const deps = makeDeps({ delete: {} as any });
await DeleteGroupFile.invoke(deps, { groupId: 12345, fileId: 'fid' });
const [wire, bytes] = deps.sendRawPacket.mock.calls[0]!;
expect(wire).toBe('OidbSvcTrpcTcp.0x6d6_3');
const env = protobuf_decode<OidbBase<OidbGroupFileReq>>(bytes);
expect(env.body?.delete).toMatchObject({ groupUin: 12345, busId: 102, fileId: 'fid' });
});
it('throws on missing delete sub-message', async () => {
const deps = makeDeps({});
await expect(DeleteGroupFile.invoke(deps, { groupId: 1, fileId: 'f' }))
.rejects.toThrow(/delete response missing/);
});
it('throws on non-zero retCode', async () => {
const deps = makeDeps({ delete: { retCode: 5, retMsg: 'no perms' } as any });
await expect(DeleteGroupFile.invoke(deps, { groupId: 1, fileId: 'f' }))
.rejects.toThrow(/code=5/);
});
});
@@ -0,0 +1,38 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
OidbGroupFileFolderReq, OidbGroupFileFolderResp,
} from '@snowluma/proto-defs/oidb-actions/group-file';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { DeleteGroupFolder } from '../../../src/oidb-services/group-file/delete-group-folder';
function makeDeps(body?: OidbGroupFileFolderResp) {
const responseData = body !== undefined
? Buffer.from(protobuf_encode<OidbBase<OidbGroupFileFolderResp>>({ body }))
: Buffer.alloc(0);
const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData };
return { sendRawPacket: vi.fn(async () => r) };
}
describe('DeleteGroupFolder namespace', () => {
it('declares 0x6D7_1 with uinForm=true', () => {
expect(DeleteGroupFolder.command).toBe(0x6D7);
expect(DeleteGroupFolder.subCommand).toBe(1);
expect(DeleteGroupFolder.uinForm).toBe(true);
});
it('packages delete.{groupUin, folderId}', async () => {
const deps = makeDeps({ delete: {} as any });
await DeleteGroupFolder.invoke(deps, { groupId: 12345, folderId: 'fid' });
const env = protobuf_decode<OidbBase<OidbGroupFileFolderReq>>(deps.sendRawPacket.mock.calls[0]![1]);
expect(env.body?.delete).toMatchObject({ groupUin: 12345, folderId: 'fid' });
});
it('throws on missing delete sub-message', async () => {
const deps = makeDeps({});
await expect(DeleteGroupFolder.invoke(deps, { groupId: 1, folderId: 'f' }))
.rejects.toThrow(/folder delete response missing/);
});
});
@@ -0,0 +1,45 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
OidbGroupFileCountViewReq, OidbGroupFileCountViewResp,
} from '@snowluma/proto-defs/oidb-actions/group-file';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { GetGroupFileCount } from '../../../src/oidb-services/group-file/get-group-file-count';
function makeDeps(body?: OidbGroupFileCountViewResp) {
const responseData = body !== undefined
? Buffer.from(protobuf_encode<OidbBase<OidbGroupFileCountViewResp>>({ body }))
: Buffer.alloc(0);
const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData };
return { sendRawPacket: vi.fn(async () => r) };
}
describe('GetGroupFileCount namespace', () => {
it('declares 0x6D8_3', () => {
expect(GetGroupFileCount.command).toBe(0x6D8);
expect(GetGroupFileCount.subCommand).toBe(3);
});
it('routes to 0x6d8_3 with groupUin + appId=7 + busId=0', async () => {
const deps = makeDeps({ count: { fileCount: 1, maxCount: 100 } });
await GetGroupFileCount.invoke(deps, { groupId: 12345 });
const [wire, bytes] = deps.sendRawPacket.mock.calls[0]!;
expect(wire).toBe('OidbSvcTrpcTcp.0x6d8_3');
const env = protobuf_decode<OidbBase<OidbGroupFileCountViewReq>>(bytes);
expect(env.body?.count).toMatchObject({ groupUin: 12345, appId: 7 });
});
it('decodes both counters as plain numbers', async () => {
const deps = makeDeps({ count: { fileCount: 42, maxCount: 1000 } });
const out = await GetGroupFileCount.invoke(deps, { groupId: 1 });
expect(out).toEqual({ fileCount: 42, maxCount: 1000 });
});
it('falls back to maxCount=10000 when the server elides it', async () => {
const deps = makeDeps({ count: {} });
const out = await GetGroupFileCount.invoke(deps, { groupId: 1 });
expect(out).toEqual({ fileCount: 0, maxCount: 10000 });
});
});
@@ -0,0 +1,50 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
OidbGroupFileReq, OidbGroupFileResp,
} from '@snowluma/proto-defs/oidb-actions/group-file';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { GetGroupFileUrl } from '../../../src/oidb-services/group-file/get-group-file-url';
function makeDeps(body?: OidbGroupFileResp) {
const responseData = body !== undefined
? Buffer.from(protobuf_encode<OidbBase<OidbGroupFileResp>>({ body }))
: Buffer.alloc(0);
const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData };
return { sendRawPacket: vi.fn(async () => r) };
}
describe('GetGroupFileUrl namespace', () => {
it('declares 0x6D6_2 with uinForm=true', () => {
expect(GetGroupFileUrl.command).toBe(0x6D6);
expect(GetGroupFileUrl.subCommand).toBe(2);
expect(GetGroupFileUrl.uinForm).toBe(true);
});
it('packages the download slot with the supplied busId', async () => {
const deps = makeDeps({ download: { downloadDns: 'cdn', downloadUrl: new Uint8Array([1, 2]) } as any });
await GetGroupFileUrl.invoke(deps, { groupId: 12345, fileId: 'fid', busId: 102 });
const [wire, bytes] = deps.sendRawPacket.mock.calls[0]!;
expect(wire).toBe('OidbSvcTrpcTcp.0x6d6_2');
const env = protobuf_decode<OidbBase<OidbGroupFileReq>>(bytes);
expect(env.body?.download).toMatchObject({
groupUin: 12345, appId: 7, busId: 102, fileId: 'fid',
});
});
it('returns the download sub-message verbatim (URL composition lives on the facade)', async () => {
const deps = makeDeps({ download: { downloadDns: 'cdn', downloadUrl: new Uint8Array([0x01]) } as any });
const out = await GetGroupFileUrl.invoke(deps, { groupId: 1, fileId: 'f', busId: 102 });
expect(out.downloadDns).toBe('cdn');
// proton round-trips bytes through a Node Buffer; assert the byte values, not the wrapper class.
expect(Array.from(out.downloadUrl ?? new Uint8Array())).toEqual([0x01]);
});
it('throws when the download sub-message is missing', async () => {
const deps = makeDeps({});
await expect(GetGroupFileUrl.invoke(deps, { groupId: 1, fileId: 'f', busId: 102 }))
.rejects.toThrow(/url response missing/);
});
});
@@ -0,0 +1,51 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { NTV2RichMediaReq, NTV2RichMediaResp } from '@snowluma/proto-defs/oidb-actions/media';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { GetGroupPttUrl } from '../../../src/oidb-services/group-file/get-group-ptt-url';
function makeDeps(body?: NTV2RichMediaResp) {
const responseData = body !== undefined
? Buffer.from(protobuf_encode<OidbBase<NTV2RichMediaResp>>({ body }))
: Buffer.alloc(0);
const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData };
return { sendRawPacket: vi.fn(async () => r) };
}
describe('GetGroupPttUrl namespace', () => {
it('declares 0x126E_200 with uinForm=true', () => {
expect(GetGroupPttUrl.command).toBe(0x126E);
expect(GetGroupPttUrl.subCommand).toBe(200);
expect(GetGroupPttUrl.uinForm).toBe(true);
});
it('emits scene{requestType=1, businessType=3, sceneType=2, group.groupUin}', async () => {
const deps = makeDeps({
respHead: { retCode: 0 },
download: { info: { domain: 'd', urlPath: '/p' }, rKeyParam: '?rk' },
} as any);
await GetGroupPttUrl.invoke(deps, { groupId: 12345, node: { fileUuid: 'uuid' } });
const env = protobuf_decode<OidbBase<NTV2RichMediaReq>>(deps.sendRawPacket.mock.calls[0]![1]);
expect(env.body?.reqHead?.scene).toMatchObject({
requestType: 1, businessType: 3, sceneType: 2,
group: { groupUin: 12345 },
});
});
it('composes the https://domain<path><rkey> URL', async () => {
const deps = makeDeps({
respHead: { retCode: 0 },
download: { info: { domain: 'cdn.qq', urlPath: '/x' }, rKeyParam: '?r=1' },
} as any);
const out = await GetGroupPttUrl.invoke(deps, { groupId: 1, node: { fileUuid: 'uuid' } });
expect(out).toBe('https://cdn.qq/x?r=1');
});
it('throws when fileUuid is missing on the node', async () => {
const deps = makeDeps({} as any);
await expect(GetGroupPttUrl.invoke(deps, { groupId: 1, node: {} }))
.rejects.toThrow(/fileUuid is required/);
});
});
@@ -0,0 +1,45 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { NTV2RichMediaReq, NTV2RichMediaResp } from '@snowluma/proto-defs/oidb-actions/media';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { GetGroupVideoUrl } from '../../../src/oidb-services/group-file/get-group-video-url';
function makeDeps(body?: NTV2RichMediaResp) {
const responseData = body !== undefined
? Buffer.from(protobuf_encode<OidbBase<NTV2RichMediaResp>>({ body }))
: Buffer.alloc(0);
const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData };
return { sendRawPacket: vi.fn(async () => r) };
}
describe('GetGroupVideoUrl namespace', () => {
it('declares 0x11EA_200 with uinForm=true', () => {
expect(GetGroupVideoUrl.command).toBe(0x11EA);
expect(GetGroupVideoUrl.subCommand).toBe(200);
expect(GetGroupVideoUrl.uinForm).toBe(true);
});
it('emits scene{requestType=2, businessType=2, sceneType=2, group}', async () => {
const deps = makeDeps({
respHead: { retCode: 0 },
download: { info: { domain: 'd', urlPath: '/v' }, rKeyParam: '' },
} as any);
await GetGroupVideoUrl.invoke(deps, { groupId: 12345, node: { fileUuid: 'uuid' } });
const env = protobuf_decode<OidbBase<NTV2RichMediaReq>>(deps.sendRawPacket.mock.calls[0]![1]);
expect(env.body?.reqHead?.scene).toMatchObject({
requestType: 2, businessType: 2, sceneType: 2,
group: { groupUin: 12345 },
});
});
it('bubbles up retCode != 0 via the shared ntv2 deserializer', async () => {
const deps = makeDeps({
respHead: { retCode: 99, message: 'gone' },
download: { info: { domain: 'd', urlPath: '/p' }, rKeyParam: '' },
} as any);
await expect(GetGroupVideoUrl.invoke(deps, { groupId: 1, node: { fileUuid: 'u' } }))
.rejects.toThrow(/code=99/);
});
});
@@ -0,0 +1,61 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
OidbPrivateFileDownloadReq, OidbPrivateFileDownloadResp,
} from '@snowluma/proto-defs/oidb-actions/media';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { GetPrivateFileUrl } from '../../../src/oidb-services/group-file/get-private-file-url';
function makeDeps(body?: OidbPrivateFileDownloadResp) {
const responseData = body !== undefined
? Buffer.from(protobuf_encode<OidbBase<OidbPrivateFileDownloadResp>>({ body }))
: Buffer.alloc(0);
const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData };
return { sendRawPacket: vi.fn(async () => r) };
}
describe('GetPrivateFileUrl namespace', () => {
it('declares 0xE37_1200', () => {
expect(GetPrivateFileUrl.command).toBe(0xE37);
expect(GetPrivateFileUrl.subCommand).toBe(1200);
});
it('packages the magic field99999 cookie + body fields', async () => {
const deps = makeDeps({
body: { result: { server: 'host', port: 80, url: '/u' } } as any,
});
await GetPrivateFileUrl.invoke(deps, { selfUid: 'self', fileId: 'fid', fileHash: 'h' });
const [wire, bytes] = deps.sendRawPacket.mock.calls[0]!;
expect(wire).toBe('OidbSvcTrpcTcp.0xe37_1200');
const env = protobuf_decode<OidbBase<OidbPrivateFileDownloadReq>>(bytes);
expect(env.body).toMatchObject({
subCommand: 1200,
field2: 1,
field101: 3,
field102: 103,
field200: 1,
});
expect(env.body?.body).toMatchObject({
receiverUid: 'self', fileUuid: 'fid', type: 2, fileHash: 'h',
});
expect(env.body?.field99999).toEqual(new Uint8Array([0xC0, 0x85, 0x2C, 0x01]));
});
it('returns the result sub-message verbatim', async () => {
const deps = makeDeps({
body: { result: { server: 'srv', port: 8080, url: '/path' } } as any,
});
const out = await GetPrivateFileUrl.invoke(deps, { selfUid: 's', fileId: 'f', fileHash: 'h' });
expect(out.server).toBe('srv');
expect(out.port).toBe(8080);
expect(out.url).toBe('/path');
});
it('throws when result is missing', async () => {
const deps = makeDeps({ body: {} });
await expect(GetPrivateFileUrl.invoke(deps, { selfUid: 's', fileId: 'f', fileHash: 'h' }))
.rejects.toThrow(/private file url response invalid/);
});
});
@@ -0,0 +1,36 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { NTV2RichMediaReq, NTV2RichMediaResp } from '@snowluma/proto-defs/oidb-actions/media';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { GetPrivatePttUrl } from '../../../src/oidb-services/group-file/get-private-ptt-url';
function makeDeps(body?: NTV2RichMediaResp) {
const responseData = body !== undefined
? Buffer.from(protobuf_encode<OidbBase<NTV2RichMediaResp>>({ body }))
: Buffer.alloc(0);
const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData };
return { sendRawPacket: vi.fn(async () => r) };
}
describe('GetPrivatePttUrl namespace', () => {
it('declares 0x126D_200 with uinForm=true', () => {
expect(GetPrivatePttUrl.command).toBe(0x126D);
expect(GetPrivatePttUrl.subCommand).toBe(200);
expect(GetPrivatePttUrl.uinForm).toBe(true);
});
it('emits c2c scene with self uid as targetUid', async () => {
const deps = makeDeps({
respHead: { retCode: 0 },
download: { info: { domain: 'd', urlPath: '/p' }, rKeyParam: '' },
} as any);
await GetPrivatePttUrl.invoke(deps, { selfUid: 'self', node: { fileUuid: 'uuid' } });
const env = protobuf_decode<OidbBase<NTV2RichMediaReq>>(deps.sendRawPacket.mock.calls[0]![1]);
expect(env.body?.reqHead?.scene).toMatchObject({
requestType: 1, businessType: 3, sceneType: 1,
c2c: { accountType: 2, targetUid: 'self' },
});
});
});
@@ -0,0 +1,36 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { NTV2RichMediaReq, NTV2RichMediaResp } from '@snowluma/proto-defs/oidb-actions/media';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { GetPrivateVideoUrl } from '../../../src/oidb-services/group-file/get-private-video-url';
function makeDeps(body?: NTV2RichMediaResp) {
const responseData = body !== undefined
? Buffer.from(protobuf_encode<OidbBase<NTV2RichMediaResp>>({ body }))
: Buffer.alloc(0);
const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData };
return { sendRawPacket: vi.fn(async () => r) };
}
describe('GetPrivateVideoUrl namespace', () => {
it('declares 0x11E9_200 with uinForm=true', () => {
expect(GetPrivateVideoUrl.command).toBe(0x11E9);
expect(GetPrivateVideoUrl.subCommand).toBe(200);
expect(GetPrivateVideoUrl.uinForm).toBe(true);
});
it('emits c2c scene with self uid as targetUid', async () => {
const deps = makeDeps({
respHead: { retCode: 0 },
download: { info: { domain: 'd', urlPath: '/v' }, rKeyParam: '' },
} as any);
await GetPrivateVideoUrl.invoke(deps, { selfUid: 'self', node: { fileUuid: 'uuid' } });
const env = protobuf_decode<OidbBase<NTV2RichMediaReq>>(deps.sendRawPacket.mock.calls[0]![1]);
expect(env.body?.reqHead?.scene).toMatchObject({
requestType: 2, businessType: 2, sceneType: 1,
c2c: { accountType: 2, targetUid: 'self' },
});
});
});
@@ -0,0 +1,58 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
OidbGroupFileViewReq, OidbGroupFileViewResp,
} from '@snowluma/proto-defs/oidb-actions/group-file';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { ListGroupFilesPage } from '../../../src/oidb-services/group-file/list-group-files-page';
function makeDeps(body?: OidbGroupFileViewResp) {
const responseData = body !== undefined
? Buffer.from(protobuf_encode<OidbBase<OidbGroupFileViewResp>>({ body }))
: Buffer.alloc(0);
const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData };
return { sendRawPacket: vi.fn(async () => r) };
}
describe('ListGroupFilesPage namespace', () => {
it('declares 0x6D8_1 with uinForm=true', () => {
expect(ListGroupFilesPage.command).toBe(0x6D8);
expect(ListGroupFilesPage.subCommand).toBe(1);
expect(ListGroupFilesPage.uinForm).toBe(true);
});
it('packages the page parameters (sortBy=1, field17=2, field18=0)', async () => {
const deps = makeDeps({ list: { isEnd: true, items: [] } as any });
await ListGroupFilesPage.invoke(deps, {
groupId: 12345, targetDirectory: '/a', startIndex: 20, pageSize: 50,
});
const env = protobuf_decode<OidbBase<OidbGroupFileViewReq>>(deps.sendRawPacket.mock.calls[0]![1]);
expect(env.body?.list).toMatchObject({
groupUin: 12345, appId: 7,
targetDirectory: '/a', fileCount: 50,
sortBy: 1, startIndex: 20,
field17: 2,
});
});
it('returns the list body so the facade can walk items / isEnd', async () => {
const deps = makeDeps({
list: { isEnd: false, items: [{ type: 1 }] } as any,
});
const out = await ListGroupFilesPage.invoke(deps, {
groupId: 1, targetDirectory: '/', startIndex: 0, pageSize: 10,
});
expect(out?.isEnd ?? false).toBe(false);
expect(out?.items).toHaveLength(1);
});
it('returns null when the server elides the list slot', async () => {
const deps = makeDeps({});
const out = await ListGroupFilesPage.invoke(deps, {
groupId: 1, targetDirectory: '/', startIndex: 0, pageSize: 10,
});
expect(out).toBeNull();
});
});
@@ -0,0 +1,45 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
OidbGroupFileReq, OidbGroupFileResp,
} from '@snowluma/proto-defs/oidb-actions/group-file';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { MoveGroupFile } from '../../../src/oidb-services/group-file/move-group-file';
function makeDeps(body?: OidbGroupFileResp) {
const responseData = body !== undefined
? Buffer.from(protobuf_encode<OidbBase<OidbGroupFileResp>>({ body }))
: Buffer.alloc(0);
const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData };
return { sendRawPacket: vi.fn(async () => r) };
}
describe('MoveGroupFile namespace', () => {
it('declares 0x6D6_5 with uinForm=true', () => {
expect(MoveGroupFile.command).toBe(0x6D6);
expect(MoveGroupFile.subCommand).toBe(5);
expect(MoveGroupFile.uinForm).toBe(true);
});
it('packages parent + target directories under the move slot', async () => {
const deps = makeDeps({ move: {} as any });
await MoveGroupFile.invoke(deps, {
groupId: 12345, fileId: 'fid',
parentDirectory: '/a', targetDirectory: '/b',
});
const env = protobuf_decode<OidbBase<OidbGroupFileReq>>(deps.sendRawPacket.mock.calls[0]![1]);
expect(env.body?.move).toMatchObject({
groupUin: 12345, appId: 7, busId: 102, fileId: 'fid',
parentDirectory: '/a', targetDirectory: '/b',
});
});
it('throws on missing move sub-message', async () => {
const deps = makeDeps({});
await expect(MoveGroupFile.invoke(deps, {
groupId: 1, fileId: 'f', parentDirectory: '/', targetDirectory: '/',
})).rejects.toThrow(/move response missing/);
});
});
@@ -0,0 +1,41 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_decode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { OidbGroupSendFileReq } from '@snowluma/proto-defs/oidb-actions/group-file';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { PublishGroupFile } from '../../../src/oidb-services/group-file/publish-group-file';
function makeDeps() {
const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: Buffer.alloc(0) };
return { sendRawPacket: vi.fn(async () => r) };
}
describe('PublishGroupFile namespace', () => {
it('declares 0x6D9_4', () => {
expect(PublishGroupFile.command).toBe(0x6D9);
expect(PublishGroupFile.subCommand).toBe(4);
});
it('routes to 0x6d9_4 with busiType=102, type=2, field5=true', async () => {
const deps = makeDeps();
await PublishGroupFile.invoke(deps, { groupId: 12345, fileId: 'fid' });
const [wire, bytes] = deps.sendRawPacket.mock.calls[0]!;
expect(wire).toBe('OidbSvcTrpcTcp.0x6d9_4');
const env = protobuf_decode<OidbBase<OidbGroupSendFileReq>>(bytes);
expect(env.body?.body).toMatchObject({
groupUin: 12345, type: 2,
info: expect.objectContaining({ busiType: 102, fileId: 'fid', field5: true }),
});
});
it('emits a non-zero `info.field3` random discriminator', async () => {
// Lagrange-V2 sets this to `Random.Shared.Next()`; our serialize uses
// Math.random() — both produce a 31-bit unsigned int, never 0.
const deps = makeDeps();
await PublishGroupFile.invoke(deps, { groupId: 1, fileId: 'f' });
const env = protobuf_decode<OidbBase<OidbGroupSendFileReq>>(deps.sendRawPacket.mock.calls[0]![1]);
const field3 = env.body?.body?.info?.field3 ?? 0;
expect(typeof field3).toBe('number');
});
});
@@ -0,0 +1,43 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
OidbGroupFileFolderReq, OidbGroupFileFolderResp,
} from '@snowluma/proto-defs/oidb-actions/group-file';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { RenameGroupFolder } from '../../../src/oidb-services/group-file/rename-group-folder';
function makeDeps(body?: OidbGroupFileFolderResp) {
const responseData = body !== undefined
? Buffer.from(protobuf_encode<OidbBase<OidbGroupFileFolderResp>>({ body }))
: Buffer.alloc(0);
const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData };
return { sendRawPacket: vi.fn(async () => r) };
}
describe('RenameGroupFolder namespace', () => {
it('declares 0x6D7_2 with uinForm=true', () => {
expect(RenameGroupFolder.command).toBe(0x6D7);
expect(RenameGroupFolder.subCommand).toBe(2);
expect(RenameGroupFolder.uinForm).toBe(true);
});
it('packages rename.{groupUin, folderId, newFolderName}', async () => {
const deps = makeDeps({ rename: {} as any });
await RenameGroupFolder.invoke(deps, {
groupId: 12345, folderId: 'fid', newFolderName: 'newname',
});
const env = protobuf_decode<OidbBase<OidbGroupFileFolderReq>>(deps.sendRawPacket.mock.calls[0]![1]);
expect(env.body?.rename).toMatchObject({
groupUin: 12345, folderId: 'fid', newFolderName: 'newname',
});
});
it('throws on missing rename sub-message', async () => {
const deps = makeDeps({});
await expect(RenameGroupFolder.invoke(deps, {
groupId: 1, folderId: 'f', newFolderName: 'n',
})).rejects.toThrow(/folder rename response missing/);
});
});
@@ -0,0 +1,64 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
OidbGroupFileReq, OidbGroupFileResp,
} from '@snowluma/proto-defs/oidb-actions/group-file';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { UploadGroupFileRequest } from '../../../src/oidb-services/group-file/upload-group-file-request';
function makeDeps(body?: OidbGroupFileResp) {
const responseData = body !== undefined
? Buffer.from(protobuf_encode<OidbBase<OidbGroupFileResp>>({ body }))
: Buffer.alloc(0);
const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData };
return { sendRawPacket: vi.fn(async () => r) };
}
describe('UploadGroupFileRequest namespace', () => {
it('declares 0x6D6_0 with uinForm=true', () => {
expect(UploadGroupFileRequest.command).toBe(0x6D6);
expect(UploadGroupFileRequest.subCommand).toBe(0);
expect(UploadGroupFileRequest.uinForm).toBe(true);
});
it('packages the file pre-flight slot (entrance=6, appId=4, busId=102)', async () => {
const deps = makeDeps({ upload: { fileId: 'fid', boolFileExist: true } as any });
await UploadGroupFileRequest.invoke(deps, {
groupId: 12345,
fileName: 'doc.pdf',
folderId: '/',
fileSize: 1024,
fileSha1: new Uint8Array(20),
fileMd5: new Uint8Array(16),
});
const [wire, bytes] = deps.sendRawPacket.mock.calls[0]!;
expect(wire).toBe('OidbSvcTrpcTcp.0x6d6_0');
const env = protobuf_decode<OidbBase<OidbGroupFileReq>>(bytes);
expect(env.reserved).toBe(1); // uinForm
expect(env.body?.file).toMatchObject({
groupUin: 12345, appId: 4, busId: 102, entrance: 6,
targetDirectory: '/', fileName: 'doc.pdf', localDirectory: '/doc.pdf',
fileSize: 1024n, field15: true,
});
});
it('returns the upload-info body for the facade orchestration', async () => {
const deps = makeDeps({ upload: { fileId: 'fid-X', boolFileExist: true } as any });
const out = await UploadGroupFileRequest.invoke(deps, {
groupId: 1, fileName: 'f', folderId: '/',
fileSize: 0, fileSha1: new Uint8Array(0), fileMd5: new Uint8Array(0),
});
expect(out.fileId).toBe('fid-X');
expect(out.boolFileExist).toBe(true);
});
it('throws when the upload sub-message is missing', async () => {
const deps = makeDeps({});
await expect(UploadGroupFileRequest.invoke(deps, {
groupId: 1, fileName: 'f', folderId: '/',
fileSize: 0, fileSha1: new Uint8Array(0), fileMd5: new Uint8Array(0),
})).rejects.toThrow(/upload response missing/);
});
});
@@ -0,0 +1,68 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
OidbPrivateFileUploadReq, OidbPrivateFileUploadResp,
} from '@snowluma/proto-defs/oidb-actions/media';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { UploadPrivateFileRequest } from '../../../src/oidb-services/group-file/upload-private-file-request';
function makeDeps(body?: OidbPrivateFileUploadResp) {
const responseData = body !== undefined
? Buffer.from(protobuf_encode<OidbBase<OidbPrivateFileUploadResp>>({ body }))
: Buffer.alloc(0);
const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData };
return { sendRawPacket: vi.fn(async () => r) };
}
describe('UploadPrivateFileRequest namespace', () => {
it('declares 0xE37_1700', () => {
expect(UploadPrivateFileRequest.command).toBe(0xE37);
expect(UploadPrivateFileRequest.subCommand).toBe(1700);
});
it('packages businessId=3, clientType=1, flagSupportMediaPlatform=1 alongside the upload body', async () => {
const deps = makeDeps({ upload: { uuid: 'fid', boolFileExist: true } as any });
await UploadPrivateFileRequest.invoke(deps, {
senderUid: 's', receiverUid: 'r',
fileName: 'f.pdf', fileSize: 4096,
fileSha1: new Uint8Array(20), fileMd5: new Uint8Array(16),
md510MCheckSum: new Uint8Array(16),
});
const [wire, bytes] = deps.sendRawPacket.mock.calls[0]!;
expect(wire).toBe('OidbSvcTrpcTcp.0xe37_1700');
const env = protobuf_decode<OidbBase<OidbPrivateFileUploadReq>>(bytes);
expect(env.body).toMatchObject({
command: 1700, businessId: 3, clientType: 1, flagSupportMediaPlatform: 1,
});
expect(env.body?.upload).toMatchObject({
senderUid: 's', receiverUid: 'r',
fileSize: 4096, fileName: 'f.pdf',
});
});
it('returns the upload body for the facade host-selection step', async () => {
const deps = makeDeps({
upload: { uuid: 'fid-Y', fileAddon: 'hash', boolFileExist: true } as any,
});
const out = await UploadPrivateFileRequest.invoke(deps, {
senderUid: 's', receiverUid: 'r',
fileName: 'f', fileSize: 0,
fileSha1: new Uint8Array(0), fileMd5: new Uint8Array(0),
md510MCheckSum: new Uint8Array(0),
});
expect(out.uuid).toBe('fid-Y');
expect(out.fileAddon).toBe('hash');
});
it('throws when the upload sub-message is missing', async () => {
const deps = makeDeps({});
await expect(UploadPrivateFileRequest.invoke(deps, {
senderUid: 's', receiverUid: 'r',
fileName: 'f', fileSize: 0,
fileSha1: new Uint8Array(0), fileMd5: new Uint8Array(0),
md510MCheckSum: new Uint8Array(0),
})).rejects.toThrow(/upload response missing/);
});
});
@@ -0,0 +1,58 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_decode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { OidbLike } from '@snowluma/proto-defs/oidb-actions/base';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { SendLike } from '../../../src/oidb-services/interaction/send-like';
function makeDeps(uid = 'target-uid-xyz') {
const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: Buffer.alloc(0) };
return {
sendRawPacket: vi.fn(async () => r),
resolveUserUid: vi.fn(async () => uid),
};
}
describe('SendLike namespace', () => {
it('declares 0x7E5_104', () => {
expect(SendLike.command).toBe(0x7E5);
expect(SendLike.subCommand).toBe(104);
});
describe('serialize', () => {
it('resolves uid via ctx and emits {targetUid, sourceId=71, count}', async () => {
const deps = makeDeps('UID-AAA');
const body = await SendLike.serialize(deps, { userId: 10001, count: 3 });
expect(deps.resolveUserUid).toHaveBeenCalledWith(10001);
expect(body).toEqual({ targetUid: 'UID-AAA', sourceId: 71, count: 3 });
});
it('throws when ctx returns an empty uid', async () => {
const deps = makeDeps('');
await expect(SendLike.serialize(deps, { userId: 10001, count: 1 }))
.rejects.toThrow(/failed to resolve uid/);
});
});
describe('invoke (e2e)', () => {
it('routes to OidbSvcTrpcTcp.0x7e5_104', async () => {
const deps = makeDeps();
await SendLike.invoke(deps, { userId: 10001, count: 3 });
expect(deps.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0x7e5_104');
});
it('encodes targetUid (field 11) + sourceId=71 (field 12) + count (field 13)', async () => {
const deps = makeDeps('UID-BBB');
await SendLike.invoke(deps, { userId: 10001, count: 5 });
const [, bytes] = deps.sendRawPacket.mock.calls[0]!;
const env = protobuf_decode<OidbBase<OidbLike>>(bytes);
expect(env.command).toBe(0x7E5);
expect(env.subCommand).toBe(104);
expect(env.body).toMatchObject({ targetUid: 'UID-BBB', sourceId: 71, count: 5 });
// Defensive: the obsolete uin-form field must not appear (server
// rejects uin-form payloads with "被点赞 QQ 号非法").
expect((env.body as any).targetUin).toBeUndefined();
});
});
});
@@ -0,0 +1,76 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_decode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { OidbPoke } from '@snowluma/proto-defs/oidb-actions/base';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { SendPoke } from '../../../src/oidb-services/interaction/send-poke';
function makeSender() {
const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: Buffer.alloc(0) };
return { sendRawPacket: vi.fn(async () => r) };
}
describe('SendPoke namespace', () => {
it('declares 0xED3_1', () => {
expect(SendPoke.command).toBe(0xED3);
expect(SendPoke.subCommand).toBe(1);
});
describe('serialize', () => {
it('group poke: groupUin = peer, friendUin = 0, uin = targetUin', () => {
expect(SendPoke.serialize({} as any, { isGroup: true, peerUin: 12345, targetUin: 67890 })).toEqual({
uin: 67890, groupUin: 12345, friendUin: 0, ext: 0,
});
});
it('group poke without targetUin: uin defaults to peer', () => {
expect(SendPoke.serialize({} as any, { isGroup: true, peerUin: 12345 })).toEqual({
uin: 12345, groupUin: 12345, friendUin: 0, ext: 0,
});
});
it('friend poke: friendUin = peer, groupUin = 0, uin = targetUin', () => {
expect(SendPoke.serialize({} as any, { isGroup: false, peerUin: 67890, targetUin: 11111 })).toEqual({
uin: 11111, groupUin: 0, friendUin: 67890, ext: 0,
});
});
it('friend poke without targetUin: uin defaults to peer', () => {
expect(SendPoke.serialize({} as any, { isGroup: false, peerUin: 67890 })).toEqual({
uin: 67890, groupUin: 0, friendUin: 67890, ext: 0,
});
});
it('always sets ext = 0', () => {
expect(SendPoke.serialize({} as any, { isGroup: true, peerUin: 1 }).ext).toBe(0);
expect(SendPoke.serialize({} as any, { isGroup: false, peerUin: 1 }).ext).toBe(0);
});
});
describe('invoke (e2e)', () => {
it('routes to OidbSvcTrpcTcp.0xed3_1', async () => {
const sender = makeSender();
await SendPoke.invoke(sender, { isGroup: true, peerUin: 1 });
expect(sender.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0xed3_1');
});
it('encodes serialize() output into envelope body', async () => {
const sender = makeSender();
await SendPoke.invoke(sender, { isGroup: true, peerUin: 12345, targetUin: 67890 });
const [, bytes] = sender.sendRawPacket.mock.calls[0]!;
const env = protobuf_decode<OidbBase<OidbPoke>>(bytes);
expect(env.command).toBe(0xED3);
expect(env.subCommand).toBe(1);
expect(env.body).toMatchObject({ uin: 67890, groupUin: 12345 });
// proto3 default 0 for friendUin/ext is omitted on the wire.
expect(env.body?.friendUin ?? 0).toBe(0);
});
it('resolves to undefined', async () => {
const sender = makeSender();
const result = await SendPoke.invoke(sender, { isGroup: false, peerUin: 1 });
expect(result).toBeUndefined();
});
});
});
@@ -0,0 +1,59 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_decode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { OidbEssence } from '@snowluma/proto-defs/oidb-actions/base';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { SetEssence } from '../../../src/oidb-services/interaction/set-essence';
function makeSender() {
const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: Buffer.alloc(0) };
return { sendRawPacket: vi.fn(async () => r) };
}
describe('SetEssence namespace', () => {
it('declares 0xEAC', () => {
expect(SetEssence.command).toBe(0xEAC);
});
describe('resolveSubCommand', () => {
it('returns 1 when enable=true', () => {
expect(SetEssence.resolveSubCommand({ groupId: 1, sequence: 1, random: 1, enable: true })).toBe(1);
});
it('returns 2 when enable=false', () => {
expect(SetEssence.resolveSubCommand({ groupId: 1, sequence: 1, random: 1, enable: false })).toBe(2);
});
});
describe('serialize', () => {
it('passes groupId / sequence / random through verbatim', () => {
expect(SetEssence.serialize({} as any, { groupId: 12345, sequence: 99, random: 0xCAFEBABE, enable: true })).toEqual({
groupUin: 12345, sequence: 99, random: 0xCAFEBABE,
});
});
});
describe('invoke (e2e)', () => {
it('routes to OidbSvcTrpcTcp.0xeac_1 when enabling', async () => {
const sender = makeSender();
await SetEssence.invoke(sender, { groupId: 12345, sequence: 99, random: 0, enable: true });
expect(sender.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0xeac_1');
});
it('routes to OidbSvcTrpcTcp.0xeac_2 when disabling', async () => {
const sender = makeSender();
await SetEssence.invoke(sender, { groupId: 12345, sequence: 99, random: 0, enable: false });
expect(sender.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0xeac_2');
});
it('encodes envelope body with the right shape', async () => {
const sender = makeSender();
await SetEssence.invoke(sender, { groupId: 12345, sequence: 99, random: 7, enable: true });
const [, bytes] = sender.sendRawPacket.mock.calls[0]!;
const env = protobuf_decode<OidbBase<OidbEssence>>(bytes);
expect(env.command).toBe(0xEAC);
expect(env.subCommand).toBe(1);
expect(env.body).toMatchObject({ groupUin: 12345, sequence: 99, random: 7 });
});
});
});
@@ -0,0 +1,98 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { Oidb0x112eReq, Oidb0x112eResp } from '@snowluma/proto-defs/oidb-actions/base';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { ClickInlineKeyboardButton } from '../../../src/oidb-services/misc/click-inline-keyboard-button';
function makeSender(resp?: Buffer) {
const r: SendPacketResult = {
success: true, gotResponse: true, errorCode: 0, errorMessage: '',
responseData: resp ?? Buffer.alloc(0),
};
return { sendRawPacket: vi.fn(async () => r) };
}
describe('ClickInlineKeyboardButton namespace', () => {
it('declares 0x112E_1', () => {
expect(ClickInlineKeyboardButton.command).toBe(0x112E);
expect(ClickInlineKeyboardButton.subCommand).toBe(1);
});
describe('serialize', () => {
it('widens numeric ids to BigInt for uint_64 fields', () => {
const out = ClickInlineKeyboardButton.serialize({} as any, {
groupId: 12345, botAppid: 67890, buttonId: 'btn', callbackData: 'data', msgSeq: 100,
});
expect(out.groupId).toBe(12345n);
expect(out.botAppid).toBe(67890n);
expect(out.msgSeq).toBe(100n);
});
it('always sends unknown7=0 / unknown9=1 magic values', () => {
const out = ClickInlineKeyboardButton.serialize({} as any, {
groupId: 1, botAppid: 1, buttonId: 'x', callbackData: 'y', msgSeq: 1,
});
expect(out.unknown7).toBe(0);
expect(out.unknown9).toBe(1);
});
it('coerces buttonId / callbackData to strings (defensive)', () => {
const out = ClickInlineKeyboardButton.serialize({} as any, {
groupId: 1, botAppid: 1, buttonId: 123 as any, callbackData: null as any, msgSeq: 1,
});
expect(out.buttonId).toBe('123');
expect(out.callbackData).toBe('');
});
});
describe('deserialize', () => {
it('shapes the response with status/promptType/promptIcon = 0', () => {
expect(ClickInlineKeyboardButton.deserialize({} as any, {
result: 1, errMsg: 'ok', promptText: 'hi',
} as Oidb0x112eResp)).toEqual({
result: 1, errMsg: 'ok', status: 0, promptText: 'hi', promptType: 0, promptIcon: 0,
});
});
it('defaults result/errMsg/promptText when omitted', () => {
expect(ClickInlineKeyboardButton.deserialize({} as any, {} as Oidb0x112eResp)).toEqual({
result: 0, errMsg: '', status: 0, promptText: '', promptType: 0, promptIcon: 0,
});
});
});
describe('invoke (e2e)', () => {
it('routes to OidbSvcTrpcTcp.0x112e_1', async () => {
const sender = makeSender();
await ClickInlineKeyboardButton.invoke(sender, {
groupId: 1, botAppid: 1, buttonId: 'x', callbackData: 'y', msgSeq: 1,
});
expect(sender.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0x112e_1');
});
it('round-trips a real envelope', async () => {
const sender = makeSender(Buffer.from(protobuf_encode<OidbBase<Oidb0x112eResp>>({
body: { result: 7, errMsg: 'denied', promptText: 'try again' } as any,
})));
const out = await ClickInlineKeyboardButton.invoke(sender, {
groupId: 1, botAppid: 1, buttonId: 'x', callbackData: 'y', msgSeq: 1,
});
expect(out).toMatchObject({ result: 7, errMsg: 'denied', promptText: 'try again' });
});
it('encodes envelope body with all fields', async () => {
const sender = makeSender();
await ClickInlineKeyboardButton.invoke(sender, {
groupId: 12345, botAppid: 67890, buttonId: 'b', callbackData: 'c', msgSeq: 999,
});
const [, bytes] = sender.sendRawPacket.mock.calls[0]!;
const env = protobuf_decode<OidbBase<Oidb0x112eReq>>(bytes);
expect(env.body).toMatchObject({
botAppid: 67890n, msgSeq: 999n, buttonId: 'b', callbackData: 'c',
groupId: 12345n, unknown9: 1,
});
});
});
});
@@ -0,0 +1,42 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_decode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { Oidb0xeb7Req } from '@snowluma/proto-defs/oidb-actions/base';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { SendGroupSign } from '../../../src/oidb-services/misc/send-group-sign';
function makeDeps() {
const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: Buffer.alloc(0) };
return {
sendRawPacket: vi.fn(async () => r),
identity: { uin: '10001' } as any,
};
}
describe('SendGroupSign namespace', () => {
it('declares 0xEB7_1', () => {
expect(SendGroupSign.command).toBe(0xEB7);
expect(SendGroupSign.subCommand).toBe(1);
});
it('overrides wire name to preserve the historic UPPERCASE EB7 byte-equality', async () => {
const deps = makeDeps();
await SendGroupSign.invoke(deps, { groupId: 12345 });
expect(deps.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0xEB7_1');
});
describe('serialize', () => {
it('packages uin / groupId as strings + hardcodes version "9.0.90"', async () => {
const deps = makeDeps();
await SendGroupSign.invoke(deps, { groupId: 12345 });
const [, bytes] = deps.sendRawPacket.mock.calls[0]!;
const env = protobuf_decode<OidbBase<Oidb0xeb7Req>>(bytes);
expect(env.body?.signInInfo).toEqual({
uin: '10001',
groupId: '12345',
version: '9.0.90',
});
});
});
});
@@ -0,0 +1,76 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { Oidb0x990Req, Oidb0x990Resp } from '@snowluma/proto-defs/oidb-actions/base';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { TranslateEnToZh } from '../../../src/oidb-services/misc/translate-en-to-zh';
function makeSender(resp?: Buffer) {
const r: SendPacketResult = {
success: true, gotResponse: true, errorCode: 0, errorMessage: '',
responseData: resp ?? Buffer.alloc(0),
};
return { sendRawPacket: vi.fn(async () => r) };
}
describe('TranslateEnToZh namespace', () => {
it('declares 0x990_2', () => {
expect(TranslateEnToZh.command).toBe(0x990);
expect(TranslateEnToZh.subCommand).toBe(2);
});
describe('serialize', () => {
it('hardcodes en → zh and tag10/12 = 1', () => {
const out = TranslateEnToZh.serialize({} as any, { words: ['hello'] });
expect(out).toEqual({
translateReq: { srcLang: 'en', dstLang: 'zh', words: ['hello'] },
tag10: 1,
tag12: 1,
});
});
it('passes the words array verbatim', () => {
const out = TranslateEnToZh.serialize({} as any, { words: ['a', 'b', 'c'] });
expect(out.translateReq?.words).toEqual(['a', 'b', 'c']);
});
});
describe('deserialize', () => {
it('returns dstWords when translateResp is present', () => {
expect(TranslateEnToZh.deserialize({} as any, {
translateResp: { dstWords: ['你好', '世界'] },
} as Oidb0x990Resp)).toEqual(['你好', '世界']);
});
it('returns [] when dstWords is omitted but translateResp exists', () => {
expect(TranslateEnToZh.deserialize({} as any, { translateResp: {} } as Oidb0x990Resp)).toEqual([]);
});
it('throws when translateResp is missing', () => {
expect(() => TranslateEnToZh.deserialize({} as any, {} as Oidb0x990Resp))
.toThrow('translate response empty');
});
});
describe('invoke (e2e)', () => {
it('routes to OidbSvcTrpcTcp.0x990_2', async () => {
const sender = makeSender(Buffer.from(protobuf_encode<OidbBase<Oidb0x990Resp>>({
body: { translateResp: { dstWords: ['x'] } } as any,
})));
await TranslateEnToZh.invoke(sender, { words: ['hello'] });
expect(sender.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0x990_2');
});
it('encodes envelope body with the request payload', async () => {
const sender = makeSender(Buffer.from(protobuf_encode<OidbBase<Oidb0x990Resp>>({
body: { translateResp: { dstWords: ['你好'] } } as any,
})));
const out = await TranslateEnToZh.invoke(sender, { words: ['hello'] });
expect(out).toEqual(['你好']);
const [, bytes] = sender.sendRawPacket.mock.calls[0]!;
const env = protobuf_decode<OidbBase<Oidb0x990Req>>(bytes);
expect(env.body?.translateReq?.words).toEqual(['hello']);
});
});
});
@@ -0,0 +1,135 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { Oidb0x7edReq, Oidb0x7edResp } from '@snowluma/proto-defs/oidb-actions/base';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { GetLike } from '../../../src/oidb-services/profile/get-like';
function makeDeps(opts: {
cachedSelfUid?: string | null;
resolveUserUid?: (uin: number) => Promise<string>;
responseBody?: Oidb0x7edResp;
} = {}) {
const responseData = opts.responseBody !== undefined
? Buffer.from(protobuf_encode<OidbBase<Oidb0x7edResp>>({ body: opts.responseBody }))
: Buffer.alloc(0);
const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData };
return {
sendRawPacket: vi.fn(async () => r),
identity: { uin: '10001', selfUid: opts.cachedSelfUid ?? null } as any,
resolveUserUid: vi.fn(opts.resolveUserUid ?? (async (uin: number) => `uid-of-${uin}`)),
};
}
describe('GetLike namespace', () => {
it('declares 0x7ED_12', () => {
expect(GetLike.command).toBe(0x7ED);
expect(GetLike.subCommand).toBe(12);
});
describe('invoke (target uid resolution)', () => {
it('uses cached self uid when userId is omitted', async () => {
const deps = makeDeps({
cachedSelfUid: 'cached-self',
responseBody: { userLikeInfos: [{ uid: 'cached-self', time: 0n, favoriteInfo: {}, voteInfo: {} }] },
});
await GetLike.invoke(deps, {});
expect(deps.resolveUserUid).not.toHaveBeenCalled();
const [, bytes] = deps.sendRawPacket.mock.calls[0]!;
const env = protobuf_decode<OidbBase<Oidb0x7edReq>>(bytes);
expect(env.body?.targetUid).toBe('cached-self');
});
it('falls back to resolveUserUid for self when cache is empty', async () => {
const deps = makeDeps({
cachedSelfUid: null,
resolveUserUid: vi.fn(async () => 'fresh-self') as any,
responseBody: { userLikeInfos: [{ uid: 'fresh-self', time: 0n, favoriteInfo: {}, voteInfo: {} }] },
});
await GetLike.invoke(deps, {});
expect(deps.resolveUserUid).toHaveBeenCalledWith(10001);
});
it('resolves other users via resolveUserUid', async () => {
const deps = makeDeps({
responseBody: { userLikeInfos: [{ uid: 'uid-of-99999', time: 0n, favoriteInfo: {}, voteInfo: {} }] },
});
await GetLike.invoke(deps, { userId: 99999 });
expect(deps.resolveUserUid).toHaveBeenCalledWith(99999);
});
it('throws when self uin is invalid and cache is empty', async () => {
const deps = makeDeps({ cachedSelfUid: null });
deps.identity.uin = 'invalid';
await expect(GetLike.invoke(deps, {})).rejects.toThrow('self uid is unavailable');
});
});
describe('serialize', () => {
it('always sets basic=1, vote=1, favorite=1 (full breakdown query)', async () => {
const deps = makeDeps({
responseBody: { userLikeInfos: [{ uid: 'u', time: 0n, favoriteInfo: {}, voteInfo: {} }] },
});
await GetLike.invoke(deps, { userId: 1 });
const [, bytes] = deps.sendRawPacket.mock.calls[0]!;
const env = protobuf_decode<OidbBase<Oidb0x7edReq>>(bytes);
expect(env.body?.basic).toBe(1);
expect(env.body?.vote).toBe(1);
expect(env.body?.favorite).toBe(1);
});
it('threads start / limit through to the request', async () => {
const deps = makeDeps({
responseBody: { userLikeInfos: [{ uid: 'u', time: 0n, favoriteInfo: {}, voteInfo: {} }] },
});
await GetLike.invoke(deps, { userId: 1, start: 5, limit: 50 });
const [, bytes] = deps.sendRawPacket.mock.calls[0]!;
const env = protobuf_decode<OidbBase<Oidb0x7edReq>>(bytes);
expect(env.body?.start).toBe(5);
expect(env.body?.limit).toBe(50);
});
it('defaults start=0 / limit=10', async () => {
const deps = makeDeps({
responseBody: { userLikeInfos: [{ uid: 'u', time: 0n, favoriteInfo: {}, voteInfo: {} }] },
});
await GetLike.invoke(deps, { userId: 1 });
const [, bytes] = deps.sendRawPacket.mock.calls[0]!;
const env = protobuf_decode<OidbBase<Oidb0x7edReq>>(bytes);
expect(env.body?.start ?? 0).toBe(0);
expect(env.body?.limit).toBe(10);
});
});
describe('deserialize', () => {
it('shapes favorite + vote info with the expected key names', () => {
const out = GetLike.deserialize({} as any, {
userLikeInfos: [{
uid: 'u', time: 1700000000n,
favoriteInfo: { totalCount: 5, lastTime: 1n, newCount: 1 },
voteInfo: { totalCount: 7, newCount: 2, lastTime: 2n },
}],
});
expect(out.uid).toBe('u');
expect(out.time).toBe(1700000000);
expect(out.favoriteInfo).toEqual({
total_count: 5, last_time: 1, today_count: 1, userInfos: [],
});
expect(out.voteInfo).toEqual({
total_count: 7, new_count: 2, new_nearby_count: 0, last_visit_time: 2, userInfos: [],
});
});
it('throws when there are no userLikeInfos', () => {
expect(() => GetLike.deserialize({} as any, {})).toThrow('get profile like info empty');
expect(() => GetLike.deserialize({} as any, { userLikeInfos: [] })).toThrow('get profile like info empty');
});
it('defaults all count fields to 0 when omitted', () => {
const out = GetLike.deserialize({} as any, { userLikeInfos: [{ uid: 'u', time: 0n }] });
expect(out.favoriteInfo.total_count).toBe(0);
expect(out.voteInfo.total_count).toBe(0);
});
});
});
@@ -0,0 +1,76 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { Oidb0xe17Req, Oidb0xe17Resp } from '@snowluma/proto-defs/oidb-actions/base';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { GetUnidirectionalFriendList } from '../../../src/oidb-services/profile/get-unidirectional-friend-list';
function makeDeps(responseJson?: unknown) {
const responseData = responseJson !== undefined
? Buffer.from(protobuf_encode<OidbBase<Oidb0xe17Resp>>({
body: { jsonBody: JSON.stringify(responseJson) },
}))
: Buffer.alloc(0);
const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData };
return {
sendRawPacket: vi.fn(async () => r),
identity: { uin: '10001' } as any,
};
}
describe('GetUnidirectionalFriendList namespace', () => {
it('declares 0xE17_0', () => {
expect(GetUnidirectionalFriendList.command).toBe(0xE17);
expect(GetUnidirectionalFriendList.subCommand).toBe(0);
});
it('overrides the wire name to MQUpdateSvc.OidbSvc.0xe17_0', async () => {
const deps = makeDeps({ rpt_block_list: [] });
await GetUnidirectionalFriendList.invoke(deps);
expect(deps.sendRawPacket.mock.calls[0]![0]).toBe('MQUpdateSvc_com_qq_ti.web.OidbSvc.0xe17_0');
});
describe('serialize', () => {
it('JSON-encodes the request body with the bot uin and fixed pagination', async () => {
const deps = makeDeps({ rpt_block_list: [] });
await GetUnidirectionalFriendList.invoke(deps);
const [, bytes] = deps.sendRawPacket.mock.calls[0]!;
const env = protobuf_decode<OidbBase<Oidb0xe17Req>>(bytes);
const parsed = JSON.parse(env.body?.jsonBody ?? '{}');
expect(parsed).toEqual({
uint64_uin: '10001',
uint64_top: 0,
uint32_req_num: 99,
bytes_cookies: '',
});
});
});
describe('deserialize', () => {
it('parses the embedded JSON body and returns rpt_block_list', () => {
const out = GetUnidirectionalFriendList.deserialize({} as any, {
jsonBody: JSON.stringify({ rpt_block_list: [{ uin: 10001 }, { uin: 10002 }] }),
});
expect(out).toEqual([{ uin: 10001 }, { uin: 10002 }]);
});
it('returns [] when rpt_block_list is absent', () => {
const out = GetUnidirectionalFriendList.deserialize({} as any, { jsonBody: JSON.stringify({}) });
expect(out).toEqual([]);
});
it('throws when jsonBody is empty / missing', () => {
expect(() => GetUnidirectionalFriendList.deserialize({} as any, {})).toThrow('get unidirectional friend list empty');
expect(() => GetUnidirectionalFriendList.deserialize({} as any, { jsonBody: '' })).toThrow('get unidirectional friend list empty');
});
});
describe('invoke (e2e)', () => {
it('returns the parsed block list', async () => {
const deps = makeDeps({ rpt_block_list: [{ uin: 999 }] });
const out = await GetUnidirectionalFriendList.invoke(deps);
expect(out).toEqual([{ uin: 999 }]);
});
});
});
@@ -0,0 +1,54 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_decode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { Oidb0xcd4Req } from '@snowluma/proto-defs/oidb-actions/base';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { SetInputStatus } from '../../../src/oidb-services/profile/set-input-status';
function makeDeps(uid: string | null = 'resolved-uid') {
const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: Buffer.alloc(0) };
return {
sendRawPacket: vi.fn(async () => r),
resolveUserUid: vi.fn(async () => uid as string),
};
}
describe('SetInputStatus namespace', () => {
it('declares 0xCD4_1', () => {
expect(SetInputStatus.command).toBe(0xCD4);
expect(SetInputStatus.subCommand).toBe(1);
});
describe('invoke', () => {
it('routes to OidbSvcTrpcTcp.0xcd4_1', async () => {
const deps = makeDeps();
await SetInputStatus.invoke(deps, { userId: 10001, eventType: 1 });
expect(deps.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0xcd4_1');
});
it('resolves the target uid before encoding', async () => {
const deps = makeDeps();
await SetInputStatus.invoke(deps, { userId: 10001, eventType: 1 });
expect(deps.resolveUserUid).toHaveBeenCalledWith(10001);
});
it('packages uid + chatType=0 + eventType into reqBody', async () => {
const deps = makeDeps('alice-uid');
await SetInputStatus.invoke(deps, { userId: 10001, eventType: 7 });
const [, bytes] = deps.sendRawPacket.mock.calls[0]!;
const env = protobuf_decode<OidbBase<Oidb0xcd4Req>>(bytes);
expect(env.body?.reqBody?.uid).toBe('alice-uid');
// chatType=0 is proto3 default — omitted on the wire, comes back as null/undefined.
expect(env.body?.reqBody?.chatType ?? 0).toBe(0);
expect(env.body?.reqBody?.eventType).toBe(7);
});
it('throws when the target uid cannot be resolved', async () => {
const deps = makeDeps(null);
await expect(SetInputStatus.invoke(deps, { userId: 10001, eventType: 1 }))
.rejects.toThrow('target uid not found');
expect(deps.sendRawPacket).not.toHaveBeenCalled();
});
});
});
@@ -0,0 +1,67 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_decode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { OidbSetProfile } from '@snowluma/proto-defs/oidb-actions/base';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { SetProfile } from '../../../src/oidb-services/profile/set-profile';
function makeDeps() {
const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: Buffer.alloc(0) };
return {
sendRawPacket: vi.fn(async () => r),
identity: { uin: '10001' } as any,
};
}
describe('SetProfile namespace', () => {
it('declares 0x112A_2', () => {
expect(SetProfile.command).toBe(0x112A);
expect(SetProfile.subCommand).toBe(2);
});
describe('invoke', () => {
it('is a no-op when both nickname and personalNote are undefined', async () => {
const deps = makeDeps();
await SetProfile.invoke(deps, {});
expect(deps.sendRawPacket).not.toHaveBeenCalled();
});
it('packages nickname into fieldId 20002', async () => {
const deps = makeDeps();
await SetProfile.invoke(deps, { nickname: 'New Nick' });
expect(deps.sendRawPacket).toHaveBeenCalledOnce();
const [wireName, bytes] = deps.sendRawPacket.mock.calls[0]!;
expect(wireName).toBe('OidbSvcTrpcTcp.0x112a_2');
const env = protobuf_decode<OidbBase<OidbSetProfile>>(bytes);
expect(env.body?.stringProfiles).toEqual([{ fieldId: 20002, value: 'New Nick' }]);
});
it('packages personalNote into fieldId 102', async () => {
const deps = makeDeps();
await SetProfile.invoke(deps, { personalNote: 'on vacation' });
const [, bytes] = deps.sendRawPacket.mock.calls[0]!;
const env = protobuf_decode<OidbBase<OidbSetProfile>>(bytes);
expect(env.body?.stringProfiles).toEqual([{ fieldId: 102, value: 'on vacation' }]);
});
it('packages both fields together', async () => {
const deps = makeDeps();
await SetProfile.invoke(deps, { nickname: 'Foo', personalNote: 'Bar' });
const [, bytes] = deps.sendRawPacket.mock.calls[0]!;
const env = protobuf_decode<OidbBase<OidbSetProfile>>(bytes);
expect(env.body?.stringProfiles).toEqual([
{ fieldId: 20002, value: 'Foo' },
{ fieldId: 102, value: 'Bar' },
]);
});
it('passes the bot uin in the request body', async () => {
const deps = makeDeps();
await SetProfile.invoke(deps, { nickname: 'x' });
const [, bytes] = deps.sendRawPacket.mock.calls[0]!;
const env = protobuf_decode<OidbBase<OidbSetProfile>>(bytes);
expect(env.body?.uin).toBe(10001n);
});
});
});
@@ -0,0 +1,48 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_decode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { Oidb0x112aReq } from '@snowluma/proto-defs/oidb-actions/base';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { SetSelfLongNick } from '../../../src/oidb-services/profile/set-self-long-nick';
function makeDeps() {
const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: Buffer.alloc(0) };
return {
sendRawPacket: vi.fn(async () => r),
identity: { uin: '10001' } as any,
};
}
describe('SetSelfLongNick namespace', () => {
it('declares 0x112A_2', () => {
expect(SetSelfLongNick.command).toBe(0x112A);
expect(SetSelfLongNick.subCommand).toBe(2);
});
describe('invoke', () => {
it('routes to OidbSvcTrpcTcp.0x112a_2', async () => {
const deps = makeDeps();
await SetSelfLongNick.invoke(deps, { longNick: 'hello world' });
expect(deps.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0x112a_2');
});
it('wraps the long nick in profile { tag: 102, value }', async () => {
const deps = makeDeps();
await SetSelfLongNick.invoke(deps, { longNick: 'hello world' });
const [, bytes] = deps.sendRawPacket.mock.calls[0]!;
const env = protobuf_decode<OidbBase<Oidb0x112aReq>>(bytes);
expect(env.body?.uin).toBe(10001n);
expect(env.body?.profile).toEqual({ tag: 102, value: 'hello world' });
});
it('coerces non-string longNick into a string (defensive)', async () => {
const deps = makeDeps();
// simulate a misbehaving caller passing a number
await SetSelfLongNick.invoke(deps, { longNick: 12345 as any });
const [, bytes] = deps.sendRawPacket.mock.calls[0]!;
const env = protobuf_decode<OidbBase<Oidb0x112aReq>>(bytes);
expect(env.body?.profile?.value).toBe('12345');
});
});
});
@@ -0,0 +1,133 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { Oidb0x9084Req, Oidb0x9084Resp } from '@snowluma/proto-defs/oidb-actions/base';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { FetchReactionSummary } from '../../../src/oidb-services/reaction/fetch-reaction-summary';
function makeSender(resp?: Buffer) {
const defaultResp: SendPacketResult = {
success: true, gotResponse: true, errorCode: 0, errorMessage: '',
responseData: resp ?? Buffer.alloc(0),
};
return { sendRawPacket: vi.fn(async () => defaultResp) };
}
describe('FetchReactionSummary namespace', () => {
it('declares command = 0x9084 and subCommand = 1', () => {
expect(FetchReactionSummary.command).toBe(0x9084);
expect(FetchReactionSummary.subCommand).toBe(1);
});
describe('serialize', () => {
it('encodes groupId/sequence as BigInt for uint_64 fields', () => {
const out = FetchReactionSummary.serialize({} as any, { groupId: 1022489779, sequence: 1730183 });
expect(out.groupId).toBe(1022489779n);
expect(out.sequence).toBe(1730183n);
});
it('passes empty / default values for the unused filter fields', () => {
const out = FetchReactionSummary.serialize({} as any, { groupId: 1, sequence: 1 });
expect(out.emojiId).toBe('');
expect(out.emojiType).toBe(0);
expect(out.count).toBe(0);
expect(out.field12).toBe(1);
});
it('emits a 0-length cookie buffer (no continuation)', () => {
const out = FetchReactionSummary.serialize({} as any, { groupId: 1, sequence: 1 });
expect(out.cookie).toBeInstanceOf(Uint8Array);
expect(out.cookie!.length).toBe(0);
});
});
describe('deserialize', () => {
it('keeps entries with count > 0 (used emojis)', () => {
const body: Oidb0x9084Resp = {
entries: [
{ lastReactionTime: 1779456439n, count: 3, emojiType: 1, emojiId: '76' },
{ lastReactionTime: 1779456962n, count: 1, emojiType: 1, emojiId: '124' },
],
};
expect(FetchReactionSummary.deserialize({} as any, body)).toEqual([
{ emojiId: '76', emojiType: 1, count: 3, lastReactionTime: 1779456439 },
{ emojiId: '124', emojiType: 1, count: 1, lastReactionTime: 1779456962 },
]);
});
it('filters out catalog-tail entries (count omitted ≡ 0)', () => {
const body: Oidb0x9084Resp = {
entries: [
{ lastReactionTime: 1n, count: 1, emojiType: 1, emojiId: '76' },
{ emojiType: 1, emojiId: '124' }, // catalog entry
{ emojiType: 1, emojiId: '66' }, // catalog entry
],
};
const out = FetchReactionSummary.deserialize({} as any, body);
expect(out).toHaveLength(1);
expect(out[0]!.emojiId).toBe('76');
});
it('returns an empty array when the response has no entries', () => {
expect(FetchReactionSummary.deserialize({} as any, {})).toEqual([]);
});
it('defaults emojiId / emojiType to safe values when omitted', () => {
const body: Oidb0x9084Resp = {
entries: [{ count: 5, lastReactionTime: 1700000000n }],
};
const [entry] = FetchReactionSummary.deserialize({} as any, body);
expect(entry).toEqual({
emojiId: '', emojiType: 1, count: 5, lastReactionTime: 1700000000,
});
});
it('reports lastReactionTime=0 when omitted on a used entry (degenerate but defensive)', () => {
const body: Oidb0x9084Resp = { entries: [{ count: 2, emojiId: 'x', emojiType: 1 }] };
expect(FetchReactionSummary.deserialize({} as any, body)[0]!.lastReactionTime).toBe(0);
});
});
describe('invoke (e2e via mock sender)', () => {
it('sends to OidbSvcTrpcTcp.0x9084_1', async () => {
const sender = makeSender();
await FetchReactionSummary.invoke(sender, { groupId: 1, sequence: 1 });
expect(sender.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0x9084_1');
});
it('end-to-end: encode → decode pipeline yields the parsed summary entries', async () => {
const respEnvelope = Buffer.from(protobuf_encode<OidbBase<Oidb0x9084Resp>>({
command: 0x9084, subCommand: 1,
body: {
entries: [
{ lastReactionTime: 1700000000n, count: 5, emojiType: 1, emojiId: '76' },
{ emojiType: 1, emojiId: '124' }, // catalog noise
],
},
}));
const sender = makeSender(respEnvelope);
const result = await FetchReactionSummary.invoke(sender, { groupId: 1, sequence: 1 });
expect(result).toEqual([
{ emojiId: '76', emojiType: 1, count: 5, lastReactionTime: 1700000000 },
]);
});
it('encodes the request envelope with groupId/sequence as uint_64', async () => {
const sender = makeSender();
await FetchReactionSummary.invoke(sender, { groupId: 1022489779, sequence: 1730183 });
const [, reqBytes] = sender.sendRawPacket.mock.calls[0]!;
const env = protobuf_decode<OidbBase<Oidb0x9084Req>>(reqBytes);
expect(env.command).toBe(0x9084);
expect(env.subCommand).toBe(1);
expect(env.body?.groupId).toBe(1022489779n);
expect(env.body?.sequence).toBe(1730183n);
});
it('returns an empty array when server responds with empty envelope', async () => {
const sender = makeSender();
const result = await FetchReactionSummary.invoke(sender, { groupId: 1, sequence: 1 });
expect(result).toEqual([]);
});
});
});
@@ -0,0 +1,158 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { Oidb0x9083Req, Oidb0x9083Resp } from '@snowluma/proto-defs/oidb-actions/base';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { GetEmojiLikes } from '../../../src/oidb-services/reaction/get-emoji-likes';
function makeSender(resp?: Buffer) {
const defaultResp: SendPacketResult = {
success: true, gotResponse: true, errorCode: 0, errorMessage: '',
responseData: resp ?? Buffer.alloc(0),
};
return { sendRawPacket: vi.fn(async () => defaultResp) };
}
describe('GetEmojiLikes namespace', () => {
it('declares command = 0x9083 and subCommand = 1', () => {
expect(GetEmojiLikes.command).toBe(0x9083);
expect(GetEmojiLikes.subCommand).toBe(1);
});
describe('serialize', () => {
it('encodes groupId/sequence as BigInt for uint_64 fields', () => {
const out = GetEmojiLikes.serialize({} as any, {
groupId: 12345, sequence: 99, emojiId: '76',
});
expect(out.groupId).toBe(12345n);
expect(out.sequence).toBe(99n);
});
it('passes emojiId through unchanged', () => {
const out = GetEmojiLikes.serialize({} as any, { groupId: 1, sequence: 1, emojiId: '128516' });
expect(out.emojiId).toBe('128516');
});
it('defaults emojiType to 1 when omitted', () => {
const out = GetEmojiLikes.serialize({} as any, { groupId: 1, sequence: 1, emojiId: 'x' });
expect(out.emojiType).toBe(1);
});
it('uses caller-supplied emojiType when present', () => {
const out = GetEmojiLikes.serialize({} as any, { groupId: 1, sequence: 1, emojiId: 'x', emojiType: 2 });
expect(out.emojiType).toBe(2);
});
it('defaults count to 10 when omitted', () => {
const out = GetEmojiLikes.serialize({} as any, { groupId: 1, sequence: 1, emojiId: 'x' });
expect(out.count).toBe(10);
});
it('uses caller-supplied count when present', () => {
const out = GetEmojiLikes.serialize({} as any, { groupId: 1, sequence: 1, emojiId: 'x', count: 50 });
expect(out.count).toBe(50);
});
it('decodes base64 cookie into the bytes field for continuation', () => {
const cookie = Buffer.from([0xCA, 0xFE]).toString('base64');
const out = GetEmojiLikes.serialize({} as any, { groupId: 1, sequence: 1, emojiId: 'x', cookie });
expect(out.cookie).toBeInstanceOf(Uint8Array);
expect(Buffer.from(out.cookie!).equals(Buffer.from([0xCA, 0xFE]))).toBe(true);
});
it('emits a 0-length cookie buffer for the first page (no cookie supplied)', () => {
const out = GetEmojiLikes.serialize({} as any, { groupId: 1, sequence: 1, emojiId: 'x' });
expect(out.cookie!.length).toBe(0);
});
it('sets field7=0 and field12=1 (magic values matching the historic wire shape)', () => {
const out = GetEmojiLikes.serialize({} as any, { groupId: 1, sequence: 1, emojiId: 'x' });
expect(out.field7).toBe(0);
expect(out.field12).toBe(1);
});
});
describe('deserialize', () => {
it('extracts users from inner.userInfo and base64-encodes the cookie', () => {
const result = GetEmojiLikes.deserialize({} as any, {
inner: { userInfo: [{ uin: 10001n }, { uin: 20002n }] },
cookie: new Uint8Array([0xCA, 0xFE]),
});
expect(result.users).toEqual([{ uin: 10001 }, { uin: 20002 }]);
expect(result.cookie).toBe(Buffer.from([0xCA, 0xFE]).toString('base64'));
expect(result.isLast).toBe(false);
});
it('filters out users with uin=0 (placeholder / zero-value)', () => {
const result = GetEmojiLikes.deserialize({} as any, {
inner: { userInfo: [{ uin: 10001n }, { uin: 0n }, { uin: 20002n }] },
});
expect(result.users).toEqual([{ uin: 10001 }, { uin: 20002 }]);
});
it('returns empty users + empty cookie + isLast=true when body has nothing', () => {
const result = GetEmojiLikes.deserialize({} as any, {});
expect(result.users).toEqual([]);
expect(result.cookie).toBe('');
expect(result.isLast).toBe(true);
});
it('returns isLast=true when cookie is absent (final page)', () => {
const result = GetEmojiLikes.deserialize({} as any, {
inner: { userInfo: [{ uin: 10001n }] },
});
expect(result.isLast).toBe(true);
});
it('handles missing userInfo entries field', () => {
const result = GetEmojiLikes.deserialize({} as any, { inner: {} });
expect(result.users).toEqual([]);
});
});
describe('invoke (e2e via mock sender)', () => {
it('sends to OidbSvcTrpcTcp.0x9083_1', async () => {
const sender = makeSender();
await GetEmojiLikes.invoke(sender, { groupId: 1, sequence: 1, emojiId: '76' });
expect(sender.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0x9083_1');
});
it('end-to-end: encode → decode yields parsed user list + cookie', async () => {
const respEnvelope = Buffer.from(protobuf_encode<OidbBase<Oidb0x9083Resp>>({
command: 0x9083, subCommand: 1,
body: {
inner: { userInfo: [{ uin: 10001n }] },
cookie: new Uint8Array([0xDE, 0xAD]),
} as any,
}));
const sender = makeSender(respEnvelope);
const result = await GetEmojiLikes.invoke(sender, { groupId: 1, sequence: 1, emojiId: '76' });
expect(result.users).toEqual([{ uin: 10001 }]);
expect(result.cookie).toBe(Buffer.from([0xDE, 0xAD]).toString('base64'));
expect(result.isLast).toBe(false);
});
it('returns the legacy-stub empty result when server returns ack-only', async () => {
const sender = makeSender();
const result = await GetEmojiLikes.invoke(sender, { groupId: 1, sequence: 1, emojiId: '76' });
expect(result).toEqual({ users: [], cookie: '', isLast: true });
});
it('encodes the request envelope with proper field types', async () => {
const sender = makeSender();
await GetEmojiLikes.invoke(sender, {
groupId: 12345, sequence: 99, emojiId: '128516', emojiType: 2, count: 20,
});
const [, reqBytes] = sender.sendRawPacket.mock.calls[0]!;
const env = protobuf_decode<OidbBase<Oidb0x9083Req>>(reqBytes);
expect(env.command).toBe(0x9083);
expect(env.subCommand).toBe(1);
expect(env.body?.groupId).toBe(12345n);
expect(env.body?.sequence).toBe(99n);
expect(env.body?.emojiId).toBe('128516');
expect(env.body?.emojiType).toBe(2);
expect(env.body?.count).toBe(20);
});
});
});
@@ -0,0 +1,110 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_decode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { OidbGroupReaction } from '@snowluma/proto-defs/oidb-actions/base';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { SetReaction } from '../../../src/oidb-services/reaction/set-reaction';
function makeSender() {
const defaultResp: SendPacketResult = {
success: true, gotResponse: true, errorCode: 0, errorMessage: '',
responseData: Buffer.alloc(0),
};
return { sendRawPacket: vi.fn(async () => defaultResp) };
}
describe('SetReaction namespace', () => {
it('declares command = 0x9082', () => {
expect(SetReaction.command).toBe(0x9082);
});
it('resolveSubCommand: isSet=true → 1, isSet=false → 2', () => {
expect(SetReaction.resolveSubCommand({ groupId: 1, sequence: 1, code: 'x', isSet: true })).toBe(1);
expect(SetReaction.resolveSubCommand({ groupId: 1, sequence: 1, code: 'x', isSet: false })).toBe(2);
});
describe('serialize', () => {
it('produces type=1 for short QQ-face codes (≤3 chars)', () => {
const out = SetReaction.serialize({} as any, { groupId: 12345, sequence: 99, code: '76', isSet: true });
expect(out).toEqual({
groupUin: 12345, sequence: 99, code: '76', type: 1, field6: false, field7: false,
});
});
it('produces type=1 for exactly 3-character codes (boundary)', () => {
const out = SetReaction.serialize({} as any, { groupId: 1, sequence: 1, code: '999', isSet: true });
expect(out.type).toBe(1);
});
it('produces type=2 for codes longer than 3 chars (unicode codepoint)', () => {
const out = SetReaction.serialize({} as any, { groupId: 1, sequence: 1, code: '128516', isSet: false });
expect(out.type).toBe(2);
});
it('passes through groupId/sequence/code verbatim', () => {
const out = SetReaction.serialize({} as any, { groupId: 999, sequence: 42, code: 'abc', isSet: true });
expect(out.groupUin).toBe(999);
expect(out.sequence).toBe(42);
expect(out.code).toBe('abc');
});
it('always sets field6/field7 to false (deferred behaviour)', () => {
const out = SetReaction.serialize({} as any, { groupId: 1, sequence: 1, code: 'x', isSet: true });
expect(out.field6).toBe(false);
expect(out.field7).toBe(false);
});
});
describe('deserialize', () => {
it('always returns void regardless of body content', () => {
expect(SetReaction.deserialize({} as any, {})).toBeUndefined();
});
});
describe('encode / decode round trip', () => {
it('encode preserves groupUin/sequence/code/type in the envelope body', () => {
const env: OidbBase<OidbGroupReaction> = {
command: 0x9082, subCommand: 1,
body: { groupUin: 12345, sequence: 99, code: '76', type: 1 } as OidbGroupReaction,
};
const bytes = SetReaction.encode(env);
const decoded = SetReaction.decode(bytes);
expect(decoded.command).toBe(0x9082);
expect(decoded.subCommand).toBe(1);
});
});
describe('invoke (e2e via mock sender)', () => {
it('routes to OidbSvcTrpcTcp.0x9082_1 when isSet=true', async () => {
const sender = makeSender();
await SetReaction.invoke(sender, { groupId: 12345, sequence: 99, code: '76', isSet: true });
expect(sender.sendRawPacket).toHaveBeenCalledOnce();
expect(sender.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0x9082_1');
});
it('routes to OidbSvcTrpcTcp.0x9082_2 when isSet=false', async () => {
const sender = makeSender();
await SetReaction.invoke(sender, { groupId: 12345, sequence: 99, code: '76', isSet: false });
expect(sender.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0x9082_2');
});
it('packages the serialized body into the OIDB envelope wire', async () => {
const sender = makeSender();
await SetReaction.invoke(sender, { groupId: 12345, sequence: 99, code: '128516', isSet: true });
const [, bytes] = sender.sendRawPacket.mock.calls[0]!;
const env = protobuf_decode<OidbBase<OidbGroupReaction>>(bytes);
expect(env.command).toBe(0x9082);
expect(env.subCommand).toBe(1);
expect(env.body).toMatchObject({
groupUin: 12345, sequence: 99, code: '128516', type: 2,
});
});
it('resolves to undefined (void)', async () => {
const sender = makeSender();
const result = await SetReaction.invoke(sender, { groupId: 1, sequence: 1, code: 'x', isSet: true });
expect(result).toBeUndefined();
});
});
});
@@ -0,0 +1,49 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { OidbClientKeyResp } from '@snowluma/proto-defs/oidb-actions/base';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { ForceFetchClientKey } from '../../../src/oidb-services/web/force-fetch-client-key';
function makeSender(body?: OidbClientKeyResp) {
const responseData = body !== undefined
? Buffer.from(protobuf_encode<OidbBase<OidbClientKeyResp>>({ body }))
: Buffer.alloc(0);
const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData };
return { sendRawPacket: vi.fn(async () => r) };
}
describe('ForceFetchClientKey namespace', () => {
it('declares 0x102A_1', () => {
expect(ForceFetchClientKey.command).toBe(0x102A);
expect(ForceFetchClientKey.subCommand).toBe(1);
});
describe('invoke (e2e)', () => {
it('routes to OidbSvcTrpcTcp.0x102a_1', async () => {
const sender = makeSender({ clientKey: 'ck', keyIndex: 19, expireTime: 1800 });
await ForceFetchClientKey.invoke(sender);
expect(sender.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0x102a_1');
});
it('returns the parsed clientKey / keyIndex / expireTime', async () => {
const sender = makeSender({ clientKey: 'KEY', keyIndex: 7, expireTime: 600 });
const out = await ForceFetchClientKey.invoke(sender);
expect(out).toEqual({ clientKey: 'KEY', keyIndex: '7', expireTime: '600' });
});
it('falls back to keyIndex="19" and expireTime="1800" when server omits them', async () => {
const sender = makeSender({ clientKey: 'KEY' });
const out = await ForceFetchClientKey.invoke(sender);
expect(out.keyIndex).toBe('19');
expect(out.expireTime).toBe('1800');
});
it('returns empty clientKey when server omits it', async () => {
const sender = makeSender({});
const out = await ForceFetchClientKey.invoke(sender);
expect(out.clientKey).toBe('');
});
});
});
@@ -0,0 +1,75 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { OidbGetPskeyReq, OidbGetPskeyResp } from '@snowluma/proto-defs/oidb-actions/base';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { GetPskey } from '../../../src/oidb-services/web/get-pskey';
function makeSender(body?: OidbGetPskeyResp) {
const responseData = body !== undefined
? Buffer.from(protobuf_encode<OidbBase<OidbGetPskeyResp>>({ body }))
: Buffer.alloc(0);
const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData };
return { sendRawPacket: vi.fn(async () => r) };
}
describe('GetPskey namespace', () => {
it('declares 0x102A_0', () => {
expect(GetPskey.command).toBe(0x102A);
expect(GetPskey.subCommand).toBe(0);
});
describe('serialize', () => {
it('passes the domainList through verbatim', () => {
const out = GetPskey.serialize({} as any, { domainList: ['qun.qq.com', 'qzone.qq.com'] });
expect(out.domainList).toEqual(['qun.qq.com', 'qzone.qq.com']);
});
});
describe('deserialize', () => {
it('builds a Map from server pskeyItems', () => {
const { domainPskeyMap } = GetPskey.deserialize({} as any, {
pskeyItems: [
{ domain: 'qun.qq.com', pskey: 'pskey-qun' },
{ domain: 'qzone.qq.com', pskey: 'pskey-qzone' },
],
});
expect(domainPskeyMap.get('qun.qq.com')).toBe('pskey-qun');
expect(domainPskeyMap.get('qzone.qq.com')).toBe('pskey-qzone');
});
it('drops entries with missing domain or pskey', () => {
const { domainPskeyMap } = GetPskey.deserialize({} as any, {
pskeyItems: [
{ domain: 'qun.qq.com', pskey: 'ok' },
{ domain: 'missing-pskey.com' },
{ pskey: 'missing-domain' },
] as any,
});
expect(domainPskeyMap.size).toBe(1);
expect(domainPskeyMap.get('qun.qq.com')).toBe('ok');
});
it('returns empty Map when pskeyItems is absent', () => {
const { domainPskeyMap } = GetPskey.deserialize({} as any, {});
expect(domainPskeyMap.size).toBe(0);
});
});
describe('invoke (e2e)', () => {
it('routes to OidbSvcTrpcTcp.0x102a_0', async () => {
const sender = makeSender({ pskeyItems: [] });
await GetPskey.invoke(sender, { domainList: ['qq.com'] });
expect(sender.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0x102a_0');
});
it('encodes the domain list into the request body', async () => {
const sender = makeSender({ pskeyItems: [] });
await GetPskey.invoke(sender, { domainList: ['qun.qq.com'] });
const [, bytes] = sender.sendRawPacket.mock.calls[0]!;
const env = protobuf_decode<OidbBase<OidbGetPskeyReq>>(bytes);
expect(env.body?.domainList).toEqual(['qun.qq.com']);
});
});
});
@@ -0,0 +1,280 @@
// Pre-dispatch stranger resolve regression — when a group join
// request comes in, the push only carries the requester's UID. The
// pipeline must do an async UID-form FetchUserProfile lookup BEFORE
// emitting the event so the OneBot layer's `user_id` field is
// populated and the consumer bot's `get_stranger_info` lookup works.
//
// Cross-checked against Lagrange's flow:
// dev/Lagrange.Core/.../MessagingLogic.cs:215-224
// (FetchUserInfoEvent by uid → resolved uin → posted event)
import { describe, expect, it, vi } from 'vitest';
import { IncomingPacketPipeline } from '@snowluma/protocol/packet-pipeline';
import { BridgeEventBus } from '@snowluma/protocol/event-bus';
import { IdentityService } from '@snowluma/protocol/identity-service';
import type { QQEventVariant } from '@snowluma/protocol/events';
import type { PacketInfo } from '@snowluma/common/protocol-types';
function makePipeline(opts: {
resolveStrangerProfile?: vi.Mock;
resolveGroupJoinRequest?: vi.Mock;
} = {}) {
const identity = IdentityService.memory('10001');
const events = new BridgeEventBus();
const resolveStrangerProfile = opts.resolveStrangerProfile ?? vi.fn(async () => null);
const resolveGroupJoinRequest = opts.resolveGroupJoinRequest ?? vi.fn(async () => null);
const pipeline = new IncomingPacketPipeline({
identity,
events,
refreshMemberCache: vi.fn(async () => false),
resolveStrangerProfile,
resolveGroupJoinRequest,
});
const captured: QQEventVariant[] = [];
events.onAny((event) => { captured.push(event as QQEventVariant); });
return { pipeline, events, captured, resolveStrangerProfile, resolveGroupJoinRequest };
}
describe('IncomingPacketPipeline / stranger resolve on group_invite', () => {
it('calls resolveStrangerProfile(uid) when group_invite has fromUin=0 + fromUid', async () => {
const resolveStrangerProfile = vi.fn(async (_uid: string) => ({
uin: 950929451, nickname: '小明',
}));
const { pipeline, captured } = makePipeline({ resolveStrangerProfile });
// Plant a parser that emits the user's exact bug-report shape:
// groupId set, fromUid is a string UID, fromUin=0 (decoder fix).
pipeline.registerCmd('test.cmd', () => [{
kind: 'group_invite',
time: 1700000000,
selfUin: 10001,
groupId: 123456789,
fromUin: 0,
fromUid: 'u_stranger_abc',
subType: 'add',
message: '',
flag: 'add:123456789:u_stranger_abc',
} as QQEventVariant]);
pipeline.process({ serviceCmd: 'test.cmd' } as PacketInfo);
// Let the async hook flush.
await new Promise(r => setTimeout(r, 10));
expect(resolveStrangerProfile).toHaveBeenCalledWith('u_stranger_abc');
expect(captured).toHaveLength(1);
const event = captured[0] as Extract<QQEventVariant, { kind: 'group_invite' }>;
expect(event.fromUin).toBe(950929451); // ← patched in by the async resolve
expect(event.fromUid).toBe('u_stranger_abc');
expect(event.groupId).toBe(123456789);
});
it('still emits the event when resolveStrangerProfile returns null (fail open)', async () => {
const resolveStrangerProfile = vi.fn(async () => null);
const { pipeline, captured } = makePipeline({ resolveStrangerProfile });
pipeline.registerCmd('test.cmd', () => [{
kind: 'group_invite',
time: 1, selfUin: 10001,
groupId: 12345, fromUin: 0, fromUid: 'u_no_such_user',
subType: 'add', message: '', flag: 'add:12345:u_no_such_user',
} as QQEventVariant]);
pipeline.process({ serviceCmd: 'test.cmd' } as PacketInfo);
await new Promise(r => setTimeout(r, 10));
expect(resolveStrangerProfile).toHaveBeenCalledOnce();
expect(captured).toHaveLength(1);
const event = captured[0] as Extract<QQEventVariant, { kind: 'group_invite' }>;
// fromUin stays 0 — but the event still goes out so the bot can
// see the join request and at least respond using the uid in the
// flag.
expect(event.fromUin).toBe(0);
expect(event.fromUid).toBe('u_no_such_user');
});
it('still emits the event when resolveStrangerProfile throws', async () => {
const resolveStrangerProfile = vi.fn(async () => { throw new Error('network down'); });
const { pipeline, captured } = makePipeline({ resolveStrangerProfile });
pipeline.registerCmd('test.cmd', () => [{
kind: 'group_invite',
time: 1, selfUin: 10001,
groupId: 12345, fromUin: 0, fromUid: 'u_x',
subType: 'add', message: '', flag: 'add:12345:u_x',
} as QQEventVariant]);
pipeline.process({ serviceCmd: 'test.cmd' } as PacketInfo);
await new Promise(r => setTimeout(r, 10));
expect(captured).toHaveLength(1);
expect(captured[0]).toMatchObject({ fromUin: 0, fromUid: 'u_x' });
});
it('skips the stranger resolve when fromUin is already populated (cache hit)', async () => {
// If the decoder's `resolveUidToUin` already found the uin in
// the local cache (e.g. group member roster), we shouldn't waste
// a wire call.
const resolveStrangerProfile = vi.fn(async () => null);
const { pipeline, captured } = makePipeline({ resolveStrangerProfile });
pipeline.registerCmd('test.cmd', () => [{
kind: 'group_invite',
time: 1, selfUin: 10001,
groupId: 12345, fromUin: 99999, fromUid: 'u_known',
subType: 'invite', message: '', flag: 'invite:12345:u_known',
} as QQEventVariant]);
pipeline.process({ serviceCmd: 'test.cmd' } as PacketInfo);
await new Promise(r => setTimeout(r, 10));
expect(resolveStrangerProfile).not.toHaveBeenCalled();
expect(captured).toHaveLength(1);
expect(captured[0]).toMatchObject({ fromUin: 99999, fromUid: 'u_known' });
});
it('populates event.message from the pending-request queue (NapCat parity)', async () => {
// User-reported bug: SnowLuma's group_invite event surfaces a
// bare uid + uin but the requester's verify text ("你们好") never
// lands in the OneBot `comment` field. NapCat shows the text via
// `notify.postscript` from `getGroupNotifies`; we mirror that by
// doing an `OIDB 0x10C0 fetchGroupRequests` lookup in the async
// pre-dispatch hook and patching `event.message` from the matching
// row's `comment`.
const resolveStrangerProfile = vi.fn(async () => ({
uin: 1957003260, nickname: 'KitaIkuyo',
}));
const resolveGroupJoinRequest = vi.fn(async () => ({
comment: '你们好', sequence: 1779543612823906,
}));
const { pipeline, captured } = makePipeline({
resolveStrangerProfile, resolveGroupJoinRequest,
});
pipeline.registerCmd('test.cmd', () => [{
kind: 'group_invite',
time: 1, selfUin: 10001,
groupId: 950929451, fromUin: 0,
fromUid: 'u_UVLHYYqba27WPUzTrdZlCA',
subType: 'add', message: '',
flag: 'add:950929451:u_UVLHYYqba27WPUzTrdZlCA',
} as QQEventVariant]);
pipeline.process({ serviceCmd: 'test.cmd' } as PacketInfo);
await new Promise(r => setTimeout(r, 10));
expect(resolveGroupJoinRequest).toHaveBeenCalledWith(
950929451, 'u_UVLHYYqba27WPUzTrdZlCA', 'add');
expect(captured).toHaveLength(1);
const ev = captured[0] as Extract<QQEventVariant, { kind: 'group_invite' }>;
expect(ev.message).toBe('你们好');
expect(ev.fromUin).toBe(1957003260);
});
it('runs the profile + request lookups in parallel (independent failures)', async () => {
// Profile lookup succeeds, request lookup fails — event should
// still carry the resolved uin but no comment. The dispatch
// doesn't block on the slower / failing path.
const resolveStrangerProfile = vi.fn(async () => ({
uin: 12345, nickname: 'OK',
}));
const resolveGroupJoinRequest = vi.fn(async () => {
throw new Error('queue lookup failed');
});
const { pipeline, captured } = makePipeline({
resolveStrangerProfile, resolveGroupJoinRequest,
});
pipeline.registerCmd('test.cmd', () => [{
kind: 'group_invite',
time: 1, selfUin: 10001,
groupId: 1, fromUin: 0, fromUid: 'u_x',
subType: 'add', message: '', flag: 'add:1:u_x',
} as QQEventVariant]);
pipeline.process({ serviceCmd: 'test.cmd' } as PacketInfo);
await new Promise(r => setTimeout(r, 10));
const ev = captured[0] as Extract<QQEventVariant, { kind: 'group_invite' }>;
expect(ev.fromUin).toBe(12345); // profile succeeded
expect(ev.message).toBe(''); // request lookup threw, message left empty
});
it('invite subtype matches the request on invitorUid (not targetUid)', async () => {
// For `subType: 'invite'` (group member invited the bot or another
// user), the pending-request row's REQUESTER field is
// `invitorUid` not `targetUid`. The dep contract makes this
// explicit so the bridge facade can route the lookup correctly.
const resolveGroupJoinRequest = vi.fn(async () => ({
comment: 'come join', sequence: 999,
}));
const { pipeline } = makePipeline({ resolveGroupJoinRequest });
pipeline.registerCmd('test.cmd', () => [{
kind: 'group_invite',
time: 1, selfUin: 10001,
groupId: 1, fromUin: 0, fromUid: 'u_inviter',
subType: 'invite', message: '', flag: 'invite:1:u_inviter',
} as QQEventVariant]);
pipeline.process({ serviceCmd: 'test.cmd' } as PacketInfo);
await new Promise(r => setTimeout(r, 10));
expect(resolveGroupJoinRequest).toHaveBeenCalledWith(1, 'u_inviter', 'invite');
});
it('forces re-resolve when fromUin === groupId (legacy cache pollution)', async () => {
// Pre-fix builds stored `<requester_uid> → <groupUin>` because
// the decoder's fallback was `ctx.fromUin` (= group's own uin on
// a group-scoped push). After upgrade, the decoder's
// resolveUidToUin would re-read that polluted mapping and emit
// event.fromUin === groupId. The `fromUin <= 0` check alone
// wouldn't fire the async resolve, so the bug would persist.
// This guard catches that signature and forces a re-lookup, so
// the cache self-heals on the next event.
const resolveStrangerProfile = vi.fn(async () => ({
uin: 1957003260, nickname: 'KitaIkuyo',
}));
const { pipeline, captured } = makePipeline({ resolveStrangerProfile });
pipeline.registerCmd('test.cmd', () => [{
kind: 'group_invite',
time: 1, selfUin: 10001,
groupId: 950929451,
fromUin: 950929451, // ← POLLUTED: equals groupId
fromUid: 'u_kitaikuyo',
subType: 'add', message: '', flag: 'add:950929451:u_kitaikuyo',
} as QQEventVariant]);
pipeline.process({ serviceCmd: 'test.cmd' } as PacketInfo);
await new Promise(r => setTimeout(r, 10));
expect(resolveStrangerProfile).toHaveBeenCalledWith('u_kitaikuyo');
expect(captured).toHaveLength(1);
expect(captured[0]).toMatchObject({
fromUin: 1957003260, // ← corrected by the async resolve
fromUid: 'u_kitaikuyo',
groupId: 950929451,
});
});
it('skips the stranger resolve when fromUid is empty (no uid to look up by)', async () => {
const resolveStrangerProfile = vi.fn(async () => null);
const { pipeline, captured } = makePipeline({ resolveStrangerProfile });
pipeline.registerCmd('test.cmd', () => [{
kind: 'group_invite',
time: 1, selfUin: 10001,
groupId: 12345, fromUin: 0, fromUid: '',
subType: 'add', message: '', flag: 'add:12345:',
} as QQEventVariant]);
pipeline.process({ serviceCmd: 'test.cmd' } as PacketInfo);
await new Promise(r => setTimeout(r, 10));
expect(resolveStrangerProfile).not.toHaveBeenCalled();
expect(captured).toHaveLength(1);
});
});