Skip to content

Commit

Permalink
perf: Faster JSON validation
Browse files Browse the repository at this point in the history
  • Loading branch information
FrederikBolding committed Oct 17, 2024
1 parent 8cd9007 commit 5a68cf2
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 2 deletions.
20 changes: 20 additions & 0 deletions src/json.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -418,6 +418,26 @@ describe('json', () => {
assertIsJsonRpcRequest(JSON_RPC_REQUEST_FIXTURES.invalid[0]),
).toThrow('Invalid JSON-RPC request: oops');
});

it('is fast for large inputs', () => {
const request = {
jsonrpc: '2.0',
id: 'foo',
method: 'wallet_invokeSnap',
params: {
snapId: 'npm:@metamask/manage-state-example-snap',
request: {
method: 'setState',
params: { items: new Array(9999999).fill(2) },
},
},
};
const now = performance.now();
expect(() =>

Check failure on line 436 in src/json.test.ts

View workflow job for this annotation

GitHub Actions / Build, lint, and test / Lint

Replace `⏎········assertIsJsonRpcRequest(request),⏎······` with `·assertIsJsonRpcRequest(request)`
assertIsJsonRpcRequest(request),
).not.toThrow();
console.log('Asserting took', performance.now() - now);
});
});

describe('isJsonRpcSuccess', () => {
Expand Down
46 changes: 44 additions & 2 deletions src/json.ts
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,48 @@ const finiteNumber = () =>
return is(value, number()) && Number.isFinite(value);
});

/**
* Validate an unknown input to be valid JSON.
*
* Useful for constructing JSON structs.
*
* @param json - An unknown value.
* @returns True if the value is valid JSON, otherwise false.
*/
function validateJson(json: unknown): boolean {
if (json === null || typeof json === 'boolean' || typeof json === 'string') {
return true;
}

if (typeof json === 'number' && Number.isFinite(json)) {
return true;
}

if (typeof json === 'object') {
if (Array.isArray(json)) {
return json.every((value) => validateJson(value));
}

const entries = Object.entries(json);
return entries.every(
([key, value]) => typeof key === 'string' && validateJson(value),
);
}

return false;
}

/**
* A struct to check if the given value is a valid JSON-serializable value.
*

Check failure on line 200 in src/json.ts

View workflow job for this annotation

GitHub Actions / Build, lint, and test / Lint

Delete `·`
* A faster alternative to {@link UnsafeJsonStruct}.
*
* Note that this struct is unsafe. For safe validation, use {@link JsonStruct}.
*/
export const UnsafeFastJsonStruct: Struct<Json> = define('JSON', (json) =>
validateJson(json),
);

/**
* A struct to check if the given value is a valid JSON-serializable value.
*
Expand All @@ -188,8 +230,8 @@ export const UnsafeJsonStruct: Struct<Json> = union([
* This struct sanitizes the value before validating it, so that it is safe to
* use with untrusted input.
*/
export const JsonStruct = coerce(UnsafeJsonStruct, any(), (value) => {
assertStruct(value, UnsafeJsonStruct);
export const JsonStruct = coerce(UnsafeFastJsonStruct, any(), (value) => {
assertStruct(value, UnsafeFastJsonStruct);
return JSON.parse(
JSON.stringify(value, (propKey, propValue) => {
// Strip __proto__ and constructor properties to prevent prototype pollution.
Expand Down

0 comments on commit 5a68cf2

Please sign in to comment.