diff --git a/packages/bridge/package.json b/packages/bridge/package.json index 842a9651..185c5128 100644 --- a/packages/bridge/package.json +++ b/packages/bridge/package.json @@ -63,6 +63,26 @@ "types": "./src/oidb-services/interaction/set-essence.ts", "default": "./src/oidb-services/interaction/set-essence.ts" }, + "./oidb-services/profile/set-profile": { + "types": "./src/oidb-services/profile/set-profile.ts", + "default": "./src/oidb-services/profile/set-profile.ts" + }, + "./oidb-services/profile/set-self-long-nick": { + "types": "./src/oidb-services/profile/set-self-long-nick.ts", + "default": "./src/oidb-services/profile/set-self-long-nick.ts" + }, + "./oidb-services/profile/set-input-status": { + "types": "./src/oidb-services/profile/set-input-status.ts", + "default": "./src/oidb-services/profile/set-input-status.ts" + }, + "./oidb-services/profile/get-like": { + "types": "./src/oidb-services/profile/get-like.ts", + "default": "./src/oidb-services/profile/get-like.ts" + }, + "./oidb-services/profile/get-unidirectional-friend-list": { + "types": "./src/oidb-services/profile/get-unidirectional-friend-list.ts", + "default": "./src/oidb-services/profile/get-unidirectional-friend-list.ts" + }, "./bridge-context": { "types": "./src/bridge-context.ts", "default": "./src/bridge-context.ts" diff --git a/packages/bridge/src/oidb-service.ts b/packages/bridge/src/oidb-service.ts index c42229cf..e2b23f63 100644 --- a/packages/bridge/src/oidb-service.ts +++ b/packages/bridge/src/oidb-service.ts @@ -47,6 +47,12 @@ export interface OidbCallSpec { resolveSubCommand?(params: TParams): number; /** Set OIDB envelope `reserved = 1` (UIN-form variant, see makeOidbEnvelope's isUid). */ uinForm?: boolean; + /** Override the default `OidbSvcTrpcTcp.0xNNNN_N` wire name. A few + * cmds route through different SSO names (e.g. 0xE17_0 lives at + * `MQUpdateSvc_com_qq_ti.web.OidbSvc.0xe17_0`); supply a function + * that takes the resolved `(cmd, subCmd)` and returns the actual + * wire name. Omit for the default scheme. */ + wireName?(command: number, subCommand: number): string; /** Business params → wire-shaped request body. */ serialize(params: TParams): TReq; /** Wire-shaped response body → business result. */ @@ -88,7 +94,9 @@ export async function invokeOidb( const reqBody = spec.serialize(params); const env = makeOidbEnvelope(spec.command, subCommand, reqBody, spec.uinForm ?? false); const reqBytes = spec.encode(env); - const wireName = `OidbSvcTrpcTcp.0x${spec.command.toString(16)}_${subCommand}`; + const wireName = spec.wireName + ? spec.wireName(spec.command, subCommand) + : `OidbSvcTrpcTcp.0x${spec.command.toString(16)}_${subCommand}`; const result = await sender.sendRawPacket(wireName, reqBytes, timeoutMs); if (!result.success) throw new Error(result.errorMessage || 'packet send failed'); @@ -127,7 +135,9 @@ export function buildOidbRequest( const reqBody = spec.serialize(params); const env = makeOidbEnvelope(spec.command, subCommand, reqBody, spec.uinForm ?? false); const bytes = spec.encode(env); - const wireName = `OidbSvcTrpcTcp.0x${spec.command.toString(16)}_${subCommand}`; + const wireName = spec.wireName + ? spec.wireName(spec.command, subCommand) + : `OidbSvcTrpcTcp.0x${spec.command.toString(16)}_${subCommand}`; return { wireName, bytes }; } diff --git a/packages/bridge/src/oidb-services/profile/get-like.ts b/packages/bridge/src/oidb-services/profile/get-like.ts new file mode 100644 index 00000000..c35074f9 --- /dev/null +++ b/packages/bridge/src/oidb-services/profile/get-like.ts @@ -0,0 +1,103 @@ +// 0x7ED_12 — fetch QQ "thumbs up" (赞) summary for self or another user. +// +// Self lookup needs the bot's own UID, hence the `identity` dependency. +// For other users we use `resolveUserUid` to translate the uin first. + +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 { invokeOidb, type OidbSender } from '../../oidb-service'; +import type { BridgeContext } from '../../bridge-context'; + +export interface LikeInfo { + uid: string; + time: number; + favoriteInfo: { + total_count: number; + last_time: number; + today_count: number; + userInfos: never[]; + }; + voteInfo: { + total_count: number; + new_count: number; + new_nearby_count: number; + last_visit_time: number; + userInfos: never[]; + }; +} + +export namespace GetLike { + export const command = 0x7ED; + export const subCommand = 12; + + export interface Params { + /** Omit / 0 → query self. */ + userId?: number; + start?: number; + limit?: number; + } + + export type Deps = OidbSender & Pick; + + export const serialize = (p: Params, targetUid: string): Oidb0x7edReq => ({ + targetUid, + basic: 1, + vote: 1, + favorite: 1, + start: p.start ?? 0, + limit: p.limit ?? 10, + }); + + export const deserialize = (body: Oidb0x7edResp): LikeInfo => { + const data = body.userLikeInfos?.[0]; + if (!data) throw new Error('get profile like info empty'); + return { + uid: data.uid ?? '', + time: Number(data.time ?? 0), + favoriteInfo: { + total_count: data.favoriteInfo?.totalCount || 0, + last_time: Number(data.favoriteInfo?.lastTime || 0), + today_count: data.favoriteInfo?.newCount || 0, + userInfos: [], + }, + voteInfo: { + total_count: data.voteInfo?.totalCount || 0, + new_count: data.voteInfo?.newCount || 0, + new_nearby_count: 0, + last_visit_time: Number(data.voteInfo?.lastTime || 0), + userInfos: [], + }, + }; + }; + + export const encode = (env: OidbBase): Uint8Array => + protobuf_encode>(env); + + export const decode = (bytes: Uint8Array): OidbBase => + protobuf_decode>(bytes); + + export const invoke = async (deps: Deps, params: Params): Promise => { + const isSelf = !params.userId; + const targetUid = isSelf + ? await resolveSelf(deps) + : await deps.resolveUserUid(params.userId!); + if (!targetUid) throw new Error('target uid not found'); + return invokeOidb(deps, { + ...GetLike, + serialize: p => serialize(p, targetUid), + }, params); + }; +} + +async function resolveSelf(deps: Pick): Promise { + // Mirrors `apis/shared.ts::resolveSelfUid` — kept inline here so the + // namespace is self-contained against just the BridgeContext slice. + const cached = deps.identity.selfUid; + if (cached) return cached; + const selfUin = Number(deps.identity.uin); + if (!Number.isFinite(selfUin) || selfUin <= 0) { + throw new Error('self uid is unavailable'); + } + return deps.resolveUserUid(selfUin); +} diff --git a/packages/bridge/src/oidb-services/profile/get-unidirectional-friend-list.ts b/packages/bridge/src/oidb-services/profile/get-unidirectional-friend-list.ts new file mode 100644 index 00000000..18b19ed1 --- /dev/null +++ b/packages/bridge/src/oidb-services/profile/get-unidirectional-friend-list.ts @@ -0,0 +1,58 @@ +// 0xE17_0 — fetch the unidirectional friend block list. Wire name is +// non-standard (`MQUpdateSvc_com_qq_ti.web.OidbSvc.0xe17_0`) — uses +// the `wireName` override to bypass the default +// `OidbSvcTrpcTcp.0xNNNN_N` scheme. +// +// Request and response carry a JSON-encoded string in a single +// protobuf field, so the namespace's `serialize` / `deserialize` do +// the JSON marshalling. + +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 { invokeOidb, type OidbSender } from '../../oidb-service'; +import type { BridgeContext } from '../../bridge-context'; + +export namespace GetUnidirectionalFriendList { + export const command = 0xE17; + export const subCommand = 0; + + /** Wire name override — this cmd lives outside the standard + * `OidbSvcTrpcTcp.0xNNNN_N` namespace. */ + export const wireName = (): string => 'MQUpdateSvc_com_qq_ti.web.OidbSvc.0xe17_0'; + + // eslint-disable-next-line @typescript-eslint/no-empty-object-type + export interface Params {} + + export type Deps = OidbSender & Pick; + + export const serialize = (_: Params, uin: string): Oidb0xe17Req => { + const reqObj = { + uint64_uin: uin, + uint64_top: 0, + uint32_req_num: 99, + bytes_cookies: '', + }; + return { jsonBody: JSON.stringify(reqObj) }; + }; + + export const deserialize = (body: Oidb0xe17Resp): unknown[] => { + if (!body || !body.jsonBody) throw new Error('get unidirectional friend list empty'); + const parsed = JSON.parse(body.jsonBody); + return parsed.rpt_block_list || []; + }; + + export const encode = (env: OidbBase): Uint8Array => + protobuf_encode>(env); + + export const decode = (bytes: Uint8Array): OidbBase => + protobuf_decode>(bytes); + + export const invoke = (deps: Deps): Promise => { + const uin = String(deps.identity.uin); + return invokeOidb(deps, { + ...GetUnidirectionalFriendList, + serialize: p => serialize(p, uin), + }, {}); + }; +} diff --git a/packages/bridge/src/oidb-services/profile/set-input-status.ts b/packages/bridge/src/oidb-services/profile/set-input-status.ts new file mode 100644 index 00000000..e0951e30 --- /dev/null +++ b/packages/bridge/src/oidb-services/profile/set-input-status.ts @@ -0,0 +1,49 @@ +// 0xCD4_1 — set typing / recording / etc. "input status" indicator +// shown to a peer in a 1:1 chat. +// +// Resolves the target uin → uid via the identity service before +// building the body. `chatType: 0` is the wire constant for friend +// chats (the only flavor SnowLuma currently supports here). + +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { Oidb0xcd4Req, Oidb0xcd4Resp } from '@snowluma/proto-defs/oidb-actions/base'; +import { invokeOidb, type OidbSender } from '../../oidb-service'; +import type { BridgeContext } from '../../bridge-context'; + +export namespace SetInputStatus { + export const command = 0xCD4; + export const subCommand = 1; + + export interface Params { + userId: number; + eventType: number; + } + + export type Deps = OidbSender & Pick; + + export const serialize = (p: Params, targetUid: string): Oidb0xcd4Req => ({ + reqBody: { + uid: targetUid, + chatType: 0, + eventType: p.eventType, + }, + }); + + export const deserialize = (_: Oidb0xcd4Resp): void => {}; + + export const encode = (env: OidbBase): Uint8Array => + protobuf_encode>(env); + + export const decode = (bytes: Uint8Array): OidbBase => + protobuf_decode>(bytes); + + export const invoke = async (deps: Deps, params: Params): Promise => { + const targetUid = await deps.resolveUserUid(params.userId); + if (!targetUid) throw new Error('target uid not found'); + await invokeOidb(deps, { + ...SetInputStatus, + serialize: p => serialize(p, targetUid), + }, params); + }; +} diff --git a/packages/bridge/src/oidb-services/profile/set-profile.ts b/packages/bridge/src/oidb-services/profile/set-profile.ts new file mode 100644 index 00000000..b7e02cc0 --- /dev/null +++ b/packages/bridge/src/oidb-services/profile/set-profile.ts @@ -0,0 +1,57 @@ +// 0x112A_2 — write profile string/int field-value pairs. +// +// SnowLuma's facade currently exposes only nickname (field 20002) and +// personalNote (field 102) but the underlying wire supports arbitrary +// (fieldId, value) tuples. The serialize step skips the call entirely +// when both inputs are undefined so the facade keeps its no-op-on- +// noop-input behavior — `invokeOidb` is bypassed at the call-site. + +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { Oidb0x112aResp, OidbSetProfile } from '@snowluma/proto-defs/oidb-actions/base'; +import { invokeOidb, type OidbSender } from '../../oidb-service'; +import type { BridgeContext } from '../../bridge-context'; + +export namespace SetProfile { + export const command = 0x112A; + export const subCommand = 2; + + export interface Params { + nickname?: string; + personalNote?: string; + } + + /** Needs identity to read `uin` for the request body. */ + export type Deps = OidbSender & Pick; + + export const serialize = (p: Params, uin: bigint): OidbSetProfile => { + const stringProfiles: { fieldId: number; value: string }[] = []; + if (p.nickname !== undefined) stringProfiles.push({ fieldId: 20002, value: p.nickname }); + if (p.personalNote !== undefined) stringProfiles.push({ fieldId: 102, value: p.personalNote }); + return { uin, stringProfiles }; + }; + + export const deserialize = (_: Oidb0x112aResp): void => {}; + + export const encode = (env: OidbBase): Uint8Array => + protobuf_encode>(env); + + export const decode = (bytes: Uint8Array): OidbBase => + protobuf_decode>(bytes); + + export const invoke = (deps: Deps, params: Params): Promise => { + // No-op when there's nothing to write — preserves the facade's + // historic short-circuit (avoid a wasted SSO round-trip). + if (params.nickname === undefined && params.personalNote === undefined) { + return Promise.resolve(); + } + const uin = BigInt(deps.identity.uin); + return invokeOidb(deps, { + ...SetProfile, + // Bind uin into serialize so the OidbCallSpec contract (single-arg + // serialize) still holds — we can't pass uin through `params` + // without leaking identity to the facade signature. + serialize: p => serialize(p, uin), + }, params); + }; +} diff --git a/packages/bridge/src/oidb-services/profile/set-self-long-nick.ts b/packages/bridge/src/oidb-services/profile/set-self-long-nick.ts new file mode 100644 index 00000000..435b6d07 --- /dev/null +++ b/packages/bridge/src/oidb-services/profile/set-self-long-nick.ts @@ -0,0 +1,44 @@ +// 0x112A_2 — set the self "long nick" / personal signature. Same cmd +// as SetProfile but a different request shape (uses the single +// `profile: { tag, value }` field instead of the repeated string +// profiles list). Kept separate because the wire body is structurally +// different — proton needs distinct types so the codec is correctly +// monomorphized per call site. + +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { Oidb0x112aReq, Oidb0x112aResp } from '@snowluma/proto-defs/oidb-actions/base'; +import { invokeOidb, type OidbSender } from '../../oidb-service'; +import type { BridgeContext } from '../../bridge-context'; + +export namespace SetSelfLongNick { + export const command = 0x112A; + export const subCommand = 2; + + export interface Params { + longNick: string; + } + + export type Deps = OidbSender & Pick; + + export const serialize = (p: Params, uin: bigint): Oidb0x112aReq => ({ + uin, + profile: { tag: 102, value: String(p.longNick) }, + }); + + export const deserialize = (_: Oidb0x112aResp): void => {}; + + export const encode = (env: OidbBase): Uint8Array => + protobuf_encode>(env); + + export const decode = (bytes: Uint8Array): OidbBase => + protobuf_decode>(bytes); + + export const invoke = (deps: Deps, params: Params): Promise => { + const uin = BigInt(deps.identity.uin); + return invokeOidb(deps, { + ...SetSelfLongNick, + serialize: p => serialize(p, uin), + }, params); + }; +} diff --git a/packages/bridge/tests/oidb-services/profile/get-like.test.ts b/packages/bridge/tests/oidb-services/profile/get-like.test.ts new file mode 100644 index 00000000..e5d6237a --- /dev/null +++ b/packages/bridge/tests/oidb-services/profile/get-like.test.ts @@ -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; + responseBody?: Oidb0x7edResp; +} = {}) { + const responseData = opts.responseBody !== undefined + ? Buffer.from(protobuf_encode>({ 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>(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>(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>(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>(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({ + 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({})).toThrow('get profile like info empty'); + expect(() => GetLike.deserialize({ userLikeInfos: [] })).toThrow('get profile like info empty'); + }); + + it('defaults all count fields to 0 when omitted', () => { + const out = GetLike.deserialize({ userLikeInfos: [{ uid: 'u', time: 0n }] }); + expect(out.favoriteInfo.total_count).toBe(0); + expect(out.voteInfo.total_count).toBe(0); + }); + }); +}); diff --git a/packages/bridge/tests/oidb-services/profile/get-unidirectional-friend-list.test.ts b/packages/bridge/tests/oidb-services/profile/get-unidirectional-friend-list.test.ts new file mode 100644 index 00000000..1f637479 --- /dev/null +++ b/packages/bridge/tests/oidb-services/profile/get-unidirectional-friend-list.test.ts @@ -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>({ + 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>(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({ + 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({ jsonBody: JSON.stringify({}) }); + expect(out).toEqual([]); + }); + + it('throws when jsonBody is empty / missing', () => { + expect(() => GetUnidirectionalFriendList.deserialize({})).toThrow('get unidirectional friend list empty'); + expect(() => GetUnidirectionalFriendList.deserialize({ 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 }]); + }); + }); +}); diff --git a/packages/bridge/tests/oidb-services/profile/set-input-status.test.ts b/packages/bridge/tests/oidb-services/profile/set-input-status.test.ts new file mode 100644 index 00000000..53b3cf85 --- /dev/null +++ b/packages/bridge/tests/oidb-services/profile/set-input-status.test.ts @@ -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>(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(); + }); + }); +}); diff --git a/packages/bridge/tests/oidb-services/profile/set-profile.test.ts b/packages/bridge/tests/oidb-services/profile/set-profile.test.ts new file mode 100644 index 00000000..348f56c1 --- /dev/null +++ b/packages/bridge/tests/oidb-services/profile/set-profile.test.ts @@ -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>(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>(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>(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>(bytes); + expect(env.body?.uin).toBe(10001n); + }); + }); +}); diff --git a/packages/bridge/tests/oidb-services/profile/set-self-long-nick.test.ts b/packages/bridge/tests/oidb-services/profile/set-self-long-nick.test.ts new file mode 100644 index 00000000..5e102578 --- /dev/null +++ b/packages/bridge/tests/oidb-services/profile/set-self-long-nick.test.ts @@ -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>(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>(bytes); + expect(env.body?.profile?.value).toBe('12345'); + }); + }); +}); diff --git a/packages/core/src/bridge/apis/profile.ts b/packages/core/src/bridge/apis/profile.ts index d92ac399..e73b57ad 100644 --- a/packages/core/src/bridge/apis/profile.ts +++ b/packages/core/src/bridge/apis/profile.ts @@ -3,29 +3,23 @@ // `actions/profile.ts` (deleted alongside actions/* in commit 13). import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; -import type { OidbBase } from '@snowluma/proto-defs/oidb'; import type { FaceroamOpReq, FaceroamOpResp, GroupAvatarExtra, - Oidb0x112aReq, - Oidb0x112aResp, - Oidb0x7edReq, - Oidb0x7edResp, - Oidb0xcd4Req, - Oidb0xcd4Resp, - Oidb0xe17Req, - Oidb0xe17Resp, - OidbSetProfile, SetStatusReq, SetStatusResp, } from '@snowluma/proto-defs/oidb-actions/base'; import type { BridgeContext } from '../bridge-context'; import type { Bridge } from '../bridge'; -import { makeOidbEnvelope, runOidb } from '@snowluma/bridge/bridge-oidb'; import { fetchHighwaySession, uploadHighwayHttp } from '@snowluma/bridge/highway'; import { computeHashes, loadBinarySource } from '@snowluma/bridge/highway/utils'; -import { resolveSelfUid } from './shared'; +// Migrated OIDB cmds — facade methods are one-line forwarders. +import { SetProfile } from '@snowluma/bridge/oidb-services/profile/set-profile'; +import { SetSelfLongNick } from '@snowluma/bridge/oidb-services/profile/set-self-long-nick'; +import { SetInputStatus } from '@snowluma/bridge/oidb-services/profile/set-input-status'; +import { GetLike } from '@snowluma/bridge/oidb-services/profile/get-like'; +import { GetUnidirectionalFriendList } from '@snowluma/bridge/oidb-services/profile/get-unidirectional-friend-list'; function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; } @@ -80,64 +74,16 @@ export class ProfileApi { } } - async setProfile(nickname?: string, personalNote?: string): Promise { - const bridge = asBridge(this.ctx); - const uin = BigInt(this.ctx.identity.uin); - const stringProfiles: any[] = []; - const intProfiles: any[] = []; - - if (nickname !== undefined) { - stringProfiles.push({ fieldId: 20002, value: nickname }); - } - - if (personalNote !== undefined) { - stringProfiles.push({ fieldId: 102, value: personalNote }); - } - - if (stringProfiles.length === 0 && intProfiles.length === 0) { - return; - } - - const req = { uin, stringProfiles }; - const env = makeOidbEnvelope(0x112A, 2, req); - await runOidb(bridge, 'OidbSvcTrpcTcp.0x112a_2', protobuf_encode>(env)); + setProfile(nickname?: string, personalNote?: string): Promise { + return SetProfile.invoke(this.ctx, { nickname, personalNote }); } - async setSelfLongNick(longNick: string): Promise { - const bridge = asBridge(this.ctx); - const req = { - uin: BigInt(this.ctx.identity.uin), - profile: { - tag: 102, - value: String(longNick), - }, - }; - - const env = makeOidbEnvelope(0x112A, 2, req); - const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x112a_2', protobuf_encode>(env)); - // Decode just to maintain the original behaviour of "consume the response". - protobuf_decode>(respBytes); + setSelfLongNick(longNick: string): Promise { + return SetSelfLongNick.invoke(this.ctx, { longNick }); } - async setInputStatus(userId: number, eventType: number): Promise { - const bridge = asBridge(this.ctx); - const targetUid = await this.ctx.resolveUserUid(userId); - - if (!targetUid) { - throw new Error('target uid not found'); - } - - const req = { - reqBody: { - uid: targetUid, - chatType: 0, - eventType, - }, - }; - - const env = makeOidbEnvelope(0xCD4, 1, req); - const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xcd4_1', protobuf_encode>(env)); - protobuf_decode>(respBytes); + setInputStatus(userId: number, eventType: number): Promise { + return SetInputStatus.invoke(this.ctx, { userId, eventType }); } async setAvatar(source: string): Promise { @@ -179,74 +125,12 @@ export class ProfileApi { // ─────────────── queries on me / my contacts ─────────────── - async getLike(userId?: number, start = 0, limit = 10): Promise { - const bridge = asBridge(this.ctx); - const isSelf = !userId; - const targetUid = isSelf - ? await resolveSelfUid(bridge) - : await this.ctx.resolveUserUid(userId); - - if (!targetUid) { - throw new Error('target uid not found'); - } - - const req = { - targetUid, - basic: 1, - vote: 1, - favorite: 1, - start, - limit, - }; - - const env = makeOidbEnvelope(0x7ED, 12, req); - const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x7ed_12', protobuf_encode>(env)); - const result = protobuf_decode>(respBytes).body; - - const data = result?.userLikeInfos?.[0]; - if (!data) { - throw new Error('get profile like info empty'); - } - - return { - uid: data.uid, - time: Number(data.time), - favoriteInfo: { - total_count: data.favoriteInfo?.totalCount || 0, - last_time: Number(data.favoriteInfo?.lastTime || 0), - today_count: data.favoriteInfo?.newCount || 0, - userInfos: [], - }, - voteInfo: { - total_count: data.voteInfo?.totalCount || 0, - new_count: data.voteInfo?.newCount || 0, - new_nearby_count: 0, - last_visit_time: Number(data.voteInfo?.lastTime || 0), - userInfos: [], - }, - }; + getLike(userId?: number, start = 0, limit = 10): Promise { + return GetLike.invoke(this.ctx, { userId, start, limit }); } - async getUnidirectionalFriendList(): Promise { - const bridge = asBridge(this.ctx); - const reqObj = { - uint64_uin: String(this.ctx.identity.uin), - uint64_top: 0, - uint32_req_num: 99, - bytes_cookies: '', - }; - - const req = { jsonBody: JSON.stringify(reqObj) }; - const env = makeOidbEnvelope(0xE17, 0, req); - const respBytes = await runOidb(bridge, 'MQUpdateSvc_com_qq_ti.web.OidbSvc.0xe17_0', protobuf_encode>(env)); - const result = protobuf_decode>(respBytes).body; - - if (!result || !result.jsonBody) { - throw new Error('get unidirectional friend list empty'); - } - - const parsed = JSON.parse(result.jsonBody); - return parsed.rpt_block_list || []; + getUnidirectionalFriendList(): Promise { + return GetUnidirectionalFriendList.invoke(this.ctx); } async fetchCustomFace(count = 10): Promise { diff --git a/packages/core/tests/actions/profile.test.ts b/packages/core/tests/actions/profile.test.ts index 2d0a9c64..24146d0a 100644 --- a/packages/core/tests/actions/profile.test.ts +++ b/packages/core/tests/actions/profile.test.ts @@ -104,30 +104,28 @@ describe('apis/profile', () => { it('setProfile is a no-op when both arguments are undefined', async () => { const bridge = mockBridge(); await new ProfileApi(bridge as any).setProfile(); - expect(oidb.runOidb).not.toHaveBeenCalled(); + // Namespace migration: no SSO packet should fire at all. + expect(bridge.sendRawPacket).not.toHaveBeenCalled(); }); it('setProfile only sends non-undefined fields', async () => { const bridge = mockBridge(); await new ProfileApi(bridge as any).setProfile('New Nick'); - expect(oidb.runOidb).toHaveBeenCalledOnce(); - const body = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2]; - expect((body as any).stringProfiles).toEqual([{ fieldId: 20002, value: 'New Nick' }]); + expect(bridge.sendRawPacket).toHaveBeenCalledOnce(); + expect(bridge.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0x112a_2'); }); - it('setSelfLongNick wraps the long nick in profile tag 102', async () => { + it('setSelfLongNick targets 0x112a_2 wire cmd', async () => { const bridge = mockBridge(); await new ProfileApi(bridge as any).setSelfLongNick( 'hello world'); - const body = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2]; - expect((body as any).profile).toEqual({ tag: 102, value: 'hello world' }); + expect(bridge.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0x112a_2'); }); it('setInputStatus resolves UID first and sends 0xcd4_1', async () => { const bridge = mockBridge(); await new ProfileApi(bridge as any).setInputStatus( 10001, 1); expect(bridge.resolveUserUid).toHaveBeenCalledWith(10001); - const [, cmd] = vi.mocked(oidb.runOidb).mock.calls[0]!; - expect(cmd).toBe('OidbSvcTrpcTcp.0xcd4_1'); + expect(bridge.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0xcd4_1'); }); it('setAvatar loads bytes and pushes through the highway upload path (cmd 90)', async () => { @@ -171,8 +169,9 @@ describe('apis/profile', () => { it('getProfileLike (self): resolves self UID, returns formatted favorite + vote info', async () => { const bridge = mockBridge(); - vi.mocked(oidb.runOidb).mockResolvedValueOnce( - protobuf_encode>({ + bridge.sendRawPacket.mockResolvedValueOnce({ + success: true, gotResponse: true, errorCode: 0, errorMessage: '', + responseData: Buffer.from(protobuf_encode>({ body: { userLikeInfos: [{ uid: 'u', @@ -181,8 +180,8 @@ describe('apis/profile', () => { voteInfo: { totalCount: 7, newCount: 2, lastTime: 2n }, }], } as any, - }), - ); + })), + }); const out = await new ProfileApi(bridge as any).getLike(); expect(out.favoriteInfo.total_count).toBe(5); expect(out.voteInfo.total_count).toBe(7); @@ -190,19 +189,21 @@ describe('apis/profile', () => { it('getProfileLike throws on empty result', async () => { const bridge = mockBridge(); - vi.mocked(oidb.runOidb).mockResolvedValueOnce( - protobuf_encode>({ body: { userLikeInfos: [] } as any }), - ); + bridge.sendRawPacket.mockResolvedValueOnce({ + success: true, gotResponse: true, errorCode: 0, errorMessage: '', + responseData: Buffer.from(protobuf_encode>({ body: { userLikeInfos: [] } as any })), + }); await expect(new ProfileApi(bridge as any).getLike()).rejects.toThrow(/empty/); }); it('getUnidirectionalFriendList parses the embedded JSON body', async () => { const bridge = mockBridge(); - vi.mocked(oidb.runOidb).mockResolvedValueOnce( - protobuf_encode>({ + bridge.sendRawPacket.mockResolvedValueOnce({ + success: true, gotResponse: true, errorCode: 0, errorMessage: '', + responseData: Buffer.from(protobuf_encode>({ body: { jsonBody: JSON.stringify({ rpt_block_list: [{ uin: 10001 }, { uin: 10002 }] }) } as any, - }), - ); + })), + }); const out = await new ProfileApi(bridge as any).getUnidirectionalFriendList(); expect(out).toEqual([{ uin: 10001 }, { uin: 10002 }]); });