Sanitize untrusted HTML (to prevent XSS) with a configuration specified by a Whitelist

Related tags

Security js-xss
Overview

NPM version build status Test coverage David deps node version npm download npm license

Sanitize untrusted HTML (to prevent XSS) with a configuration specified by a Whitelist.

Greenkeeper badge

xss


xss is a module used to filter input from users to prevent XSS attacks. (What is XSS attack?)

Project Homepage: http://jsxss.com

Try Online: http://jsxss.com/en/try.html

中文版文档


Features

  • Specifies HTML tags and their attributes allowed with whitelist
  • Handle any tags or attributes using custom function.

Reference

Benchmark (for references only)

For test code please refer to benchmark directory.

They are using xss module

Install

NPM

npm install xss

Bower

bower install xss

Or

bower install https://github.com/leizongmin/js-xss.git

Usages

On Node.js

var xss = require("xss");
var html = xss('<script>alert("xss");</script>');
console.log(html);

On Browser

Shim mode (reference file test/test.html):

<script src="https://rawgit.com/leizongmin/js-xss/master/dist/xss.js"></script>
<script>
// apply function filterXSS in the same way
var html = filterXSS('<script>alert("xss");</scr' + 'ipt>');
alert(html);
</script>

AMD mode - shim:

<script>
require.config({
  baseUrl: './',
  paths: {
    xss: 'https://rawgit.com/leizongmin/js-xss/master/dist/xss.js'
  },
  shim: {
    xss: {exports: 'filterXSS'}
  }
})
require(['xss'], function (xss) {
  var html = xss('<script>alert("xss");</scr' + 'ipt>');
  alert(html);
});
</script>

Notes: please don't use the URL https://rawgit.com/leizongmin/js-xss/master/dist/xss.js in production environment.

Command Line Tool

Process File

You can use the xss command line tool to process a file. Usage:

xss -i <input_file> -o <output_file>

Example:

xss -i origin.html -o target.html

Active Test

Run the following command, them you can type HTML code in the command-line, and check the filtered output:

xss -t

For more details, please run $ xss -h to see it.

Custom filter rules

When using the xss() function, the second parameter could be used to specify custom rules:

options = {}; // Custom rules
html = xss('<script>alert("xss");</script>', options);

To avoid passing options every time, you can also do it in a faster way by creating a FilterXSS instance:

options = {}; // Custom rules
myxss = new xss.FilterXSS(options);
// then apply myxss.process()
html = myxss.process('<script>alert("xss");</script>');

Details of parameters in options would be described below.

Whitelist

By specifying a whiteList, e.g. { 'tagName': [ 'attr-1', 'attr-2' ] }. Tags and attributes not in the whitelist would be filter out. For example:

// only tag a and its attributes href, title, target are allowed
var options = {
  whiteList: {
    a: ["href", "title", "target"]
  }
};
// With the configuration specified above, the following HTML:
// <a href="#" onclick="hello()"><i>Hello</i></a>
// would become:
// <a href="#">&lt;i&gt;Hello&lt;/i&gt;</a>

For the default whitelist, please refer xss.whiteList.

Customize the handler function for matched tags

By specifying the handler function with onTag:

function onTag(tag, html, options) {
  // tag is the name of current tag, e.g. 'a' for tag <a>
  // html is the HTML of this tag, e.g. '<a>' for tag <a>
  // options is some addition informations:
  //   isWhite    boolean, whether the tag is in whitelist
  //   isClosing  boolean, whether the tag is a closing tag, e.g. true for </a>
  //   position        integer, the position of the tag in output result
  //   sourcePosition  integer, the position of the tag in input HTML source
  // If a string is returned, the current tag would be replaced with the string
  // If return nothing, the default measure would be taken:
  //   If in whitelist: filter attributes using onTagAttr, as described below
  //   If not in whitelist: handle by onIgnoreTag, as described below
}

Customize the handler function for attributes of matched tags

By specifying the handler function with onTagAttr:

function onTagAttr(tag, name, value, isWhiteAttr) {
  // tag is the name of current tag, e.g. 'a' for tag <a>
  // name is the name of current attribute, e.g. 'href' for href="#"
  // isWhiteAttr whether the attribute is in whitelist
  // If a string is returned, the attribute would be replaced with the string
  // If return nothing, the default measure would be taken:
  //   If in whitelist: filter the value using safeAttrValue as described below
  //   If not in whitelist: handle by onIgnoreTagAttr, as described below
}

Customize the handler function for tags not in the whitelist

By specifying the handler function with onIgnoreTag:

function onIgnoreTag(tag, html, options) {
  // Parameters are the same with onTag
  // If a string is returned, the tag would be replaced with the string
  // If return nothing, the default measure would be taken (specifies using
  // escape, as described below)
}

Customize the handler function for attributes not in the whitelist

By specifying the handler function with onIgnoreTagAttr:

function onIgnoreTagAttr(tag, name, value, isWhiteAttr) {
  // Parameters are the same with onTagAttr
  // If a string is returned, the value would be replaced with this string
  // If return nothing, then keep default (remove the attribute)
}

Customize escaping function for HTML

By specifying the handler function with escapeHtml. Following is the default function (Modification is not recommended):

function escapeHtml(html) {
  return html.replace(/</g, "&lt;").replace(/>/g, "&gt;");
}

Customize escaping function for value of attributes

By specifying the handler function with safeAttrValue:

function safeAttrValue(tag, name, value) {
  // Parameters are the same with onTagAttr (without options)
  // Return the value as a string
}

Customize CSS filter

If you allow the attribute style, the value will be processed by cssfilter module. The cssfilter module includes a default css whitelist. You can specify the options for cssfilter module like this:

myxss = new xss.FilterXSS({
  css: {
    whiteList: {
      position: /^fixed|relative$/,
      top: true,
      left: true
    }
  }
});
html = myxss.process('<script>alert("xss");</script>');

If you don't want to filter out the style content, just specify false to the css option:

myxss = new xss.FilterXSS({
  css: false
});

For more help, please see https://github.com/leizongmin/js-css-filter

Quick Start

Filter out tags not in the whitelist

By using stripIgnoreTag parameter:

  • true filter out tags not in the whitelist
  • false: by default: escape the tag using configured escape function

Example:

If stripIgnoreTag = true is set, the following code:

code:<script>alert(/xss/);</script>

would output filtered:

code:alert(/xss/);

Filter out tags and tag bodies not in the whitelist

By using stripIgnoreTagBody parameter:

  • false|null|undefined by default: do nothing
  • '*'|true: filter out all tags not in the whitelist
  • ['tag1', 'tag2']: filter out only specified tags not in the whitelist

Example:

If stripIgnoreTagBody = ['script'] is set, the following code:

code:<script>alert(/xss/);</script>

would output filtered:

code:

Filter out HTML comments

By using allowCommentTag parameter:

  • true: do nothing
  • false by default: filter out HTML comments

Example:

If allowCommentTag = false is set, the following code:

code:<!-- something --> END

would output filtered:

code: END

Examples

Allow attributes of whitelist tags start with data-

var source = '<div a="1" b="2" data-a="3" data-b="4">hello</div>';
var html = xss(source, {
  onIgnoreTagAttr: function(tag, name, value, isWhiteAttr) {
    if (name.substr(0, 5) === "data-") {
      // escape its value using built-in escapeAttrValue function
      return name + '="' + xss.escapeAttrValue(value) + '"';
    }
  }
});

console.log("%s\nconvert to:\n%s", source, html);

Result:

<div a="1" b="2" data-a="3" data-b="4">hello</div>
convert to:
<div data-a="3" data-b="4">hello</div>

Allow tags start with x-

var source = "<x><x-1>he<x-2 checked></x-2>wwww</x-1><a>";
var html = xss(source, {
  onIgnoreTag: function(tag, html, options) {
    if (tag.substr(0, 2) === "x-") {
      // do not filter its attributes
      return html;
    }
  }
});

console.log("%s\nconvert to:\n%s", source, html);

Result:

<x><x-1>he<x-2 checked></x-2>wwww</x-1><a>
convert to:
&lt;x&gt;<x-1>he<x-2 checked></x-2>wwww</x-1><a>

Parse images in HTML

var source =
  '<img src="img1">a<img src="img2">b<img src="img3">c<img src="img4">d';
var list = [];
var html = xss(source, {
  onTagAttr: function(tag, name, value, isWhiteAttr) {
    if (tag === "img" && name === "src") {
      // Use the built-in friendlyAttrValue function to escape attribute
      // values. It supports converting entity tags such as &lt; to printable
      // characters such as <
      list.push(xss.friendlyAttrValue(value));
    }
    // Return nothing, means keep the default handling measure
  }
});

console.log("image list:\n%s", list.join(", "));

Result:

image list:
img1, img2, img3, img4

Filter out HTML tags (keeps only plain text)

var source = "<strong>hello</strong><script>alert(/xss/);</script>end";
var html = xss(source, {
  whiteList: [], // empty, means filter out all tags
  stripIgnoreTag: true, // filter out all HTML not in the whitelist
  stripIgnoreTagBody: ["script"] // the script tag is a special case, we need
  // to filter out its content
});

console.log("text: %s", html);

Result:

text: helloend

License

Copyright (c) 2012-2018 Zongmin Lei(雷宗民) <[email protected]>
http://ucdok.com

The MIT License

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Comments
  • An in-range update of uglify-js is breaking the build 🚨

    An in-range update of uglify-js is breaking the build 🚨

    The devDependency uglify-js was updated from 3.5.13 to 3.5.14.

    🚨 View failing branch.

    This version is covered by your current version range and after updating it in your project the build failed.

    uglify-js is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

    Status Details
    • continuous-integration/travis-ci/push: The Travis CI build could not complete due to an error (Details).

    Release Notes for v3.5.14

     

    Commits

    The new version differs by 2 commits.

    See the full diff

    FAQ and help

    There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


    Your Greenkeeper Bot :palm_tree:

    greenkeeper 
    opened by greenkeeper[bot] 20
  • class is wrong separated by attributes in method onTagAttr

    class is wrong separated by attributes in method onTagAttr

    Hi everyone,

    I have some issue, when I tried to check string like this: <span class=\"preference__text--green text--bold\">BP</span>

    I got in method onTagAttr in first iteration name tag class value = \"preference__text--green

    and second iteration name tag text--bold value ``

    Its shouldn't be like that

    I expected this only in one iteration as: name tag class value = \"preference__text--green text--bold

    I used js-xss in version 1.0.8 and 1.0.10

    Please fix

    opened by sh4d0q 13
  • An in-range update of uglify-js is breaking the build 🚨

    An in-range update of uglify-js is breaking the build 🚨

    The devDependency uglify-js was updated from 3.5.4 to 3.5.5.

    🚨 View failing branch.

    This version is covered by your current version range and after updating it in your project the build failed.

    uglify-js is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

    Status Details
    • continuous-integration/travis-ci/push: The Travis CI build could not complete due to an error (Details).

    Release Notes for v3.5.5

     

    Commits

    The new version differs by 5 commits.

    • f1a77e4 v3.5.5
    • b55a2fd fix corner case in functions (#3367)
    • e8a2c0b fix corner case in functions (#3365)
    • 21cd7e3 reduce test exports (#3361)
    • 5172ba5 introduce functions (#3360)

    See the full diff

    FAQ and help

    There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


    Your Greenkeeper Bot :palm_tree:

    greenkeeper 
    opened by greenkeeper[bot] 9
  • An in-range update of coveralls is breaking the build 🚨

    An in-range update of coveralls is breaking the build 🚨

    The devDependency coveralls was updated from 3.0.3 to 3.0.4.

    🚨 View failing branch.

    This version is covered by your current version range and after updating it in your project the build failed.

    coveralls is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

    Status Details
    • continuous-integration/travis-ci/push: The Travis CI build could not complete due to an error (Details).

    Commits

    The new version differs by 5 commits.

    • 8ac4325 version bump
    • 9d9c227 Bump extend from 3.0.1 to 3.0.2 (#226)
    • 33119a7 Bump js-yaml from 3.11.0 to 3.13.1 (#225)
    • f5549c7 Bump handlebars from 4.1.0 to 4.1.2 (#224)
    • 4df732b Style fix (#211)

    See the full diff

    FAQ and help

    There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


    Your Greenkeeper Bot :palm_tree:

    greenkeeper 
    opened by greenkeeper[bot] 8
  • 为什么当定义白名单时使用new xss.FilterXSS,会报 xss is not defined ?

    为什么当定义白名单时使用new xss.FilterXSS,会报 xss is not defined ?

    你好,我在使用xss的白名单时,按照文档的方法貌似行不通:

    var options = {
      whiteList: {
        i: []
      }
    };
    var myxss = new xss.FilterXSS(options); //直接报错
    // 以后直接调用 myxss.process() 来处理即可
    var text3 = myxss.process('<a href="#" onclick="hello()">大家好</a>,<i>我是i标签</i>');
    document.write(text3);
    

    但是我换成另一种写法就可以避免这个问题:

    var options = {
      whiteList: {
        i: []
      }
    };
    var text1 = filterXSS('<a href="#" onclick="hello()">大家好</a>,<i>我是i标签</i>');
    document.write(text1+'<br>');
    // 通过把options传入到filterXSS
    var text2 = filterXSS('<a href="#" onclick="hello()">大家好</a>,<i>我是i标签</i>',options);
    document.write(text2+'<br>');
    

    所以很疑惑第一种情况是我用得不对,还是文档写错了呢?望指教,谢谢~

    Demo:http://runjs.cn/code/btg94cup

    opened by w3cmark 8
  • "invalid group specifier name" error in Safari after upgrade to 1.0.12

    We use xss in one of our front-end applications (bundled using webpack).

    After recently upgrading from v1.0.11 to v1.0.12, our production error monitoring service started reporting occurrences of the following error:

    SyntaxError: Invalid regular expression: invalid group specifier name

    On further investigation we found that it was only impacting Safari users. Downgrading back to v1.0.11 resolves the issue.

    We hope to follow up this issue with an example that demonstrates the error; but in the meantime we wanted to make you aware of the issue in case you may already have an idea which of the four fix: commits that went into v1.0.12 could be causing this.

    bug 
    opened by scottohara 7
  • Update commander to the latest version 🚀

    Update commander to the latest version 🚀

    The dependency commander was updated from 2.20.0 to 3.0.0.

    This version is not covered by your current version range.

    If you don’t accept this pull request, your project will work just like it did before. However, you might be missing out on a bunch of new features, fixes and/or performance improvements from the dependency update.


    Publisher: abetomo License: MIT

    Release Notes for v3.0.0
    • Add option to specify executable file name (#999)
      • e.g. .command('clone', 'clone description', { executableFile: 'myClone' })
    • Change docs for .command to contrast action handler vs git-style executable. (#938 #990)
    • Breaking Change TypeScript to use overloaded function for .command. (#938 #990)
    • Change to use straight quotes around strings in error messages (like 'this' instead of `this') (#915)
    • Add TypeScript "reference types" for node (#974)
    • Add support for hyphen as an option argument in subcommands (#697)
    • Add support for a short option flag and its value to be concatenated for action handler subcommands (#599)
      • e.g. -p 80 can also be supplied as -p80
    • Add executable arguments to spawn in win32, for git-style executables (#611)
      • e.g. node --harmony myCommand.js clone
    • Add parent command as prefix of subcommand in help (#980)
    • Add optional custom description to .version (#963)
      • e.g. program.version('0.0.1', '-v, --vers', 'output the current version')
    • Add .helpOption(flags, description) routine to customise help flags and description (#963)
      • e.g. .helpOption('-e, --HELP', 'read more information')
    • Fix behavior of --no-* options (#795)
      • can now define both --foo and --no-foo
      • Breaking custom event listeners: --no-foo on cli now emits option:no-foo (previously option:foo)
      • Breaking default value: defining --no-foo after defining --foo leaves the default value unchanged (previously set it to false)
      • allow boolean default value, such as from environment (#987)
    • Increment inspector port for spawned subcommands (#991)
      • e.g. node --inspect myCommand.js clone

    Example Breaking Changes

    The custom event for a negated option like --no-foo is option:no-foo (previously option:foo).

    program
      .option('--no-foo')
      .on('option:no-foo', () => {
        console.log('removing foo');
      });

    When using TypeScript, adding a command does not allow an explicit undefined for an unwanted executable description (e.g. for a command with an action handler).

    program
      .command('action1', undefined, { noHelp: true }) // No longer valid
      .command('action2', { noHelp: true }) // Correct
    Commits

    The new version differs by 104 commits.

    • 3b0127b update Readme_zh-CN to v3.0.0 and modify some old translation problems
    • bfcd39a Set release date for 3.0.0
    • d1469c0 Bump version for release
    • 41d0bdb Add explicit breaking notes (#1006)
    • 5b1b2fe Add links for issues (so work for direct viewing of CHANGELOG)
    • fb56370 Add Tidelift links (#1004)
    • f743bf4 Expand changelog for prerelease
    • e5bce2f Add #987 to CHANGELOG
    • a9503bb Allow boolean default for flag option (#987)
    • 55e88dc Add missing changes to v3.0.0 changelog
    • fb00b0e Merge branch 'master' into release/3.0.0
    • 831d52f Merge pull request #999 from shadowspawn/feature/specifyExecutableFile
    • a59e90f Merge pull request #998 from shadowspawn/feature/develop
    • 6d68637 Increment inspector port for spawned subcommands (#991)
    • facd66f Add debugging note with issue for mixed action/executable

    There are 104 commits in total.

    See the full diff


    FAQ and help

    There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


    Your Greenkeeper bot :palm_tree:

    greenkeeper 
    opened by greenkeeper[bot] 7
  • XSS whiteList issue.

    XSS whiteList issue.

    Whenever I use whiteList option all html content is converted into encoded string instead of sample html.

    I have used below string:

    var source = '<p>Hotel Kadi Palace is located in the <strong>heart </strong>of the <strong>historic center of Florence </strong>'; var html = xss(source, { whiteList: ['href','target'] }); console.log(html);

    So I just want to know whether it is functionality or minor bug, and what should I do to get plain html here.

    opened by 4auvar 7
  • Add `<summary>` to default whitelist

    Add `` to default whitelist

    Since <details> is in there, it makes sense for <summary> as well since that is used inside <details> to define the text label/title for the collapsible element.

    See example: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/details

    opened by spacegaier 6
  • Update mocha to the latest version 🚀

    Update mocha to the latest version 🚀

    The devDependency mocha was updated from 4.1.0 to 6.0.0.

    This version is not covered by your current version range.

    If you don’t accept this pull request, your project will work just like it did before. However, you might be missing out on a bunch of new features, fixes and/or performance improvements from the dependency update.


    Release Notes for v6.0.0

    6.0.0 / 2019-02-18

    💥 Breaking Changes

    • #3149: Drop Node.js v4.x support (@outsideris)
    • #3556: Changes to command-line options (@boneskull):
      • --grep and --fgrep are now mutually exclusive; attempting to use both will cause Mocha to fail instead of simply ignoring --grep
      • --compilers is no longer supported; attempting to use will cause Mocha to fail with a link to more information
      • -d is no longer an alias for --debug; -d is currently ignored
      • #3275: --watch-extensions no longer implies js; it must be explicitly added (@TheDancingCode)
    • #2908: tap reporter emits error messages (@chrmod)
    • #2819: When conditionally skipping in a before hook, subsequent before hooks and tests in nested suites are now skipped (@bannmoore)
    • #627: Emit filepath in "timeout exceeded" exceptions where applicable (@boneskull)
    • #3556: lib/template.html has moved to lib/browser/template.html (@boneskull)
    • #2576: An exception is now thrown if Mocha fails to parse or find a mocha.opts at a user-specified path (@plroebuck)
    • #3458: Instantiating a Base-extending reporter without a Runner parameter will throw an exception (@craigtaub)
    • #3125: For consumers of Mocha's programmatic API, all exceptions thrown from Mocha now have a code property (and some will have additional metadata). Some Error messages have changed. Please use the code property to check Error types instead of the message property; these descriptions will be localized in the future. (@craigtaub)

    📠 Deprecations

    These are soft-deprecated, and will emit a warning upon use. Support will be removed in (likely) the next major version of Mocha:

    • -gc users should use --gc-global instead
    • Consumers of the function exported by bin/options should now use the loadMochaOpts or loadOptions (preferred) functions exported by the lib/cli/options module

    Regarding the Mocha class constructor (from lib/mocha):

    • Use property color: false instead of useColors: false
    • Use property timeout: false instead of enableTimeouts: false

    All of the above deprecations were introduced by #3556.

    mocha.opts is now considered "legacy"; please prefer RC file or package.json over mocha.opts.

    🎉 Enhancements

    Enhancements introduced in #3556:

    • Mocha now supports "RC" files in JS, JSON, YAML, or package.json-based (using mocha property) format

      • .mocharc.js, .mocharc.json, .mocharc.yaml or .mocharc.yml are valid "rc" file names and will be automatically loaded
      • Use --config /path/to/rc/file to specify an explicit path
      • Use --package /path/to/package.json to specify an explicit package.json to read the mocha prop from
      • Use --no-config or --no-package to completely disable loading of configuration via RC file and package.json, respectively
      • Configurations are merged as applicable using the priority list:
        1. Command-line arguments
        2. RC file
        3. package.json
        4. mocha.opts
        5. Mocha's own defaults
      • Check out these example config files
    • Node/V8 flag support in mocha executable:

      • Support all allowed node flags as supported by the running version of node (also thanks to @demurgos)
      • Support any V8 flag by prepending --v8- to the flag name
      • All flags are also supported via config files, package.json properties, or mocha.opts
      • Debug-related flags (e.g., --inspect) now imply --no-timeouts
      • Use of e.g., --debug will automatically invoke --inspect if supported by running version of node
    • Support negation of any Mocha-specific command-line flag by prepending --no- to the flag name

    • Interfaces now have descriptions when listed using --interfaces flag

    • Mocha constructor supports all options

    • --extension is now an alias for --watch-extensions and affects non-watch-mode test runs as well. For example, to run only test/*.coffee (not test/*.js), you can do mocha --require coffee-script/register --extensions coffee.

    • #3552: tap reporter is now TAP13-capable (@plroebuck & @mollstam)

    • #3535: Mocha's version can now be queried programmatically via public property Mocha.prototype.version (@plroebuck)

    • #3428: xunit reporter shows diffs (@mlucool)

    • #2529: Runner now emits a retry event when tests are retried (reporters can listen for this) (@catdad)

    • #2962, #3111: In-browser notification support; warn about missing prereqs when --growl supplied (@plroebuck)

    🐛 Fixes

    📖 Documentation

    🔩 Other

    Commits

    The new version differs by 308 commits.

    • 42303e2 Release v6.0.0
    • a553ca7 punctuation updates for changelog v6.0.0
    • c710792 grammar updates for changelog v6.0.0
    • 9f9293a update changelog for v6.0.0
    • a540eb0 remove "projects" section from MAINTAINERS.md [ci skip]
    • 52b5c42 Uppercased JSON reporter name in describe title (#3739)
    • 82307fb Fix .globals to remove falsy values (#3737)
    • 56dc28e Remove unnecessary post-processing code having no effect; closes #3708 (#3733)
    • 16b4281 Documentation updates (#3728)
    • 5d9d3eb Update nyc
    • 118c9ae Refactor out usages of Suite#_onlyTests and Suite#_onlyTests (#3689) (#3707)
    • 0dacd1f Add ability to unload files from require cache (redux) (#3726)
    • 66a52f2 update release steps [ci skip]
    • 45ae014 Refactor lookupFiles and files (#3722)
    • 94c9320 fix --reporter-option to allow comma-separated options; closes #3706

    There are 250 commits in total.

    See the full diff

    FAQ and help

    There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


    Your Greenkeeper bot :palm_tree:

    greenkeeper 
    opened by greenkeeper[bot] 6
  • Fix 'DedicatedWorkerGlobalScope is not defined' error on Web env

    Fix 'DedicatedWorkerGlobalScope is not defined' error on Web env

    This fixes code added in https://github.com/leizongmin/js-xss/commit/723b307a32541044e4f4dcbb260c34b3168e87f2 which causes #140

    I didn't commit built version because that'd could be a chance for me to put nasty code in the minified file without anybody noticing :) .

    opened by Asvarox 6
  • whiteList fails when using slashes to separate tag attributes (PR included)

    whiteList fails when using slashes to separate tag attributes (PR included)

    Let's say you have whitelisted the img tag. The following will not get filtered (good):

    <img src="cat.jpg"/>
    

    And neither will this (good):

    <img
    src="cat.jpg"/>
    

    However, this will get filtered (bad):

    <img/src="cat.jpg"/>
    

    The use of / as a separator is supported by browsers so this ought to work. As reported in this article, the following characters may be used to separate attributes in an HTML tag:

    • Space (0x20)
    • Slash (0x2F)
    • Carriage-Return (0x0D)
    • Line-Feed (0x0A)
    • Horizontal Tab (0x09)
    • Form-Feed (0x0C)

    The problem seems to be that the regexes in spaceIndex() and parseAttr() do not know about slashes: https://github.com/leizongmin/js-xss/blob/5711a9c5fac93f3f54541a7b4f7c780ba38adac6/lib/util.js#L30 https://github.com/leizongmin/js-xss/blob/c339c1f777f2f9ba34bb26d5ed67ae2eaede7c2a/lib/parser.js#L169-L170

    Therefore, getTagName() should return img, but incorrectly returns img/src="cat.jpg" instead (which is obviously not on the whitelist). The attribute parser has the same issue: it comes back with all the attributes in one string separated by /.

    The regexes in the code snippets above are doubly redundant, because \n (literal newline) and \t (literal tab) will already get matched by \s (any whitespace character). All of the other whitespace characters in the list above will also get matched by \s.

    I can provide a PR that will fix the issue.

    opened by hensleysecurity 0
  • Escaping attribute does not work sufficient

    Escaping attribute does not work sufficient

    I have the following Code:

    const userInput = 'https://heise.de" onmouseover="alert(document.cookie)"';
    const html = '<a href="' + xss(userInput) + '">link</a>';
    

    the output of html is the following: '<a href="https://heise.de" onmouseover="alert(document.cookie)"">link</a>'

    This leads to an xss Attack. Is this a general problem with this library or am i using it wrong?

    opened by djschilling 1
  • At v1.0.14 stripIgnoreTag behavior changed

    At v1.0.14 stripIgnoreTag behavior changed

    Overview

    With the update to v1.0.14 I noticed that with the stripIgnoreTag: true option set, strings containing < but no actual HTML began to be stripped at the point of the < character. Example, "x < 12" at v1.0.13 would be sanitized to "x &lt; 12", but at v1.0.14 that same string would be sanitized to "x ".

    Is this new behavior in v1.0.14 fixing prior incorrect behavior of stripIgnoreTag, or is it an unintended regression? Based on past behavior, it looks like a regression, but I would like to understand this as it does cause quite a big change when processing strings that do not contain actual HTML tags.

    This behavior change seems to be caused by this commit: https://github.com/leizongmin/js-xss/commit/72844ddc6f59cb613312b92e58c090c5f414b6fb

    Demo

    I have created a CodePen where you can switch between v1.0.13 and v1.0.14 and see the change in behavior visually.

    opened by BlakeStearman 0
Owner
老雷
Software Engineer
老雷
Secure XSS Filters.

Secure XSS Filters Just sufficient output filtering to prevent XSS! Goals More Secure. Context-dependent output filters that are developer-friendly. I

Yahoo Archive 1.1k Jan 9, 2023
Clean up user-submitted HTML, preserving whitelisted elements and whitelisted attributes on a per-element basis. Built on htmlparser2 for speed and tolerance

sanitize-html sanitize-html provides a simple HTML sanitizer with a clear API. sanitize-html is tolerant. It is well suited for cleaning up HTML fragm

Apostrophe Technologies 3.2k Dec 26, 2022
Solidity NFT whitelist contract example using MerkleTree.js for constructing merkle root and merkle proofs.

MerkleTree.js Solidity NFT Whitelist example Allow NFT minting only to whitelisted accounts by verifying merkle proof in Solidity contract. Merkle roo

Miguel Mota 65 Dec 29, 2022
CDK construct to periodically take snapshots of RDS databases, sanitize them, and share with selected accounts.

CDK Construct for RDS Sanitized Snapshots Periodically take snapshots of RDS databases, sanitize them, and share with selected accounts. Use this to a

CloudSnorkel 6 Dec 7, 2022
DOMPurify - a DOM-only, super-fast, uber-tolerant XSS sanitizer for HTML, MathML and SVG. DOMPurify works with a secure default, but offers a lot of configurability and hooks. Demo:

DOMPurify DOMPurify is a DOM-only, super-fast, uber-tolerant XSS sanitizer for HTML, MathML and SVG. It's also very simple to use and get started with

Cure53 10.2k Jan 7, 2023
Secure XSS Filters.

Secure XSS Filters Just sufficient output filtering to prevent XSS! Goals More Secure. Context-dependent output filters that are developer-friendly. I

Yahoo Archive 1.1k Jan 9, 2023
Moodle (< 3.6.2, < 3.5.4, < 3.4.7, < 3.1.16) XSS PoC for Privilege Escalation (Student to Admin)

Moodle CVE-2019-3810 Moodle (< 3.6.2, < 3.5.4, < 3.4.7, < 3.1.16) XSS PoC for Privilege Escalation (Student to Admin). This is one of the past bugs th

Fariskhi Vidyan 18 Sep 3, 2022
A cyber-sec tool to be used responsibly in identifying XSS vulnerabilities

Visit the Breach website here Table of Contents About Breach Getting Started Demo Scan URL Results History Settings Looking Ahead Contributors License

OSLabs Beta 39 Apr 14, 2022
A websocket-based reverse shell for XSS attacks.

CrossSiteShell A javascript/nodejs "reverse shell" that makes it easier to interact with the victim's browser during XSS attacks. Usage Run the follow

Rafael 13 Oct 7, 2022
TypeScript clients for databases that prevent SQL Injection

Safe From HTML Injection Using tagged template literals for queries, e.g. db.query(sql`SELECT * FROM users WHERE id=${userID}`); makes it virtually im

Forbes Lindesay 478 Dec 21, 2022
LunaSec - Open Source Security Software built by Security Engineers. Scan your dependencies for Log4Shell, or add Data Tokenization to prevent data leaks. Try our live Tokenizer demo: https://app.lunasec.dev

Our Software We're a team of Security Engineers on a mission to make awesome Open Source Application Security tooling. It all lives in this repo. Here

LunaSec 1.2k Jan 7, 2023
Statically prevent 404s in your Next.js applications using TypeScript

next-static-paths Statically prevent HTTP 404 Not Found in your Next.js applications using TypeScript and code generation. Features ?? A command-line

Gal Schlezinger 23 Jul 3, 2022
Convert your SVG file directly to Flutter paths and prevent all the messing with bezier curves.

svg-to-flutter-path-converter Convert your SVG file directly to Flutter paths and prevent all the messing with bezier curves. Flutter Clutter The tool

null 30 Jan 2, 2023
Node.js package with a customized HTTP and HTTPS agents to prevent SSRF with hosts validations and custom DNS feature.

http-agent-dns This is a Node.js package with a customized HTTP and HTTPS agents to prevent SSRF with hosts validations with a possibility to use a cu

Bruno Germano 4 Jul 21, 2022
Make text fit container, prevent overflow and underflow.

AutoTextSize Make text fit container, prevent overflow and underflow. The font size of the text is adjusted so that it precisely fills its container.

Sana Labs 10 Dec 30, 2022
⌨️ A tiny library for creating a typing effect on specified text element.

⌨️ TinyTyper - a tiny library for creating a typing effect on specified text element. Demo Size (It's really tiny) Minimized: 2.9KB Gziped: 1.1KB Inst

Korney Vasilchenko 175 Sep 29, 2021
Delay a promise a specified amount of time

delay Delay a promise a specified amount of time If you target Node.js 15 or later, you can do await require('timers/promises').setTimeout(1000) inste

Sindre Sorhus 518 Dec 26, 2022
An alarm clock is a clock that is designed to alert an individual or group of individuals at a specified time.

An alarm clock (or sometimes just an alarm) is a clock that is designed to alert an individual or group of individuals at a specified time. The primary function of these clocks is to awaken people from their night's sleep or short naps; they are sometimes used for other reminders as well.

Anupam Moharana 1 Dec 25, 2021
Notifies and then closes draft pull requests that have had no activity for a specified amount of time.

Close Stale Draft Pull Requests This action has been inspired by microsoft/vscode-github-triage-actions, actions/stale and probot/stale, ultimately wr

Multi Theft Auto 2 Jan 7, 2022
An interpreter for College Board's specified pseudocode for the AP Computer Science Principles Exam.

College Board Pseudocode Interpreter A playground for this interpreter is up on my website. This project is a mostly-functioning interpreter for Colle

Daniel 7 Nov 16, 2022