feat(onebot): expose public contact profiles

Refs #615
This commit is contained in:
DrSmoothl committed 2026-11-02 08:06:27 +08:00
1 parent 2b63f375fc
commit 45c3a6841a
34 files changed
+2427 -211

No files matched your search

@@ -14,6 +14,7 @@ import type { OidbFriendListRequest } from '@snowluma/proto-defs/oidb-actions/ba
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { FriendInfo } from '../../qq-info';
import { invokeOidb, type OidbSender } from '../../oidb-service';
import { decodePublicProfile, PUBLIC_PROFILE_KEYS } from './public-profile';
export interface FriendListPageEntry {
friend: FriendInfo;
@@ -33,8 +34,9 @@ export interface FriendListPage {
cookie?: Uint8Array;
}
function friendProperties(raw: OidbFriend): Map<number, string> {
const props = new Map<number, string>();
function friendProperties(raw: OidbFriend) {
const props = new Map<number, Uint8Array>();
const numbers = new Map<number, number>();
for (const additional of raw.additional ?? []) {
if ((additional.type ?? 0) !== 1 || !additional.layer1) {
@@ -42,22 +44,31 @@ function friendProperties(raw: OidbFriend): Map<number, string> {
}
for (const property of additional.layer1.properties ?? []) {
props.set(property.code ?? 0, property.value ?? '');
props.set(property.code ?? 0, property.value ?? new Uint8Array(0));
}
for (const property of additional.layer1.numberProperties ?? []) {
numbers.set(property.key ?? 0, property.value ?? 0);
}
}
return props;
return { props, numbers };
}
function mapFriend(raw: OidbFriend): FriendListPageEntry {
const props = friendProperties(raw);
const { props, numbers } = friendProperties(raw);
const profile = decodePublicProfile(props, numbers);
return {
categoryId: raw.customGroup ?? 0,
friend: {
uin: raw.uin ?? 0,
uid: raw.uid ?? '',
nickname: props.get(20002) ?? String(raw.uin ?? 0),
remark: props.get(103) ?? '',
nickname: props.has(20002)
? Buffer.from(props.get(20002)!).toString('utf8')
: String(raw.uin ?? 0),
remark: Buffer.from(props.get(103) ?? []).toString('utf8'),
categoryId: raw.customGroup ?? 0,
...(Object.keys(profile).length ? { profile } : {}),
},
};
}
@@ -80,7 +91,12 @@ export namespace FetchFriendListPage {
field6: 1,
field7: 0x7fffffff,
body: [
{ type: 1, number: { numbers: [103, 102, 20002, 27394] } },
{
type: 1,
number: {
numbers: [...new Set([103, 102, 20002, 27394, ...PUBLIC_PROFILE_KEYS])],
},
},
{ type: 4, number: { numbers: [100, 101, 102] } },
],
field10002: [13578, 13579, 13573, 13572, 13568],
@@ -24,12 +24,30 @@ import type {
import type { UserProfileInfo } from '../../qq-info';
import { applyBirthday, applyOnlineStatus, applyProfileDetails } from './fetch-user-profile';
import { invokeOidb, type OidbSender } from '../../oidb-service';
import { decodePublicProfile, PUBLIC_PROFILE_KEYS } from './public-profile';
const REQUESTED_KEYS = [
20002, 27394, 20009, 20031, 101, 103, 102, 20020, 20003, 20026, 105, 27372, 27406, 20037, 41756,
41757, 42241,
20002,
27394,
20009,
20031,
101,
103,
102,
20020,
20003,
20026,
105,
27372,
27406,
20037,
41756,
41757,
42241,
// 企点标志(QQ 企点 / 企业版 QQ 账号):员工号实测为 1,普通账号为 0
40410, 42031,
40410,
42031,
...PUBLIC_PROFILE_KEYS,
];
export namespace FetchUserProfileByUid {
@@ -47,7 +65,7 @@ export namespace FetchUserProfileByUid {
export const serialize = (_ctx: Deps, p: Params): OidbUserInfoByUidRequest => ({
uid: p.uid,
keys: REQUESTED_KEYS.map((k) => ({ key: k })),
keys: [...new Set(REQUESTED_KEYS)].map((k) => ({ key: k })),
});
export const deserialize = (_ctx: Deps, body: OidbUserInfoResponse): UserProfileInfo => {
@@ -110,6 +128,12 @@ export namespace FetchUserProfileByUid {
applyOnlineStatus(info, bytesMap, numMap);
applyProfileDetails(info, numMap);
applyBirthday(info, bytesMap);
const profile = decodePublicProfile(bytesMap, numMap);
if (Object.keys(profile).length > 0) {
info.profile = profile;
}
// 企点标志:40410 / 42031,服务器仅在返回时才出现(普通账号缺省 → 0)
info.qidianMasterFlag = numMap.get(42031) ?? 0;
info.qidianCrewFlag = numMap.get(40410) ?? 0;
@@ -29,6 +29,7 @@ import type {
import type { UserProfileInfo } from '../../qq-info';
import { unpackStatusWord } from '../extras/get-stranger-status';
import { invokeOidb, type OidbSender } from '../../oidb-service';
import { decodeMembership, decodePublicProfile, PUBLIC_PROFILE_KEYS } from './public-profile';
export function applyOnlineStatus(
info: UserProfileInfo,
@@ -63,27 +64,7 @@ export function applyProfileDetails(info: UserProfileInfo, numMap: Map<number, n
info.regTime = registered;
}
const flags = numMap.get(41756);
if (flags !== undefined) {
info.vipFlag = (flags & 1) !== 0;
info.yearVipFlag = (flags & 2) !== 0;
info.svipFlag = (flags & 0x100) !== 0;
}
const level = numMap.get(41757);
if (level !== undefined) {
const mask = level & 0xfff;
if (mask !== 0) {
info.vipLevel = 33 - Math.clz32(mask);
} else if (info.vipFlag || info.yearVipFlag || info.svipFlag || numMap.get(42241) === 1) {
info.vipLevel = 1;
} else if (flags !== undefined && numMap.has(42241)) {
info.vipLevel = 0;
}
}
Object.assign(info, decodeMembership(numMap));
}
/**
@@ -120,10 +101,27 @@ export function applyBirthday(info: UserProfileInfo, bytesMap: Map<number, Uint8
}
const REQUESTED_KEYS = [
20002, 27394, 20009, 20031, 101, 103, 102, 20020, 20003, 20026, 105, 27372, 27406, 20037, 41756,
41757, 42241,
20002,
27394,
20009,
20031,
101,
103,
102,
20020,
20003,
20026,
105,
27372,
27406,
20037,
41756,
41757,
42241,
// 企点标志(QQ 企点 / 企业版 QQ 账号):员工号实测为 1,普通账号为 0
40410, 42031,
40410,
42031,
...PUBLIC_PROFILE_KEYS,
];
export namespace FetchUserProfile {
@@ -139,7 +137,7 @@ export namespace FetchUserProfile {
export const serialize = (_ctx: Deps, p: Params): OidbUserInfoRequest => ({
uin: p.uin,
keys: REQUESTED_KEYS.map((k) => ({ key: k })),
keys: [...new Set(REQUESTED_KEYS)].map((k) => ({ key: k })),
});
/** Defaults the response uin to `requestedUin` because the server
@@ -154,6 +152,10 @@ export namespace FetchUserProfile {
throw new Error('user info response body missing');
}
if (requestedUin > 0 && body.body.uin != null && body.body.uin !== requestedUin) {
throw new Error('profile response does not match the requested account');
}
const info: UserProfileInfo = {
uin: body.body.uin ?? requestedUin,
uid: body.body.uid ?? '',
@@ -209,6 +211,12 @@ export namespace FetchUserProfile {
applyOnlineStatus(info, bytesMap, numMap);
applyProfileDetails(info, numMap);
applyBirthday(info, bytesMap);
const profile = decodePublicProfile(bytesMap, numMap);
if (Object.keys(profile).length > 0) {
info.profile = profile;
}
// 企点标志:40410 / 42031,服务器仅在返回时才出现(普通账号缺省 → 0)
info.qidianMasterFlag = numMap.get(42031) ?? 0;
info.qidianCrewFlag = numMap.get(40410) ?? 0;
@@ -0,0 +1,194 @@
import { protobuf_decode, protobuf_getUnknownFields } from '@snowluma/proton';
import { createLogger } from '@snowluma/common/logger';
import type {
OidbProfilePrivileges,
OidbProfilePrivilege,
} from '@snowluma/proto-defs/oidb-actions/base';
import type { ProfilePrivilege, PublicProfileFields } from '../../qq-info';
// Shared by the roster and both profile request forms.
export const PUBLIC_PROFILE_KEYS = [
102, 105, 107, 20003, 20004, 20020, 20009, 20011, 20016, 20021, 20031, 20037, 41756, 41757,
42241,
];
const log = createLogger('Protocol.Profile');
function text(value: Uint8Array, code: number): string {
try {
return new TextDecoder('utf-8', { fatal: true }).decode(value);
} catch (cause) {
throw new Error(`invalid UTF-8 in profile property ${code}`, { cause });
}
}
export function decodeBirthday(
raw: Uint8Array,
): Pick<PublicProfileFields, 'birthdayYear' | 'birthdayMonth' | 'birthdayDay'> {
if (raw.length !== 4) {
throw new Error('invalid birthday length in profile property 20031');
}
const year = (raw[0]! << 8) | raw[1]!;
const month = raw[2]!;
const day = raw[3]!;
if (month === 0 && day === 0) {
return {};
}
const date = new Date(0);
date.setUTCFullYear(year || 2000, month - 1, day);
if (year > 9999 || date.getUTCMonth() !== month - 1 || date.getUTCDate() !== day) {
throw new Error('invalid date in profile property 20031');
}
return {
...(year > 0 ? { birthdayYear: year } : {}),
birthdayMonth: month,
birthdayDay: day,
};
}
function privilege(entry: OidbProfilePrivilege): ProfilePrivilege {
checkKnownFields(entry, [1, 4, 5, 6, 7, 8, 9]);
return {
...(entry.type != null ? { type: entry.type } : {}),
...(entry.level != null ? { level: entry.level } : {}),
...(entry.flag != null ? { flag: entry.flag } : {}),
...(entry.isBig != null ? { isBig: entry.isBig } : {}),
...(entry.jumpUrl != null ? { jumpUrl: text(entry.jumpUrl, 107) } : {}),
...(entry.iconUrl != null ? { iconUrl: text(entry.iconUrl, 107) } : {}),
...(entry.deluxeIconUrl != null ? { deluxeIconUrl: text(entry.deluxeIconUrl, 107) } : {}),
};
}
function checkKnownFields(value: unknown, tags: readonly number[]): void {
for (const field of protobuf_getUnknownFields(value)) {
if (tags.includes(field.fieldNumber)) {
throw new Error(`unexpected wire type for privilege field ${field.fieldNumber}`);
}
}
}
export function decodeMembership(
numbers: ReadonlyMap<number, number>,
): Pick<PublicProfileFields, 'vipFlag' | 'yearVipFlag' | 'svipFlag' | 'vipLevel'> {
const result: Pick<PublicProfileFields, 'vipFlag' | 'yearVipFlag' | 'svipFlag' | 'vipLevel'> =
{};
const flags = numbers.get(41756);
if (flags !== undefined) {
result.vipFlag = (flags & 1) !== 0;
result.yearVipFlag = (flags & 2) !== 0;
result.svipFlag = (flags & 0x100) !== 0;
}
const level = numbers.get(41757);
if (level !== undefined) {
const mask = level & 0xfff;
if (mask !== 0) {
result.vipLevel = 33 - Math.clz32(mask);
} else if (
result.vipFlag ||
result.yearVipFlag ||
result.svipFlag ||
numbers.get(42241) === 1
) {
result.vipLevel = 1;
} else if (flags !== undefined && numbers.has(42241)) {
result.vipLevel = 0;
}
}
return result;
}
export function decodePublicProfile(
bytes: ReadonlyMap<number, Uint8Array>,
numbers: ReadonlyMap<number, number>,
): PublicProfileFields {
const result: PublicProfileFields = {};
for (const [code, field] of [
[102, 'sign'],
[20011, 'email'],
[20016, 'phoneNum'],
[20003, 'country'],
[20004, 'province'],
[20020, 'city'],
[20021, 'college'],
] as const) {
const value = bytes.get(code);
if (value !== undefined) {
result[field] = text(value, code);
}
}
for (const [code, field] of [
[20037, 'age'],
[105, 'level'],
] as const) {
const value = numbers.get(code);
if (value !== undefined && Number.isInteger(value) && value >= 0) {
result[field] = value;
}
}
const sex = numbers.get(20009);
if (sex !== undefined) {
result.sex = sex === 1 ? 'male' : sex === 2 ? 'female' : 'unknown';
}
const birthday = bytes.get(20031);
if (birthday !== undefined && birthday.length > 0) {
// Keep the existing optional-birthday behavior, but make malformed
// upstream values diagnosable without recording personal data.
try {
Object.assign(result, decodeBirthday(birthday));
} catch (error) {
log.warn(
'birthday unavailable: bytes=%d error=%s',
birthday.length,
error instanceof Error ? error.message : String(error),
);
}
}
Object.assign(result, decodeMembership(numbers));
const icons = bytes.get(107);
if (icons !== undefined) {
try {
const decoded = protobuf_decode<OidbProfilePrivileges>(icons);
checkKnownFields(decoded, [3]);
if (!decoded.lists) {
// The client treats an absent list body as unavailable, not
// as a returned list containing zero entries.
return result;
}
checkKnownFields(decoded.lists, [2, 3, 4]);
result.privilegeIcons = {
...(decoded.lists.jumpUrl != null
? { jumpUrl: text(decoded.lists.jumpUrl, 107) }
: {}),
open: (decoded.lists.open ?? []).map(privilege),
closed: (decoded.lists.closed ?? []).map(privilege),
};
} catch (cause) {
throw new Error('invalid privilege data in profile property 107', { cause });
}
}
return result;
}
+39
View File
@@ -1,3 +1,39 @@
export interface ProfilePrivilege {
type?: number;
level?: number;
flag?: number;
isBig?: number;
jumpUrl?: string;
iconUrl?: string;
deluxeIconUrl?: string;
}
/** Only fields actually supplied by the profile service; absent values stay absent. */
export interface PublicProfileFields {
sign?: string;
sex?: 'male' | 'female' | 'unknown';
age?: number;
level?: number;
birthdayYear?: number;
birthdayMonth?: number;
birthdayDay?: number;
phoneNum?: string;
email?: string;
country?: string;
province?: string;
city?: string;
college?: string;
vipFlag?: boolean;
svipFlag?: boolean;
yearVipFlag?: boolean;
vipLevel?: number;
privilegeIcons?: {
jumpUrl?: string;
open: ProfilePrivilege[];
closed: ProfilePrivilege[];
};
}
export interface UserProfileInfo {
uin: number;
uid: string;
@@ -12,6 +48,7 @@ export interface UserProfileInfo {
* Already requested in `fetchUserProfile` keys[]; LagrangeV2
* `FetchStrangerService.cs` confirms `// Level`. */
level: number;
profile?: PublicProfileFields;
regTime?: number;
/**
* 生日 — OIDB 0xFE1_2 bytes-property key 20031。
@@ -46,6 +83,8 @@ export interface FriendInfo {
uid: string;
nickname: string;
remark: string;
categoryId?: number;
profile?: PublicProfileFields;
}
export interface FriendCategoryInfo {
@@ -63,10 +63,18 @@ describe('FetchFriendListPage namespace', () => {
expect(out.nextUin).toBeUndefined();
});
it('emits the verbatim property request list (codes 100/101/102/103/20002/27394)', () => {
it('requests basic identity and public profiles in the same roster page', () => {
const out = FetchFriendListPage.serialize({} as any, {}) as any;
expect(out.body).toEqual([
{ type: 1, number: { numbers: [103, 102, 20002, 27394] } },
{
type: 1,
number: {
numbers: [
103, 102, 20002, 27394, 105, 107, 20003, 20004, 20020, 20009, 20011,
20016, 20021, 20031, 20037, 41756, 41757, 42241,
],
},
},
{ type: 4, number: { numbers: [100, 101, 102] } },
]);
});
@@ -92,8 +100,8 @@ describe('FetchFriendListPage namespace', () => {
type: 1,
layer1: {
properties: [
{ code: 20002, value: 'Alice' },
{ code: 103, value: 'A' },
{ code: 20002, value: Buffer.from('Alice') },
{ code: 103, value: Buffer.from('A') },
],
},
},
@@ -114,7 +122,13 @@ describe('FetchFriendListPage namespace', () => {
entries: [
{
categoryId: 7,
friend: { uin: 10001, uid: 'u1', nickname: 'Alice', remark: 'A' },
friend: {
uin: 10001,
uid: 'u1',
nickname: 'Alice',
remark: 'A',
categoryId: 7,
},
},
],
categories: [
@@ -138,7 +152,7 @@ describe('FetchFriendListPage namespace', () => {
entries: [
{
categoryId: 0,
friend: { uin: 0, uid: '', nickname: '0', remark: '' },
friend: { uin: 0, uid: '', nickname: '0', remark: '', categoryId: 0 },
},
],
categories: [],
@@ -99,6 +99,7 @@ describe('FetchUserProfile namespace', () => {
yearVipFlag: !!(flags & 2),
svipFlag: !!(flags & 0x100),
vipLevel: level,
profile: { vipLevel: level },
});
},
);
@@ -0,0 +1,176 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_encode } from '@snowluma/proton';
import type { OidbBase, OidbSvcTrpcTcp0xFD4_1Response } from '@snowluma/proto-defs/oidb';
import type { OidbUserInfoResponse } from '@snowluma/proto-defs/oidb-actions/base';
import { FetchFriendListPage } from '../../../src/oidb-services/contacts/fetch-friend-list-page';
import { FetchUserProfile } from '../../../src/oidb-services/contacts/fetch-user-profile';
import { FetchUserProfileByUid } from '../../../src/oidb-services/contacts/fetch-user-profile-by-uid';
import { decodePublicProfile } from '../../../src/oidb-services/contacts/public-profile';
// Synthetic wire fixture, independent of the privilege schema: top-level tag 3;
// body tags 2 (jump), 3 (open), 4 (closed); both entry URLs are present.
const icons = Buffer.from(
'1a2c1204636172641a1e08022000280032066e6f726d616c3a0664656c75786542046a756d704801220408032001',
'hex',
);
const bytes = [
{ code: 102, value: Buffer.from('') },
{ code: 20011, value: Buffer.from('[email protected]') },
{ code: 20016, value: Buffer.from('') },
{ code: 20003, value: Buffer.from('中国') },
{ code: 20004, value: Buffer.from('省份') },
{ code: 20020, value: Buffer.from('城市') },
{ code: 20005, value: Buffer.from('邮编') },
{ code: 20021, value: Buffer.from('学校') },
{ code: 20031, value: Uint8Array.from([0, 0, 2, 29]) },
{ code: 107, value: icons },
];
const numbers = [
[20037, 0],
[105, 0],
[20009, 2],
[41756, 0],
[41757, 0],
[42241, 0],
] as const;
function sender(responseData: Uint8Array) {
return {
sendRawPacket: vi.fn(async () => ({
success: true,
gotResponse: true,
errorCode: 0,
errorMessage: '',
responseData: Buffer.from(responseData),
})),
};
}
describe('public contact profiles', () => {
it.each(['roster', 'uin', 'uid'])(
'preserves presence and privilege lists through the %s wire codec',
async (form) => {
let profile;
if (form === 'roster') {
const page = await FetchFriendListPage.invoke(
sender(
protobuf_encode<OidbBase<OidbSvcTrpcTcp0xFD4_1Response>>({
body: {
friends: [
{
uin: 10001,
customGroup: 0,
additional: [
{
type: 1,
layer1: {
properties: bytes,
numberProperties: numbers.map(
([key, value]) => ({ key, value }),
),
},
},
],
},
],
},
}),
),
{},
);
expect(page.entries[0]?.friend.categoryId).toBe(0);
profile = page.entries[0]?.friend.profile;
} else {
const deps = sender(
protobuf_encode<OidbBase<OidbUserInfoResponse>>({
body: {
body: {
uin: 10001,
uid: 'u_test',
properties: {
bytesProperties: bytes,
numberProperties: numbers.map(([number1, number2]) => ({
number1,
number2,
})),
},
},
},
}),
);
const user =
form === 'uin'
? await FetchUserProfile.invoke(deps, { uin: 10001 })
: await FetchUserProfileByUid.invoke(deps, { uid: 'u_test' });
profile = user.profile;
}
expect(profile).toEqual({
sign: '',
age: 0,
level: 0,
sex: 'female',
email: '[email protected]',
phoneNum: '',
country: '中国',
province: '省份',
city: '城市',
college: '学校',
birthdayMonth: 2,
birthdayDay: 29,
vipFlag: false,
svipFlag: false,
yearVipFlag: false,
vipLevel: 0,
privilegeIcons: {
jumpUrl: 'card',
open: [
{
type: 2,
level: 0,
flag: 0,
iconUrl: 'normal',
deluxeIconUrl: 'deluxe',
jumpUrl: 'jump',
isBig: 1,
},
],
closed: [{ type: 3, level: 1 }],
},
});
},
);
it('distinguishes missing, unavailable and explicitly empty icon lists', () => {
expect(decodePublicProfile(new Map(), new Map())).toEqual({});
expect(decodePublicProfile(new Map([[107, Buffer.alloc(0)]]), new Map())).toEqual({});
expect(decodePublicProfile(new Map([[107, Buffer.from([0x1a, 0])]]), new Map())).toEqual({
privilegeIcons: { open: [], closed: [] },
});
});
it('rejects truncated icons and invalid text without returning successful empty data', () => {
expect(() =>
decodePublicProfile(new Map([[107, Buffer.from([0x1a, 0xff])]]), new Map()),
).toThrow('invalid privilege data');
expect(() =>
decodePublicProfile(new Map([[107, Buffer.from([0x18, 0])]]), new Map()),
).toThrow('invalid privilege data');
expect(() =>
decodePublicProfile(new Map([[107, Buffer.from('1a041a020a00', 'hex')]]), new Map()),
).toThrow('invalid privilege data');
expect(() =>
decodePublicProfile(new Map([[20011, Buffer.from([0xff])]]), new Map()),
).toThrow('invalid UTF-8');
});
it('rejects a profile response belonging to a different requested account', async () => {
const deps = sender(
protobuf_encode<OidbBase<OidbUserInfoResponse>>({ body: { body: { uin: 10002 } } }),
);
await expect(FetchUserProfile.invoke(deps, { uin: 10001 })).rejects.toThrow(
'does not match',
);
});
});