{"name":"egg-security","version":"3.8.1","engines":{"node":">=14.20.0"},"description":"security plugin in egg framework","eggPlugin":{"name":"security","optionalDependencies":["session"]},"keywords":["egg","eggPlugin","egg-plugin","security"],"dependencies":{"@eggjs/ip":"^2.0.2","csrf":"^3.0.6","delegates":"^1.0.0","egg-path-matching":"^1.2.0","escape-html":"^1.0.3","extend":"^3.0.1","koa-compose":"^4.1.0","matcher":"^4.0.0","methods":"^1.1.2","nanoid":"^3.3.6","platform":"^1.3.4","statuses":"^2.0.1","type-is":"^1.6.15","xss":"^1.0.3"},"devDependencies":{"beautify-benchmark":"^0.2.4","benchmark":"^2.1.4","egg":"^3.26.0","egg-bin":"^6.4.0","egg-mock":"^5.10.6","egg-view-nunjucks":"^2.3.0","eslint":"^8.40.0","eslint-config-egg":"^12.2.1","spy":"^1.0.0","supertest":"^6.3.3","path-to-regexp-v8":"npm:path-to-regexp@8"},"scripts":{"lint":"eslint .","test":"npm run lint -- --fix && npm run test-local","test-local":"egg-bin test","cov":"egg-bin cov","ci":"npm run lint && npm run cov"},"repository":{"type":"git","url":"git+https://github.com/eggjs/security.git"},"bugs":{"url":"https://github.com/eggjs/egg/issues"},"homepage":"https://github.com/eggjs/security#readme","author":{"name":"jtyjty99999"},"license":"MIT","_id":"egg-security@3.8.1","gitHead":"cef5a7fc5ec0b5ad4458bea59f0e1cafb7096bbe","_nodeVersion":"22.22.3","_npmVersion":"10.9.8","dist":{"integrity":"sha512-zFGjDo+Z9X0lv2QAWeE7I+LAvP77uqTDNP3+xfgj6g5MYVLLPfubIVli9CemViYBhVmcXm3uvm2vFibFzxN+qQ==","shasum":"d6ec2fccd62670e1f6a9e9b563d9b2833db336fa","tarball":"http://registry-npm.ywwl.com/egg-security/download/egg-security-3.8.1.tgz","fileCount":37,"unpackedSize":73630,"signatures":[{"keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U","sig":"MEUCIQC6LwUC9IiCQkSruM5cOVE1aIvFcGY3zML8axQ+46qx1QIgYfhq9SOXSXlgEY9hOfF2U/sr2lZj1oh25TN1BoqWVfM="}],"size":24748,"noattachment":false,"key":"/egg-security/-/egg-security-3.8.1.tgz"},"_npmUser":{"name":"killagu","email":"killa07071201@gmail.com"},"directories":{},"maintainers":[{"name":"gxkl","email":"gxkl203@gmail.com"},{"name":"eggjs-admin","email":"fengmk2+eggjs@gmail.com"},{"name":"fengmk2","email":"fengmk2@gmail.com"},{"name":"atian25","email":"atian25@qq.com"},{"name":"hyj1991","email":"yeekwanvong@gmail.com"},{"name":"killagu","email":"killa07071201@gmail.com"},{"name":"coolme200","email":"2001-wms@163.com"},{"name":"akitasummer","email":"644171127@qq.com"},{"name":"elrrrrrrr","email":"elrrrrrrr@gmail.com"},{"name":"niania","email":"ljracm@gmail.com"},{"name":"jtyjty99999","email":"jtyjty99999@126.com"},{"name":"dead_horse","email":"dead_horse@qq.com"},{"name":"shaoshuai0102","email":"shaoshuai0102@gmail.com"},{"name":"popomore","email":"sakura9515@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/egg-security_3.8.1_1784126999530_0.7913411338884699"},"_hasShrinkwrap":false,"readme":"# egg-security\n\negg 内置的安全插件\n\n[![NPM version][npm-image]][npm-url]\n[![Node.js CI](https://github.com/eggjs/security/actions/workflows/nodejs.yml/badge.svg)](https://github.com/eggjs/security/actions/workflows/nodejs.yml)\n[![Test coverage][codecov-image]][codecov-url]\n[![Known Vulnerabilities][snyk-image]][snyk-url]\n[![npm download][download-image]][download-url]\n\n[npm-image]: https://img.shields.io/npm/v/egg-security.svg?style=flat-square\n[npm-url]: https://npmjs.org/package/egg-security\n[codecov-image]: https://codecov.io/gh/eggjs/security/branch/master/graph/badge.svg\n[codecov-url]: https://codecov.io/gh/eggjs/security\n[snyk-image]: https://snyk.io/test/npm/egg-security/badge.svg?style=flat-square\n[snyk-url]: https://snyk.io/test/npm/egg-security\n[download-image]: https://img.shields.io/npm/dm/egg-security.svg?style=flat-square\n[download-url]: https://npmjs.org/package/egg-security\n\n## 使用方式\n\negg 默认开启此插件，所以无需配置。\n\n修改 `config/config.js` 文件修改配置\n\n```js\nexports.security = {\n  xframe: {\n    value: 'SAMEORIGIN',\n  },\n};\n```\n\n### 关闭安全防范\n\n如果你想关闭其中一些安全防范，直接设置该项的 `enable` 属性为 false 即可，如关闭 xfame 防范：\n\n```js\nexports.security = {\n  xframe: {\n    enable: false,\n  },\n};\n```\n\n### match 和 ignore\n\n如果只想开启针对某一路径，则配置 match 选项，例如只针对 `/example` 开启 csp\n\n```js\nexports.security = {\n  csp: {\n    match: '/example',\n    // match: /^\\/api/, // support regexp\n    // match: ctx => ctx.path.startsWith('/api'), // support function\n    // match: [ ctx => ctx.path.startsWith('/api'), /^\\/foo$/, '/bar'], // support Array\n    policy: {\n      //...\n    },\n  },\n};\n\n```\n\n如果需要针对某一路径忽略某安全选项，则配置 ignore 选项，例如针对 `/example` 关闭 xframe，以便合作商户能够嵌入我们的页面：\n\n```js\nexports.security = {\n  xframe: {\n    ignore: '/example',\n    // ignore: /^\\/api/, // support regexp\n    // ignore: ctx => ctx.path.startsWith('/api'), // support function\n    // ignore: [ ctx => ctx.path.startsWith('/api'), /^\\/foo$/, '/bar'], // support Array\n    // ...\n  },\n};\n\n```\n\n__注意：如果存在 match 则忽略 ignore。__\n\n## API\n\n### ctx.isSafeDomain(domain)\n\n是否为安全域名。安全域名在配置中配置，见 `ctx.redirect` 部分\n\n## 接口限制\n\n### csrf\n\n__使用__\n\n* `ctx.csrf` 获取 csrf token\n\n一般在 POST 表单时使用。\n\n页面渲染时，将 `ctx.csrf` 作为 form 隐藏域或 query string 渲染在页面上。(`_csrf` 作为 key)\n\n在提交表单时，带上 token 即可。\n\n#### 通过 formData 上传时使用 csrf\n\n浏览器端 html 代码:\n\n```html\n<form method=\"POST\" action=\"/upload?_csrf={{ ctx.csrf | safe }}\" enctype=\"multipart/form-data\">\n  title: <input name=\"title\" />\n  file: <input name=\"file\" type=\"file\" />\n  <button type=\"submit\">上传</button>\n</form>\n```\n\n### ctoken\n\najax 防跨站攻击。\n\n__使用__\n\n在 ajax 请求时，以 `ctoken` 为 name 带上 ctoken 即可。\n\nctoken 从 cookie 中获取\n\n__安全开发者约定__\n\n* `ctx.ctoken` 获取 ctoken 的逻辑。使用者不要调用，安全插件内部使用。\n* `ctx.setCTOKEN()` 设置 ctoken 的逻辑。使用者不要调用，安全插件内部使用。\n* `ctx.assertCTOKEN()` ctoken 校验逻辑。使用者不要调用，安全插件内部使用。\n* `ctx.setCTOKEN()`会将cookie设置到主域名下，主要考虑主域名下其他子域名对应的应用之间的互相调用。例如 A.xx.com 域种了 ctoken,会设置cookie到xx.com域上，在 B.xx.com 域的时候可以利用 ctoken 去请求，在 A 域 jsonp 请求 B 域的时候，B 域也可以验证 ctoken。\n\n可拓展实现。例如 ctoken token 存在什么 cookie，存什么字段等，都可以通过以上两个接口拓展。\n\n#### 配置项\n\n```js\nexports.security = {\n  csrf: {\n    type: 'ctoken',             // 可以是 ctoken / referer / all, 默认为 ctoken\n    useSession: false,          // 如果设为 true，secret 将存储在 session 中\n    ignoreJSON: false,          // 如果设为 true ，将忽略 json 请求\n    cookieName: 'csrfToken',    // csrf 的 token 在 cookie 中存储的 key 名称\n    sessionName: 'csrfToken',   // csrf 的 token 在 session 中存储的 key 名称\n    headerName: 'x-csrf-token', // csrf token 在 header 中的名称\n    bodyName: '_csrf',          // csrf token 在 body 中的名称\n    queryName: '_csrf',         // csrf token 在 query 中的名称\n    rotateWhenInvalid: false,   // csrf invalid 时刷新 token，用于同域名下多个业务 token 可能互相影响的情况\n    refererWhiteList: [],       // referer 白名单\n    supportedRequests: [        // 支持的 url path pattern 和方法，根据配置名单由上至下匹配 url path 正则，建议在自定义时配置 {path: /^\\//, methods:['POST','PATCH','DELETE','PUT','CONNECT']} 为兜底规则\n      {path: /^\\//, methods:['POST','PATCH','DELETE','PUT','CONNECT']},\n    ],\n  },\n}\n```\n\n注意，methods 可以为空， 如果将 supportedRequests 设置为`supportedRequests: [{path: /^\\//, methods:[]}]`, 那么等效于关闭 csrf 防御。\n\n### safe redirect\n\n* `ctx.redirect(url)` 如果不在配置的白名单内，则禁止\n* `ctx.unsafeRedirect(url)` 不建议使用\n\n安全方案覆盖了默认的`ctx.redirect`方法，所有的跳转均会经过安全域名的判断。\n\n用户如果使用`ctx.redirect`方法，需要在应用的配置文件中做如下配置：\n\n```js\nexports.security = {\n  domainWhiteList:['.domain.com'],  // 安全白名单，以.开头\n};\n```\n\n若用户没有配置 `domainWhiteList` 或者 `domainWhiteList` 数组内为空，则默认会对所有跳转请求放行，即等同于`ctx.unsafeRedirect(url)`。同时域名和 url 检查时不区分大小写。\n\n### jsonp\n\n使用 [jsonp-body](https://github.com/node-modules/jsonp-body)，在 egg context 中实现，并不再 egg-security 中。\n\n防御内容：\n\n* callback函数名词最长50个字符限制\n* callback函数名只允许\"[\",\"]\",\"a-zA-Z0123456789_\", \"$\" \".\"，防止一般的 xss，utf-7 xss等攻击\n\n可定义配置：\n\n* callback 默认 `_callback`，可以改名\n* limit - 函数名 length 限制，默认 50\n\n## helper\n\n### .escape()\n\n对字符串进行 xss 过滤，安全性最高的过滤方式。\n\n```js\nconst str = '><script>alert(\"abc\") </script><';\nconsole.log(ctx.helper.escape(str));\n// => &gt;&lt;script&gt;alert(&quot;abc&quot;) &lt;/script&gt;&lt;\n```\n\n在 nunjucks 模板中，默认进行 escape，不需要显式调用。\n\n### .surl()\n\nurl 过滤。\n\n用于在html标签中中要解析 url 的地方（比如 `<a href=\"\"/><img src=\"\"/>`），其他地方不允许使用。\n\n对模板中要输出的变量，加 `helper.surl($value)`。\n\n__特别需要注意的是在需要解析url的地方，surl 外面一定要加上双引号，否则就会导致XSS漏洞。__\n\n不使用 surl\n\n```html\n<a href=\"$value\" />\n```\n\noutput:\n\n```html\n<a href=\"http://www.domain.com<script>\" />\n```\n\n使用 surl\n\n```html\n<a href=\"helper.surl($value)\" />\n```\n\noutput:\n\n```html\n<a href=\"http://www.domain.com&lt;script&gt;\" />\n```\n\n### .sjs()\n\n用于在 js（包括 onload 等 event）中输出变量，会对变量中字符进行 JAVASCRIPT ENCODE，\n将所有非白名单字符转义为 `\\x` 形式，防止xss攻击，也确保在 js 中输出的正确性。\n\n```js\nconst foo = '\"hello\"';\n\n// 未使用 sjs\nconsole.log(`var foo = \"${foo}\";`);\n// => var foo = \"\"hello\"\";\n\n// 使用 sjs\nconsole.log(`var foo = \"${this.helper.sjs(foo)}\";`);\n// => var foo = \"\\\\x22hello\\\\x22\";\n```\n\n### .shtml()\n\n将富文本（包含 html 代码的文本）当成变量直接在模版里面输出时，需要用到 shtml 来处理。\n使用 shtml 可以输出 html 的 tag，同时执行 xss 的过滤动作，过滤掉非法的脚本。\n\n**由于是一个非常复杂的安全处理过程，对服务器处理性能一定影响，如果不是输出 HTML，请勿使用。**\n\n简单示例：\n\n```js\n// js\nconst value = `<a href=\"http://www.domain.com\">google</a><script>evilcode…</script>`;\n\n// 模板\n<html>\n<body>\n  ${helper.shtml($value)}\n</body>\n</html>\n// => <a href=\"http://www.domain.com\">google</a>&lt;script&gt;evilcode…&lt;/script&gt;\n```\n\nshtml 在 [xss](https://github.com/leizongmin/js-xss/) 模块基础上增加了针对域名的过滤。\n\n* [默认规则](https://github.com/leizongmin/js-xss/blob/master/lib/default.js)\n* 自定义过滤项 <http://jsxss.com/zh/options.html>\n\n例如只支持 a 标签，且除了 title 其他属性都过滤掉：\n\n```javascript\nwhiteList: {a: ['title']}\n```\n\noptions:\n\n> `config.helper.shtml.domainWhiteList` 已过时，请使用 `config.security.domainWhiteList` 代替。\n\n注意，shtml 使用了严格的白名单机制，除了过滤掉 xss 风险的字符串外，\n在 [默认规则](https://github.com/leizongmin/js-xss/blob/master/lib/default.js) 外的 tag 和 attr 都会被过滤掉。\n\n例如 html 标签就不在白名单中，\n\n```js\nconst html = '<html></html>';\n\n// html\n${helper.shtml($html)}\n\n// 输出空\n```\n\n常见的 `data-xx` 属性由于不在白名单中，所以都会被过滤。\n\n所以，一定要注意 shtml 的适用场景，一般是针对来自用户的富文本输入，切忌滥用，功能既受到限制，又会影响服务端性能。\n此类场景一般是论坛、评论系统等，即便是论坛等如果不支持 html 内容输入，也不要使用此 helper，直接使用 escape 即可。\n\n### .spath()\n\n如果把输入字符串用作 path 路径，需要使用 spath 进行安全检验。若路径不合法，返回 null。\n\n不合法的路径包括：\n\n* 使用 `..` 的相对路径\n* 使用 `/` 开头的绝对路径\n* 以及以上试图通过 url encode 试图绕过校验的结果字符串\n\n```js\nconst foo = '/usr/local/bin';\nconsole.log(this.helper.spath(foo2));\n// => null\n```\n\n### .sjson()\n\njson转义\n\n在js中输出json，若未做转义，易被利用为xss漏洞。提供此宏做json encode，会遍历json中的key，将value的值中，所有非白名单字符转义为\\x形式，防止xss攻击。同时保持json结构不变。\n若你有模板中输出一个json字符串给js应用的场景，请使用 `${this.helper.sjson(变量名)}`进行转义。\n\n__处理过程较复杂，性能损耗较大，尽量避免使用__\n\n实例:\n\n```js\n  <script>\n    window.locals = ${this.helper.sjson(locals)};\n  </script>\n```\n\n### .cliFilter()\n\n远程命令执行漏洞，用户通过浏览器提交执行命令，由于服务器端没有针对执行函数做过滤，导致可以执行命令，通常可导致入侵服务器。\n\n如果用户可控变量为命令中的参数。则直接使用安全包函数过滤。\n\n修复前：\n\n```js\n\n  cp.exec(\"bash /home/admin/ali-knowledge-graph-backend/initrun.sh \" + port);\n\n```\n\n修复后：\n\n```js\n\n  cp.exec(\"bash /home/admin/ali-knowledge-graph-backend/initrun.sh \" + this.helper.cliFilter(port));\n\n```\n\n如果因为业务需要，需要在参数中添加白名单之外的字符。可以将用户输入按照该字符分割，并使用过滤函数过滤每一段数据。\n\n如果用户可控变量为命令中的命令，则和开发协商修改功能或功能下线。\n\n### .escapeShellArg()\n\nPOSIX shell 命令行参数转义。给字符串增加一对单引号并且能引用或者转码任何已经存在的单引号， 这样以确保能够直接将一个字符串传入 shell 函数，并且还是确保安全的。\n\n如果可以，优先使用 `child_process.execFile()` 或 `child_process.spawn()` 的参数数组。这个 helper 只用于 POSIX shell 命令字符串里的单个参数，不适用于 Windows `cmd.exe` 或 PowerShell 转义。\n\n```js\nconst ip = '127.0.0.1 && cat /etc/passwd'\nconst cmd = 'ping -c 1 ' + this.helper.escapeShellArg(ip);\n\nconsole.log(cmd);\n//ping -c 1 '127.0.0.1 && cat /etc/passwd'\n```\n\n### .escapeShellCmd()\n\n命令行转义，从输入的命令行中删除下列字符: ```#&;`|*?~<>^()[]{}$;'\", 0x0A 和 0xFF```\n\n```js\nconst ip = '127.0.0.1 && cat /etc/passwd'\nconst cmd = 'ping -c 1 ' + this.helper.escapeShellCmd(ip);\n\nconsole.log(cmd);\n//ping -c 1 127.0.0.1  cat /etc/passwd\n```\n\n## Web 安全头\n\n### hsts Strict-Transport-Security\n\n默认开启，如果是 http 站点，需要关闭\n\n* maxAge 默认一年 `365 * 24 * 3600`\n* includeSubdomains 默认 false\n\n### csp\n\n默认关闭。需要开启的话，需要和安全工程师确定开启策略。\n\n* policy 策略\n\n### X-Download-Options:noopen\n\n默认开启，禁用IE下下载框Open按钮，防止 ie 下下载文件默认被打开 xss\n\n### X-Content-Type-Options:nosniff\n\n禁用 IE8 自动嗅探 mime 功能。例如：`text/plain` 却当成 `text/html` 渲染，特别当本站点服务内容未必可信的时候。\n\n### X-Frame-Options\n\n默认 SAMEORIGIN，只允许同域把本页面当作 iframe 嵌入。\n\n* value 默认值 `SAMEORIGIN`\n\n### X-XSS-Protection\n\n* close 默认值false，即设置为 `1; mode=block`\n\n## 其他\n\n* crossdomain.xml robots.txt 支持，默认都不加，系统可自行加，需要咨询项目安全工程师\n* 禁止 trace track 两种类型请求\n\n## License\n\n[MIT](LICENSE)\n\n## Contributors\n\n[![Contributors](https://contrib.rocks/image?repo=eggjs/security)](https://github.com/eggjs/security/graphs/contributors)\n\nMade with [contributors-img](https://contrib.rocks).\n","publish_time":1784126999664,"_cnpm_publish_time":1784126999664,"dist-tags":{"latest":"3.8.1","latest-1":"1.14.0","release-3.x":"3.8.0"}}