• Stars
    star
    5,037
  • Rank 8,280 (Top 0.2 %)
  • Language
    HTML
  • License
    Other
  • Created about 12 years ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

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

NPM version Node.js CI 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.

allowList is also supported, and has the same function as 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></a></a
></x>

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.

More Repositories

1

node-segment

基于Node.js的中文分词模块
JavaScript
1,174
star
2

node-doc-cn

Node.js中文文档
JavaScript
174
star
3

book-crawler-mysql-cron

爬虫,MySQL,定时任务
JavaScript
156
star
4

node-rd

列出(遍历)目录下的所有文件,包括子目录
JavaScript
148
star
5

node-lei-stream

Read/Write stream line by line 按行读写流
JavaScript
99
star
6

book-nodejs-in-action-season-2

《Node.js实战 第二季》示例代码
JavaScript
65
star
7

programmer-calendar

命令行版程序员老黄历
JavaScript
65
star
8

tinyliquid

A Liquid syntax template engine.
JavaScript
63
star
9

vscode-node-module-intellisense

Visual Studio Code plugin that autocompletes JavaScript / TypeScript modules in import statements.
TypeScript
62
star
10

huobiapi

火币网API Go客户端
Go
60
star
11

QuickWeb

快速搭建基于Nodejs的Web运行环境
JavaScript
58
star
12

clouds

lightweight microservices framework, simple to call remote functions 轻量级微服务框架
JavaScript
58
star
13

jssh

一款使用JS编写命令行小工具的神器
C
54
star
14

qchat

基于QuickWeb + socket.io的聊天室
JavaScript
45
star
15

bamei

JavaScript
44
star
16

leizm-web

现代的 Web 中间件基础框架,完美支持 TypeScript,构建可维护的大型 Web 项目
TypeScript
42
star
17

node-umeditor-qiniu

支持上传图片到七牛的百度UMeditor编辑器
JavaScript
31
star
18

leiphp

轻量级的 PHP MVC 框架 Lightweight MVC framework for simplistic PHP apps
PHP
30
star
19

js-css-filter

CSS白名单过滤器
JavaScript
27
star
20

htmlstream-rust

Lightweight HTML parser
Rust
23
star
21

leizm-utils

一些常用的工具函数
JavaScript
20
star
22

tora

运维部署系统,包括文件传输、命令执行、日志监控等模块
Go
19
star
23

tcp-tunnel

TCP tunnel server & client, multi-user support
JavaScript
18
star
24

docker-shadowsocks

Shadowsocks server docker image.
Shell
17
star
25

node-lei-udp

可靠的UDP传输模块
JavaScript
17
star
26

practice-node-project

Node.js项目实战
JavaScript
16
star
27

simpledb

NoSQL embedded database on top of RocksDB.
Rust
16
star
28

MQTTClient

JavaScript
16
star
29

node-lei-download

用于从网络下载文件或复制本地文件,具有自动分配临时文件名和进度通知功能
JavaScript
15
star
30

express-liquid

Using TinyLiquid in Express 3.x
JavaScript
15
star
31

luckypg

Lucky Programmer 给程序员带来好运的小工具
Go
15
star
32

node-lei-proto

简单的Buffer编码/解析模块
JavaScript
14
star
33

eslint-config-lei

eslint-config 配置
JavaScript
12
star
34

vscode-quick-open

Visual Studio Code plugin that provide a quick open file command
TypeScript
11
star
35

hojs

轻量级 RESTful API 服务器框架
JavaScript
11
star
36

writing-os-in-rust

学习用Rust写一个操作系统
Rust
10
star
37

nodejs-web-project-best-practice

Node.js Web 项目结构最佳实践
JavaScript
9
star
38

go

我的Go语言公共库
Go
8
star
39

url-forwarding

HTTP转发服务,解决国内主机不能绑定未备案问题,可将域名解析到该服务器,然后重定向到国内IP
JavaScript
8
star
40

taskmanager

基于Node.js的任务管理器,可通过插件形式来实现管理(包括启动、状态监控等)不同类型的Node.js文件
JavaScript
7
star
41

gogo

简单易用的Go包管理工具
Go
7
star
42

serverless-sqlite

Serverless SQLite database read from and write to Object Storage Service, run on FaaS platform.
C++
7
star
43

node-lei-crawler

简单爬虫工具
JavaScript
7
star
44

simple-http-server-in-java

使用Java编写的简单HTTP服务器
Java
7
star
45

node-project-core

JavaScript
7
star
46

lei-dev-server

npm install lei-dev-server -g 简单的前端开发服务器
TypeScript
7
star
47

newos

A Linux kernel based operating system
Makefile
6
star
48

study-rust-osdev

学习Rust编写操作系统内核
Rust
6
star
49

node-web-installer

基于Node.js的Web应用安装器,让小白用户可以通过简单的Web界面来完成应用的初始化配置
JavaScript
6
star
50

lei-deploy

通过pm2和git来管理代码部署
JavaScript
5
star
51

node-weibo-sdk

JavaScript
5
star
52

connect-limit-requests

防止恶意刷新攻击 connect中间件
JavaScript
5
star
53

leizm-html-parser

Fast HTML parser written in pure JavaScript
HTML
5
star
54

HttpRequest

NodeJs HttpRequest模块
JavaScript
4
star
55

lei-coroutine

简单的 coroutine 库
JavaScript
4
star
56

leizm-sql

SQL查询构造器
TypeScript
4
star
57

html5-canvas-box-drag-resize-demo

基于 HTML5 Canvas 实现的对象多拽缩放实验代码
TypeScript
4
star
58

lei-theme-vscode

Lei's best theme for VSCode
4
star
59

node-lei-mysql

Simple MySQL Pool
JavaScript
4
star
60

imbot

an IM Bot modules for NodeJs, use bot.im API.
JavaScript
4
star
61

leizm-async-cache-getter

异步获得数据,保证同一时间多个相同的请求只会实际执行一个
TypeScript
4
star
62

PlayWithCompiler

极客时间《编译原理之美》课程练习
Go
4
star
63

leizm-http-proxy

一个简单灵活的 HTTP 代理服务器
TypeScript
4
star
64

lei-php-cgi

简单的PHP-CGI中间件,实现在connect/express中执行php脚本
JavaScript
4
star
65

js-bright

一种更优雅的JavaScript异步流程控制方式。
JavaScript
3
star
66

toy-docker

写一个玩具Docker玩玩
JavaScript
3
star
67

peento

一个简单的博客系统,模块化、主题与程序分离,像Wordpress那样灵活
JavaScript
3
star
68

taskcloud

taskcloud
JavaScript
3
star
69

leizm-benchmark

简单性能测试框架
TypeScript
3
star
70

go-websocket-examples

Go语言WebSocket使用例子
Go
3
star
71

fuser

Find the Process That is Using a File in Linux
Go
3
star
72

node-lei-config

根据环境变量加载配置文件
JavaScript
3
star
73

query-tool

快速查询工具
JavaScript
3
star
74

express-router-async-support

async function support for express.Router
JavaScript
3
star
75

nodejs-accuracy-time

高精度时间相关模块
TypeScript
3
star
76

os-in-c-example

操作系统内核练习
C
3
star
77

simple-file-transfer-tools

简单文件传输工具
TypeScript
3
star
78

leizm-cache

高性能缓存管理器,支持 Redis、Memcached 和内存存储
TypeScript
3
star
79

node-lei-onepage

基于Node.js的单页面应用框架
JavaScript
3
star
80

leizm-mysql

基于 Node.js/TypeScript 的 MySQL 连接管理器
TypeScript
3
star
81

node-lei-hot

Node.js代码热更新方案
JavaScript
2
star
82

api-proxy

API代理服务器
JavaScript
2
star
83

the-eyuyan-dot-fly-examples

我用过的易语言
2
star
84

node-lei-ns

Organizing your code without writing wired variable constructs and helper objects
JavaScript
2
star
85

yedda

简单限流计数服务
Go
2
star
86

xss.rs

Sanitize untrusted HTML (to prevent XSS) with a configuration specified by a Whitelist.
Rust
2
star
87

weixin-api

个人版微信API
JavaScript
2
star
88

go-utils

私人订制 Go 语言工具函数库
Go
2
star
89

clouds-benchmark

clouds模块性能测试
JavaScript
2
star
90

random-chat

随机聊天
JavaScript
2
star
91

holyhi

state management library for React that very easy to use
TypeScript
1
star
92

dev-clean

Free up developer disk space.
Go
1
star
93

leizm-logger

简单日志记录器
TypeScript
1
star
94

node-lei-cycle

循环返回指定数组中的一个元素
JavaScript
1
star
95

taskcloud-node

The taskcloud node
JavaScript
1
star
96

node-file-lookup

指定一组目录,依次搜索指定文件(相对路径),返回其绝对文件路径,支持同步和异步方法
JavaScript
1
star
97

nodejs-distributed-modules

Node.js分布式应用相关模块
TypeScript
1
star
98

leisp

Leisp is a Lisp-Like programming language
Go
1
star
99

nodejs.ucdok.com

《Node.js 实战》读者反馈网站
HTML
1
star
100

bright-flow

JavaScript流程控制库
JavaScript
1
star