diff --git a/packages/core/tests/actions/group-admin.test.ts b/packages/core/tests/actions/group-admin.test.ts index c951f8e1..6d263ee0 100644 --- a/packages/core/tests/actions/group-admin.test.ts +++ b/packages/core/tests/actions/group-admin.test.ts @@ -143,12 +143,11 @@ describe('apis/group-admin', () => { expect(nameEnv.body).toMatchObject({ groupUin: 1, body: { targetName: 'newName' } }); const titleEnv = protobuf_decode>(bridge.sendRawPacket.mock.calls[2]![1]); - // expireTime is proto int_32 with -1 sentinel; after wire round-trip the - // proton decoder surfaces it as the unsigned reinterpretation (-1 ≡ 0xFFFFFFFF). + // expireTime is proto int_32 and preserves the signed -1 sentinel. expect(titleEnv.body?.groupUin).toBe(1); expect(titleEnv.body?.body?.targetUid).toBe('resolved-uid'); expect(titleEnv.body?.body?.specialTitle).toBe('newTitle'); - expect(titleEnv.body?.body?.expireTime).toBe(0xFFFFFFFF); + expect(titleEnv.body?.body?.expireTime).toBe(-1); const remarkEnv = protobuf_decode>(bridge.sendRawPacket.mock.calls[3]![1]); expect(remarkEnv.body?.inner).toMatchObject({ groupId: 1n, remark: 'newRemark' }); diff --git a/packages/protocol/tests/oidb-services/group-admin/set-special-title.test.ts b/packages/protocol/tests/oidb-services/group-admin/set-special-title.test.ts index c82139fc..8264ec8b 100644 --- a/packages/protocol/tests/oidb-services/group-admin/set-special-title.test.ts +++ b/packages/protocol/tests/oidb-services/group-admin/set-special-title.test.ts @@ -32,7 +32,7 @@ describe('SetSpecialTitle namespace', () => { expect(env.body?.body?.specialTitle).toBe('crown'); // uinName (tag 7) must mirror specialTitle or the server silently no-ops. expect(env.body?.body?.uinName).toBe('crown'); - // -1 (int_32) round-trips as 0xFFFFFFFF after the proton decoder reinterprets. - expect(env.body?.body?.expireTime).toBe(0xFFFFFFFF); + // int_32 preserves the signed -1 sentinel after the wire round-trip. + expect(env.body?.body?.expireTime).toBe(-1); }); }); diff --git a/packages/proton/protobuf.d.ts b/packages/proton/protobuf.d.ts index b6f52593..4c8cbccb 100644 --- a/packages/proton/protobuf.d.ts +++ b/packages/proton/protobuf.d.ts @@ -32,6 +32,22 @@ export type bytes = Uint8Array; export function protobuf_encode(params: T): Uint8Array; export function protobuf_decode(data: Uint8Array): T; +/** Non-enumerable metadata retained for protobuf tags unknown to the schema. */ +export interface ProtobufUnknownField { + fieldNumber: number; + wireType: number; + count: number; + totalByteLength: number; +} +export interface ProtobufUnknownFieldMetadata { + fields: readonly ProtobufUnknownField[]; + totalOccurrences: number; + omittedOccurrences: number; + omittedByteLength: number; +} +export function protobuf_getUnknownFields(value: unknown): readonly ProtobufUnknownField[]; +export function protobuf_getUnknownFieldMetadata(value: unknown): ProtobufUnknownFieldMetadata; + // ── Optional runtime map fallback (disabled by default) ─────────────── export interface ProtobufRuntimeField { name: string; diff --git a/packages/proton/src/codegen/decoder.ts b/packages/proton/src/codegen/decoder.ts index 9b8477d2..3a7f349d 100644 --- a/packages/proton/src/codegen/decoder.ts +++ b/packages/proton/src/codegen/decoder.ts @@ -10,19 +10,15 @@ function tagValue(field: ProtobufField): number { /** Emit inline varint decode, storing result in `varName`. */ function varintDec(varName: string, ind: string): string { return [ - `${ind}let ${varName} = data[offset++];`, - `${ind}if (${varName} & 0x80) {`, - `${ind} let _s = 7, _b;`, - `${ind} ${varName} &= 0x7f;`, - `${ind} do { _b = data[offset++]; ${varName} |= (_b & 0x7f) << _s; _s += 7; } while (_b & 0x80);`, - `${ind}}`, + `${ind}const [${varName}, ${varName}_offset] = __readVarint32(data, offset, end);`, + `${ind}offset = ${varName}_offset;`, ].join('\n'); } function varintDec64(varName: string, ind: string): string { return [ - `${ind}let ${varName} = 0n, _s = 0n, _b;`, - `${ind}do { _b = data[offset++]; ${varName} |= BigInt(_b & 0x7f) << _s; _s += 7n; } while (_b & 0x80);`, + `${ind}const [${varName}, ${varName}_offset] = __readVarint64(data, offset, end);`, + `${ind}offset = ${varName}_offset;`, ].join('\n'); } @@ -34,13 +30,7 @@ function isFixed64BigInt(typeName: string): boolean { return typeName === 'fixed_64' || typeName === 'sfixed_64'; } -const INLINE_SKIP = [ - ` const wireType = _tag & 0x7;`, - ` if (wireType === 0) { while (data[offset] & 0x80) offset++; offset++; }`, - ` else if (wireType === 1) offset += 8;`, - ` else if (wireType === 2) { let _l = data[offset++]; if (_l & 0x80) { let _s = 7, _b; _l &= 0x7f; do { _b = data[offset++]; _l |= (_b & 0x7f) << _s; _s += 7; } while (_b & 0x80); } offset += _l; }`, - ` else if (wireType === 5) offset += 4;`, -].join('\n'); +const INLINE_SKIP = ` offset = __skipUnknownField(data, offset, end, wireType, _tag >>> 3);`; export function generateDecoder(msg: ProtobufMessage, _registry: MessageRegistry): string { const locals = msg.fields.map((field, index) => { @@ -51,14 +41,20 @@ export function generateDecoder(msg: ProtobufMessage, _registry: MessageRegistry const L = [ `function protobuf_decode_${msg.name}(data, offset = 0, end = data.length) {`, + ` if (!Number.isSafeInteger(offset) || !Number.isSafeInteger(end) || offset < 0 || end < offset || end > data.length) {`, + ` throw new Error('protobuf decoder bounds are invalid');`, + ` }`, ...locals, + ` let _unknownFields = null;`, + ` let _unknownFieldsByKey = null;`, + ` let _unknownTotalOccurrences = 0;`, + ` let _unknownOmittedOccurrences = 0;`, + ` let _unknownOmittedByteLength = 0;`, ` while (offset < end) {`, - ` let _tag = data[offset++];`, - ` if (_tag & 0x80) {`, - ` let _ts = 7, _tb;`, - ` _tag &= 0x7f;`, - ` do { _tb = data[offset++]; _tag |= (_tb & 0x7f) << _ts; _ts += 7; } while (_tb & 0x80);`, - ` }`, + ` const _fieldStart = offset;`, + ` const [_tag, _tagOffset] = __readVarint32(data, offset, end);`, + ` offset = _tagOffset;`, + ` if ((_tag >>> 3) === 0) throw new Error('protobuf field number 0 is invalid');`, ` switch (_tag) {`, ]; @@ -68,12 +64,50 @@ export function generateDecoder(msg: ProtobufMessage, _registry: MessageRegistry L.push( ` default: {`, + ` const _unknownStart = offset;`, + ` const wireType = _tag & 0x7;`, INLINE_SKIP, + ` const _unknownFieldNumber = _tag >>> 3;`, + ` const _unknownByteLength = offset - _unknownStart;`, + ` const _unknownKey = (_unknownFieldNumber * 8) + wireType;`, + ` _unknownTotalOccurrences++;`, + ` const _knownUnknown = _unknownFieldsByKey?.get(_unknownKey);`, + ` if (_knownUnknown) {`, + ` _knownUnknown.count++;`, + ` _knownUnknown.totalByteLength += _unknownByteLength;`, + ` } else if ((_unknownFields?.length ?? 0) < 64) {`, + ` const _unknown = {`, + ` fieldNumber: _unknownFieldNumber,`, + ` wireType,`, + ` count: 1,`, + ` totalByteLength: _unknownByteLength,`, + ` };`, + ` (_unknownFields ??= []).push(_unknown);`, + ` (_unknownFieldsByKey ??= new Map()).set(_unknownKey, _unknown);`, + ` } else {`, + ` _unknownOmittedOccurrences++;`, + ` _unknownOmittedByteLength += _unknownByteLength;`, + ` }`, ` break;`, ` }`, ` }`, + ` if (offset <= _fieldStart || offset > end) throw new Error('protobuf decoder made invalid progress');`, ` }`, - ` return { ${result} };`, + ` const _result = { ${result} };`, + ` if (_unknownTotalOccurrences > 0) Object.defineProperty(`, + ` _result,`, + ` Symbol.for('snowluma.proton.unknownFields'),`, + ` {`, + ` value: {`, + ` fields: _unknownFields ?? [],`, + ` totalOccurrences: _unknownTotalOccurrences,`, + ` omittedOccurrences: _unknownOmittedOccurrences,`, + ` omittedByteLength: _unknownOmittedByteLength,`, + ` },`, + ` enumerable: false,`, + ` },`, + ` );`, + ` return _result;`, `}`, ); return L.join('\n'); @@ -91,16 +125,17 @@ function decodeField(field: ProtobufField, index: number): string { if (isMessage) { L.push(varintDec('_len', I)); - L.push(assign(`protobuf_decode_${typeName}(data, offset, offset + _len)`)); - L.push(`${I}offset += _len;`); + L.push(`${I}const _end = __checkedEnd(offset, _len, end);`); + L.push(assign(`protobuf_decode_${typeName}(data, offset, _end)`)); + L.push(`${I}offset = _end;`); } else if (typeName === 'string') { L.push(varintDec('_len', I)); - L.push(`${I}const _end = offset + _len;`); + L.push(`${I}const _end = __checkedEnd(offset, _len, end);`); L.push(assign(`__td.decode(data.subarray(offset, _end))`)); L.push(`${I}offset = _end;`); } else if (typeName === 'bytes') { L.push(varintDec('_len', I)); - L.push(`${I}const _end = offset + _len;`); + L.push(`${I}const _end = __checkedEnd(offset, _len, end);`); L.push(assign(`data.slice(offset, _end)`)); L.push(`${I}offset = _end;`); } else if (typeName === 'bool') { @@ -115,6 +150,13 @@ function decodeField(field: ProtobufField, index: number): string { } else { L.push(assign(`__zigZagDecode64(_val)`)); } + } 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. + 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)`)); @@ -122,15 +164,19 @@ function decodeField(field: ProtobufField, index: number): string { L.push(varintDec('_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');`); L.push(assign(`__readFloat32(data, offset)`)); L.push(`${I}offset += 4;`); } else if (wireType === WireType.Bit32) { + L.push(`${I}if (end - offset < 4) throw new Error('protobuf truncated fixed32 field');`); L.push(assign(`data[offset] | (data[offset + 1] << 8) | (data[offset + 2] << 16) | (data[offset + 3] << 24)`)); L.push(`${I}offset += 4;`); } else if (typeName === 'double') { + L.push(`${I}if (end - offset < 8) throw new Error('protobuf truncated double field');`); L.push(assign(`__readFloat64(data, offset)`)); L.push(`${I}offset += 8;`); } else if (isFixed64BigInt(typeName)) { + L.push(`${I}if (end - offset < 8) throw new Error('protobuf truncated fixed64 field');`); if (typeName === 'fixed_64') { L.push(assign(`__readFixed64(data, offset)`)); } else { @@ -138,6 +184,7 @@ function decodeField(field: ProtobufField, index: number): string { } L.push(`${I}offset += 8;`); } else if (wireType === WireType.Bit64) { + L.push(`${I}if (end - offset < 8) throw new Error('protobuf truncated fixed64 field');`); L.push(assign(`data[offset] | (data[offset + 1] << 8) | (data[offset + 2] << 16) | (data[offset + 3] << 24)`)); L.push(`${I}offset += 8;`); } diff --git a/packages/proton/src/codegen/generator.ts b/packages/proton/src/codegen/generator.ts index ee4ee9ca..466226cc 100644 --- a/packages/proton/src/codegen/generator.ts +++ b/packages/proton/src/codegen/generator.ts @@ -95,6 +95,74 @@ function __zigZagEncode64(value) { function __zigZagDecode64(value) { return BigInt.asIntN(64, (value >> 1n) ^ -(value & 1n)); } +function __readVarint32(data, offset, end) { + let value = 0; + for (let i = 0; i < 5; i++) { + if (offset >= end) throw new Error('protobuf truncated uint32 varint'); + const byte = data[offset++]; + if (i === 4 && (byte & 0xf0) !== 0) throw new Error('protobuf uint32 varint overflow'); + value += (byte & 0x7f) * (2 ** (i * 7)); + if ((byte & 0x80) === 0) return [value >>> 0, offset]; + } + throw new Error('protobuf uint32 varint overflow'); +} +function __readVarint64(data, offset, end) { + let value = 0n; + for (let i = 0; i < 10; i++) { + if (offset >= end) throw new Error('protobuf truncated uint64 varint'); + const byte = data[offset++]; + if (i === 9 && byte > 1) throw new Error('protobuf uint64 varint overflow'); + value |= BigInt(byte & 0x7f) << BigInt(i * 7); + if ((byte & 0x80) === 0) return [value, offset]; + } + throw new Error('protobuf uint64 varint overflow'); +} +function __skipVarint(data, offset, end) { + for (let i = 0; i < 10; i++) { + if (offset >= end) throw new Error('protobuf truncated varint'); + const byte = data[offset++]; + if (i === 9 && byte > 1) throw new Error('protobuf varint overflow'); + if ((byte & 0x80) === 0) return offset; + } + throw new Error('protobuf varint overflow'); +} +function __checkedEnd(offset, length, end) { + if (length > end - offset) throw new Error('protobuf length-delimited field exceeds parent bounds'); + return offset + length; +} +function __skipUnknownField(data, offset, end, wireType, fieldNumber, depth = 0) { + if (depth > 64) throw new Error('protobuf group nesting exceeds 64'); + if (wireType === 0) return __skipVarint(data, offset, end); + if (wireType === 1) { + if (end - offset < 8) throw new Error('protobuf truncated fixed64 field'); + return offset + 8; + } + if (wireType === 2) { + const [length, next] = __readVarint32(data, offset, end); + return __checkedEnd(next, length, end); + } + if (wireType === 3) { + while (offset < end) { + const [tag, next] = __readVarint32(data, offset, end); + offset = next; + const nestedField = tag >>> 3; + const nestedWire = tag & 0x7; + if (nestedField === 0) throw new Error('protobuf field number 0 is invalid'); + if (nestedWire === 4) { + if (nestedField !== fieldNumber) throw new Error('protobuf mismatched end-group tag'); + return offset; + } + offset = __skipUnknownField(data, offset, end, nestedWire, nestedField, depth + 1); + } + throw new Error('protobuf unterminated group'); + } + if (wireType === 4) throw new Error('protobuf unexpected end-group tag'); + if (wireType === 5) { + if (end - offset < 4) throw new Error('protobuf truncated fixed32 field'); + return offset + 4; + } + throw new Error('protobuf invalid wire type ' + wireType); +} function __writeFloat32(buf, offset, value) { __scratch.setFloat32(0, value, true); buf[offset++] = __scratch.getUint8(0); diff --git a/packages/proton/src/runtime.ts b/packages/proton/src/runtime.ts index c48cc583..7dfbd394 100644 --- a/packages/proton/src/runtime.ts +++ b/packages/proton/src/runtime.ts @@ -12,6 +12,49 @@ import { type DynamicEncode = (params: unknown) => Uint8Array; type DynamicDecode = (data: Uint8Array) => unknown; +export interface ProtobufUnknownField { + fieldNumber: number; + wireType: number; + count: number; + totalByteLength: number; +} + +export interface ProtobufUnknownFieldMetadata { + fields: readonly ProtobufUnknownField[]; + totalOccurrences: number; + omittedOccurrences: number; + omittedByteLength: number; +} + +const PROTOBUF_UNKNOWN_FIELDS = Symbol.for('snowluma.proton.unknownFields'); +const EMPTY_UNKNOWN_FIELD_METADATA: ProtobufUnknownFieldMetadata = Object.freeze({ + fields: Object.freeze([]), + totalOccurrences: 0, + omittedOccurrences: 0, + omittedByteLength: 0, +}); + +/** Unknown wire tags retained by generated decoders. The symbol-backed + * metadata is non-enumerable, so decoded object shapes and re-encoding remain + * unchanged while protocol boundaries can make schema drift observable. */ +export function protobuf_getUnknownFields(value: unknown): readonly ProtobufUnknownField[] { + return protobuf_getUnknownFieldMetadata(value).fields; +} + +export function protobuf_getUnknownFieldMetadata(value: unknown): ProtobufUnknownFieldMetadata { + if (typeof value !== 'object' || value === null) return EMPTY_UNKNOWN_FIELD_METADATA; + const metadata = (value as Record)[PROTOBUF_UNKNOWN_FIELDS]; + if (typeof metadata !== 'object' || metadata === null) return EMPTY_UNKNOWN_FIELD_METADATA; + const candidate = metadata as Partial; + if (!Array.isArray(candidate.fields)) return EMPTY_UNKNOWN_FIELD_METADATA; + return { + fields: candidate.fields, + totalOccurrences: candidate.totalOccurrences ?? candidate.fields.length, + omittedOccurrences: candidate.omittedOccurrences ?? 0, + omittedByteLength: candidate.omittedByteLength ?? 0, + }; +} + interface DynamicTypeFns { encode?: DynamicEncode; decode?: DynamicDecode; diff --git a/packages/proton/test/__tests__/generator.test.ts b/packages/proton/test/__tests__/generator.test.ts index 09fc54f8..f546be6f 100644 --- a/packages/proton/test/__tests__/generator.test.ts +++ b/packages/proton/test/__tests__/generator.test.ts @@ -1,6 +1,7 @@ import { describe, it, expect } from 'vitest'; import { analyzeSource } from '../../src/ast/analyzer'; import { generateCode } from '../../src/codegen/generator'; +import { protobuf_getUnknownFieldMetadata } from '../../src/runtime'; import { loadFixture } from '../helpers'; /** Analyze fixture → generate → eval → return encode/decode pair */ @@ -24,6 +25,18 @@ function makeRoundTripFromSchema(schema: string, msgName: string) { return { enc, dec }; } +function encodeVarint32(value: number): number[] { + const bytes: number[] = []; + let remaining = value >>> 0; + do { + let byte = remaining & 0x7f; + remaining >>>= 7; + if (remaining !== 0) byte |= 0x80; + bytes.push(byte); + } while (remaining !== 0); + return bytes; +} + describe('code generator', () => { it('generates encode/decode for simple uint_32', () => { const gen = generateCode(analyzeSource(loadFixture('simple.ts'), 't.ts')); @@ -36,7 +49,7 @@ describe('code generator', () => { it('generates nested message code', () => { const gen = generateCode(analyzeSource(loadFixture('nested.ts'), 't.ts')); expect(gen).toContain('protobuf_encode_Inner('); - expect(gen).toContain('protobuf_decode_Inner(data, offset, offset + _len)'); + expect(gen).toContain('protobuf_decode_Inner(data, offset, _end)'); }); it('round-trip uint_32', () => { @@ -126,6 +139,99 @@ interface Sint32Msg { expect(dec(enc(input))).toEqual(input); }); + it('preserves legacy outbound int_32 bytes while accepting canonical negative varints', () => { + const schema = ` +interface Int32Msg { + value: pb<1, int_32>; + values: pb_repeated<2, int_32>; + forced: pb_optional<3, int_32>; +}`; + const { enc, dec } = makeRoundTripFromSchema(schema, 'Int32Msg'); + const input = { + value: -1, + values: [-2147483648, -1, 0, 1, 2147483647], + forced: -2147483648, + }; + const encoded = enc(input); + + // Keep SnowLuma's established five-byte negative int32 encoding on the + // outbound path until QQ interoperability is verified on a live account. + // The decoder remains liberal and accepts protobuf's canonical ten-byte + // negative form below. + expect(Array.from(encoded.slice(0, 6))).toEqual([ + 0x08, + 0xff, 0xff, 0xff, 0xff, 0x0f, + ]); + expect(dec(encoded)).toEqual(input); + expect(dec(Uint8Array.from([ + 0x08, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01, + ])).value).toBe(-1); + }); + + 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')); + const { dec } = makeRoundTripFromSchema(schema, 'BytesMsg'); + + expect(gen).toContain('const _end = __checkedEnd(offset, _len, end);'); + expect(() => dec(Uint8Array.from([0x0a, 0x80]))).toThrow(/truncated uint32 varint/); + expect(() => dec(Uint8Array.from([0x0a, 0x80, 0x80, 0x80, 0x80, 0x10]))).toThrow(/uint32 varint overflow/); + }); + + it('skips unknown groups without decoding their fields into the parent', () => { + const schema = ` +interface Text { str: pb<1, string>; } +interface Elem { text: pb<1, Text>; } +`; + const { dec } = makeRoundTripFromSchema(schema, 'Elem'); + const decoded = dec(Uint8Array.from([ + 0x7b, + 0x0a, 0x08, 0x0a, 0x06, 0x66, 0x6f, 0x72, 0x67, 0x65, 0x64, + 0x7c, + ])); + + expect(decoded.text).toBeNull(); + expect(protobuf_getUnknownFieldMetadata(decoded).fields).toMatchObject([ + { fieldNumber: 15, wireType: 3 }, + ]); + }); + + it('aggregates repeated unknown fields instead of retaining every occurrence', () => { + const { dec } = makeRoundTripFromSchema( + `interface UnknownMsg { known: pb<1, uint_32>; }`, + 'UnknownMsg', + ); + const wire: number[] = []; + const tag = encodeVarint32((60 << 3) | 0); + for (let index = 0; index < 1_000; index++) wire.push(...tag, 0); + + const metadata = protobuf_getUnknownFieldMetadata(dec(Uint8Array.from(wire))); + expect(metadata).toEqual({ + fields: [{ fieldNumber: 60, wireType: 0, count: 1_000, totalByteLength: 1_000 }], + totalOccurrences: 1_000, + omittedOccurrences: 0, + omittedByteLength: 0, + }); + }); + + it('caps retained unknown field kinds and summarizes overflow', () => { + const { dec } = makeRoundTripFromSchema( + `interface UnknownKindsMsg { known: pb<1, uint_32>; }`, + 'UnknownKindsMsg', + ); + const wire: number[] = []; + for (let fieldNumber = 2; fieldNumber <= 66; fieldNumber++) { + wire.push(...encodeVarint32((fieldNumber << 3) | 0), 0); + } + + const metadata = protobuf_getUnknownFieldMetadata(dec(Uint8Array.from(wire))); + expect(metadata.fields).toHaveLength(64); + expect(metadata.totalOccurrences).toBe(65); + expect(metadata.omittedOccurrences).toBe(1); + expect(metadata.omittedByteLength).toBe(1); + }); + it('round-trip double as ieee754 number', () => { const schema = ` interface DoubleMsg {