Skip to content

Commit

Permalink
fix(Byte): hexValidator should remove leading 0 (#717)
Browse files Browse the repository at this point in the history
A leading 0 in the hex string can throw off the hex validator, since
this information is lost in the parseInt action. This results in the
string check to return `false` instead of `true`, because the parsed
hex string does not contain the leading 0.
  • Loading branch information
rufman authored Feb 17, 2021
1 parent 4e53ccd commit a2273e6
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 2 deletions.
6 changes: 4 additions & 2 deletions src/scalars/Byte.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -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) {
Expand Down
8 changes: 8 additions & 0 deletions tests/Byte.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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);
});
});

0 comments on commit a2273e6

Please sign in to comment.