All files / platform/packages/url-signer/src Helper.js

100% Statements 24/24
95% Branches 19/20
100% Functions 5/5
100% Lines 23/23

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55  1x     1x 1x 1x             35x               41x 5x   36x 1x   35x 2x   33x 22x   30x         138x 3x 135x 1x   134x       22x 4x   18x     1x  
'use strict';
const fastSafeStringify = require('fast-safe-stringify');
// https://github.com/fastify/secure-json-parse
// https://github.com/hapijs/bourne
const suspectProtoRx = /"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/;
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*:/;
const JsonSigRx = /^["{[]|^-?[0-9][0-9.]*$/;
 
/**
 * Helper class to base64 encode/decode values with option
 * for url encoding and decoding
 */
function safeStringify(object) {
  return fastSafeStringify(object, jsonStringifyReplacer);
}
 
/**
 * Copied directly from https://github.com/nuxt-contrib/destr/blob/master/src/index.ts but
 * instead raises the malformed JSON exceptions vs swallowing them
 */
function safeJsonParse(val) {
  if (typeof val !== 'string') {
    return val;
  }
  if (val === 'null') {
    return null;
  }
  if (!JsonSigRx.test(val)) {
    return val;
  }
  if (suspectProtoRx.test(val) || suspectConstructorRx.test(val)) {
    return JSON.parse(val, (key, value) => jsonParseTransform(key, value));
  }
  return JSON.parse(val);
}
 
function jsonStringifyReplacer(key, value) {
  // Remove the circular structure
  if (value === '[Circular]') {
    return;
  } else if (typeof value === 'bigint') {
    return value.toString();
  }
  return value;
}
 
function jsonParseTransform(key, value, reviver) {
  if (key === '__proto__' || key === 'constructor') {
    return;
  }
  return reviver ? reviver(key, value) : value;
}
 
module.exports = { safeStringify, safeJsonParse };