Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make content XSS safe #153

Closed
micmro opened this issue Feb 19, 2017 · 1 comment
Closed

Make content XSS safe #153

micmro opened this issue Feb 19, 2017 · 1 comment

Comments

@micmro
Copy link
Owner

micmro commented Feb 19, 2017

escape all rendered content to avoid possibility of tempered HAR to inject code.
See #149 as reference.

@Janpot
Copy link

Janpot commented Feb 19, 2017

a nice way of doing this:

const assert = require('assert');

class HtmlEscapedString extends String {
  constructor(parts, subs) {
    super();
    this._parts = Array.isArray(parts) ? parts : [parts];
    this._subs = subs || [];
  }
  _escapeHtml(unsafe) {
    if (unsafe instanceof HtmlEscapedString) {
      return unsafe;
    }
    return String(unsafe)
      .replace(/&/g, "&")
      .replace(/</g, "&lt;")
      .replace(/>/g, "&gt;")
      .replace(/"/g, "&quot;")
      .replace(/'/g, "&#039;");
  }
  toString() {
    return this._parts.reduce((result, part, i) => {
      return result + this._escapeHtml(this._subs[i - 1]).toString() + part;
    });
  }
}

function HTML (parts, ...subs) {
  return new HtmlEscapedString(parts, subs);
}

assert.strictEqual(String(HTML`<a>`), '<a>');
assert.strictEqual(String(HTML`${'<a>'}`), '&lt;a&gt;');
assert.strictEqual(String(HTML`${HTML`<a>`}`), '<a>');
assert.strictEqual(String(HTML`${HTML`${'<a>'}`}`), '&lt;a&gt;');
assert.strictEqual(String(HTML('<a>')), '<a>');
assert.strictEqual(HTML` <a> `.trim(), '<a>');

This has the added benefit that you can't forget to escape a substitution if your outer string is tagged with HTML.

micmro pushed a commit that referenced this issue Mar 26, 2017
micmro pushed a commit that referenced this issue Apr 1, 2017
micmro added a commit that referenced this issue Apr 2, 2017
@micmro micmro closed this as completed Apr 2, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants