Skip to content

Commit 9f95b35

Browse files
lgrammelgr2m
andauthored
refactor (provider-utils): copy relevant code from secure-json-parse into codebase (#5622)
Co-authored-by: Gregor Martynus <39992+gr2m@users.noreply.github.com>
1 parent d874386 commit 9f95b35

File tree

6 files changed

+155
-9
lines changed

6 files changed

+155
-9
lines changed

‎.changeset/late-foxes-battle.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@ai-sdk/provider-utils': patch
3+
---
4+
5+
refactor (provider-utils): copy relevant code from `secure-json-parse` into codebase

‎packages/provider-utils/package.json

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,8 +37,7 @@
3737
}
3838
},
3939
"dependencies": {
40-
"@ai-sdk/provider": "2.0.0-canary.1",
41-
"secure-json-parse": "^2.7.0"
40+
"@ai-sdk/provider": "2.0.0-canary.1"
4241
},
4342
"devDependencies": {
4443
"@types/node": "20.17.24",

‎packages/provider-utils/src/parse-json.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import {
33
JSONValue,
44
TypeValidationError,
55
} from '@ai-sdk/provider';
6-
import SecureJSON from 'secure-json-parse';
6+
import { secureJsonParse } from './secure-json-parse';
77
import { ZodSchema } from 'zod';
88
import { safeValidateTypes, validateTypes } from './validate-types';
99
import { Validator } from './validator';
@@ -38,7 +38,7 @@ export function parseJSON<T>({
3838
schema?: ZodSchema<T> | Validator<T>;
3939
}): T {
4040
try {
41-
const value = SecureJSON.parse(text);
41+
const value = secureJsonParse(text);
4242

4343
if (schema == null) {
4444
return value;
@@ -91,7 +91,7 @@ export function safeParseJSON<T>({
9191
schema?: ZodSchema<T> | Validator<T>;
9292
}): ParseResult<T> {
9393
try {
94-
const value = SecureJSON.parse(text);
94+
const value = secureJsonParse(text);
9595

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

115115
export function isParsableJson(input: string): boolean {
116116
try {
117-
SecureJSON.parse(input);
117+
secureJsonParse(input);
118118
return true;
119119
} catch {
120120
return false;
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
// Licensed under BSD-3-Clause (this file only)
2+
// Code adapted from https://github.com/fastify/secure-json-parse/blob/783fcb1b5434709466759847cec974381939673a/test/index.test.js
3+
//
4+
// Copyright (c) Vercel, Inc. (https://vercel.com)
5+
// Copyright (c) 2019 The Fastify Team
6+
// Copyright (c) 2019, Sideway Inc, and project contributors
7+
// All rights reserved.
8+
//
9+
// The complete list of contributors can be found at:
10+
// - https://github.com/hapijs/bourne/graphs/contributors
11+
// - https://github.com/fastify/secure-json-parse/graphs/contributors
12+
// - https://github.com/vercel/ai/commits/main/packages/provider-utils/src/secure-parse-json.test.ts
13+
//
14+
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
15+
//
16+
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
17+
//
18+
// 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.
19+
//
20+
// 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.
21+
//
22+
// 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.
23+
24+
import { describe, it, expect } from 'vitest';
25+
import { secureJsonParse } from './secure-json-parse';
26+
27+
describe('secureJsonParse', () => {
28+
it('parses object string', () => {
29+
expect(secureJsonParse('{"a": 5, "b": 6}')).toStrictEqual(
30+
JSON.parse('{"a": 5, "b": 6}'),
31+
);
32+
});
33+
34+
it('parses null string', () => {
35+
expect(secureJsonParse('null')).toStrictEqual(JSON.parse('null'));
36+
});
37+
38+
it('parses 0 string', () => {
39+
expect(secureJsonParse('0')).toStrictEqual(JSON.parse('0'));
40+
});
41+
42+
it('parses string string', () => {
43+
expect(secureJsonParse('"X"')).toStrictEqual(JSON.parse('"X"'));
44+
});
45+
46+
it('errors on constructor property', () => {
47+
const text =
48+
'{ "a": 5, "b": 6, "constructor": { "x": 7 }, "c": { "d": 0, "e": "text", "__proto__": { "y": 8 }, "f": { "g": 2 } } }';
49+
50+
expect(() => secureJsonParse(text)).toThrow(SyntaxError);
51+
});
52+
53+
it('errors on proto property', () => {
54+
const text =
55+
'{ "a": 5, "b": 6, "__proto__": { "x": 7 }, "c": { "d": 0, "e": "text", "__proto__": { "y": 8 }, "f": { "g": 2 } } }';
56+
57+
expect(() => secureJsonParse(text)).toThrow(SyntaxError);
58+
});
59+
});
Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
// Licensed under BSD-3-Clause (this file only)
2+
// Code adapted from https://github.com/fastify/secure-json-parse/blob/783fcb1b5434709466759847cec974381939673a/index.js
3+
//
4+
// Copyright (c) Vercel, Inc. (https://vercel.com)
5+
// Copyright (c) 2019 The Fastify Team
6+
// Copyright (c) 2019, Sideway Inc, and project contributors
7+
// All rights reserved.
8+
//
9+
// The complete list of contributors can be found at:
10+
// - https://github.com/hapijs/bourne/graphs/contributors
11+
// - https://github.com/fastify/secure-json-parse/graphs/contributors
12+
// - https://github.com/vercel/ai/commits/main/packages/provider-utils/src/secure-parse-json.ts
13+
//
14+
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
15+
//
16+
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
17+
//
18+
// 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.
19+
//
20+
// 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.
21+
//
22+
// 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.
23+
24+
const suspectProtoRx = /"__proto__"\s*:/;
25+
const suspectConstructorRx = /"constructor"\s*:/;
26+
27+
function _parse(text: string) {
28+
// Parse normally
29+
const obj = JSON.parse(text);
30+
31+
// Ignore null and non-objects
32+
if (obj === null || typeof obj !== 'object') {
33+
return obj;
34+
}
35+
36+
if (
37+
suspectProtoRx.test(text) === false &&
38+
suspectConstructorRx.test(text) === false
39+
) {
40+
return obj;
41+
}
42+
43+
// Scan result for proto keys
44+
return filter(obj);
45+
}
46+
47+
function filter(obj: any) {
48+
let next = [obj];
49+
50+
while (next.length) {
51+
const nodes = next;
52+
next = [];
53+
54+
for (const node of nodes) {
55+
if (Object.prototype.hasOwnProperty.call(node, '__proto__')) {
56+
throw new SyntaxError('Object contains forbidden prototype property');
57+
}
58+
59+
if (
60+
Object.prototype.hasOwnProperty.call(node, 'constructor') &&
61+
Object.prototype.hasOwnProperty.call(node.constructor, 'prototype')
62+
) {
63+
throw new SyntaxError('Object contains forbidden prototype property');
64+
}
65+
66+
for (const key in node) {
67+
const value = node[key];
68+
if (value && typeof value === 'object') {
69+
next.push(value);
70+
}
71+
}
72+
}
73+
}
74+
return obj;
75+
}
76+
77+
export function secureJsonParse(text: string) {
78+
// Performance optimization, see https://github.com/fastify/secure-json-parse/pull/90
79+
const { stackTraceLimit } = Error;
80+
Error.stackTraceLimit = 0;
81+
try {
82+
return _parse(text);
83+
} finally {
84+
Error.stackTraceLimit = stackTraceLimit;
85+
}
86+
}

‎pnpm-lock.yaml

Lines changed: 0 additions & 3 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)