@aomex/csrf 0.0.0-stage → 4.1.1-alpha.be6dbd1.0
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.
- package/LICENSE +21 -0
- package/README.md +2 -2
- package/dist/index.d.ts +42 -0
- package/dist/index.js +80 -0
- package/dist/index.js.map +1 -0
- package/package.json +37 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2023-2024 geekact
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @aomex/csrf
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
文档:https://aomex.js.org
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { CookieSerializeOptions, WebContext, WebMiddleware } from "@aomex/web";
|
|
2
|
+
export declare namespace Csrf {
|
|
3
|
+
type CookieOptions = Omit<CookieSerializeOptions, 'encode' | 'httpOnly'> & {
|
|
4
|
+
/**
|
|
5
|
+
* Cookie 名。默认:`csrfToken`
|
|
6
|
+
*
|
|
7
|
+
* 该 Cookie 必须可被前端 JS 读取(强制 `HttpOnly=false`),以便写入请求头与 Cookie 做双提交校验。
|
|
8
|
+
*/
|
|
9
|
+
name?: string;
|
|
10
|
+
};
|
|
11
|
+
type Options = {
|
|
12
|
+
/**
|
|
13
|
+
* CSRF Cookie 配置。默认名 `csrfToken`;强制 `httpOnly: false`
|
|
14
|
+
*/
|
|
15
|
+
cookie?: CookieOptions;
|
|
16
|
+
/**
|
|
17
|
+
* 客户端提交 token 的请求头名。默认:`x-csrf-token`
|
|
18
|
+
*/
|
|
19
|
+
headerName?: string;
|
|
20
|
+
/**
|
|
21
|
+
* 跳过 CSRF 校验的 HTTP 方法(大小写不敏感)。默认:`GET`、`HEAD`、`OPTIONS`
|
|
22
|
+
*/
|
|
23
|
+
ignoreMethods?: readonly string[];
|
|
24
|
+
/**
|
|
25
|
+
* 按请求跳过校验(如健康检查、外部 webhook)。返回 `true` 时跳过
|
|
26
|
+
*/
|
|
27
|
+
ignore?: (ctx: WebContext) => boolean | Promise<boolean>;
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* CSRF 防护(双提交 Cookie):签发可读 CSRF Cookie,非安全方法校验请求头与 Cookie 一致。
|
|
32
|
+
* 只读 Header + Cookie,不接触请求体。
|
|
33
|
+
*
|
|
34
|
+
* ```ts
|
|
35
|
+
* app.mount([csrf()]);
|
|
36
|
+
* // 前端从 Cookie `csrfToken` 读取,写入请求头 `x-csrf-token`
|
|
37
|
+
* // 服务端可通过 `ctx.csrfToken` 取当前 token
|
|
38
|
+
* ```
|
|
39
|
+
*/
|
|
40
|
+
export declare const csrf: (options?: Csrf.Options) => WebMiddleware<{
|
|
41
|
+
readonly csrfToken: string;
|
|
42
|
+
}>;
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { randomBytes, timingSafeEqual } from "node:crypto";
|
|
2
|
+
import { I18n, createI18n, middleware } from "@aomex/common";
|
|
3
|
+
import { HttpError } from "@aomex/web";
|
|
4
|
+
// src/i18n/locales/zh-cn.ts
|
|
5
|
+
const zh = I18n.define({ invalid_csrf_token: "CSRF 校验失败" });
|
|
6
|
+
// src/i18n/locales/en-us.ts
|
|
7
|
+
const en = I18n.satisfies(zh).define({ invalid_csrf_token: "CSRF token validation failed" });
|
|
8
|
+
// src/i18n/index.ts
|
|
9
|
+
const i18n = createI18n({
|
|
10
|
+
zh,
|
|
11
|
+
en,
|
|
12
|
+
load: (file) => import(new URL(`./locales/${file}.js`, import.meta.url).href)
|
|
13
|
+
});
|
|
14
|
+
// src/index.ts
|
|
15
|
+
/** Cookie / Header 中 token 允许的字符集(与 `base64url` 一致) */
|
|
16
|
+
const TOKEN_PATTERN = /^[A-Za-z0-9_-]+$/;
|
|
17
|
+
/** `randomBytes(32).toString('base64url')` 的固定长度 */
|
|
18
|
+
const TOKEN_LENGTH = 43;
|
|
19
|
+
/**
|
|
20
|
+
* CSRF 防护(双提交 Cookie):签发可读 CSRF Cookie,非安全方法校验请求头与 Cookie 一致。
|
|
21
|
+
* 只读 Header + Cookie,不接触请求体。
|
|
22
|
+
*
|
|
23
|
+
* ```ts
|
|
24
|
+
* app.mount([csrf()]);
|
|
25
|
+
* // 前端从 Cookie `csrfToken` 读取,写入请求头 `x-csrf-token`
|
|
26
|
+
* // 服务端可通过 `ctx.csrfToken` 取当前 token
|
|
27
|
+
* ```
|
|
28
|
+
*/
|
|
29
|
+
const csrf = (options = {}) => {
|
|
30
|
+
const cookieName = options.cookie?.name || "csrfToken";
|
|
31
|
+
const headerName = (options.headerName || "x-csrf-token").toLowerCase();
|
|
32
|
+
const ignoreMethods = new Set((options.ignoreMethods ?? [
|
|
33
|
+
"GET",
|
|
34
|
+
"HEAD",
|
|
35
|
+
"OPTIONS"
|
|
36
|
+
]).map((m) => m.toUpperCase()));
|
|
37
|
+
const { name: _name, ...cookieAttrs } = options.cookie ?? {};
|
|
38
|
+
return middleware.web({ fn: async (ctx, next) => {
|
|
39
|
+
let token = readCookieToken(ctx, cookieName);
|
|
40
|
+
if (!token) {
|
|
41
|
+
token = randomBytes(32).toString("base64url");
|
|
42
|
+
ctx.response.setCookie(cookieName, token, {
|
|
43
|
+
...cookieAttrs,
|
|
44
|
+
httpOnly: false
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
ctx.csrfToken = token;
|
|
48
|
+
if (ignoreMethods.has(ctx.request.method.toUpperCase())) return next();
|
|
49
|
+
if (options.ignore && await options.ignore(ctx)) return next();
|
|
50
|
+
const submitted = readHeaderToken(ctx, headerName);
|
|
51
|
+
if (!isValidToken(submitted) || !isSameToken(submitted, token)) throwInvalid(ctx);
|
|
52
|
+
return next();
|
|
53
|
+
} });
|
|
54
|
+
};
|
|
55
|
+
function isValidToken(value) {
|
|
56
|
+
return typeof value === "string" && value.length === TOKEN_LENGTH && TOKEN_PATTERN.test(value);
|
|
57
|
+
}
|
|
58
|
+
function readCookieToken(ctx, name) {
|
|
59
|
+
const value = ctx.request.cookies[name];
|
|
60
|
+
if (typeof value !== "string") return false;
|
|
61
|
+
const token = value.trim();
|
|
62
|
+
return isValidToken(token) ? token : false;
|
|
63
|
+
}
|
|
64
|
+
function readHeaderToken(ctx, headerName) {
|
|
65
|
+
const raw = ctx.request.headers[headerName];
|
|
66
|
+
if (typeof raw !== "string") return void 0;
|
|
67
|
+
return raw.trim() || void 0;
|
|
68
|
+
}
|
|
69
|
+
/** 调用方须先经 `isValidToken`,两侧长度已对齐 */
|
|
70
|
+
function isSameToken(a, b) {
|
|
71
|
+
return timingSafeEqual(Buffer.from(a), Buffer.from(b));
|
|
72
|
+
}
|
|
73
|
+
/** onError / format-error 会清空已写报头;刚签发的 `Set-Cookie` 挂到错误上带回,便于客户端拿到 token 后重试 */
|
|
74
|
+
function throwInvalid(ctx) {
|
|
75
|
+
const setCookie = ctx.response.getHeader("Set-Cookie");
|
|
76
|
+
throw new HttpError(403, i18n.t("invalid_csrf_token"), { ...setCookie ? { headers: { "Set-Cookie": setCookie } } : null });
|
|
77
|
+
}
|
|
78
|
+
export { csrf };
|
|
79
|
+
|
|
80
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../src/i18n/locales/zh-cn.ts","../src/i18n/locales/en-us.ts","../src/i18n/index.ts","../src/index.ts"],"sourcesContent":["import { I18n } from '@aomex/common';\n\nexport const zh = I18n.define({\n invalid_csrf_token: 'CSRF 校验失败',\n});\n","import { I18n } from '@aomex/common';\nimport { zh } from './zh-cn';\n\nexport const en = I18n.satisfies(zh).define({\n invalid_csrf_token: 'CSRF token validation failed',\n});\n","import { createI18n } from '@aomex/common';\nimport { zh } from './locales/zh-cn';\nimport { en } from './locales/en-us';\n\nexport const i18n = createI18n({\n zh,\n en,\n load: (file) => import(new URL(`./locales/${file}.js`, import.meta.url).href),\n});\n","import { randomBytes, timingSafeEqual } from 'node:crypto';\nimport { middleware } from '@aomex/common';\nimport {\n HttpError,\n type CookieSerializeOptions,\n type WebContext,\n type WebMiddleware,\n} from '@aomex/web';\nimport { i18n } from './i18n';\n\n/** Cookie / Header 中 token 允许的字符集(与 `base64url` 一致) */\nconst TOKEN_PATTERN = /^[A-Za-z0-9_-]+$/;\n/** `randomBytes(32).toString('base64url')` 的固定长度 */\nconst TOKEN_LENGTH = 43;\n\nexport namespace Csrf {\n export type CookieOptions = Omit<CookieSerializeOptions, 'encode' | 'httpOnly'> & {\n /**\n * Cookie 名。默认:`csrfToken`\n *\n * 该 Cookie 必须可被前端 JS 读取(强制 `HttpOnly=false`),以便写入请求头与 Cookie 做双提交校验。\n */\n name?: string;\n };\n\n export type Options = {\n /**\n * CSRF Cookie 配置。默认名 `csrfToken`;强制 `httpOnly: false`\n */\n cookie?: CookieOptions;\n /**\n * 客户端提交 token 的请求头名。默认:`x-csrf-token`\n */\n headerName?: string;\n /**\n * 跳过 CSRF 校验的 HTTP 方法(大小写不敏感)。默认:`GET`、`HEAD`、`OPTIONS`\n */\n ignoreMethods?: readonly string[];\n /**\n * 按请求跳过校验(如健康检查、外部 webhook)。返回 `true` 时跳过\n */\n ignore?: (ctx: WebContext) => boolean | Promise<boolean>;\n };\n}\n\n/**\n * CSRF 防护(双提交 Cookie):签发可读 CSRF Cookie,非安全方法校验请求头与 Cookie 一致。\n * 只读 Header + Cookie,不接触请求体。\n *\n * ```ts\n * app.mount([csrf()]);\n * // 前端从 Cookie `csrfToken` 读取,写入请求头 `x-csrf-token`\n * // 服务端可通过 `ctx.csrfToken` 取当前 token\n * ```\n */\nexport const csrf = (\n options: Csrf.Options = {},\n): WebMiddleware<{ readonly csrfToken: string }> => {\n const cookieName = options.cookie?.name || 'csrfToken';\n const headerName = (options.headerName || 'x-csrf-token').toLowerCase();\n const ignoreMethods = new Set(\n (options.ignoreMethods ?? ['GET', 'HEAD', 'OPTIONS']).map((m) => m.toUpperCase()),\n );\n const { name: _name, ...cookieAttrs } = options.cookie ?? {};\n\n return middleware.web({\n fn: async (ctx, next) => {\n let token = readCookieToken(ctx, cookieName);\n if (!token) {\n token = randomBytes(32).toString('base64url');\n ctx.response.setCookie(cookieName, token, {\n ...cookieAttrs,\n // 双提交要求前端可读;覆盖 setCookie 默认的 httpOnly: true\n httpOnly: false,\n });\n }\n ctx.csrfToken = token;\n\n if (ignoreMethods.has(ctx.request.method.toUpperCase())) {\n return next();\n }\n if (options.ignore && (await options.ignore(ctx))) {\n return next();\n }\n\n const submitted = readHeaderToken(ctx, headerName);\n if (!isValidToken(submitted) || !isSameToken(submitted, token)) {\n throwInvalid(ctx);\n }\n\n return next();\n },\n });\n};\n\nfunction isValidToken(value: string | undefined): value is string {\n return (\n typeof value === 'string' &&\n value.length === TOKEN_LENGTH &&\n TOKEN_PATTERN.test(value)\n );\n}\n\nfunction readCookieToken(ctx: WebContext, name: string): string | false {\n const value = ctx.request.cookies[name];\n if (typeof value !== 'string') return false;\n const token = value.trim();\n return isValidToken(token) ? token : false;\n}\n\nfunction readHeaderToken(ctx: WebContext, headerName: string): string | undefined {\n const raw = ctx.request.headers[headerName];\n if (typeof raw !== 'string') return undefined;\n const token = raw.trim();\n return token || undefined;\n}\n\n/** 调用方须先经 `isValidToken`,两侧长度已对齐 */\nfunction isSameToken(a: string, b: string): boolean {\n return timingSafeEqual(Buffer.from(a), Buffer.from(b));\n}\n\n/** onError / format-error 会清空已写报头;刚签发的 `Set-Cookie` 挂到错误上带回,便于客户端拿到 token 后重试 */\nfunction throwInvalid(ctx: WebContext): never {\n const setCookie = ctx.response.getHeader('Set-Cookie');\n throw new HttpError(403, i18n.t('invalid_csrf_token'), {\n ...(setCookie ? { headers: { 'Set-Cookie': setCookie } } : null),\n });\n}\n"],"mappings":";;;;AAEA,MAAa,KAAK,KAAK,OAAO,EAC5B,oBAAoB,YACtB,CAAC;;ACDD,MAAa,KAAK,KAAK,UAAU,EAAE,CAAC,CAAC,OAAO,EAC1C,oBAAoB,+BACtB,CAAC;;ACDD,MAAa,OAAO,WAAW;CAC7B;CACA;CACA,OAAO,SAAS,OAAO,IAAI,IAAI,aAAa,KAAK,MAAM,YAAY,GAAG,CAAC,CAAC;AAC1E,CAAC;;;ACGD,MAAM,gBAAgB;;AAEtB,MAAM,eAAe;;;;;;;;;;;AA0CrB,MAAa,QACX,UAAwB,CAAC,MACyB;CAClD,MAAM,aAAa,QAAQ,QAAQ,QAAQ;CAC3C,MAAM,cAAc,QAAQ,cAAc,eAAA,CAAgB,YAAY;CACtE,MAAM,gBAAgB,IAAI,KACvB,QAAQ,iBAAi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K,CAAC,CAAC;AACvD;;AAGA,SAAS,aAAa,KAAwB;CAC5C,MAAM,YAAY,IAAI,SAAS,UAAU,YAAY;CACrD,MAAM,IAAI,UAAU,KAAK,KAAK,EAAE,oBAAoB,GAAG,EACrD,GAAI,YAAY,EAAE,SAAS,EAAE,cAAc,UAAU,EAAE,IAAI,KAC7D,CAAC;AACH"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,40 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aomex/csrf",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "4.1.1-alpha.be6dbd1.0",
|
|
4
|
+
"description": "CSRF 防护",
|
|
5
|
+
"repository": {
|
|
6
|
+
"type": "git",
|
|
7
|
+
"url": "git@github.com:aomex/aomex.git"
|
|
8
|
+
},
|
|
9
|
+
"homepage": "https://aomex.js.org",
|
|
10
|
+
"license": "MIT",
|
|
11
|
+
"type": "module",
|
|
12
|
+
"sideEffects": false,
|
|
13
|
+
"types": "dist/index.d.ts",
|
|
14
|
+
"exports": {
|
|
15
|
+
".": {
|
|
16
|
+
"types": "./dist/index.d.ts",
|
|
17
|
+
"import": "./dist/index.js"
|
|
18
|
+
},
|
|
19
|
+
"./package.json": "./package.json"
|
|
20
|
+
},
|
|
21
|
+
"files": [
|
|
22
|
+
"dist",
|
|
23
|
+
"LICENSE",
|
|
24
|
+
"package.json",
|
|
25
|
+
"README.md",
|
|
26
|
+
"CHANGELOG.md"
|
|
27
|
+
],
|
|
28
|
+
"publishConfig": {
|
|
29
|
+
"access": "public"
|
|
30
|
+
},
|
|
31
|
+
"peerDependencies": {
|
|
32
|
+
"@aomex/common": "^4.0.0",
|
|
33
|
+
"@aomex/web": "^4.0.0"
|
|
34
|
+
},
|
|
35
|
+
"devDependencies": {
|
|
36
|
+
"@aomex/common": "4.1.1-alpha.be6dbd1.0",
|
|
37
|
+
"@aomex/web": "4.1.1-alpha.be6dbd1.0"
|
|
38
|
+
},
|
|
39
|
+
"scripts": {}
|
|
6
40
|
}
|