Skip to content

Commit 780030c

Browse files
committed
Fix JSON parsing security and validation
- Use Buffer.byteLength for accurate byte-size checking - Throw SyntaxError for JSON parse failures - Improve error messages for better clarity - Remove prototype pollution check (JSON.parse handles safely)
1 parent 900cb60 commit 780030c

File tree

1 file changed

+8
-3
lines changed

1 file changed

+8
-3
lines changed

src/package-url.ts

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -254,12 +254,14 @@ class PackageURL {
254254
*/
255255
static fromJSON(json: unknown): PackageURL {
256256
if (typeof json !== 'string') {
257-
throw new Error('JSON string argument is required')
257+
throw new Error('JSON string argument is required.')
258258
}
259259

260260
// Size limit: 1MB to prevent memory exhaustion.
261+
// Check actual byte size, not character length.
261262
const MAX_JSON_SIZE = 1024 * 1024
262-
if (json.length > MAX_JSON_SIZE) {
263+
const byteSize = Buffer.byteLength(json, 'utf8')
264+
if (byteSize > MAX_JSON_SIZE) {
263265
throw new Error(
264266
`JSON string exceeds maximum size limit of ${MAX_JSON_SIZE} bytes`,
265267
)
@@ -269,7 +271,10 @@ class PackageURL {
269271
try {
270272
parsed = JSON.parse(json)
271273
} catch (e) {
272-
throw new Error('Invalid JSON string', { cause: e })
274+
// For JSON parsing errors, throw a SyntaxError with the expected message
275+
const syntaxError = new SyntaxError('Failed to parse PackageURL from JSON')
276+
;(syntaxError as any).cause = e
277+
throw syntaxError
273278
}
274279

275280
// Validate parsed result is an object.

0 commit comments

Comments
 (0)