@eggjs/security 5.0.0-beta.19 → 5.0.0-beta.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. package/dist/agent.js +1 -1
  2. package/dist/app/extend/agent.d.ts +2 -1
  3. package/dist/app/extend/agent.js +1 -1
  4. package/dist/app/extend/application.d.ts +3 -11
  5. package/dist/app/extend/application.js +2 -30
  6. package/dist/app/extend/context.d.ts +3 -60
  7. package/dist/app/extend/context.js +2 -189
  8. package/dist/app/extend/helper.d.ts +8 -8
  9. package/dist/app/extend/helper.js +11 -1
  10. package/dist/app/extend/response.d.ts +3 -38
  11. package/dist/app/extend/response.js +3 -68
  12. package/dist/app/middleware/securities.js +12 -1
  13. package/dist/app.js +2 -2
  14. package/dist/application-COC0mYEe.js +32 -0
  15. package/dist/application-n5bk2L_z.d.ts +12 -0
  16. package/dist/cliFilter-7BSD8Nc_.js +18 -0
  17. package/dist/cliFilter-DKZxCxSe.d.ts +7 -0
  18. package/dist/config/config.default.d.ts +1 -869
  19. package/dist/config/config.default.js +1 -164
  20. package/dist/config.default-AcwQOAG0.js +166 -0
  21. package/dist/config.default-D8v08Vox.d.ts +870 -0
  22. package/dist/context-C-N1IY85.d.ts +95 -0
  23. package/dist/context-e-QJTKfq.js +191 -0
  24. package/dist/csp-BW5AJd_f.js +46 -0
  25. package/dist/csrf-9aSLHiby.js +33 -0
  26. package/dist/dta-DVAKEpJ3.js +13 -0
  27. package/dist/escape-Dex_Pk9e.d.ts +2 -0
  28. package/dist/escape-p8-cW8c_.js +7 -0
  29. package/dist/escapeShellArg-BnzDicAC.d.ts +4 -0
  30. package/dist/escapeShellArg-C0v1ZeCl.js +7 -0
  31. package/dist/escapeShellCmd-CkAdyhtO.js +15 -0
  32. package/dist/escapeShellCmd-DQZZIHde.d.ts +4 -0
  33. package/dist/helper-DylzfQ_5.js +25 -0
  34. package/dist/hsts-CWMKNTEh.js +19 -0
  35. package/dist/index.d.ts +5 -1
  36. package/dist/index.js +6 -3
  37. package/dist/lib/extend/safe_curl.d.ts +2 -19
  38. package/dist/lib/extend/safe_curl.js +1 -17
  39. package/dist/lib/helper/cliFilter.d.ts +1 -6
  40. package/dist/lib/helper/cliFilter.js +1 -16
  41. package/dist/lib/helper/escape.d.ts +1 -1
  42. package/dist/lib/helper/escape.js +1 -5
  43. package/dist/lib/helper/escapeShellArg.d.ts +1 -3
  44. package/dist/lib/helper/escapeShellArg.js +1 -5
  45. package/dist/lib/helper/escapeShellCmd.d.ts +1 -3
  46. package/dist/lib/helper/escapeShellCmd.js +1 -13
  47. package/dist/lib/helper/index.d.ts +9 -9
  48. package/dist/lib/helper/index.js +11 -23
  49. package/dist/lib/helper/shtml.d.ts +1 -5
  50. package/dist/lib/helper/shtml.js +2 -51
  51. package/dist/lib/helper/sjs.d.ts +1 -6
  52. package/dist/lib/helper/sjs.js +1 -34
  53. package/dist/lib/helper/sjson.d.ts +1 -3
  54. package/dist/lib/helper/sjson.js +2 -30
  55. package/dist/lib/helper/spath.d.ts +1 -6
  56. package/dist/lib/helper/spath.js +1 -14
  57. package/dist/lib/helper/surl.d.ts +1 -5
  58. package/dist/lib/helper/surl.js +1 -23
  59. package/dist/lib/middlewares/csp.d.ts +1 -1
  60. package/dist/lib/middlewares/csp.js +2 -44
  61. package/dist/lib/middlewares/csrf.d.ts +1 -1
  62. package/dist/lib/middlewares/csrf.js +2 -31
  63. package/dist/lib/middlewares/dta.js +2 -11
  64. package/dist/lib/middlewares/hsts.d.ts +1 -1
  65. package/dist/lib/middlewares/hsts.js +2 -17
  66. package/dist/lib/middlewares/index.d.ts +12 -12
  67. package/dist/lib/middlewares/index.js +12 -25
  68. package/dist/lib/middlewares/methodnoallow.js +1 -13
  69. package/dist/lib/middlewares/noopen.d.ts +1 -1
  70. package/dist/lib/middlewares/noopen.js +2 -15
  71. package/dist/lib/middlewares/nosniff.d.ts +1 -1
  72. package/dist/lib/middlewares/nosniff.js +2 -25
  73. package/dist/lib/middlewares/referrerPolicy.d.ts +1 -1
  74. package/dist/lib/middlewares/referrerPolicy.js +2 -29
  75. package/dist/lib/middlewares/xframe.d.ts +1 -1
  76. package/dist/lib/middlewares/xframe.js +2 -16
  77. package/dist/lib/middlewares/xssProtection.d.ts +1 -1
  78. package/dist/lib/middlewares/xssProtection.js +2 -15
  79. package/dist/lib/utils.d.ts +1 -1
  80. package/dist/lib/utils.js +1 -125
  81. package/dist/methodnoallow-BAZONArS.js +15 -0
  82. package/dist/middlewares-CkQjv8t0.js +27 -0
  83. package/dist/noopen-C3jUBwoH.js +17 -0
  84. package/dist/nosniff-CcLkhX2I.js +27 -0
  85. package/dist/referrerPolicy-D4Uafq6c.js +31 -0
  86. package/dist/response-BFnHAJrV.js +69 -0
  87. package/dist/safe_curl-UlViaxoF.js +19 -0
  88. package/dist/safe_curl-mqZZv_YQ.d.ts +20 -0
  89. package/dist/shtml-CAquTzgV.d.ts +6 -0
  90. package/dist/shtml-CgF4kOx-.js +53 -0
  91. package/dist/sjs-Cbmkk5xS.js +36 -0
  92. package/dist/sjs-QZIJYS71.d.ts +7 -0
  93. package/dist/sjson-BetFnVR6.js +32 -0
  94. package/dist/sjson-O-vKJPws.d.ts +4 -0
  95. package/dist/spath-Bu9sy6Kz.js +16 -0
  96. package/dist/spath-DseDPHxf.d.ts +7 -0
  97. package/dist/surl-ClleTea7.js +25 -0
  98. package/dist/surl-JV70X_RZ.d.ts +6 -0
  99. package/dist/types-BZR2U30p.d.ts +38 -0
  100. package/dist/types-DnJpiSJb.js +1 -0
  101. package/dist/types.d.ts +3 -38
  102. package/dist/types.js +2 -0
  103. package/dist/utils-Cajs5P8M.js +127 -0
  104. package/dist/xframe-q9fEZkVI.js +18 -0
  105. package/dist/xssProtection-D5QsHX-e.js +17 -0
  106. package/package.json +5 -5
@@ -1,17 +1,4 @@
1
- import { checkIfIgnore } from "../utils.js";
1
+ import "../../utils-Cajs5P8M.js";
2
+ import { xssProtection_default } from "../../xssProtection-D5QsHX-e.js";
2
3
 
3
- //#region src/lib/middlewares/xssProtection.ts
4
- var xssProtection_default = (options) => {
5
- return async function xssProtection(ctx, next) {
6
- await next();
7
- const opts = {
8
- ...options,
9
- ...ctx.securityOptions.xssProtection
10
- };
11
- if (checkIfIgnore(opts, ctx)) return;
12
- ctx.set("x-xss-protection", opts.value);
13
- };
14
- };
15
-
16
- //#endregion
17
4
  export { xssProtection_default as default };
@@ -1,4 +1,4 @@
1
- import { SecurityConfig } from "../config/config.default.js";
1
+ import { SecurityConfig } from "../config.default-D8v08Vox.js";
2
2
  import { Context } from "egg";
3
3
  import { PathMatchingFun } from "egg-path-matching";
4
4
 
package/dist/lib/utils.js CHANGED
@@ -1,127 +1,3 @@
1
- import { normalize } from "node:path";
2
- import matcher from "matcher";
3
- import IP from "@eggjs/ip";
1
+ import { checkIfIgnore, getCookieDomain, getFromUrl, isSafeDomain, isSafePath, merge, preprocessConfig } from "../utils-Cajs5P8M.js";
4
2
 
5
- //#region src/lib/utils.ts
6
- /**
7
- * Check whether a domain is in the safe domain white list or not.
8
- * @param {String} domain The inputted domain.
9
- * @param {Array<string>} whiteList The white list for domain.
10
- * @return {Boolean} If the `domain` is in the white list, return true; otherwise false.
11
- */
12
- function isSafeDomain(domain, whiteList) {
13
- if (typeof domain !== "string") return false;
14
- domain = domain.toLowerCase();
15
- const hostname = "." + domain;
16
- return whiteList.some((rule) => {
17
- if (rule.includes("*")) return matcher.isMatch(domain, rule);
18
- if (domain === rule) return true;
19
- if (!rule.startsWith(".")) rule = `.${rule}`;
20
- return hostname.endsWith(rule);
21
- });
22
- }
23
- function isSafePath(path, ctx) {
24
- path = "." + path;
25
- if (path.includes("%")) try {
26
- path = decodeURIComponent(path);
27
- } catch {
28
- if (ctx.app.config.env === "local" || ctx.app.config.env === "unittest") ctx.coreLogger.warn("[@eggjs/security: dta global block] : decode file path %j failed.", path);
29
- }
30
- const normalizePath = normalize(path);
31
- return !(normalizePath.startsWith("../") || normalizePath.startsWith("..\\"));
32
- }
33
- function checkIfIgnore(opts, ctx) {
34
- if (!opts.enable) return true;
35
- return !opts.matching?.(ctx);
36
- }
37
- const IP_RE = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
38
- const topDomains = {};
39
- [
40
- ".net.cn",
41
- ".gov.cn",
42
- ".org.cn",
43
- ".com.cn"
44
- ].forEach((item) => {
45
- topDomains[item] = 2 - item.split(".").length;
46
- });
47
- function getCookieDomain(hostname) {
48
- if (IP_RE.test(hostname)) return hostname;
49
- const splits = hostname.split(".");
50
- let index = -2;
51
- if (splits.length >= 4 && splits[splits.length - 3] === "test") index = -3;
52
- let domain = getDomain(splits, index);
53
- if (topDomains[domain]) domain = getDomain(splits, index + topDomains[domain]);
54
- return domain;
55
- }
56
- function getDomain(splits, index) {
57
- return "." + splits.slice(index).join(".");
58
- }
59
- function merge(origin, opts) {
60
- if (!opts) return origin;
61
- const res = {};
62
- const originKeys = Object.keys(origin);
63
- for (let i = 0; i < originKeys.length; i++) {
64
- const key = originKeys[i];
65
- res[key] = origin[key];
66
- }
67
- const keys = Object.keys(opts);
68
- for (let i = 0; i < keys.length; i++) {
69
- const key = keys[i];
70
- res[key] = opts[key];
71
- }
72
- return res;
73
- }
74
- function preprocessConfig(config) {
75
- const ssrf = config.ssrf;
76
- if (ssrf && ssrf.ipBlackList && !ssrf.checkAddress) {
77
- const blackList = ssrf.ipBlackList.map(getContains);
78
- const exceptionList = (ssrf.ipExceptionList || []).map(getContains);
79
- const hostnameExceptionList = ssrf.hostnameExceptionList;
80
- ssrf.checkAddress = (ipAddresses, _family, hostname) => {
81
- if (hostname && hostnameExceptionList) {
82
- if (hostnameExceptionList.includes(hostname)) return true;
83
- }
84
- if (!Array.isArray(ipAddresses)) ipAddresses = [ipAddresses];
85
- for (const ipAddress of ipAddresses) {
86
- let address;
87
- if (typeof ipAddress === "string") address = ipAddress;
88
- else {
89
- if (ipAddress.family === 6) continue;
90
- address = ipAddress.address;
91
- }
92
- for (const exception of exceptionList) if (exception(address)) return true;
93
- for (const contains of blackList) if (contains(address)) return false;
94
- }
95
- return true;
96
- };
97
- }
98
- config.domainWhiteList = config.domainWhiteList || [];
99
- config.domainWhiteList = config.domainWhiteList.map((domain) => domain.toLowerCase());
100
- config.protocolWhiteList = config.protocolWhiteList || [];
101
- config.protocolWhiteList = config.protocolWhiteList.map((protocol) => protocol.toLowerCase());
102
- if (config.csrf && config.csrf.refererWhiteList) config.csrf.refererWhiteList = config.csrf.refererWhiteList.map((ref) => ref.toLowerCase());
103
- const protocolWhiteListSet = new Set(config.protocolWhiteList);
104
- protocolWhiteListSet.add("http");
105
- protocolWhiteListSet.add("https");
106
- protocolWhiteListSet.add("file");
107
- protocolWhiteListSet.add("data");
108
- Object.defineProperty(config, "__protocolWhiteListSet", {
109
- value: protocolWhiteListSet,
110
- enumerable: false
111
- });
112
- }
113
- function getFromUrl(url, prop) {
114
- try {
115
- const parsed = new URL(url);
116
- return Reflect.get(parsed, prop);
117
- } catch {
118
- return null;
119
- }
120
- }
121
- function getContains(ip) {
122
- if (IP.isV4Format(ip) || IP.isV6Format(ip)) return (address) => address === ip;
123
- return IP.cidrSubnet(ip).contains;
124
- }
125
-
126
- //#endregion
127
3
  export { checkIfIgnore, getCookieDomain, getFromUrl, isSafeDomain, isSafePath, merge, preprocessConfig };
@@ -0,0 +1,15 @@
1
+ import { METHODS } from "node:http";
2
+
3
+ //#region src/lib/middlewares/methodnoallow.ts
4
+ const METHODS_NOT_ALLOWED = ["TRACE", "TRACK"];
5
+ const safeHttpMethodsMap = {};
6
+ for (const method of METHODS) if (!METHODS_NOT_ALLOWED.includes(method)) safeHttpMethodsMap[method.toUpperCase()] = true;
7
+ var methodnoallow_default = () => {
8
+ return function notAllow(ctx, next) {
9
+ if (!safeHttpMethodsMap[ctx.method]) ctx.throw(405);
10
+ return next();
11
+ };
12
+ };
13
+
14
+ //#endregion
15
+ export { methodnoallow_default };
@@ -0,0 +1,27 @@
1
+ import { csp_default } from "./csp-BW5AJd_f.js";
2
+ import { csrf_default } from "./csrf-9aSLHiby.js";
3
+ import { dta_default } from "./dta-DVAKEpJ3.js";
4
+ import { hsts_default } from "./hsts-CWMKNTEh.js";
5
+ import { methodnoallow_default } from "./methodnoallow-BAZONArS.js";
6
+ import { noopen_default } from "./noopen-C3jUBwoH.js";
7
+ import { nosniff_default } from "./nosniff-CcLkhX2I.js";
8
+ import { referrerPolicy_default } from "./referrerPolicy-D4Uafq6c.js";
9
+ import { xframe_default } from "./xframe-q9fEZkVI.js";
10
+ import { xssProtection_default } from "./xssProtection-D5QsHX-e.js";
11
+
12
+ //#region src/lib/middlewares/index.ts
13
+ var middlewares_default = {
14
+ csp: csp_default,
15
+ csrf: csrf_default,
16
+ dta: dta_default,
17
+ hsts: hsts_default,
18
+ methodnoallow: methodnoallow_default,
19
+ noopen: noopen_default,
20
+ nosniff: nosniff_default,
21
+ referrerPolicy: referrerPolicy_default,
22
+ xframe: xframe_default,
23
+ xssProtection: xssProtection_default
24
+ };
25
+
26
+ //#endregion
27
+ export { middlewares_default };
@@ -0,0 +1,17 @@
1
+ import { checkIfIgnore } from "./utils-Cajs5P8M.js";
2
+
3
+ //#region src/lib/middlewares/noopen.ts
4
+ var noopen_default = (options) => {
5
+ return async function noopen(ctx, next) {
6
+ await next();
7
+ const opts = {
8
+ ...options,
9
+ ...ctx.securityOptions.noopen
10
+ };
11
+ if (checkIfIgnore(opts, ctx)) return;
12
+ ctx.set("x-download-options", "noopen");
13
+ };
14
+ };
15
+
16
+ //#endregion
17
+ export { noopen_default };
@@ -0,0 +1,27 @@
1
+ import { checkIfIgnore } from "./utils-Cajs5P8M.js";
2
+
3
+ //#region src/lib/middlewares/nosniff.ts
4
+ const RedirectStatus = {
5
+ 300: true,
6
+ 301: true,
7
+ 302: true,
8
+ 303: true,
9
+ 305: true,
10
+ 307: true,
11
+ 308: true
12
+ };
13
+ var nosniff_default = (options) => {
14
+ return async function nosniff(ctx, next) {
15
+ await next();
16
+ if (RedirectStatus[ctx.status]) return;
17
+ const opts = {
18
+ ...options,
19
+ ...ctx.securityOptions.nosniff
20
+ };
21
+ if (checkIfIgnore(opts, ctx)) return;
22
+ ctx.set("x-content-type-options", "nosniff");
23
+ };
24
+ };
25
+
26
+ //#endregion
27
+ export { nosniff_default };
@@ -0,0 +1,31 @@
1
+ import { checkIfIgnore } from "./utils-Cajs5P8M.js";
2
+
3
+ //#region src/lib/middlewares/referrerPolicy.ts
4
+ const ALLOWED_POLICIES_ENUM = [
5
+ "no-referrer",
6
+ "no-referrer-when-downgrade",
7
+ "origin",
8
+ "origin-when-cross-origin",
9
+ "same-origin",
10
+ "strict-origin",
11
+ "strict-origin-when-cross-origin",
12
+ "unsafe-url",
13
+ ""
14
+ ];
15
+ var referrerPolicy_default = (options) => {
16
+ return async function referrerPolicy(ctx, next) {
17
+ await next();
18
+ const opts = {
19
+ ...options,
20
+ ...ctx.securityOptions.refererPolicy,
21
+ ...ctx.securityOptions.referrerPolicy
22
+ };
23
+ if (checkIfIgnore(opts, ctx)) return;
24
+ const policy = opts.value;
25
+ if (!ALLOWED_POLICIES_ENUM.includes(policy)) throw new Error(`"${policy}" is not available.`);
26
+ ctx.set("referrer-policy", policy);
27
+ };
28
+ };
29
+
30
+ //#endregion
31
+ export { referrerPolicy_default };
@@ -0,0 +1,69 @@
1
+ import { Response } from "egg";
2
+
3
+ //#region src/app/extend/response.ts
4
+ const unsafeRedirect = Response.prototype.redirect;
5
+ var SecurityResponse = class extends Response {
6
+ /**
7
+ * This is an unsafe redirection, and we WON'T check if the
8
+ * destination url is safe or not.
9
+ * Please DO NOT use this method unless in some very special cases,
10
+ * otherwise there may be security vulnerabilities.
11
+ *
12
+ * @function Response#unsafeRedirect
13
+ * @param {String} url URL to forward
14
+ * @example
15
+ * ```js
16
+ * ctx.response.unsafeRedirect('http://www.domain.com');
17
+ * ctx.unsafeRedirect('http://www.domain.com');
18
+ * ```
19
+ */
20
+ unsafeRedirect(url, alt) {
21
+ unsafeRedirect.call(this, url, alt);
22
+ }
23
+ /**
24
+ * A safe redirection, and we'll check if the URL is in
25
+ * a safe domain or not.
26
+ * We've overridden the default Koa's implementation by adding a
27
+ * white list as the filter for that.
28
+ *
29
+ * @function Response#redirect
30
+ * @param {String} url URL to forward
31
+ * @example
32
+ * ```js
33
+ * ctx.response.redirect('/login');
34
+ * ctx.redirect('/login');
35
+ * ```
36
+ */
37
+ redirect(url, alt) {
38
+ url = (url || "/").trim();
39
+ if (url[0] === "/" && url[1] === "/") url = "/";
40
+ if (url[0] === "/" && url[1] !== "\\") {
41
+ this.unsafeRedirect(url, alt);
42
+ return;
43
+ }
44
+ let urlObject;
45
+ try {
46
+ urlObject = new URL(url);
47
+ } catch {
48
+ url = "/";
49
+ this.unsafeRedirect(url);
50
+ return;
51
+ }
52
+ const domainWhiteList = this.app.config.security.domainWhiteList;
53
+ if (urlObject.protocol !== "http:" && urlObject.protocol !== "https:") url = "/";
54
+ else if (!urlObject.hostname) url = "/";
55
+ else if (domainWhiteList && domainWhiteList.length !== 0) {
56
+ if (!this.ctx.isSafeDomain(urlObject.hostname)) {
57
+ const message = `a security problem has been detected for url "${url}", redirection is prohibited.`;
58
+ if (process.env.NODE_ENV === "production") {
59
+ this.app.coreLogger.warn("[@eggjs/security/response/redirect] %s", message);
60
+ url = "/";
61
+ } else return this.ctx.throw(500, message);
62
+ }
63
+ }
64
+ this.unsafeRedirect(url);
65
+ }
66
+ };
67
+
68
+ //#endregion
69
+ export { SecurityResponse };
@@ -0,0 +1,19 @@
1
+ //#region src/lib/extend/safe_curl.ts
2
+ const SSRF_HTTPCLIENT = Symbol("SSRF_HTTPCLIENT");
3
+ /**
4
+ * safe curl with ssrf protection
5
+ */
6
+ async function safeCurlForApplication(app, url, options = {}) {
7
+ const ssrfConfig = app.config.security.ssrf;
8
+ if (ssrfConfig?.checkAddress) options.checkAddress = ssrfConfig.checkAddress;
9
+ else app.logger.warn("[@eggjs/security] please configure `config.security.ssrf` first");
10
+ if (ssrfConfig?.checkAddress) {
11
+ let httpClient = app[SSRF_HTTPCLIENT];
12
+ if (!httpClient) httpClient = app[SSRF_HTTPCLIENT] = app.createHttpClient({ checkAddress: ssrfConfig.checkAddress });
13
+ return await httpClient.request(url, options);
14
+ }
15
+ return await app.curl(url, options);
16
+ }
17
+
18
+ //#endregion
19
+ export { safeCurlForApplication };
@@ -0,0 +1,20 @@
1
+ import { SSRFCheckAddressFunction } from "./config.default-D8v08Vox.js";
2
+ import * as egg0 from "egg";
3
+ import { EggApplicationCore } from "egg";
4
+
5
+ //#region src/lib/extend/safe_curl.d.ts
6
+ type HttpClient = EggApplicationCore['HttpClient'];
7
+ type HttpClientParameters = Parameters<HttpClient['prototype']['request']>;
8
+ type HttpClientRequestURL = HttpClientParameters[0];
9
+ type HttpClientOptions = HttpClientParameters[1] & {
10
+ checkAddress?: SSRFCheckAddressFunction;
11
+ };
12
+ type HttpClientResponse<T = any> = Awaited<ReturnType<HttpClient['prototype']['request']>> & {
13
+ data: T;
14
+ };
15
+ /**
16
+ * safe curl with ssrf protection
17
+ */
18
+ declare function safeCurlForApplication<T = any>(app: EggApplicationCore, url: HttpClientRequestURL, options?: HttpClientOptions): Promise<egg0.HttpClientResponse<T>>;
19
+ //#endregion
20
+ export { HttpClientOptions, HttpClientRequestURL, HttpClientResponse, safeCurlForApplication };
@@ -0,0 +1,6 @@
1
+ import { BaseContextClass } from "egg";
2
+
3
+ //#region src/lib/helper/shtml.d.ts
4
+ declare function shtml(this: BaseContextClass, val: string): string;
5
+ //#endregion
6
+ export { shtml };
@@ -0,0 +1,53 @@
1
+ import { getFromUrl, isSafeDomain } from "./utils-Cajs5P8M.js";
2
+ import xss from "xss";
3
+
4
+ //#region src/lib/helper/shtml.ts
5
+ const BUILD_IN_ON_TAG_ATTR = Symbol("buildInOnTagAttr");
6
+ function shtml(val) {
7
+ if (typeof val !== "string") return val;
8
+ const securityOptions = this.ctx.securityOptions;
9
+ const shtmlConfig = {
10
+ ...this.app.config.helper.shtml,
11
+ ...securityOptions.shtml,
12
+ [BUILD_IN_ON_TAG_ATTR]: void 0
13
+ };
14
+ const domainWhiteList = this.app.config.security.domainWhiteList;
15
+ const app = this.app;
16
+ if (!shtmlConfig[BUILD_IN_ON_TAG_ATTR]) {
17
+ shtmlConfig[BUILD_IN_ON_TAG_ATTR] = (_tag, name, value, isWhiteAttr) => {
18
+ if (isWhiteAttr && (name === "href" || name === "src")) {
19
+ if (!value) return;
20
+ value = String(value);
21
+ if (value[0] === "/" || value[0] === "#") return;
22
+ const hostname = getFromUrl(value, "hostname");
23
+ if (!hostname) return;
24
+ if (!isSafeDomain(hostname, domainWhiteList)) if (shtmlConfig.domainWhiteList && shtmlConfig.domainWhiteList.length > 0) {
25
+ app.deprecate("[@eggjs/security/lib/helper/shtml] `config.helper.shtml.domainWhiteList` has been deprecate. Please use `config.security.domainWhiteList` instead.");
26
+ if (!isSafeDomain(hostname, shtmlConfig.domainWhiteList)) return "";
27
+ } else return "";
28
+ }
29
+ };
30
+ if (shtmlConfig.onTagAttr) {
31
+ const customOnTagAttrHandler = shtmlConfig.onTagAttr;
32
+ shtmlConfig.onTagAttr = function(tag, name, value, isWhiteAttr) {
33
+ const result = customOnTagAttrHandler.apply(this, [
34
+ tag,
35
+ name,
36
+ value,
37
+ isWhiteAttr
38
+ ]);
39
+ if (result !== void 0) return result;
40
+ return shtmlConfig[BUILD_IN_ON_TAG_ATTR].apply(this, [
41
+ tag,
42
+ name,
43
+ value,
44
+ isWhiteAttr
45
+ ]);
46
+ };
47
+ } else shtmlConfig.onTagAttr = shtmlConfig[BUILD_IN_ON_TAG_ATTR];
48
+ }
49
+ return xss(val, shtmlConfig);
50
+ }
51
+
52
+ //#endregion
53
+ export { shtml };
@@ -0,0 +1,36 @@
1
+ //#region src/lib/helper/sjs.ts
2
+ /**
3
+ * Escape JavaScript to \xHH format
4
+ */
5
+ const MATCH_VULNERABLE_REGEXP = /[\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]/;
6
+ const BASIC_ALPHABETS = new Set("abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""));
7
+ const map = {
8
+ " ": "\\t",
9
+ "\n": "\\n",
10
+ "\r": "\\r"
11
+ };
12
+ function escapeJavaScript(text) {
13
+ const str = "" + text;
14
+ const match = MATCH_VULNERABLE_REGEXP.exec(str);
15
+ if (!match) return str;
16
+ let res = "";
17
+ let index = 0;
18
+ let lastIndex = 0;
19
+ let ascii;
20
+ for (index = match.index; index < str.length; index++) {
21
+ ascii = str[index];
22
+ if (BASIC_ALPHABETS.has(ascii)) continue;
23
+ else if (map[ascii] === void 0) {
24
+ const code = ascii.charCodeAt(0);
25
+ if (code > 127) continue;
26
+ else map[ascii] = "\\x" + code.toString(16);
27
+ }
28
+ if (lastIndex !== index) res += str.substring(lastIndex, index);
29
+ lastIndex = index + 1;
30
+ res += map[ascii];
31
+ }
32
+ return lastIndex !== index ? res + str.substring(lastIndex, index) : res;
33
+ }
34
+
35
+ //#endregion
36
+ export { escapeJavaScript };
@@ -0,0 +1,7 @@
1
+ //#region src/lib/helper/sjs.d.ts
2
+ /**
3
+ * Escape JavaScript to \xHH format
4
+ */
5
+ declare function escapeJavaScript(text: string): string;
6
+ //#endregion
7
+ export { escapeJavaScript };
@@ -0,0 +1,32 @@
1
+ import { escapeJavaScript } from "./sjs-Cbmkk5xS.js";
2
+
3
+ //#region src/lib/helper/sjson.ts
4
+ /**
5
+ * escape json
6
+ * for output json in script
7
+ */
8
+ function sanitizeKey(obj) {
9
+ if (typeof obj !== "object") return obj;
10
+ if (Array.isArray(obj)) return obj;
11
+ if (obj === null) return null;
12
+ if (typeof obj === "boolean") return obj;
13
+ if (typeof obj === "number") return obj;
14
+ if (Buffer.isBuffer(obj)) return obj.toString();
15
+ for (const k in obj) {
16
+ const escapedK = escapeJavaScript(k);
17
+ if (escapedK !== k) {
18
+ obj[escapedK] = sanitizeKey(obj[k]);
19
+ obj[k] = void 0;
20
+ } else obj[k] = sanitizeKey(obj[k]);
21
+ }
22
+ return obj;
23
+ }
24
+ function jsonEscape(obj) {
25
+ return JSON.stringify(sanitizeKey(obj), (_k, v) => {
26
+ if (typeof v === "string") return escapeJavaScript(v);
27
+ return v;
28
+ });
29
+ }
30
+
31
+ //#endregion
32
+ export { jsonEscape };
@@ -0,0 +1,4 @@
1
+ //#region src/lib/helper/sjson.d.ts
2
+ declare function jsonEscape(obj: any): string;
3
+ //#endregion
4
+ export { jsonEscape };
@@ -0,0 +1,16 @@
1
+ //#region src/lib/helper/spath.ts
2
+ function pathFilter(path) {
3
+ if (typeof path !== "string") return path;
4
+ const pathSource = path;
5
+ while (path.indexOf("%") !== -1) try {
6
+ path = decodeURIComponent(path);
7
+ } catch {
8
+ if (process.env.NODE_ENV !== "production") this.ctx.coreLogger.warn("[@eggjs/security/lib/helper/spath] : decode file path %j failed.", path);
9
+ break;
10
+ }
11
+ if (path.indexOf("..") !== -1 || path[0] === "/") return null;
12
+ return pathSource;
13
+ }
14
+
15
+ //#endregion
16
+ export { pathFilter };
@@ -0,0 +1,7 @@
1
+ import { BaseContextClass } from "egg";
2
+
3
+ //#region src/lib/helper/spath.d.ts
4
+
5
+ declare function pathFilter(this: BaseContextClass, path: string): string | null;
6
+ //#endregion
7
+ export { pathFilter };
@@ -0,0 +1,25 @@
1
+ //#region src/lib/helper/surl.ts
2
+ const escapeMap = {
3
+ "\"": "&quot;",
4
+ "<": "&lt;",
5
+ ">": "&gt;",
6
+ "'": "&#x27;"
7
+ };
8
+ function surl(val) {
9
+ const protocolWhiteListSet = this.app.config.security.__protocolWhiteListSet;
10
+ if (typeof val !== "string") return val;
11
+ if (val[0] !== "/") {
12
+ const arr = val.split("://", 2);
13
+ const protocol = arr.length > 1 ? arr[0].toLowerCase() : "";
14
+ if (protocol === "" || !protocolWhiteListSet.has(protocol)) {
15
+ if (this.app.config.env === "local") this.ctx.coreLogger.warn("[@eggjs/security/surl] url: %j, protocol: %j, protocol is empty or not in white list, convert to empty string", val, protocol);
16
+ return "";
17
+ }
18
+ }
19
+ return val.replace(/["'<>]/g, (ch) => {
20
+ return escapeMap[ch];
21
+ });
22
+ }
23
+
24
+ //#endregion
25
+ export { surl };
@@ -0,0 +1,6 @@
1
+ import { BaseContextClass } from "egg";
2
+
3
+ //#region src/lib/helper/surl.d.ts
4
+ declare function surl(this: BaseContextClass, val: string): string;
5
+ //#endregion
6
+ export { surl };
@@ -0,0 +1,38 @@
1
+ import { SecurityConfig, SecurityHelperConfig } from "./config.default-D8v08Vox.js";
2
+ import { HttpClientOptions, HttpClientRequestURL, HttpClientResponse } from "./safe_curl-mqZZv_YQ.js";
3
+
4
+ //#region src/types.d.ts
5
+ declare module 'egg' {
6
+ interface EggAppConfig {
7
+ /**
8
+ * security options
9
+ * @member Config#security
10
+ */
11
+ security: SecurityConfig;
12
+ helper: SecurityHelperConfig;
13
+ }
14
+ interface Agent {
15
+ safeCurl<T = any>(url: HttpClientRequestURL, options?: HttpClientOptions): Promise<HttpClientResponse<T>>;
16
+ }
17
+ interface Application {
18
+ injectCsrf(html: string): string;
19
+ injectNonce(html: string): string;
20
+ injectHijackingDefense(html: string): string;
21
+ safeCurl<T = any>(url: HttpClientRequestURL, options?: HttpClientOptions): Promise<HttpClientResponse<T>>;
22
+ }
23
+ interface Context {
24
+ get securityOptions(): Partial<SecurityConfig & SecurityHelperConfig>;
25
+ isSafeDomain(domain: string, customWhiteList?: string[]): boolean;
26
+ get nonce(): string;
27
+ get csrf(): string;
28
+ ensureCsrfSecret(rotate?: boolean): void;
29
+ rotateCsrfSecret(): void;
30
+ assertCsrf(): void;
31
+ safeCurl<T = any>(url: HttpClientRequestURL, options?: HttpClientOptions): Promise<HttpClientResponse<T>>;
32
+ unsafeRedirect(url: string, alt?: string): void;
33
+ }
34
+ interface Response {
35
+ unsafeRedirect(url: string, alt?: string): void;
36
+ redirect(url: string, alt?: string): void;
37
+ }
38
+ }
@@ -0,0 +1 @@
1
+ export { };