diff --git a/src/scalars/Byte.ts b/src/scalars/Byte.ts index 46b0ab26c..fbac4f5db 100644 --- a/src/scalars/Byte.ts +++ b/src/scalars/Byte.ts @@ -10,6 +10,8 @@ import { type BufferJson = { type: 'Buffer'; data: number[] }; const base64Validator = /^(?:[A-Za-z0-9+]{4})*(?:[A-Za-z0-9+]{2}==|[A-Za-z0-9+]{3}=)?$/; function hexValidator(value: string) { + // Ensure that any leading 0 is removed from the hex string to avoid false negatives. + const sanitizedValue = value.charAt(0) === '0' ? value.slice(1) : value; // For larger strings, we run into issues with MAX_SAFE_INTEGER, so split the string // into smaller pieces to avoid this issue. if (value.length > 8) { @@ -23,9 +25,9 @@ function hexValidator(value: string) { 16, ); } - return parsedString === value; + return parsedString === sanitizedValue; } - return parseInt(value, 16).toString(16) === value; + return parseInt(value, 16).toString(16) === sanitizedValue; } function validate(value: Buffer | string | BufferJson) { diff --git a/tests/Byte.test.ts b/tests/Byte.test.ts index f85fba782..47105f42c 100644 --- a/tests/Byte.test.ts +++ b/tests/Byte.test.ts @@ -18,8 +18,10 @@ const byte = Buffer.from([ 101, 33, ]); +const byteLeading0 = Buffer.from([4, 8, 15, 16, 23, 42]); const base64String = byte.toString('base64'); const hexString = byte.toString('hex'); +const hexLeading0 = byteLeading0.toString('hex'); const notBase64 = 'RG9kZ2VycyBSdWxlIQ='; const notHex = '446f64676572732052756c65z'; const looksLikeBase64 = 'c40473746174'; @@ -142,3 +144,9 @@ describe.each<[string, string, Buffer]>([ expect(GraphQLByte.parseValue(encodedValue)).toEqual(decodedValue); }); }); + +describe('hex with leading 0', () => { + test('should return true when validating', () => { + expect(GraphQLByte.parseValue(hexLeading0)).toEqual(byteLeading0); + }); +});