fix(proton): accept sign-extended uint32 field values

This commit is contained in:
DrSmoothl committed 2026-07-10 18:20:11 +08:00
1 parent c04864dd21
commit b53004ee23
4 files changed
+139 -4

No files matched your search

@@ -6,10 +6,12 @@
// - formatEvent prints something readable in the [Event] log
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import type { PacketInfo } from '@snowluma/common/protocol-types';
import { protobuf_encode } from '@snowluma/proton';
import type { GroupReactNotify } from '@snowluma/proto-defs/notify';
import { MSG_PUSH_CMD, parseMsgPush } from '@snowluma/protocol/msg-push';
import { decodeEvent0x2DC } from '@snowluma/protocol/msg-push/decoders/event-0x2dc';
import type { MsgPushContext } from '@snowluma/protocol/msg-push/context';
import { buildContext, type MsgPushContext } from '@snowluma/protocol/msg-push/context';
import { IdentityService } from '@snowluma/protocol/identity-service';
import type { GroupMsgEmojiLikeEvent, QQEventVariant } from '@snowluma/protocol/events';
import { convertGroupMsgEmojiLike } from '../src/event-converter/to-notice';
@@ -35,6 +37,64 @@ function buildReactContent(notify: Record<string, unknown>): Uint8Array {
return out;
}
function encodeVarint(value: bigint): number[] {
const out: number[] = [];
let remaining = value;
do {
let byte = Number(remaining & 0x7fn);
remaining >>= 7n;
if (remaining !== 0n) byte |= 0x80;
out.push(byte);
} while (remaining !== 0n);
return out;
}
function encodeSignedInt32Varint(value: number): number[] {
return encodeVarint(BigInt.asUintN(64, BigInt(value | 0)));
}
function varintField(fieldNumber: number, value: number[] | bigint): number[] {
const bytes = Array.isArray(value) ? value : encodeVarint(value);
return [...encodeVarint(BigInt(fieldNumber << 3)), ...bytes];
}
function messageField(fieldNumber: number, payload: number[] | Uint8Array): number[] {
const bytes = Array.from(payload);
return [
...encodeVarint(BigInt((fieldNumber << 3) | 2)),
...encodeVarint(BigInt(bytes.length)),
...bytes,
];
}
function buildPushPacket(
content: Uint8Array,
options: { sequence: number[] | bigint; msgId: number[] | bigint },
): PacketInfo {
const contentHead = [
...varintField(1, 732n),
...varintField(2, 16n),
...varintField(4, options.msgId),
...varintField(5, options.sequence),
...varintField(6, 1735000000n),
];
const body = messageField(2, content);
const message = [
...messageField(2, contentHead),
...messageField(3, body),
];
return {
pid: 1,
uin: SELF_UIN,
serviceCmd: MSG_PUSH_CMD,
seqId: 1,
retCode: 0,
fromClient: false,
body: Uint8Array.from(messageField(1, message)),
};
}
function makeCtx(content: Uint8Array, identity = makeIdentity()): MsgPushContext {
return {
head: { msgType: 732, subType: 16, sequence: 0, timestamp: 1735000000, msgId: 0 },
@@ -49,6 +109,46 @@ function makeCtx(content: Uint8Array, identity = makeIdentity()): MsgPushContext
}
describe('decodeEvent0x2DC subType=16 — GroupMsgEmojiLike', () => {
it('decodes a full PushMsg whose envelope sequence uses a sign-extended 10-byte varint', () => {
const content = buildReactContent({
groupUin: BigInt(GROUP_ID),
field13: 35,
groupReactionData: {
data: {
data: {
groupReactionTarget: { seq: 4242n },
groupReactionDataContent: {
code: '76', count: 1, operatorUid: 'u_operator_xxx', type: 1,
},
},
},
},
});
const packet = buildPushPacket(content, {
msgId: 123n,
sequence: encodeSignedInt32Varint(-2),
});
const [event] = parseMsgPush(packet, makeIdentity()) as GroupMsgEmojiLikeEvent[];
expect(event).toMatchObject({
kind: 'group_msg_emoji_like',
groupId: GROUP_ID,
msgSeq: 4242,
emojiId: '76',
});
});
it('accepts a sign-extended negative ContentHead field 4 without losing its low 32 bits', () => {
const packet = buildPushPacket(new Uint8Array(0), {
msgId: encodeSignedInt32Varint(-1),
sequence: 7n,
});
const ctx = buildContext(packet, makeIdentity());
expect(ctx?.head.msgId).toBe(0xffffffff);
expect(ctx?.head.sequence).toBe(7);
});
it('decodes a field13=35 react add into a GroupMsgEmojiLikeEvent', () => {
const content = buildReactContent({
groupUin: BigInt(GROUP_ID),
+9 -3
View File
@@ -22,6 +22,13 @@ function varintDec64(varName: string, ind: string): string {
].join('\n');
}
function varintDec32Value(varName: string, ind: string): string {
return [
`${ind}const [${varName}, ${varName}_offset] = __readVarint32Value(data, offset, end);`,
`${ind}offset = ${varName}_offset;`,
].join('\n');
}
function isVarint64(typeName: string): boolean {
return typeName === 'uint_64' || typeName === 'int_64' || typeName === 'sint_64';
}
@@ -153,15 +160,14 @@ function decodeField(field: ProtobufField, index: number): string {
} else if (typeName === 'int_32') {
// Protobuf encodes negative int32 values as a sign-extended 10-byte
// varint. Read the full uint64 representation, then keep its signed low
// 32 bits. uint32/sint32/tag/length values must remain on the stricter
// five-byte reader.
// 32 bits.
L.push(varintDec64('_val', I));
L.push(assign(`Number(BigInt.asIntN(32, _val))`));
} else if (typeName === 'sint_32') {
L.push(varintDec('_val', I));
L.push(assign(`(_val >>> 1) ^ -(_val & 1)`));
} else if (wireType === WireType.Varint) {
L.push(varintDec('_val', I));
L.push(varintDec32Value('_val', I));
L.push(assign(`_val >>> 0`));
} else if (typeName === 'float') {
L.push(`${I}if (end - offset < 4) throw new Error('protobuf truncated float field');`);
+7
View File
@@ -117,6 +117,13 @@ function __readVarint64(data, offset, end) {
}
throw new Error('protobuf uint64 varint overflow');
}
function __readVarint32Value(data, offset, end) {
const [value, next] = __readVarint64(data, offset, end);
if (value > 0xffffffffn && value < 0xffffffff80000000n) {
throw new Error('protobuf uint32 field varint overflow');
}
return [Number(BigInt.asUintN(32, value)), next];
}
function __skipVarint(data, offset, end) {
for (let i = 0; i < 10; i++) {
if (offset >= end) throw new Error('protobuf truncated varint');
@@ -169,6 +169,28 @@ interface Int32Msg {
])).value).toBe(-1);
});
it('accepts sign-extended 10-byte values for uint_32 fields without accepting real overflow', () => {
const { dec } = makeRoundTripFromSchema(
`interface Uint32Msg { value: pb<1, uint_32>; }`,
'Uint32Msg',
);
// QQ sometimes serializes a signed 32-bit source into a schema slot that
// clients expose as uint32. Protobuf readers consume the full ten-byte
// varint and retain its low 32 bits for wire compatibility.
expect(dec(Uint8Array.from([
0x08,
0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01,
])).value).toBe(0xfffffffe);
// 2^32 is neither uint32 nor a sign-extended negative int32, so accepting
// ten-byte compatibility must not turn genuine overflow into truncation.
expect(() => dec(Uint8Array.from([
0x08,
0x80, 0x80, 0x80, 0x80, 0x10,
]))).toThrow(/uint32 field varint overflow/);
});
it('rejects malformed length-delimited fields without leaving parent bounds', () => {
const schema = `interface BytesMsg { data: pb<1, bytes>; }`;
const gen = generateCode(analyzeSource(schema, 'BytesMsg.ts'));