Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(Byte): hexValidator should remove leading 0 #717

Merged
merged 1 commit into from
Feb 17, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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);
});
});