Remove unsafe params from serialize-javascript

JavaScript pattern

serialize-javascript used with unsafe parameter, this could be vulnerable to XSS.

references


Apply with the Grit CLI
grit apply remove_unsafe_params_from_serialize_javascript

Apollo Graphql Schema Directives while migrating from v2 to v3 or v4

BEFORE
var serialize = require('serialize-javascript');

function test(userInput) {
  // BAD: unsafe serialize javascript
  const result = serialize({ foo: userInput }, { unsafe: true, space: 2 });
  return result;
}

function test2() {
  // BAD: unsafe serialize javascript
  const result = serialize({ foo: '<img src=x />' }, { unsafe: true, space: 2 });
  return result;
}

function testOk() {
  // GOOD: unsafe serialize javascript
  const result = serialize({ foo: '<img src=x />' }, { space: 2 });
  return result;
}

function testOk2() {
  // GOOD: unsafe serialize javascript
  const result = escape(serialize({ foo: '<img src=x />' }, { space: 2 }));
  return result;
}

function testOk3() {
  // GOOD: unsafe serialize javascript
  const result = encodeURI(escape(serialize({ foo: '<img src=x />' }, { space: 2 })));
  return result;
}
AFTER
var serialize = require('serialize-javascript');

function test(userInput) {
  // BAD: unsafe serialize javascript
  const result = serialize({ foo: userInput }, { space: 2 });
  return result;
}

function test2() {
  // BAD: unsafe serialize javascript
  const result = serialize({ foo: '<img src=x />' }, { space: 2 });
  return result;
}

function testOk() {
  // GOOD: unsafe serialize javascript
  const result = serialize({ foo: '<img src=x />' }, { space: 2 });
  return result;
}

function testOk2() {
  // GOOD: unsafe serialize javascript
  const result = escape(serialize({ foo: '<img src=x />' }, { space: 2 }));
  return result;
}

function testOk3() {
  // GOOD: unsafe serialize javascript
  const result = encodeURI(escape(serialize({ foo: '<img src=x />' }, { space: 2 })));
  return result;
}