{"name":"@eggjs/security","version":"5.0.0-beta.27","keywords":["egg","eggPlugin","egg-plugin","security"],"author":{"name":"jtyjty99999"},"license":"MIT","_id":"@eggjs/security@5.0.0-beta.27","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":"akitasummer@outlook.com"}],"homepage":"https://github.com/eggjs/egg/tree/next/plugins/security#readme","bugs":{"url":"https://github.com/eggjs/egg/issues"},"dist":{"shasum":"1a00c684931d0165f6d04b094e51cfc5fb6f8b29","tarball":"http://registry-npm.ywwl.com/@eggjs/security/download/@eggjs/security-5.0.0-beta.27.tgz","fileCount":74,"integrity":"sha512-IT49Fm83Lr9KGzm1zSFzrGEt0JcgztYRTZ+OdhN8gAANVp7GYZDv/QGvT23ePOT1kzjTmHXCKhDrvQiJIqSDyw==","signatures":[{"sig":"MEYCIQCvrvrUM3F1pqOy+26tZLML0qVpicTTrvUlLo+KX5GjCAIhANjmqCB9R1sSyclJgJRoPsoOUl96zsQ1w+XMMeyNw1AP","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"attestations":{"url":"https://registry.npmjs.org/-/npm/v1/attestations/@eggjs%2fsecurity@5.0.0-beta.27","provenance":{"predicateType":"https://slsa.dev/provenance/v1"}},"unpackedSize":221419,"size":49621,"noattachment":false,"key":"/@eggjs/security/-/@eggjs/security-5.0.0-beta.27.tgz"},"main":"./dist/index.js","type":"module","_from":"file:eggjs-security-5.0.0-beta.27.tgz","types":"./dist/index.d.ts","module":"./dist/index.js","engines":{"node":">= 22.18.0"},"exports":{".":"./dist/index.js","./app":"./dist/app.js","./agent":"./dist/agent.js","./types":"./dist/types.js","./lib/utils":"./dist/lib/utils.js","./lib/helper":"./dist/lib/helper/index.js","./package.json":"./package.json","./lib/helper/sjs":"./dist/lib/helper/sjs.js","./lib/helper/surl":"./dist/lib/helper/surl.js","./lib/middlewares":"./dist/lib/middlewares/index.js","./app/extend/agent":"./dist/app/extend/agent.js","./lib/helper/shtml":"./dist/lib/helper/shtml.js","./lib/helper/sjson":"./dist/lib/helper/sjson.js","./lib/helper/spath":"./dist/lib/helper/spath.js","./app/extend/helper":"./dist/app/extend/helper.js","./lib/helper/escape":"./dist/lib/helper/escape.js","./app/extend/context":"./dist/app/extend/context.js","./app/extend/response":"./dist/app/extend/response.js","./config/config.local":"./dist/config/config.local.js","./lib/middlewares/csp":"./dist/lib/middlewares/csp.js","./lib/middlewares/dta":"./dist/lib/middlewares/dta.js","./lib/extend/safe_curl":"./dist/lib/extend/safe_curl.js","./lib/helper/cliFilter":"./dist/lib/helper/cliFilter.js","./lib/middlewares/csrf":"./dist/lib/middlewares/csrf.js","./lib/middlewares/hsts":"./dist/lib/middlewares/hsts.js","./config/config.default":"./dist/config/config.default.js","./app/extend/application":"./dist/app/extend/application.js","./lib/middlewares/noopen":"./dist/lib/middlewares/noopen.js","./lib/middlewares/xframe":"./dist/lib/middlewares/xframe.js","./lib/middlewares/nosniff":"./dist/lib/middlewares/nosniff.js","./app/middleware/securities":"./dist/app/middleware/securities.js","./lib/helper/escapeShellArg":"./dist/lib/helper/escapeShellArg.js","./lib/helper/escapeShellCmd":"./dist/lib/helper/escapeShellCmd.js","./lib/middlewares/methodnoallow":"./dist/lib/middlewares/methodnoallow.js","./lib/middlewares/xssProtection":"./dist/lib/middlewares/xssProtection.js","./lib/middlewares/referrerPolicy":"./dist/lib/middlewares/referrerPolicy.js"},"scripts":{"lint":"oxlint --type-aware","test":"npm run lint:fix && vitest","build":"tsdown && rimraf dist *.tsbuildinfo && tsc -p tsconfig.build.json","lint:fix":"npm run lint -- --fix","typecheck":"tsc --noEmit"},"_npmUser":{"name":"GitHub Actions","email":"npm-oidc-no-reply@github.com","trustedPublisher":{"id":"github","oidcConfigId":"oidc:207521cc-6822-4b67-802a-f98c8eab637b"}},"_resolved":"/tmp/46ad70714ff39de98084c0251d4aa63c/eggjs-security-5.0.0-beta.27.tgz","eggPlugin":{"name":"security","optionalDependencies":["session"]},"_integrity":"sha512-IT49Fm83Lr9KGzm1zSFzrGEt0JcgztYRTZ+OdhN8gAANVp7GYZDv/QGvT23ePOT1kzjTmHXCKhDrvQiJIqSDyw==","repository":{"url":"git+https://github.com/eggjs/egg.git","type":"git","directory":"plugins/security"},"_npmVersion":"11.6.1","description":"security plugin in egg framework","directories":{},"_nodeVersion":"22.20.0","dependencies":{"xss":"^1.0.15","zod":"^3.24.1","csrf":"^3.1.0","extend":"^3.0.2","nanoid":"^5.0.0","matcher":"^4.0.0","type-is":"^2.0.0","@eggjs/ip":"^2.1.0","escape-html":"^1.0.3","koa-compose":"^4.1.0","egg-path-matching":"^2.0.0"},"publishConfig":{"access":"public"},"_hasShrinkwrap":false,"readmeFilename":"README.zh-CN.md","devDependencies":{"spy":"^1.0.0","tsdown":"^0.15.4","vitest":"4.0.0-beta.16","benchmark":"^2.1.4","typescript":"^5.9.3","@eggjs/mock":"7.0.0-beta.27","@types/node":"^24.6.2","@types/mocha":"^10.0.10","@types/extend":"^3.0.4","@types/type-is":"^1.6.6","@eggjs/tsconfig":"3.1.0-beta.27","@eggjs/supertest":"9.0.0-beta.27","egg-view-nunjucks":"^2.3.0","@types/escape-html":"^1.0.4","@types/koa-compose":"^3.2.8","beautify-benchmark":"^0.2.4"},"peerDependencies":{"egg":"4.1.0-beta.27"},"_npmOperationalInternal":{"tmp":"tmp/security_5.0.0-beta.27_1759808425599_0.44973451675414866","host":"s3://npm-registry-packages-npm-production"},"readme":"# @eggjs/security\n\n[![NPM version][npm-image]][npm-url]\n[![Known Vulnerabilities][snyk-image]][snyk-url]\n[![npm download][download-image]][download-url]\n[![Node.js Version](https://img.shields.io/node/v/eggjs/security.svg?style=flat)](https://nodejs.org/en/download/)\n[![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square)](https://makeapullrequest.com)\n![CodeRabbit Pull Request Reviews](https://img.shields.io/coderabbit/prs/github/eggjs/security)\n\n[npm-image]: https://img.shields.io/npm/v/@eggjs/security.svg?style=flat-square\n[npm-url]: https://npmjs.org/package/@eggjs/security\n[snyk-image]: https://snyk.io/test/npm/@eggjs/security/badge.svg?style=flat-square\n[snyk-url]: https://snyk.io/test/npm/@eggjs/security\n[download-image]: https://img.shields.io/npm/dm/@eggjs/security.svg?style=flat-square\n[download-url]: https://npmjs.org/package/@eggjs/security\n\negg 内置的安全插件\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如果需要针对某一路径忽略某安全选项，则配置 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**注意：如果存在 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\" /> 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: [\n      // 支持的 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>${helper.shtml($value)}</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: {\n  a: ['title'];\n}\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>window.locals = ${this.helper.sjson(locals)};</script>\n```\n\n### .cliFilter()\n\n远程命令执行漏洞，用户通过浏览器提交执行命令，由于服务器端没有针对执行函数做过滤，导致可以执行命令，通常可导致入侵服务器。\n\n如果用户可控变量为命令中的参数。则直接使用安全包函数过滤。\n\n修复前：\n\n```js\ncp.exec('bash /home/admin/ali-knowledge-graph-backend/initrun.sh ' + port);\n```\n\n修复后：\n\n```js\ncp.exec('bash /home/admin/ali-knowledge-graph-backend/initrun.sh ' + this.helper.cliFilter(port));\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/egg)](https://github.com/eggjs/egg/graphs/contributors)\n\nMade with [contributors-img](https://contrib.rocks).\n","publish_time":1759808425795,"_cnpm_publish_time":1759808425795,"dist-tags":{"beta":"5.0.2-beta.27","latest":"5.1.0","rc":"5.0.2-rc.1"}}