Skip to content

refactor (provider-utils): copy relevant code from secure-json-parse into codebase #5566

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

Closed
wants to merge 14 commits into from
Closed
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
5 changes: 5 additions & 0 deletions .changeset/late-foxes-battle.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@ai-sdk/provider-utils': patch
---

refactor (provider-utils): copy relevant code from `secure-json-parse` into codebase
3 changes: 1 addition & 2 deletions packages/provider-utils/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,7 @@
}
},
"dependencies": {
"@ai-sdk/provider": "2.0.0-canary.0",
"secure-json-parse": "^2.7.0"
"@ai-sdk/provider": "2.0.0-canary.0"
},
"devDependencies": {
"@types/node": "20.17.24",
Expand Down
8 changes: 4 additions & 4 deletions packages/provider-utils/src/parse-json.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import {
JSONValue,
TypeValidationError,
} from '@ai-sdk/provider';
import SecureJSON from 'secure-json-parse';
import { secureJsonParse } from './secure-json-parse';
import { ZodSchema } from 'zod';
import { safeValidateTypes, validateTypes } from './validate-types';
import { Validator } from './validator';
Expand Down Expand Up @@ -38,7 +38,7 @@ export function parseJSON<T>({
schema?: ZodSchema<T> | Validator<T>;
}): T {
try {
const value = SecureJSON.parse(text);
const value = secureJsonParse(text);

if (schema == null) {
return value;
Expand Down Expand Up @@ -91,7 +91,7 @@ export function safeParseJSON<T>({
schema?: ZodSchema<T> | Validator<T>;
}): ParseResult<T> {
try {
const value = SecureJSON.parse(text);
const value = secureJsonParse(text);

if (schema == null) {
return { success: true, value: value as T, rawValue: value };
Expand All @@ -114,7 +114,7 @@ export function safeParseJSON<T>({

export function isParsableJson(input: string): boolean {
try {
SecureJSON.parse(input);
secureJsonParse(input);
return true;
} catch {
return false;
Expand Down
59 changes: 59 additions & 0 deletions packages/provider-utils/src/secure-json-parse.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
// Licensed under BSD-3-Clause (this file only)
// Code adapted from https://github.com/fastify/secure-json-parse/blob/783fcb1b5434709466759847cec974381939673a/test/index.test.js
//
// Copyright (c) Vercel, Inc. (https://vercel.com)
// Copyright (c) 2019 The Fastify Team
// Copyright (c) 2019, Sideway Inc, and project contributors
// All rights reserved.
//
// The complete list of contributors can be found at:
// - https://github.com/hapijs/bourne/graphs/contributors
// - https://github.com/fastify/secure-json-parse/graphs/contributors
// - https://github.com/vercel/ai/commits/main/packages/provider-utils/src/secure-parse-json.test.ts
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

import { describe, it, expect } from 'vitest';
import { secureJsonParse } from './secure-json-parse';

describe('secureJsonParse', () => {
it('parses object string', () => {
expect(secureJsonParse('{"a": 5, "b": 6}')).toStrictEqual(
JSON.parse('{"a": 5, "b": 6}'),
);
});

it('parses null string', () => {
expect(secureJsonParse('null')).toStrictEqual(JSON.parse('null'));
});

it('parses 0 string', () => {
expect(secureJsonParse('0')).toStrictEqual(JSON.parse('0'));
});

it('parses string string', () => {
expect(secureJsonParse('"X"')).toStrictEqual(JSON.parse('"X"'));
});

it('errors on constructor property', () => {
const text =
'{ "a": 5, "b": 6, "constructor": { "x": 7 }, "c": { "d": 0, "e": "text", "__proto__": { "y": 8 }, "f": { "g": 2 } } }';

expect(() => secureJsonParse(text)).toThrow(SyntaxError);
});

it('errors on proto property', () => {
const text =
'{ "a": 5, "b": 6, "__proto__": { "x": 7 }, "c": { "d": 0, "e": "text", "__proto__": { "y": 8 }, "f": { "g": 2 } } }';

expect(() => secureJsonParse(text)).toThrow(SyntaxError);
});
});
86 changes: 86 additions & 0 deletions packages/provider-utils/src/secure-json-parse.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
// Licensed under BSD-3-Clause (this file only)
// Code adapted from https://github.com/fastify/secure-json-parse/blob/783fcb1b5434709466759847cec974381939673a/index.js
//
// Copyright (c) Vercel, Inc. (https://vercel.com)
// Copyright (c) 2019 The Fastify Team
// Copyright (c) 2019, Sideway Inc, and project contributors
// All rights reserved.
//
// The complete list of contributors can be found at:
// - https://github.com/hapijs/bourne/graphs/contributors
// - https://github.com/fastify/secure-json-parse/graphs/contributors
// - https://github.com/vercel/ai/commits/main/packages/provider-utils/src/secure-parse-json.ts
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

const suspectProtoRx = /"__proto__"\s*:/;
const suspectConstructorRx = /"constructor"\s*:/;

function _parse(text: string) {
// Parse normally
const obj = JSON.parse(text);

// Ignore null and non-objects
if (obj === null || typeof obj !== 'object') {
return obj;
}

if (
suspectProtoRx.test(text) === false &&
suspectConstructorRx.test(text) === false
) {
return obj;
}

// Scan result for proto keys
return filter(obj);
}

function filter(obj: any) {
let next = [obj];

while (next.length) {
const nodes = next;
next = [];

for (const node of nodes) {
if (Object.prototype.hasOwnProperty.call(node, '__proto__')) {
throw new SyntaxError('Object contains forbidden prototype property');
}

if (
Object.prototype.hasOwnProperty.call(node, 'constructor') &&
Object.prototype.hasOwnProperty.call(node.constructor, 'prototype')
) {
throw new SyntaxError('Object contains forbidden prototype property');
}

for (const key in node) {
const value = node[key];
if (value && typeof value === 'object') {
next.push(value);
}
}
}
}
return obj;
}

export function secureJsonParse(text: string) {
// Performance optimization, see https://github.com/fastify/secure-json-parse/pull/90
const { stackTraceLimit } = Error;
Error.stackTraceLimit = 0;
try {
return _parse(text);
} finally {
Error.stackTraceLimit = stackTraceLimit;
}
Comment on lines +79 to +85
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@gr2m do you know what this is for? I usually don't like messing w/ globals - but this might be for security reasons?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's for performance reasons, see fastify/secure-json-parse#90. Let me know if you want to keep it or not, I will add a comment with the pull request URL for future reference.

Fun fact: I know @Uzlopak, the author of that PR quite well, he is helping co-maintain @probot and @octokit for years now.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

let's keep it - might be worth adding a comment that this is for performance reasons

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ah nevermind the comment is there

}
3 changes: 0 additions & 3 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.