fix(friend): verify and synchronize remark updates
Validate the service result before reporting friend remark changes as successful. Rejected, incomplete, or contradictory confirmations now reach callers instead of being reported as completed. Keep confirmed remarks synchronized in the identity cache and consume cross-client remark updates without exposing a new OneBot event. Local cache failures remain observable without turning an already completed remote change into a retryable failure. Preserve friend remarks exactly across restarts and add request, response, persistence, receive-pipeline, and action-level regression coverage. Fixes #303.
This commit is contained in:
17 files changed
+511
-18
No files matched your search
@@ -526,6 +526,18 @@ export interface OnlineDevicesChangedEvent extends QQEvent {
|
||||
devices: OnlineDeviceInfo[];
|
||||
}
|
||||
|
||||
/**
|
||||
* A friend or stranger remark changed on another client (Event 0x210 /
|
||||
* subType 364). Internal-only: the packet pipeline consumes this event to
|
||||
* keep the identity cache synchronized; it is not forwarded to OneBot.
|
||||
*/
|
||||
export interface FriendRemarkChangedEvent extends QQEvent {
|
||||
kind: 'friend_remark_changed';
|
||||
userUid: string;
|
||||
userUin: number;
|
||||
remark: string;
|
||||
}
|
||||
|
||||
export type QQEventVariant =
|
||||
| FriendMessage
|
||||
| GroupMessage
|
||||
@@ -551,4 +563,5 @@ export type QQEventVariant =
|
||||
| GroupTitleChangeEvent
|
||||
| FriendProfileLikeEvent
|
||||
| OnlineDevicesChangedEvent
|
||||
| FriendRemarkChangedEvent
|
||||
| BotOfflineEvent;
|
||||
@@ -322,6 +322,56 @@ export class IdentityService {
|
||||
this.runWrite('group member update', () => this.transaction(() => this.upsertGroupMember(persisted)));
|
||||
}
|
||||
|
||||
/** Apply the server-authoritative friend/stranger remark synchronization push. */
|
||||
updateFriendRemark(uid: string, uin: number, remark: string): boolean {
|
||||
this.beginObservation('friend remark update');
|
||||
const normalizedUid = normalizeUid(uid);
|
||||
const normalizedUin = normalizeUin(uin);
|
||||
if (!normalizedUid && normalizedUin === null) {
|
||||
throw new Error('friend remark update is missing both UID and UIN');
|
||||
}
|
||||
|
||||
const byUid = normalizedUid
|
||||
? this.friends_.find((friend) => friend.uid === normalizedUid) ?? null
|
||||
: null;
|
||||
const byUin = normalizedUin !== null
|
||||
? this.friends_.find((friend) => friend.uin === normalizedUin) ?? null
|
||||
: null;
|
||||
if (byUid && byUin && byUid !== byUin) {
|
||||
throw new Error(`friend remark update identity mismatch: uid=${normalizedUid} uin=${normalizedUin}`);
|
||||
}
|
||||
|
||||
const friend = byUid ?? byUin;
|
||||
if (friend && normalizedUid && friend.uid && friend.uid !== normalizedUid) {
|
||||
throw new Error(`friend remark update UID mismatch for uin=${friend.uin}`);
|
||||
}
|
||||
if (friend && normalizedUin !== null && friend.uin !== normalizedUin) {
|
||||
throw new Error(`friend remark update UIN mismatch for uid=${friend.uid}`);
|
||||
}
|
||||
|
||||
const observedUid = normalizedUid || friend?.uid || '';
|
||||
const observedUin = normalizedUin ?? friend?.uin ?? 0;
|
||||
if (friend) {
|
||||
const index = this.friends_.indexOf(friend);
|
||||
this.friends_[index] = { ...friend, remark };
|
||||
}
|
||||
const profile = observedUin > 0 ? this.userProfiles_.get(observedUin) : undefined;
|
||||
if (profile) this.userProfiles_.set(observedUin, { ...profile, remark });
|
||||
this.rememberUidUin(observedUid, observedUin);
|
||||
|
||||
const persisted: UserInput = {
|
||||
uid: observedUid || undefined,
|
||||
uin: observedUin > 0 ? observedUin : undefined,
|
||||
remark,
|
||||
isFriend: friend ? true : undefined,
|
||||
};
|
||||
this.runWrite(
|
||||
'friend remark update',
|
||||
() => this.transaction(() => this.upsertUser(persisted)),
|
||||
);
|
||||
return friend !== null;
|
||||
}
|
||||
|
||||
// ─── ID translation ───
|
||||
|
||||
/**
|
||||
@@ -816,7 +866,7 @@ export class IdentityService {
|
||||
uid: uid || primary?.uid || null,
|
||||
uin: uin ?? primary?.uin ?? null,
|
||||
nickname: mergeOptionalText(input.nickname, primary?.nickname ?? ''),
|
||||
remark: mergeOptionalText(input.remark, primary?.remark ?? ''),
|
||||
remark: mergeOptionalExactText(input.remark, primary?.remark ?? ''),
|
||||
isFriend: input.isFriend === true ? 1 : (primary?.is_friend ?? 0),
|
||||
source: mergeOptionalText(input.source, primary?.source ?? ''),
|
||||
updatedAt: nowSeconds(),
|
||||
@@ -1247,6 +1297,10 @@ function mergeOptionalText(value: unknown, fallback: string): string {
|
||||
return value === undefined ? fallback : normalizeText(value);
|
||||
}
|
||||
|
||||
function mergeOptionalExactText(value: unknown, fallback: string): string {
|
||||
return value === undefined ? fallback : (typeof value === 'string' ? value : '');
|
||||
}
|
||||
|
||||
function normalizeNonNegative(value: unknown, fallback: number): number {
|
||||
if (typeof value === 'number' && Number.isFinite(value)) return Math.max(0, Math.trunc(value));
|
||||
return fallback;
|
||||
|
||||
@@ -10,6 +10,7 @@ import type {
|
||||
} from '../../events';
|
||||
import type {
|
||||
FriendRecall,
|
||||
FriendRemarkChangedNotify,
|
||||
FriendRequest,
|
||||
GeneralGrayTipInfo,
|
||||
InputStatusNotify,
|
||||
@@ -46,6 +47,7 @@ export const decodeEvent0x210: MsgPushDecoder = (ctx) => {
|
||||
case Event0x210SubType.FriendPokeNotice: return decodeFriendPoke(ctx);
|
||||
case Event0x210SubType.InputStatusNotice: return decodeInputStatus(ctx);
|
||||
case Event0x210SubType.OnlineDevicesNotice: return decodeOnlineDevices(ctx);
|
||||
case Event0x210SubType.FriendRemarkChangedNotice: return decodeFriendRemarkChanged(ctx);
|
||||
case Event0x210SubType.ProfileLikeNotice: return decodeProfileLike(ctx);
|
||||
// 179 + 226 both carry the NewFriend payload — see enum comment.
|
||||
case Event0x210SubType.NewFriendNotice:
|
||||
@@ -70,6 +72,32 @@ export const decodeEvent0x210: MsgPushDecoder = (ctx) => {
|
||||
return [];
|
||||
};
|
||||
|
||||
function decodeFriendRemarkChanged(ctx: MsgPushContext): QQEventVariant[] {
|
||||
const notify = protobuf_decode<FriendRemarkChangedNotify>(ctx.content);
|
||||
const change = notify?.change;
|
||||
const uid = change?.target?.uid?.trim() ?? '';
|
||||
const rawUin = change?.target?.uin;
|
||||
const uin = rawUin === undefined ? 0 : Number(rawUin);
|
||||
if (rawUin !== undefined && (!Number.isSafeInteger(uin) || uin <= 0)) {
|
||||
throw new Error(`friend remark synchronization has invalid UIN ${rawUin}`);
|
||||
}
|
||||
if (!uid && uin <= 0) {
|
||||
throw new Error('friend remark synchronization is missing both UID and UIN');
|
||||
}
|
||||
if (change?.remark === undefined) {
|
||||
throw new Error(`friend remark synchronization is missing the remark value (uid=${uid} uin=${uin})`);
|
||||
}
|
||||
if (ctx.isHistorical) return [];
|
||||
return [{
|
||||
kind: 'friend_remark_changed',
|
||||
time: ctx.head.timestamp,
|
||||
selfUin: ctx.selfUin,
|
||||
userUid: uid,
|
||||
userUin: uin,
|
||||
remark: change.remark,
|
||||
}];
|
||||
}
|
||||
|
||||
const COMPUTER_CLIENT_TYPES = new Set([1, 5, 15]);
|
||||
const PHONE_CLIENT_TYPES = new Set([2, 3, 4, 6, 7, 12]);
|
||||
const PAD_CLIENT_TYPES = new Set([8, 9, 10, 11, 13]);
|
||||
|
||||
@@ -90,6 +90,8 @@ export enum Event0x210SubType {
|
||||
* does not issue a separate network request.
|
||||
*/
|
||||
OnlineDevicesNotice = 349,
|
||||
/** Server-authoritative friend/stranger remark synchronization push. */
|
||||
FriendRemarkChangedNotice = 364,
|
||||
/**
|
||||
* Group-app state push (troop shortcut bar / discussion app).
|
||||
*
|
||||
|
||||
@@ -3,11 +3,17 @@
|
||||
// StrangerRemarkSetWorker with scene=0.
|
||||
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import type { OidbBase, OidbEmpty } from '@snowluma/proto-defs/oidb';
|
||||
import type { OidbSetFriendRemark } from '@snowluma/proto-defs/oidb-actions/base';
|
||||
import { invokeOidb, type OidbSender } from '../../oidb-service';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type { OidbBase } from '@snowluma/proto-defs/oidb';
|
||||
import type {
|
||||
OidbSetFriendRemark,
|
||||
OidbSetFriendRemarkResponse,
|
||||
} from '@snowluma/proto-defs/oidb-actions/base';
|
||||
import { invokeOidb, OidbError, type OidbSender } from '../../oidb-service';
|
||||
import type { BridgeContext } from '../../bridge-context';
|
||||
|
||||
const log = createLogger('Bridge.Friend');
|
||||
|
||||
export namespace SetFriendRemark {
|
||||
export const command = 0x912E;
|
||||
export const subCommand = 0;
|
||||
@@ -17,24 +23,83 @@ export namespace SetFriendRemark {
|
||||
remark: string;
|
||||
}
|
||||
|
||||
export type Deps = OidbSender & Pick<BridgeContext, 'resolveUserUid'>;
|
||||
interface WireParams {
|
||||
targetUid: string;
|
||||
remark: string;
|
||||
}
|
||||
|
||||
export const serialize = async (ctx: Deps, p: Params): Promise<OidbSetFriendRemark> => ({
|
||||
export interface Result {
|
||||
targetUid: string;
|
||||
targetUin: number;
|
||||
remark: string;
|
||||
}
|
||||
|
||||
export type Deps = OidbSender & Pick<BridgeContext, 'identity' | 'resolveUserUid'>;
|
||||
|
||||
export const serialize = (_ctx: Deps, p: WireParams): OidbSetFriendRemark => ({
|
||||
change: {
|
||||
target: { targetUid: await ctx.resolveUserUid(p.userId) },
|
||||
target: { targetUid: p.targetUid },
|
||||
remark: p.remark,
|
||||
},
|
||||
scene: 0,
|
||||
});
|
||||
|
||||
export const deserialize = (_ctx: Deps, _: OidbEmpty): void => {};
|
||||
export const deserialize = (_ctx: Deps, response: OidbSetFriendRemarkResponse): Result => {
|
||||
if (response.error) {
|
||||
const code = response.error.code ?? 0;
|
||||
const message = response.error.message ?? '';
|
||||
if (code !== 0) throw new OidbError(code, message, command, subCommand);
|
||||
throw new Error(`invalid friend remark response: error result has no failure code${message ? ` (${message})` : ''}`);
|
||||
}
|
||||
|
||||
const result = response.result;
|
||||
if (!result) throw new Error('invalid friend remark response: missing result');
|
||||
const targetUid = result?.target?.targetUid ?? '';
|
||||
const rawTargetUin = result?.target?.targetUin ?? '';
|
||||
const targetUin = rawTargetUin ? Number(rawTargetUin) : 0;
|
||||
if (rawTargetUin && (!Number.isSafeInteger(targetUin) || targetUin <= 0)) {
|
||||
throw new Error(`invalid friend remark response: invalid target UIN ${rawTargetUin}`);
|
||||
}
|
||||
return { targetUid, targetUin, remark: result?.remark ?? '' };
|
||||
};
|
||||
|
||||
export const encode = (env: OidbBase<OidbSetFriendRemark>): Uint8Array =>
|
||||
protobuf_encode<OidbBase<OidbSetFriendRemark>>(env);
|
||||
|
||||
export const decode = (bytes: Uint8Array): OidbBase<OidbEmpty> =>
|
||||
protobuf_decode<OidbBase<OidbEmpty>>(bytes);
|
||||
export const decode = (bytes: Uint8Array): OidbBase<OidbSetFriendRemarkResponse> =>
|
||||
protobuf_decode<OidbBase<OidbSetFriendRemarkResponse>>(bytes);
|
||||
|
||||
export const invoke = (deps: Deps, params: Params): Promise<void> =>
|
||||
invokeOidb(deps, SetFriendRemark, params);
|
||||
export const invoke = async (deps: Deps, params: Params): Promise<void> => {
|
||||
const targetUid = await deps.resolveUserUid(params.userId);
|
||||
const result = await invokeOidb(deps, SetFriendRemark, {
|
||||
targetUid,
|
||||
remark: params.remark,
|
||||
});
|
||||
if (result.targetUid !== targetUid) {
|
||||
throw new Error(`friend remark response target mismatch: expected UID ${targetUid}, got ${result.targetUid || '(missing)'}`);
|
||||
}
|
||||
if (result.targetUin > 0 && result.targetUin !== params.userId) {
|
||||
throw new Error(`friend remark response target mismatch: expected UIN ${params.userId}, got ${result.targetUin}`);
|
||||
}
|
||||
if (result.remark !== params.remark) {
|
||||
throw new Error('friend remark response value does not match the requested remark');
|
||||
}
|
||||
// The server-side mutation has already completed. A local cache failure
|
||||
// must remain observable, but reporting the Action as failed here would
|
||||
// encourage callers to repeat an operation that QQ already accepted.
|
||||
try {
|
||||
deps.identity.updateFriendRemark(
|
||||
result.targetUid,
|
||||
result.targetUin || params.userId,
|
||||
result.remark,
|
||||
);
|
||||
} catch (error: unknown) {
|
||||
log.error(
|
||||
'local identity synchronization failed after confirmed friend remark update: uid=%s uin=%d: %s',
|
||||
result.targetUid,
|
||||
result.targetUin || params.userId,
|
||||
error instanceof Error ? error.message : String(error),
|
||||
);
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -691,6 +691,21 @@ export class IncomingPacketPipeline {
|
||||
source: 'friend_request',
|
||||
});
|
||||
break;
|
||||
case 'friend_remark_changed': {
|
||||
const rosterUpdated = this.deps.identity.updateFriendRemark(
|
||||
event.userUid,
|
||||
event.userUin,
|
||||
event.remark,
|
||||
);
|
||||
this.log.debug(
|
||||
'friend remark synchronized (uid=%s uin=%d length=%d rosterUpdated=%s)',
|
||||
event.userUid,
|
||||
event.userUin,
|
||||
event.remark.length,
|
||||
rosterUpdated,
|
||||
);
|
||||
break;
|
||||
}
|
||||
case 'group_invite': {
|
||||
// Defensive: never cache a uid→uin mapping where uin equals
|
||||
// the group's own uin — that's the pollution signature the
|
||||
|
||||
Reference in new issue
Block a user