### Install secure-json-parse Source: https://github.com/fastify/secure-json-parse/blob/main/README.md Install the secure-json-parse package using npm. ```bash npm i secure-json-parse ``` -------------------------------- ### ParseOptions Type Example Source: https://github.com/fastify/secure-json-parse/blob/main/_autodocs/MANIFEST.txt Example demonstrating the usage of ParseOptions for configuring the parsing behavior. This includes setting actions for proto and constructor. ```javascript const secureJsonParse = require('secure-json-parse'); const jsonString = '{"key": "value"}'; const options = { protoAction: 'remove', constructorAction: 'remove' }; const obj = secureJsonParse(jsonString, options); console.log(obj); ``` -------------------------------- ### ProtoAction: 'error' Example Source: https://github.com/fastify/secure-json-parse/blob/main/_autodocs/configuration.md Demonstrates how to configure protoAction to throw a SyntaxError when a '__proto__' key is encountered. ```javascript const json = '{"a": 5, "__proto__": {"x": 7}}'; try { sjson.parse(json, { protoAction: 'error' }); } catch (err) { // SyntaxError: Object contains forbidden prototype property } ``` -------------------------------- ### ConstructorAction: 'error' Example Source: https://github.com/fastify/secure-json-parse/blob/main/_autodocs/configuration.md Demonstrates the default behavior of constructorAction, which throws a SyntaxError when a 'constructor' key with a 'prototype' property is found. ```javascript const json = '{"a": 5, "constructor": {"prototype": {"x": 7}}}'; try { sjson.parse(json, { constructorAction: 'error' }); } catch (err) { // SyntaxError: Object contains forbidden prototype property } ``` -------------------------------- ### Scan Function Usage Source: https://github.com/fastify/secure-json-parse/blob/main/_autodocs/types.md Example of using the scan() function with specific options for prototype and constructor actions, and safety. ```javascript sjson.scan(obj, { protoAction: 'remove', constructorAction: 'error', safe: false }); ``` -------------------------------- ### Metrics and Monitoring Source: https://github.com/fastify/secure-json-parse/blob/main/_autodocs/MANIFEST.txt Example of instrumenting JSON parsing with metrics collection. This pattern helps in monitoring parsing performance and error rates. ```javascript const secureJsonParse = require('secure-json-parse'); // Assume 'metrics' is a monitoring client function parseWithMetrics(jsonString) { const startTime = process.hrtime.bigint(); try { const result = secureJsonParse(jsonString); const endTime = process.hrtime.bigint(); const duration = Number(endTime - startTime) / 1e6; // milliseconds // metrics.increment('json_parse.success'); // metrics.histogram('json_parse.duration', duration); return result; } catch (error) { const endTime = process.hrtime.bigint(); const duration = Number(endTime - startTime) / 1e6; // milliseconds // metrics.increment('json_parse.error'); // metrics.histogram('json_parse.duration', duration); throw error; } } // const jsonString = '{"key": "value"}'; // const parsed = parseWithMetrics(jsonString); // console.log(parsed); ``` -------------------------------- ### ConstructorAction: 'ignore' Example Source: https://github.com/fastify/secure-json-parse/blob/main/_autodocs/configuration.md Illustrates using constructorAction set to 'ignore' to skip 'constructor' validation. ```javascript const json = '{"a": 5, "constructor": {"prototype": {"x": 7}}}'; const result = sjson.parse(json, { constructorAction: 'ignore' }); // result = { a: 5, constructor: { prototype: { x: 7 } } } ``` -------------------------------- ### ProtoAction: 'ignore' Example Source: https://github.com/fastify/secure-json-parse/blob/main/_autodocs/configuration.md Illustrates using protoAction set to 'ignore' to skip '__proto__' validation, making it equivalent to JSON.parse(). ```javascript const json = '{"a": 5, "__proto__": {"x": 7}}'; const result = sjson.parse(json, { protoAction: 'ignore' }); // result = { a: 5, __proto__: { x: 7 } } // SECURITY WARNING: prototype pollution is now possible ``` -------------------------------- ### Detecting and Removing '__proto__' Source: https://github.com/fastify/secure-json-parse/blob/main/_autodocs/api-reference.md Use this example to parse JSON containing a `__proto__` key and have it automatically removed. This is useful for sanitizing input. ```javascript const badJson = '{"a": 5, "__proto__": {"x": 7}}'; const result = sjson.parse(badJson, { protoAction: 'remove' }); console.log(result); // { a: 5 } (no __proto__ key) ``` -------------------------------- ### Ignoring '__proto__' and Throwing on 'constructor.prototype' Source: https://github.com/fastify/secure-json-parse/blob/main/_autodocs/api-reference.md Configure specific actions for different prototype-related keys. This example ignores `__proto__` but throws an error if `constructor.prototype` is found. ```javascript const json = '{"a": 5, "__proto__": {"x": 7}}'; const result = sjson.parse(json, { protoAction: 'ignore', constructorAction: 'error' }); console.log(result); // { a: 5, __proto__: { x: 7 } } ``` -------------------------------- ### Usage Example for secure-json-parse Source: https://github.com/fastify/secure-json-parse/blob/main/README.md Demonstrates how to use the secure-json-parse library to parse both valid and potentially malicious JSON strings. It shows the default behavior and how to configure actions for handling `__proto__` and `constructor.prototype` properties. ```javascript const sjson = require('secure-json-parse') const goodJson = '{ "a": 5, "b": 6 }' const badJson = '{ "a": 5, "b": 6, "__proto__": { "x": 7 }, "constructor": {"prototype": {"bar": "baz"} } }' console.log(JSON.parse(goodJson), sjson.parse(goodJson, undefined, { protoAction: 'remove', constructorAction: 'remove' })) console.log(JSON.parse(badJson), sjson.parse(badJson, undefined, { protoAction: 'remove', constructorAction: 'remove' })) ``` -------------------------------- ### Selective Protection with Options Source: https://github.com/fastify/secure-json-parse/blob/main/_autodocs/MANIFEST.txt Example of applying selective protection by configuring specific actions for prototype and constructor properties. This allows fine-grained control over security. ```javascript const secureJsonParse = require('secure-json-parse'); const jsonString = '{"__proto__": {"isAdmin": true}, "constructor": {"prototype": {"isAdmin": true}}}'; const options = { protoAction: 'ignore', // Or 'error' constructorAction: 'remove' }; const obj = secureJsonParse(jsonString, options); console.log(obj); ``` -------------------------------- ### Runtime Configuration Based on Trust Source: https://github.com/fastify/secure-json-parse/blob/main/_autodocs/configuration.md Configure parsing options dynamically based on whether the JSON source is trusted. This example shows how to set `protoAction` and `constructorAction` to either 'remove' or 'error'. ```javascript function parseConfig(json, isUntrusted) { const options = isUntrusted ? { protoAction: 'remove', constructorAction: 'remove' } : { protoAction: 'error', constructorAction: 'error' }; return sjson.parse(json, options); } ``` -------------------------------- ### TypeScript Usage with Options Source: https://github.com/fastify/secure-json-parse/blob/main/_autodocs/quick-reference.md Leverage TypeScript for type safety. This example shows how to import the parse function and options, and define custom types for parsed data. ```typescript import parse, { ParseOptions, Reviver } from 'secure-json-parse'; interface MyData { name: string; age: number; } const options: ParseOptions = { protoAction: 'remove', constructorAction: 'remove' }; const data: MyData = parse(json, options); ``` -------------------------------- ### Distinguishing Parsing Errors from Security Violations Source: https://github.com/fastify/secure-json-parse/blob/main/_autodocs/configuration.md Example showing how to use 'safe: true' to differentiate between general parsing errors and security-related forbidden property detections. ```javascript const result = sjson.parse(json, { protoAction: 'error', constructorAction: 'error', safe: true }); if (result === null) { console.log('Forbidden prototype property detected'); } else { console.log('Parsed successfully:', result); } ``` -------------------------------- ### Secure JSON Parsing: Example with __proto__ Source: https://github.com/fastify/secure-json-parse/blob/main/_autodocs/errors.md Illustrates how secure-json-parse throws a SyntaxError when a JSON string contains a '__proto__' property, assuming the default 'protoAction' of 'error'. ```javascript const json = '{"a": 5, "__proto__": {"x": 7}}'; try { sjson.parse(json); // protoAction defaults to 'error' } catch (err) { console.log(err.message); // 'Object contains forbidden prototype property' console.log(err instanceof SyntaxError); // true } ``` -------------------------------- ### Vulnerable Reviver Function Example Source: https://github.com/fastify/secure-json-parse/blob/main/_autodocs/security-model.md This example demonstrates a vulnerable reviver function that reintroduces a prototype pollution vector after the library has already filtered the original JSON. Use caution when implementing reviver functions. ```javascript const reviver = (key, value) => { // Vulnerable: reviver creates new __proto__ property if (key === 'data') { return { __proto__: value }; // This creates a new attack vector } return value; }; sjson.parse(json, reviver); // Library filtered original, reviver created new one ``` -------------------------------- ### Secure JSON Parsing: Example with constructor.prototype Source: https://github.com/fastify/secure-json-parse/blob/main/_autodocs/errors.md Demonstrates secure-json-parse throwing a SyntaxError when a JSON string includes a 'constructor' property that contains a 'prototype' object, with 'constructorAction' defaulting to 'error'. ```javascript const json = '{"a": 5, "constructor": {"prototype": {"x": 7}}}'; try { sjson.parse(json); // constructorAction defaults to 'error' } catch (err) { console.log(err.message); // 'Object contains forbidden prototype property' } ``` -------------------------------- ### ProtoAction: 'remove' Example Source: https://github.com/fastify/secure-json-parse/blob/main/_autodocs/configuration.md Shows how protoAction set to 'remove' silently deletes all '__proto__' keys from the parsed object and nested objects. ```javascript const json = '{"a": 5, "__proto__": {"x": 7}, "nested": {"__proto__": {"y": 8}}}'; const result = sjson.parse(json, { protoAction: 'remove' }); // result = { a: 5, nested: {} } ``` -------------------------------- ### Feature Flag Based Behavior Source: https://github.com/fastify/secure-json-parse/blob/main/_autodocs/MANIFEST.txt Example of conditionally applying secure JSON parsing based on a feature flag. This allows for gradual rollout or A/B testing of security features. ```javascript const secureJsonParse = require('secure-json-parse'); const jsonString = '{"key": "value"}'; const enableSecureParsing = process.env.ENABLE_SECURE_PARSE === 'true'; let obj; if (enableSecureParsing) { obj = secureJsonParse(jsonString); } else { obj = JSON.parse(jsonString); // Standard JSON.parse } console.log(obj); ``` -------------------------------- ### Scan nested structures Source: https://github.com/fastify/secure-json-parse/blob/main/_autodocs/api-reference.md This example demonstrates scanning deeply nested objects for forbidden properties. The `scan` function performs a breadth-first traversal. ```javascript const obj = { a: 5, nested: { b: 6, __proto__: { y: 8 } }, __proto__: { x: 7 } }; const result = sjson.scan(obj, { protoAction: 'remove' }); console.log(result); // { a: 5, nested: { b: 6 } } ``` -------------------------------- ### ConstructorAction: 'remove' Example Source: https://github.com/fastify/secure-json-parse/blob/main/_autodocs/configuration.md Shows how constructorAction set to 'remove' silently deletes all 'constructor' keys from the parsed object and nested objects. ```javascript const json = '{"a": 5, "constructor": {"prototype": {"x": 7}}}'; const result = sjson.parse(json, { constructorAction: 'remove' }); // result = { a: 5 } ``` -------------------------------- ### Content Security Policy Validation Source: https://github.com/fastify/secure-json-parse/blob/main/_autodocs/MANIFEST.txt Example of using secure-json-parse to validate a Content Security Policy (CSP) string. This pattern ensures the CSP is well-formed and free of malicious content. ```javascript const secureJsonParse = require('secure-json-parse'); const cspString = 'default-src \'self\'; script-src \'self\';'; try { // Assuming CSP can be represented as a JSON-like structure for parsing // This is a conceptual example; actual CSP validation might be more complex. const cspObject = secureJsonParse(`{"policy": "${cspString}"}`); console.log('CSP is valid and secure:', cspObject); } catch (error) { console.error('Invalid or insecure CSP:', error); } ``` -------------------------------- ### Secure JSON Parsing: Handle Malformed JSON Source: https://github.com/fastify/secure-json-parse/blob/main/_autodocs/errors.md This example shows how secure-json-parse handles malformed JSON input by catching the SyntaxError thrown by the native JSON.parse function. ```javascript try { sjson.parse('{invalid json}'); } catch (err) { console.log(err instanceof SyntaxError); // true console.log(err.message); // "Unexpected token i in JSON at position 1" } ``` -------------------------------- ### Using Default Parsing Options Source: https://github.com/fastify/secure-json-parse/blob/main/_autodocs/configuration.md Demonstrates how to use the `parse` function with all default options, or with specific options overriding defaults. It also shows how to handle an undefined reviver function. ```javascript sjson.parse(json); // All defaults sjson.parse(json, { protoAction: 'remove' }); // Others default sjson.parse(json, undefined, { protoAction: 'remove' }); // Reviver undefined sjson.parse(json, reviverFn, { protoAction: 'remove' }); // All specified ``` -------------------------------- ### Importing secure-json-parse Source: https://github.com/fastify/secure-json-parse/blob/main/_autodocs/README.md Shows different ways to import and use the parse function from the secure-json-parse library. ```javascript const sjson = require('secure-json-parse'); // All equivalent: sjson.parse(json); sjson.default(json); require('secure-json-parse')(json); ``` -------------------------------- ### Importing secure-json-parse (CommonJS) Source: https://github.com/fastify/secure-json-parse/blob/main/_autodocs/module-structure.md Demonstrates different ways to import and use the `parse` function from the secure-json-parse library using CommonJS module syntax. ```javascript const sjson = require('secure-json-parse'); const result = sjson.parse(json); ``` ```javascript const { parse, safeParse, scan } = require('secure-json-parse'); const result = parse(json); ``` ```javascript const parse = require('secure-json-parse'); const result = parse(json); ``` ```javascript const { default: parse } = require('secure-json-parse'); const result = parse(json); ``` -------------------------------- ### Reviver Function Support Source: https://github.com/fastify/secure-json-parse/blob/main/_autodocs/MANIFEST.txt Example of using a reviver function with secure-json-parse to transform parsed JSON values. The reviver is applied after parsing. ```javascript const secureJsonParse = require('secure-json-parse'); const jsonString = '{"date": "2023-10-27T10:00:00.000Z"}'; const options = { reviver: (key, value) => { if (key === 'date' && typeof value === 'string') { return new Date(value); } return value; } }; const obj = secureJsonParse(jsonString, options); console.log(obj.date instanceof Date); ``` -------------------------------- ### Import and Use Default Parse Function Source: https://github.com/fastify/secure-json-parse/blob/main/_autodocs/api-reference.md Demonstrates how to import and use the default `parse` function from the 'secure-json-parse' module. This is the primary way to parse JSON strings securely. ```javascript const parse = require('secure-json-parse'); // or const parse = require('secure-json-parse').default; parse('{"a": 5}'); ``` -------------------------------- ### Streaming JSON Parser Integration Source: https://github.com/fastify/secure-json-parse/blob/main/_autodocs/MANIFEST.txt Conceptual example of integrating secure-json-parse with a streaming JSON parser. This pattern is for handling large JSON payloads efficiently. ```javascript const secureJsonParse = require('secure-json-parse'); // Assume 'stream' is a readable stream emitting JSON chunks // Assume 'JSONStream' is a hypothetical streaming JSON parser // const JSONStream = require('jsonstream'); // const stream = getJsonStream(); // stream.pipe(JSONStream.parse('*')).on('data', (chunk) => { // try { // const parsedChunk = secureJsonParse(JSON.stringify(chunk)); // Re-parse chunk securely // console.log('Processed chunk:', parsedChunk); // } catch (error) { // console.error('Error processing chunk:', error); // } // }); ``` -------------------------------- ### TypeScript Support Source: https://github.com/fastify/secure-json-parse/blob/main/_autodocs/MANIFEST.txt Demonstrates using secure-json-parse with TypeScript, including type definitions for functions and options. This enhances code safety and developer experience. ```typescript import secureJsonParse, { ParseOptions } from 'secure-json-parse'; const jsonString: string = '{"key": "value"}'; const options: ParseOptions = { protoAction: 'remove', constructorAction: 'remove' }; const obj: any = secureJsonParse(jsonString, options); console.log(obj); ``` -------------------------------- ### Defensive JSON Parsing with Property Removal Source: https://github.com/fastify/secure-json-parse/blob/main/_autodocs/00-START-HERE.md Shows how to use secure-json-parse with defensive options to remove dangerous properties like '__proto__' and 'constructor.prototype' instead of throwing an error. ```javascript // Defensive (removes dangerous properties) const data = sjson.parse(userInput, { protoAction: 'remove', constructorAction: 'remove' }); ``` -------------------------------- ### Handle Options Argument Source: https://github.com/fastify/secure-json-parse/blob/main/_autodocs/quick-reference.md Options can be passed as the second argument directly if it's not a function, or as the third argument. ```javascript sjson.parse(json, { protoAction: 'remove' }); // Works sjson.parse(json, undefined, { protoAction: 'remove' }); // Also works ``` -------------------------------- ### Reviver Function Usage Example Source: https://github.com/fastify/secure-json-parse/blob/main/_autodocs/types.md Demonstrates a reviver function that transforms 'date' values into Date objects and doubles numeric values. The reviver is applied after prototype poisoning checks. ```javascript const reviver = (key, value) => { if (key === 'date') { return new Date(value); } if (typeof value === 'number') { return value * 2; } return value; }; const result = sjson.parse('{"date": "2024-01-01", "count": 5}', reviver); // result.date is a Date object, result.count is 10 ``` -------------------------------- ### Browser and Node.js Compatibility Source: https://github.com/fastify/secure-json-parse/blob/main/_autodocs/README.md Demonstrates how to use the parse function in different environments. Node.js automatically converts Buffers, while browsers only support string inputs. ```javascript // Node.js: Buffer auto-converted sjson.parse(Buffer.from('{"a": 1}')); // Browser: Buffer undefined, only string supported sjson.parse('{"a": 1}'); ``` -------------------------------- ### Safe Mode: Handling Forbidden Properties Source: https://github.com/fastify/secure-json-parse/blob/main/_autodocs/configuration.md Demonstrates how the 'safe' option, when true, returns null instead of throwing an error when forbidden properties are detected. ```javascript const json = '{"a": 5, "__proto__": {"x": 7}}'; const result = sjson.parse(json, { safe: true }); // result = null (instead of throwing) ``` -------------------------------- ### REST API Endpoint Handler Source: https://github.com/fastify/secure-json-parse/blob/main/_autodocs/MANIFEST.txt Example of using secure-json-parse within a REST API endpoint handler to safely parse incoming JSON request bodies. This pattern prioritizes security. ```javascript const secureJsonParse = require('secure-json-parse'); // Assume 'request' is an object with a 'body' property containing the JSON string // const request = { body: '{"user": "admin"}' }; function handleRequest(request) { try { const data = secureJsonParse(request.body); // Process the securely parsed data console.log('Parsed data:', data); } catch (error) { console.error('Failed to parse JSON:', error); // Handle parsing error, e.g., send a 400 Bad Request response } } ``` -------------------------------- ### Graceful Fallback with safeParse() Source: https://github.com/fastify/secure-json-parse/blob/main/_autodocs/MANIFEST.txt Illustrates a graceful fallback mechanism where safeParse() is used, and if it fails, a default value or behavior is applied. This ensures application stability. ```javascript const secureJsonParse = require('secure-json-parse'); const jsonString = '{invalid json}'; const defaultData = { message: 'Default data' }; const data = secureJsonParse.safeParse(jsonString) || defaultData; console.log('Final data:', data); ``` -------------------------------- ### Benchmarking Results Source: https://github.com/fastify/secure-json-parse/blob/main/_autodocs/security-model.md Performance comparison between secure-json-parse and native JSON.parse() on input containing forbidden properties. This demonstrates the minimal overhead of security checks. ```plaintext secure-json-parse parse (with proto): 657.25 ns/op (1.67M ops/s) JSON.parse() (with proto): 875.42 ns/op (1.21M ops/s) ``` -------------------------------- ### Buffer and BOM Handling Source: https://github.com/fastify/secure-json-parse/blob/main/_autodocs/MANIFEST.txt Illustrates how secure-json-parse handles Buffer objects and Byte Order Marks (BOM) during parsing. This ensures correct interpretation of various input formats. ```javascript const secureJsonParse = require('secure-json-parse'); // Example with a Buffer (Node.js specific) const buffer = Buffer.from('{"key": "value"}', 'utf-8'); const objFromBuffer = secureJsonParse(buffer); console.log('Parsed from Buffer:', objFromBuffer); // Example with BOM (UTF-8 BOM: EF BB BF) const jsonWithBom = Buffer.from([0xEF, 0xBB, 0xBF]) .toString('utf-8') + '{"key": "value"}'; const objFromBom = secureJsonParse(jsonWithBom); console.log('Parsed with BOM:', objFromBom); ``` -------------------------------- ### Flexible Argument Passing for parse() Source: https://github.com/fastify/secure-json-parse/blob/main/_autodocs/configuration.md Illustrates the different ways to call the `parse` function, including variations in providing text, a reviver function, and options. The library automatically normalizes argument types. ```javascript // Form 1: Text only (all defaults) sjson.parse(text) // Form 2: Text + options (options as 2nd arg, reviver undefined) sjson.parse(text, { protoAction: 'remove' }) // Form 3: Text + reviver + options sjson.parse(text, (key, value) => value, { protoAction: 'remove' }) // Form 4: Text + null reviver + options (explicit) sjson.parse(text, null, { protoAction: 'remove' }) // Form 5: Text + options (as 2nd arg) + implicit undefined reviver // Is automatically normalized to Form 2 sjson.parse(text, { constructorAction: 'remove' }) ``` -------------------------------- ### Import Variants Source: https://github.com/fastify/secure-json-parse/blob/main/_autodocs/MANIFEST.txt Shows different ways to import the secure-json-parse library, including CommonJS and ES Module syntax. Choose the import method appropriate for your environment. ```javascript // CommonJS const secureJsonParse = require('secure-json-parse'); ``` ```javascript // ES Module import secureJsonParse from 'secure-json-parse'; ``` -------------------------------- ### ParseOptions Configuration Source: https://github.com/fastify/secure-json-parse/blob/main/_autodocs/00-START-HERE.md Defines the configuration options for JSON parsing, including handling of __proto__ and constructor.prototype, and a safe mode. ```typescript { protoAction?: 'error' | 'remove' | 'ignore', // __proto__ handling constructorAction?: 'error' | 'remove' | 'ignore', // constructor.prototype handling safe?: boolean // Return null instead of throw } ``` -------------------------------- ### safeParse() Return Values Source: https://github.com/fastify/secure-json-parse/blob/main/_autodocs/quick-reference.md Details the return values for the `safeParse()` function, highlighting its behavior in case of success, security issues, and parsing errors. ```APIDOC ## safeParse() Return Values ### Success Returns the parsed JavaScript object. ### Security Issue Returns `null`. ### Parse Error Returns `undefined`. ``` -------------------------------- ### Error Handling Patterns Source: https://github.com/fastify/secure-json-parse/blob/main/_autodocs/quick-reference.md Illustrates different strategies for handling errors when using the secure-json-parse library, including try-catch blocks and safe mode checks. ```APIDOC ## Error Handling ### Pattern 1: Try-catch (default) Handles potential errors during parsing using a standard try-catch block. ```javascript try { const data = sjson.parse(json); // use data } catch (err) { console.error(err.message); } ``` ### Pattern 2: Safe mode with null check Utilizes the `safe: true` option to prevent security exceptions and checks for a `null` return value. ```javascript const data = sjson.parse(json, { safe: true }); if (data === null) { console.error('Security issue'); } else { // use data } ``` ### Pattern 3: SafeParse with fallback Employs `sjson.safeParse()` and provides a default value using the nullish coalescing operator (`??`) for cases where parsing fails or results in `null`. ```javascript const data = sjson.safeParse(json) ?? defaultValue; // use data ``` ``` -------------------------------- ### scan() Return Values Source: https://github.com/fastify/secure-json-parse/blob/main/_autodocs/quick-reference.md Details the return values for the `scan()` function, including its behavior for success, security issues, and parsing errors. ```APIDOC ## scan() Return Values ### Success Returns the parsed JavaScript object. ### Security Issue Throws a `SyntaxError`. ### Parse Error Throws a `SyntaxError`. ``` -------------------------------- ### Basic Secure JSON Parsing Source: https://github.com/fastify/secure-json-parse/blob/main/_autodocs/00-START-HERE.md Demonstrates the basic usage of secure-json-parse to parse a JSON string. This function will throw an error if dangerous properties like '__proto__' are detected. ```javascript const sjson = require('secure-json-parse'); // Basic usage (throws on dangerous properties) const data = sjson.parse('{"a": 5}'); ``` -------------------------------- ### Lenient JSON Parsing (No Protection) Source: https://github.com/fastify/secure-json-parse/blob/main/_autodocs/quick-reference.md Use this for lenient parsing, equivalent to JSON.parse(), by ignoring __proto__ and constructor.prototype. ```javascript sjson.parse(json, { protoAction: 'ignore', constructorAction: 'ignore' }) // Equivalent to JSON.parse() ``` -------------------------------- ### Default Parse Options Source: https://github.com/fastify/secure-json-parse/blob/main/_autodocs/types.md Uses the default parsing options where both `__proto__` and `constructor.prototype` properties will cause a `SyntaxError`. ```javascript const options = {}; // Equivalent to: // { protoAction: 'error', constructorAction: 'error', safe: false } sjson.parse(json, options); ``` -------------------------------- ### Secure JSON Parsing with parse() Source: https://github.com/fastify/secure-json-parse/blob/main/_autodocs/MANIFEST.txt Demonstrates basic secure JSON parsing using the parse() function. Ensure the input is a valid JSON string. ```javascript const secureJsonParse = require('secure-json-parse'); const jsonString = '{"key": "value"}'; const obj = secureJsonParse(jsonString); console.log(obj); ``` -------------------------------- ### SafeParse vs. Parse with Safe Option Source: https://github.com/fastify/secure-json-parse/blob/main/_autodocs/quick-reference.md Illustrates the difference in error handling between `safeParse` and `parse` when the `safe` option is enabled. `safeParse` returns `undefined` on error, while `parse` throws an error. ```javascript sjson.safeParse(json); // Returns undefined on parse error sjson.parse(json, { safe: true }); // Throws on parse error ``` -------------------------------- ### Safe Mode with Action: 'remove' Source: https://github.com/fastify/secure-json-parse/blob/main/_autodocs/configuration.md Shows how 'safe: true' combined with 'protoAction: 'remove'' returns null if '__proto__' was present, otherwise returns the cleaned object. ```javascript const result = sjson.parse(json, { protoAction: 'remove', safe: true }); // Returns null if __proto__ was present, otherwise the cleaned object ``` -------------------------------- ### No Prototype Benchmark Source: https://github.com/fastify/secure-json-parse/blob/main/README.md Tests the performance of 'secure-json-parse' when explicitly not handling prototype properties, comparing it against 'JSON.parse'. This benchmark is relevant for understanding performance differences when prototype pollution is not a concern. ```bash > benchmarks@1.0.0 no_proto > node no__proto__.js no __proto__ benchmark ┌─────────┬───────────────────────────────┬──────────────────┬───────────────────┬────────────────────────┬────────────────────────┬─────────┐ │ (index) │ Task name │ Latency avg (ns) │ Latency med (ns) │ Throughput avg (ops/s) │ Throughput med (ops/s) │ Samples │ ├─────────┼───────────────────────────────┼──────────────────┼───────────────────┼────────────────────────┼────────────────────────┼─────────┤ │ 0 │ 'JSON.parse' │ '930.41 ± 0.56%' │ '800.00 ± 0.00' │ '1154630 ± 0.03%' │ '1250000 ± 0' │ 1074798 │ │ 1 │ 'secure-json-parse parse' │ '996.09 ± 0.27%' │ '900.00 ± 0.00' │ '1039752 ± 0.02%' │ '1111111 ± 0' │ 1003921 │ │ 2 │ 'secure-json-parse safeParse' │ '1050.5 ± 7.38%' │ '900.00 ± 0.00' │ '1038060 ± 0.02%' │ '1111111 ± 0' │ 951942 │ │ 3 │ 'reviver' │ '5424.7 ± 3.23%' │ '5100.0 ± 100.00' │ '192362 ± 0.05%' │ '196078 ± 3922' │ 184341 │ └─────────┴───────────────────────────────┴──────────────────┴───────────────────┴────────────────────────┴────────────────────────┴─────────┘ ``` -------------------------------- ### Detect Node.js vs. Browser Environment Source: https://github.com/fastify/secure-json-parse/blob/main/_autodocs/quick-reference.md Use this check to conditionally execute code based on whether the Buffer object is available, indicating a Node.js environment. ```javascript if (typeof Buffer !== 'undefined') { // Node.js } else { // Browser } ``` -------------------------------- ### Import Variants Source: https://github.com/fastify/secure-json-parse/blob/main/_autodocs/quick-reference.md Shows various ways to import and use the secure-json-parse library in both CommonJS and TypeScript environments. ```APIDOC ## Import Variants ### CommonJS default import Imports the entire library as a default export. ```javascript const sjson = require('secure-json-parse'); sjson.parse(json); ``` ### CommonJS named import Imports specific functions from the library. ```javascript const { parse, safeParse, scan } = require('secure-json-parse'); parse(json); ``` ### CommonJS direct function import Imports a single function as the default export. ```javascript const parse = require('secure-json-parse'); parse(json); ``` ### TypeScript import Uses ES module syntax for importing functions. ```typescript import parse, { safeParse, scan } from 'secure-json-parse'; parse(json); ``` ``` -------------------------------- ### Regex for constructor Key Detection Source: https://github.com/fastify/secure-json-parse/blob/main/_autodocs/module-structure.md This regex pattern checks for the `constructor` key in JSON strings, accounting for unicode escapes. It helps mitigate prototype pollution vulnerabilities. ```javascript const suspectConstructorRx = /"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/ ``` -------------------------------- ### Metrics and Monitoring for Parsing Source: https://github.com/fastify/secure-json-parse/blob/main/_autodocs/usage-patterns.md Track parsing statistics, including successful parses, blocked attempts, and failures, to enable security monitoring and operational visibility. Use this to gain insights into parsing events. ```javascript const sjson = require('secure-json-parse'); const stats = { parsed: 0, blocked: 0, failed: 0 }; function parseWithMetrics(json) { const result = sjson.safeParse(json); if (result === undefined) { stats.failed++; console.error('[PARSE_FAILED]', json.substring(0, 50)); } else if (result === null) { stats.blocked++; console.warn('[PROTO_POLLUTION_BLOCKED]', json.substring(0, 50)); } else { stats.parsed++; } return result; } // Later, log metrics console.log('Statistics:', stats); ``` -------------------------------- ### Error Handling Patterns for JSON Parsing Source: https://github.com/fastify/secure-json-parse/blob/main/_autodocs/quick-reference.md Demonstrates different strategies for handling errors during JSON parsing, including default try-catch, safe mode with null checks, and safeParse with fallbacks. ```javascript // Pattern 1: Try-catch (default) try { const data = sjson.parse(json); // use data } catch (err) { console.error(err.message); } ``` ```javascript // Pattern 2: Safe mode with null check const data = sjson.parse(json, { safe: true }); if (data === null) { console.error('Security issue'); } else { // use data } ``` ```javascript // Pattern 3: SafeParse with fallback const data = sjson.safeParse(json) ?? defaultValue; // use data ``` -------------------------------- ### Safe Parsing with Error Handling Source: https://github.com/fastify/secure-json-parse/blob/main/_autodocs/api-reference.md Demonstrates how safeParse handles both security violations (returning null) and parsing errors (returning undefined). ```javascript const sjson = require('secure-json-parse'); const badJson = '{\"a\": 5, \"b\": 6, \"__proto__\": {\"x\": 7}}'; const result = sjson.safeParse(badJson); console.log(result); // null (security issue found) const invalidJson = 'not valid json'; const result2 = sjson.safeParse(invalidJson); console.log(result2); // undefined (parse error) ``` -------------------------------- ### Error-Tolerant Code with safeParse() Source: https://github.com/fastify/secure-json-parse/blob/main/_autodocs/MANIFEST.txt Demonstrates how to handle potential JSON parsing errors gracefully using safeParse(). This pattern is useful when input validity is uncertain. ```javascript const secureJsonParse = require('secure-json-parse'); const potentiallyInvalidJson = '{invalid json}'; const data = secureJsonParse.safeParse(potentiallyInvalidJson); if (data === null) { console.log('JSON parsing failed.'); } else { console.log('Parsed data:', data); } ``` -------------------------------- ### Import Variants for secure-json-parse Source: https://github.com/fastify/secure-json-parse/blob/main/_autodocs/quick-reference.md Shows various ways to import the secure-json-parse library, including CommonJS default, named, and direct function imports, as well as TypeScript imports. ```javascript // CommonJS default const sjson = require('secure-json-parse'); sjson.parse(json); ``` ```javascript // CommonJS named const { parse, safeParse, scan } = require('secure-json-parse'); parse(json); ``` ```javascript // CommonJS direct function const parse = require('secure-json-parse'); parse(json); ``` ```typescript // TypeScript import parse, { safeParse, scan } from 'secure-json-parse'; parse(json); ``` -------------------------------- ### Parse Function Return Values Source: https://github.com/fastify/secure-json-parse/blob/main/_autodocs/quick-reference.md Details the return values for the `parse()` function under different conditions, including success, security issues, and parsing errors. ```APIDOC ## parse() Return Values ### Success Returns the parsed JavaScript object. ### Security Issue Throws a `SyntaxError`. ### Parse Error Throws a `SyntaxError`. ``` -------------------------------- ### Strict JSON Parsing Source: https://github.com/fastify/secure-json-parse/blob/main/_autodocs/quick-reference.md Use this for strict parsing that fails on __proto__ or constructor.prototype attacks. ```javascript sjson.parse(json) // Throws on __proto__ or constructor.prototype ``` -------------------------------- ### Parsing Buffer Input Source: https://github.com/fastify/secure-json-parse/blob/main/_autodocs/api-reference.md This snippet demonstrates parsing JSON directly from a Node.js Buffer object. The module handles the conversion to a string automatically. ```javascript const buffer = Buffer.from('{"a": 5}'); const result = sjson.parse(buffer); console.log(result); // { a: 5 } ``` -------------------------------- ### Safe Mode Parsing (Return Null on Security Issues) Source: https://github.com/fastify/secure-json-parse/blob/main/_autodocs/api-reference.md Enable safe mode to prevent errors when forbidden properties are detected. Instead of throwing an error, the function returns `null`. ```javascript const badJson = '{"a": 5, "__proto__": {"x": 7}}'; const result = sjson.parse(badJson, { safe: true }); console.log(result); // null ``` -------------------------------- ### sjson.scan(obj, [options]) Source: https://github.com/fastify/secure-json-parse/blob/main/README.md Scans a given object for prototype properties and applies configured actions to mitigate prototype poisoning. ```APIDOC ## sjson.scan(obj, [options]) ### Description Scans a given object for prototype properties where: - `obj` - the object being scanned. - `options` - optional configuration object where: - `protoAction` - optional string with one of: - `'error'` - throw a `SyntaxError` when a `__proto__` key is found. This is the default value. - `'remove'` - deletes any `__proto__` keys from the input `obj`. - `constructorAction` - optional string with one of: - `'error'` - throw a `SyntaxError` when a `constructor.prototype` key is found. This is the default value. - `'remove'` - deletes any `constructor` keys from the input `obj`. - `safe` - optional boolean: - `true` - returns `null` instead of throwing when a forbidden prototype property is found. - `false` - default behavior (throws or removes based on `protoAction`/`constructorAction`). ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json { "obj": { "a": 5, "b": 6, "__proto__": { "x": 7 } }, "options": { "protoAction": "remove", "constructorAction": "remove" } } ``` ### Response #### Success Response (200) - **object** - The scanned and potentially modified object. #### Response Example ```json { "example": "{ \"a\": 5, \"b\": 6 }" } ``` ``` -------------------------------- ### JSON Parsing with Property Removal Source: https://github.com/fastify/secure-json-parse/blob/main/_autodocs/README.md Demonstrates how to configure secure-json-parse to silently remove forbidden properties like '__proto__' and 'constructor.prototype' during parsing. ```javascript // Remove forbidden properties silently const data = sjson.parse(json, { protoAction: 'remove', constructorAction: 'remove' }); ``` -------------------------------- ### Basic Secure JSON Parsing Source: https://github.com/fastify/secure-json-parse/blob/main/_autodocs/usage-patterns.md Use for standard parsing of untrusted JSON. Throws an error if `__proto__` or `constructor.prototype` are found; otherwise, it behaves like `JSON.parse()`. ```javascript const sjson = require('secure-json-parse'); try { const data = sjson.parse('{"name": "Alice", "age": 30}'); console.log(data); // { name: 'Alice', age: 30 } } catch (err) { console.error('Parse error:', err.message); } ``` -------------------------------- ### Demonstrate Prototype Poisoning with JSON.parse Source: https://github.com/fastify/secure-json-parse/blob/main/README.md Illustrates how the standard JSON.parse() can be vulnerable to prototype poisoning by parsing a JSON string containing a `__proto__` property. This can lead to unexpected behavior when the parsed object is assigned or iterated upon. ```javascript const a = '{"__proto__":{ "b":5}}'; const b = JSON.parse(a); b.b; const c = Object.assign({}, b); c.b ``` -------------------------------- ### Safe Mode JSON Parsing Source: https://github.com/fastify/secure-json-parse/blob/main/_autodocs/00-START-HERE.md Illustrates using secure-json-parse in safe mode. When enabled, the parse function returns null instead of throwing an error upon detecting an attack. ```javascript // Safe mode (returns null on attack) const data = sjson.parse(maliciousJson, { safe: true }); ``` -------------------------------- ### Mixed Action Parsing Source: https://github.com/fastify/secure-json-parse/blob/main/_autodocs/types.md Configures parsing to remove `__proto__` properties while allowing `constructor.prototype` properties to be ignored. ```javascript const options = { protoAction: 'remove', constructorAction: 'ignore' }; sjson.parse(json, options); // Remove __proto__, allow constructor ``` -------------------------------- ### Feature Flag Based Behavior Source: https://github.com/fastify/secure-json-parse/blob/main/_autodocs/usage-patterns.md Configure parsing behavior based on feature flags, allowing for flexible security levels in different environments. Use this when runtime state should dictate parsing strictness. ```javascript const sjson = require('secure-json-parse'); function parseWithFeatureControl(json, features) { const options = { protoAction: features.strictProtoParsing ? 'error' : 'remove', constructorAction: features.strictConstructorParsing ? 'error' : 'remove', safe: features.returnNullOnSecurityIssue }; return sjson.parse(json, options); } // Strict parsing in production const productionData = parseWithFeatureControl(json, { strictProtoParsing: true, strictConstructorParsing: true, returnNullOnSecurityIssue: true }); // Lenient parsing in development const devData = parseWithFeatureControl(json, { strictProtoParsing: false, strictConstructorParsing: false, returnNullOnSecurityIssue: false }); ``` -------------------------------- ### Ignore __proto__, Error on constructor.prototype Source: https://github.com/fastify/secure-json-parse/blob/main/_autodocs/types.md Configures parsing to ignore `__proto__` properties while still throwing an error for `constructor.prototype` properties. ```javascript const options = { protoAction: 'ignore', constructorAction: 'error' }; sjson.parse(json, options); ``` -------------------------------- ### Valid JSON Parsing Benchmark Source: https://github.com/fastify/secure-json-parse/blob/main/README.md Compares the performance of secure-json-parse's 'parse' and 'safeParse' methods against the native 'JSON.parse' for valid JSON strings. This benchmark includes tests with and without prototype properties. ```bash v22.20.0 > benchmarks@1.0.0 valid > node valid.js valid benchmark ┌─────────┬─────────────────────────────────────┬──────────────────┬──────────────────┬────────────────────────┬────────────────────────┬─────────┐ │ (index) │ Task name │ Latency avg (ns) │ Latency med (ns) │ Throughput avg (ops/s) │ Throughput med (ops/s) │ Samples │ ├─────────┼─────────────────────────────────────┼──────────────────┼──────────────────┼────────────────────────┼────────────────────────┼─────────┤ │ 0 │ 'JSON.parse' │ '610.10 ± 0.39%' │ '600.00 ± 0.00' │ '1740515 ± 0.02%' │ '1666667 ± 0' │ 1639075 │ │ 1 │ 'JSON.parse proto' │ '875.42 ± 0.39%' │ '800.00 ± 0.00' │ '1210508 ± 0.03%' │ '1250000 ± 0' │ 1142308 │ │ 2 │ 'secure-json-parse parse' │ '634.34 ± 0.32%' │ '600.00 ± 0.00' │ '1624445 ± 0.01%' │ '1666667 ± 0' │ 1576434 │ │ 3 │ 'secure-json-parse parse proto' │ '657.25 ± 0.42%' │ '600.00 ± 0.00' │ '1666577 ± 0.03%' │ '1666667 ± 0' │ 1521499 │ │ 4 │ 'secure-json-parse safeParse' │ '646.03 ± 1.68%' │ '600.00 ± 0.00' │ '1622543 ± 0.02%' │ '1666667 ± 0' │ 1547914 │ │ 5 │ 'secure-json-parse safeParse proto' │ '912.34 ± 0.20%' │ '900.00 ± 0.00' │ '1122250 ± 0.02%' │ '1111111 ± 0' │ 1096080 │ │ 6 │ 'JSON.parse reviver' │ '3448.5 ± 0.59%' │ '3200.0 ± 0.00' │ '300173 ± 0.04%' │ '312500 ± 0' │ 289982 │ └─────────┴─────────────────────────────────────┴──────────────────┴──────────────────┴────────────────────────┴────────────────────────┴─────────┘ ```