@aomex/abuse 0.0.0-stage → 4.3.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/CHANGELOG.md ADDED
@@ -0,0 +1,10 @@
1
+ # Change Log
2
+
3
+ All notable changes to this project will be documented in this file.
4
+ See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
5
+
6
+ # [4.3.0](https://github.com/aomex/aomex/compare/v4.2.0...v4.3.0) (2026-11-21)
7
+
8
+ ### Features
9
+
10
+ * **abuse:** 新增滥用计数与封禁中间件 ([6e0c8ef](https://github.com/aomex/aomex/commit/6e0c8ef7a151b23087591fea2d8ec1ec0bc9642f))
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
- # Temporary Holding Version
1
+ # @aomex/abuse
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ 文档:https://aomex.js.org
@@ -0,0 +1,211 @@
1
+ import { CacheAdapter } from "@aomex/cache";
2
+ import { DurationInput } from "@aomex/common";
3
+ import { HttpError, WebContext, WebMiddleware } from "@aomex/web";
4
+ /** 用户主体标识。存储前统一 `String(id)` */
5
+ type AbuseId = string | number;
6
+ /** 路径匹配:精确路径、简单 glob,或正则(正则会匹配 pathname+search) */
7
+ type AbusePathMatcher = string | RegExp;
8
+ /**
9
+ * 蜜罐路径:命中后按 IP 计数,满额封 IP。
10
+ */
11
+ type AbuseHoneypotStrategy = {
12
+ strategy: 'honeypot';
13
+ /**
14
+ * 蜜罐路径(不能为空)。字符串支持 `*` / `**`;正则匹配 `pathname + search`
15
+ */
16
+ paths: readonly AbusePathMatcher[];
17
+ /**
18
+ * 仅统计匹配方法的响应。未配置则不限方法
19
+ */
20
+ methods?: readonly string[];
21
+ /** 窗口内累计次数上限,须为正整数 */
22
+ limit: number;
23
+ /**
24
+ * 固定计数窗口(须为正数时长)。自该 IP 首次命中起算,窗口内累计次数;到期后计数清零重开
25
+ */
26
+ window: DurationInput;
27
+ /**
28
+ * 撞线后封禁 IP 的时长(须为正数)
29
+ */
30
+ blockFor: DurationInput;
31
+ };
32
+ /**
33
+ * 按响应状态码累计。满额后封 IP。
34
+ */
35
+ type AbuseHttpErrorStrategy = {
36
+ strategy: 'http-error';
37
+ /**
38
+ * 计入的 HTTP 状态码(不能为空;同一策略内混合累计)
39
+ */
40
+ statusCodes: readonly number[];
41
+ /**
42
+ * 仅统计匹配路径的响应。字符串支持 `*` / `**`;正则匹配 `pathname + search`。未配置则不限路径
43
+ */
44
+ paths?: readonly AbusePathMatcher[];
45
+ /**
46
+ * 仅统计匹配方法的响应。未配置则不限方法
47
+ */
48
+ methods?: readonly string[];
49
+ /**
50
+ * 窗口内累计次数上限,达到后封禁该 IP;须为正整数
51
+ */
52
+ limit: number;
53
+ /**
54
+ * 固定计数窗口(须为正数时长)。自该 IP 首次命中起算,窗口内累计次数;到期后计数清零重开
55
+ */
56
+ window: DurationInput;
57
+ /**
58
+ * 撞线后封禁 IP 的时长(须为正数)
59
+ */
60
+ blockFor: DurationInput;
61
+ };
62
+ /**
63
+ * 业务上报的用户滥用。只吃返回值上的 `userAbuse()`;满额触发 `onBanUser`,不自动封 IP。
64
+ */
65
+ type AbuseUserAbuseStrategy<Reason extends string | number = string | number> = {
66
+ strategy: 'user-abuse';
67
+ /**
68
+ * 滥用分桶标识(`string | number`),与 `userAbuse(id, reason)` 的第二参对应;存储前统一 `String(reason)`
69
+ */
70
+ reason: Reason;
71
+ /**
72
+ * 窗口内累计次数上限,达到后触发 `onBanUser`;须为正整数
73
+ */
74
+ limit: number;
75
+ /**
76
+ * 固定计数窗口(须为正数时长)。自该用户该 reason 首次上报起算,窗口内累计次数;到期后计数清零重开
77
+ */
78
+ window: DurationInput;
79
+ /**
80
+ * 建议封禁时长(须为正数),经 `onBanUser` 传出;包内不写用户库
81
+ */
82
+ banFor?: DurationInput;
83
+ };
84
+ /**
85
+ * 业务上报的 IP 滥用(如 logout token 未命中仍返回 204)。只吃 `ipAbuse()`;满额封 IP。
86
+ */
87
+ type AbuseIpAbuseStrategy<Reason extends string | number = string | number> = {
88
+ strategy: 'ip-abuse';
89
+ /**
90
+ * 滥用分桶标识,与 `ipAbuse(ip, reason)` 的第二参对应;存储前统一 `String(reason)`
91
+ */
92
+ reason: Reason;
93
+ /**
94
+ * 窗口内累计次数上限,达到后封禁该 IP;须为正整数
95
+ */
96
+ limit: number;
97
+ /**
98
+ * 固定计数窗口(须为正数时长)。自该 IP 该 reason 首次上报起算,窗口内累计次数;到期后计数清零重开
99
+ */
100
+ window: DurationInput;
101
+ /**
102
+ * 撞线后封禁 IP 的时长(须为正数)
103
+ */
104
+ blockFor: DurationInput;
105
+ };
106
+ type AbuseStrategy = AbuseHoneypotStrategy | AbuseHttpErrorStrategy | AbuseUserAbuseStrategy | AbuseIpAbuseStrategy;
107
+ type InferUserAbuseReasons<S extends readonly AbuseStrategy[]> = Extract<S[number], {
108
+ strategy: 'user-abuse';
109
+ }> extends {
110
+ reason: infer R;
111
+ } ? R extends string | number ? R : never : never;
112
+ type InferIpAbuseReasons<S extends readonly AbuseStrategy[]> = Extract<S[number], {
113
+ strategy: 'ip-abuse';
114
+ }> extends {
115
+ reason: infer R;
116
+ } ? R extends string | number ? R : never : never;
117
+ /** `onBlockIP` 的 reason */
118
+ type AbuseBlockStrategy = 'honeypot' | 'http-error' | 'ip-abuse' | 'manual';
119
+ type AbuseApi<UserAbuseReason extends string | number = string | number, IpAbuseReason extends string | number = string | number> = {
120
+ /**
121
+ * 上报一次用户滥用(按 reason 分桶计数)。满额只回调 `onBanUser`,需业务自行写库封用户
122
+ */
123
+ userAbuse(id: AbuseId, reason: UserAbuseReason): Promise<void>;
124
+ /**
125
+ * 上报一次 IP 滥用(按 reason 分桶计数)。满额封 IP 并触发 `onBlockIP`
126
+ *
127
+ * @example logout 时 token 未命中 Redis 仍返回 204,可 `ipAbuse(ctx.request.ip, 'logout-miss')`
128
+ */
129
+ ipAbuse(ip: string, reason: IpAbuseReason): Promise<void>;
130
+ /**
131
+ * 手动封禁 IP。未封禁时写入并触发 `onBlockIP`;已封禁则跳过(不刷新 TTL、不重复回调)
132
+ */
133
+ blockIP(ip: string, duration: DurationInput): Promise<void>;
134
+ /**
135
+ * 解除 IP 封禁
136
+ */
137
+ unblockIP(ip: string): Promise<void>;
138
+ /**
139
+ * 是否已封禁该 IP
140
+ */
141
+ isIPBlocked(ip: string): Promise<boolean>;
142
+ };
143
+ /**
144
+ * `createAbuse()` 返回值:中间件 + API。不挂 `ctx`,service / 路由均直接调用返回值上的方法
145
+ */
146
+ type AbuseMiddleware<UserAbuseReason extends string | number = string | number, IpAbuseReason extends string | number = string | number> = WebMiddleware & AbuseApi<UserAbuseReason, IpAbuseReason>;
147
+ type AbuseOnBanUser<S extends readonly AbuseStrategy[]> = (id: AbuseId, reason: InferUserAbuseReasons<S>, detail: {
148
+ count: number;
149
+ limit: number;
150
+ banFor?: number;
151
+ }) => void | Promise<void>;
152
+ type AbuseOptionsBase<S extends readonly AbuseStrategy[]> = {
153
+ /**
154
+ * 缓存适配器(`@aomex/cache`,如 memory / redis)
155
+ */
156
+ store: CacheAdapter;
157
+ /**
158
+ * 跳过探测与封禁检查(如健康检查、内网)
159
+ */
160
+ bypass?: (ctx: WebContext) => boolean | Promise<boolean>;
161
+ /**
162
+ * IP 被封禁时回调(策略撞线、`ipAbuse` 满额或手动 `blockIP`)
163
+ */
164
+ onBlockIP?: (ip: string, reason: AbuseBlockStrategy, detail: AbuseBlockDetail) => void | Promise<void>;
165
+ /**
166
+ * IP被封禁时抛出的错误。默认:`403 Forbidden`
167
+ */
168
+ blockedError?: HttpError;
169
+ strategies: S;
170
+ };
171
+ /**
172
+ * 配置项。存在 `user-abuse` 策略时 `onBanUser` 必填,否则可选
173
+ */
174
+ type AbuseOptions<S extends readonly AbuseStrategy[] = readonly AbuseStrategy[]> = AbuseOptionsBase<S> & ([Extract<S[number], {
175
+ strategy: 'user-abuse';
176
+ }>] extends [never] ? {
177
+ /**
178
+ * `user-abuse` 计数满额时回调。应在此写入用户库完成账号封禁
179
+ */
180
+ onBanUser?: AbuseOnBanUser<S>;
181
+ } : {
182
+ /**
183
+ * `user-abuse` 计数满额时回调。应在此写入用户库完成账号封禁。
184
+ * 配置了 `user-abuse` 时必填;未提供时创建阶段会抛错
185
+ */
186
+ onBanUser: AbuseOnBanUser<S>;
187
+ });
188
+ /** IP 封禁终态详情。手动 `blockIP` 时 `count` / `limit` 为 `1` */
189
+ type AbuseBlockDetail = {
190
+ count: number;
191
+ limit: number;
192
+ /** 封禁时长,单位毫秒 */
193
+ blockFor: number;
194
+ };
195
+ /**
196
+ * 蜜罐路径 / 错误累计 / 业务滥用计数。
197
+ *
198
+ * - `honeypot` / `http-error`:按请求匹配计数,满额封 IP
199
+ * - `ip-abuse`:业务上报 IP 滥用(如 logout token 未命中),满额封 IP
200
+ * - `user-abuse`:业务上报,满额只触发 `onBanUser`(账号封禁由业务写库)
201
+ *
202
+ * 返回值既是中间件,也带 API(不挂到 `ctx`):
203
+ * ```ts
204
+ * const abuse = createAbuse({ store, strategies });
205
+ * app.mount([abuse]);
206
+ * await abuse.ipAbuse(ip, 'logout-miss'); // 路由内上报
207
+ * await abuse.userAbuse(userId, 'order-probe');
208
+ * ```
209
+ */
210
+ export declare const createAbuse: <const S extends readonly AbuseStrategy[]>(options: AbuseOptions<S>) => AbuseMiddleware<InferUserAbuseReasons<S>, InferIpAbuseReasons<S>>;
211
+ export type { AbuseApi, AbuseBlockDetail, AbuseBlockStrategy, AbuseHoneypotStrategy, AbuseHttpErrorStrategy, AbuseId, AbuseIpAbuseStrategy, AbuseMiddleware, AbuseOptions, AbusePathMatcher, AbuseStrategy, AbuseUserAbuseStrategy, InferIpAbuseReasons, InferUserAbuseReasons };
package/dist/index.js ADDED
@@ -0,0 +1,274 @@
1
+ import { CacheKey, Caching } from "@aomex/cache";
2
+ import { I18n, createI18n, middleware, parseDuration, registerLifecycle } from "@aomex/common";
3
+ import { HttpError } from "@aomex/web";
4
+ // src/i18n/locales/zh-cn.ts
5
+ const zh = I18n.define({
6
+ unknown_user_abuse_reason: "未知的用户滥用原因:{{reason}}",
7
+ unknown_ip_abuse_reason: "未知的 IP 滥用原因:{{reason}}",
8
+ duplicate_user_abuse_reason: "重复的用户滥用原因:{{reason}}",
9
+ duplicate_ip_abuse_reason: "重复的 IP 滥用原因:{{reason}}",
10
+ missing_on_ban_user: "配置了 user-abuse 策略时必须提供 onBanUser",
11
+ invalid_limit: "limit 必须为正整数,收到:{{limit}}",
12
+ invalid_window: "window 必须为正数时长,收到:{{window}}",
13
+ invalid_block_for: "blockFor 必须为正数时长,收到:{{blockFor}}",
14
+ invalid_ban_for: "banFor 必须为正数时长,收到:{{banFor}}",
15
+ empty_honeypot_paths: "honeypot 策略的 paths 不能为空",
16
+ empty_http_error_status_codes: "http-error 策略的 statusCodes 不能为空"
17
+ });
18
+ // src/i18n/locales/en-us.ts
19
+ const en = I18n.satisfies(zh).define({
20
+ unknown_user_abuse_reason: "Unknown user abuse reason: {{reason}}",
21
+ unknown_ip_abuse_reason: "Unknown IP abuse reason: {{reason}}",
22
+ duplicate_user_abuse_reason: "Duplicate user abuse reason: {{reason}}",
23
+ duplicate_ip_abuse_reason: "Duplicate IP abuse reason: {{reason}}",
24
+ missing_on_ban_user: "onBanUser is required when user-abuse strategies are configured",
25
+ invalid_limit: "limit must be a positive integer, got: {{limit}}",
26
+ invalid_window: "window must be a positive duration, got: {{window}}",
27
+ invalid_block_for: "blockFor must be a positive duration, got: {{blockFor}}",
28
+ invalid_ban_for: "banFor must be a positive duration, got: {{banFor}}",
29
+ empty_honeypot_paths: "honeypot strategy paths must not be empty",
30
+ empty_http_error_status_codes: "http-error strategy statusCodes must not be empty"
31
+ });
32
+ // src/i18n/index.ts
33
+ const i18n = createI18n({
34
+ zh,
35
+ en,
36
+ load: (file) => import(new URL(`./locales/${file}.js`, import.meta.url).href)
37
+ });
38
+ // src/match.ts
39
+ /**
40
+ * 路径匹配:精确字符串、简单 glob(`*` / `**`)、或正则。
41
+ * 正则会对 `pathname + search` 检测,便于捕获 query 中的探测特征。
42
+ */
43
+ function matchPath(pathname, search, matcher) {
44
+ if (matcher instanceof RegExp) return matcher.test(pathname + search);
45
+ if (!matcher.includes("*")) return pathname === matcher;
46
+ return globToRegExp(matcher).test(pathname);
47
+ }
48
+ /**
49
+ * 任一路径匹配器命中即为 true。
50
+ * `paths` 为 `undefined` 时视为不限路径;空数组不命中。
51
+ */
52
+ function matchAnyPath(pathname, search, paths) {
53
+ if (paths === void 0) return true;
54
+ return paths.some((item) => matchPath(pathname, search, item));
55
+ }
56
+ /**
57
+ * 匹配 HTTP 方法(忽略大小写)。
58
+ * `methods` 为 `undefined` 或空数组时视为不限方法。
59
+ */
60
+ function matchMethod(method, methods) {
61
+ if (!methods?.length) return true;
62
+ const upper = method.toUpperCase();
63
+ return methods.some((item) => item.toUpperCase() === upper);
64
+ }
65
+ function globToRegExp(glob) {
66
+ let source = glob;
67
+ let optionalDeep = false;
68
+ if (source.endsWith("/**")) {
69
+ source = source.slice(0, -3);
70
+ optionalDeep = true;
71
+ }
72
+ let pattern = "";
73
+ for (let i = 0; i < source.length; i += 1) {
74
+ const char = source[i];
75
+ if (char === "*") {
76
+ if (source[i + 1] === "*") {
77
+ pattern += ".*";
78
+ i += 1;
79
+ } else pattern += "[^/]*";
80
+ continue;
81
+ }
82
+ if (/[.+?^${}()|[\]\\]/.test(char)) {
83
+ pattern += `\\${char}`;
84
+ continue;
85
+ }
86
+ pattern += char;
87
+ }
88
+ if (optionalDeep) pattern += "(?:/.*)?";
89
+ return new RegExp(`^${pattern}$`);
90
+ }
91
+ // src/abuse.ts
92
+ const abuseKey = new CacheKey().key("abuse");
93
+ /** 校验策略并按 reason 分桶;非法配置创建期抛错 */
94
+ const validateStrategies = (strategies) => {
95
+ const userAbuseStrategies = /* @__PURE__ */ new Map();
96
+ const ipAbuseStrategies = /* @__PURE__ */ new Map();
97
+ for (const item of strategies) {
98
+ if (!Number.isInteger(item.limit) || item.limit <= 0) throw new Error(i18n.t("invalid_limit", { limit: String(item.limit) }));
99
+ if (parseDuration(item.window) <= 0) throw new Error(i18n.t("invalid_window", { window: String(item.window) }));
100
+ if (item.strategy === "honeypot") {
101
+ if (item.paths.length === 0) throw new Error(i18n.t("empty_honeypot_paths"));
102
+ } else if (item.strategy === "http-error") {
103
+ if (item.statusCodes.length === 0) throw new Error(i18n.t("empty_http_error_status_codes"));
104
+ }
105
+ if (item.strategy === "user-abuse") {
106
+ if (item.banFor !== void 0) {
107
+ if (parseDuration(item.banFor) <= 0) throw new Error(i18n.t("invalid_ban_for", { banFor: String(item.banFor) }));
108
+ }
109
+ const reasonKey = String(item.reason);
110
+ if (userAbuseStrategies.has(reasonKey)) throw new Error(i18n.t("duplicate_user_abuse_reason", { reason: reasonKey }));
111
+ userAbuseStrategies.set(reasonKey, item);
112
+ } else {
113
+ if (parseDuration(item.blockFor) <= 0) throw new Error(i18n.t("invalid_block_for", { blockFor: String(item.blockFor) }));
114
+ if (item.strategy === "ip-abuse") {
115
+ const reasonKey = String(item.reason);
116
+ if (ipAbuseStrategies.has(reasonKey)) throw new Error(i18n.t("duplicate_ip_abuse_reason", { reason: reasonKey }));
117
+ ipAbuseStrategies.set(reasonKey, item);
118
+ }
119
+ }
120
+ }
121
+ return {
122
+ userAbuseStrategies,
123
+ ipAbuseStrategies
124
+ };
125
+ };
126
+ /**
127
+ * 蜜罐路径 / 错误累计 / 业务滥用计数。
128
+ *
129
+ * - `honeypot` / `http-error`:按请求匹配计数,满额封 IP
130
+ * - `ip-abuse`:业务上报 IP 滥用(如 logout token 未命中),满额封 IP
131
+ * - `user-abuse`:业务上报,满额只触发 `onBanUser`(账号封禁由业务写库)
132
+ *
133
+ * 返回值既是中间件,也带 API(不挂到 `ctx`):
134
+ * ```ts
135
+ * const abuse = createAbuse({ store, strategies });
136
+ * app.mount([abuse]);
137
+ * await abuse.ipAbuse(ip, 'logout-miss'); // 路由内上报
138
+ * await abuse.userAbuse(userId, 'order-probe');
139
+ * ```
140
+ */
141
+ const createAbuse = (options) => {
142
+ const adapter = options.store;
143
+ const caching = new Caching(adapter);
144
+ const getBlockKey = (ip) => abuseKey.key("block", ip);
145
+ const onBanUser = options.onBanUser;
146
+ const onBlockIP = options.onBlockIP;
147
+ const bypass = options.bypass ?? (() => false);
148
+ const blockedError = options.blockedError;
149
+ const throwBlocked = (ctx) => {
150
+ if (blockedError) throw blockedError;
151
+ return ctx.throw(403);
152
+ };
153
+ const bumpCount = async (countKey, windowMs) => {
154
+ const count = await caching.increment(countKey);
155
+ if (count === 1 || await caching.ttl(countKey) === -1) await caching.expire(countKey, Math.max(windowMs, 1));
156
+ return count;
157
+ };
158
+ /**
159
+ * 封 IP:`setNX` 原子抢占,已封禁则跳过钩子;抢到则写入并触发 `onBlockIP`
160
+ */
161
+ const ensureBlocked = async (ip, reason, detail) => {
162
+ if (!await caching.setNX(getBlockKey(ip), reason, detail.blockFor)) return false;
163
+ await onBlockIP?.(ip, reason, detail);
164
+ return true;
165
+ };
166
+ const honeypotStrategies = options.strategies.filter((item) => item.strategy === "honeypot");
167
+ const httpErrorStrategies = options.strategies.filter((item) => item.strategy === "http-error");
168
+ const { userAbuseStrategies, ipAbuseStrategies } = validateStrategies(options.strategies);
169
+ if (userAbuseStrategies.size > 0 && !onBanUser) throw new Error(i18n.t("missing_on_ban_user"));
170
+ registerLifecycle({
171
+ onInit: () => adapter.connect(),
172
+ onDestroy: () => adapter.disconnect()
173
+ });
174
+ const api = {
175
+ async userAbuse(id, reason) {
176
+ const reasonKey = String(reason);
177
+ const strategy = userAbuseStrategies.get(reasonKey);
178
+ if (!strategy) throw new Error(i18n.t("unknown_user_abuse_reason", { reason: reasonKey }));
179
+ const idKey = String(id);
180
+ const countKey = abuseKey.key("count", "user-abuse", reasonKey, idKey);
181
+ const windowMs = parseDuration(strategy.window);
182
+ const count = await bumpCount(countKey, windowMs);
183
+ if (count < strategy.limit) return;
184
+ const hookKey = abuseKey.key("hook", "user-abuse", reasonKey, idKey);
185
+ const banFor = strategy.banFor === void 0 ? void 0 : parseDuration(strategy.banFor);
186
+ const countTtl = await caching.ttl(countKey);
187
+ if (!await caching.setNX(hookKey, "1", Math.max(countTtl > 0 ? countTtl : windowMs, 1))) return;
188
+ try {
189
+ await onBanUser(id, reason, {
190
+ count,
191
+ limit: strategy.limit,
192
+ banFor
193
+ });
194
+ } catch (e) {
195
+ await caching.delete(hookKey);
196
+ throw e;
197
+ }
198
+ },
199
+ async ipAbuse(ip, reason) {
200
+ const reasonKey = String(reason);
201
+ const strategy = ipAbuseStrategies.get(reasonKey);
202
+ if (!strategy) throw new Error(i18n.t("unknown_ip_abuse_reason", { reason: reasonKey }));
203
+ const countKey = abuseKey.key("count", "ip-abuse", reasonKey, ip);
204
+ const count = await bumpCount(countKey, parseDuration(strategy.window));
205
+ if (count < strategy.limit) return;
206
+ await ensureBlocked(ip, "ip-abuse", {
207
+ count,
208
+ limit: strategy.limit,
209
+ blockFor: parseDuration(strategy.blockFor)
210
+ });
211
+ },
212
+ async blockIP(ip, duration) {
213
+ const blockFor = parseDuration(duration);
214
+ if (blockFor <= 0) throw new Error(i18n.t("invalid_block_for", { blockFor: String(duration) }));
215
+ await ensureBlocked(ip, "manual", {
216
+ count: 1,
217
+ limit: 1,
218
+ blockFor
219
+ });
220
+ },
221
+ async unblockIP(ip) {
222
+ await caching.delete(getBlockKey(ip));
223
+ },
224
+ async isIPBlocked(ip) {
225
+ return caching.exists(getBlockKey(ip));
226
+ }
227
+ };
228
+ const md = middleware.web(async (ctx, next) => {
229
+ if (await bypass(ctx)) return next();
230
+ const ip = ctx.request.ip;
231
+ if (!ip) return next();
232
+ if (await caching.exists(getBlockKey(ip))) return throwBlocked(ctx);
233
+ const request = ctx.request;
234
+ for (let i = 0; i < honeypotStrategies.length; i += 1) {
235
+ const strategy = honeypotStrategies[i];
236
+ if (!matchMethod(request.method, strategy.methods) || !matchAnyPath(request.pathname, request.search, strategy.paths)) continue;
237
+ const countKey = abuseKey.key("count", "honeypot", i, ip);
238
+ const count = await bumpCount(countKey, parseDuration(strategy.window));
239
+ if (count < strategy.limit) continue;
240
+ await ensureBlocked(ip, "honeypot", {
241
+ count,
242
+ limit: strategy.limit,
243
+ blockFor: parseDuration(strategy.blockFor)
244
+ });
245
+ return throwBlocked(ctx);
246
+ }
247
+ let statusCode;
248
+ let thrown;
249
+ try {
250
+ await next();
251
+ statusCode = ctx.response.statusCode;
252
+ } catch (e) {
253
+ thrown = HttpError.from(e);
254
+ statusCode = thrown.statusCode;
255
+ }
256
+ for (let i = 0; i < httpErrorStrategies.length; i += 1) {
257
+ const strategy = httpErrorStrategies[i];
258
+ if (!strategy.statusCodes.includes(statusCode) || !matchMethod(request.method, strategy.methods) || !matchAnyPath(request.pathname, request.search, strategy.paths)) continue;
259
+ const countKey = abuseKey.key("count", "http-error", i, ip);
260
+ const count = await bumpCount(countKey, parseDuration(strategy.window));
261
+ if (count < strategy.limit) continue;
262
+ await ensureBlocked(ip, "http-error", {
263
+ count,
264
+ limit: strategy.limit,
265
+ blockFor: parseDuration(strategy.blockFor)
266
+ });
267
+ }
268
+ if (thrown) throw thrown;
269
+ });
270
+ return Object.assign(md, api);
271
+ };
272
+ export { createAbuse };
273
+
274
+ //# 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/match.ts","../src/abuse.ts"],"sourcesContent":["import { I18n } from '@aomex/common';\n\nexport const zh = I18n.define({\n unknown_user_abuse_reason: '未知的用户滥用原因:{{reason}}',\n unknown_ip_abuse_reason: '未知的 IP 滥用原因:{{reason}}',\n duplicate_user_abuse_reason: '重复的用户滥用原因:{{reason}}',\n duplicate_ip_abuse_reason: '重复的 IP 滥用原因:{{reason}}',\n missing_on_ban_user: '配置了 user-abuse 策略时必须提供 onBanUser',\n invalid_limit: 'limit 必须为正整数,收到:{{limit}}',\n invalid_window: 'window 必须为正数时长,收到:{{window}}',\n invalid_block_for: 'blockFor 必须为正数时长,收到:{{blockFor}}',\n invalid_ban_for: 'banFor 必须为正数时长,收到:{{banFor}}',\n empty_honeypot_paths: 'honeypot 策略的 paths 不能为空',\n empty_http_error_status_codes: 'http-error 策略的 statusCodes 不能为空',\n});\n","import { I18n } from '@aomex/common';\nimport { zh } from './zh-cn';\n\nexport const en = I18n.satisfies(zh).define({\n unknown_user_abuse_reason: 'Unknown user abuse reason: {{reason}}',\n unknown_ip_abuse_reason: 'Unknown IP abuse reason: {{reason}}',\n duplicate_user_abuse_reason: 'Duplicate user abuse reason: {{reason}}',\n duplicate_ip_abuse_reason: 'Duplicate IP abuse reason: {{reason}}',\n missing_on_ban_user: 'onBanUser is required when user-abuse strategies are configured',\n invalid_limit: 'limit must be a positive integer, got: {{limit}}',\n invalid_window: 'window must be a positive duration, got: {{window}}',\n invalid_block_for: 'blockFor must be a positive duration, got: {{blockFor}}',\n invalid_ban_for: 'banFor must be a positive duration, got: {{banFor}}',\n empty_honeypot_paths: 'honeypot strategy paths must not be empty',\n empty_http_error_status_codes: 'http-error strategy statusCodes must not be empty',\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","/**\n * 路径匹配:精确字符串、简单 glob(`*` / `**`)、或正则。\n * 正则会对 `pathname + search` 检测,便于捕获 query 中的探测特征。\n */\nexport function matchPath(\n pathname: string,\n search: string,\n matcher: string | RegExp,\n): boolean {\n if (matcher instanceof RegExp) {\n return matcher.test(pathname + search);\n }\n\n if (!matcher.includes('*')) {\n return pathname === matcher;\n }\n\n const re = globToRegExp(matcher);\n return re.test(pathname);\n}\n\n/**\n * 任一路径匹配器命中即为 true。\n * `paths` 为 `undefined` 时视为不限路径;空数组不命中。\n */\nexport function matchAnyPath(\n pathname: string,\n search: string,\n paths?: readonly (string | RegExp)[],\n): boolean {\n if (paths === undefined) return true;\n return paths.some((item) => matchPath(pathname, search, item));\n}\n\n/**\n * 匹配 HTTP 方法(忽略大小写)。\n * `methods` 为 `undefined` 或空数组时视为不限方法。\n */\nexport function matchMethod(method: string, methods?: readonly string[]): boolean {\n if (!methods?.length) return true;\n const upper = method.toUpperCase();\n return methods.some((item) => item.toUpperCase() === upper);\n}\n\nfunction globToRegExp(glob: string): RegExp {\n let source = glob;\n let optionalDeep = false;\n if (source.endsWith('/**')) {\n source = source.slice(0, -3);\n optionalDeep = true;\n }\n\n let pattern = '';\n for (let i = 0; i < source.length; i += 1) {\n const char = source[i]!;\n if (char === '*') {\n if (source[i + 1] === '*') {\n pattern += '.*';\n i += 1;\n } else {\n pattern += '[^/]*';\n }\n continue;\n }\n if (/[.+?^${}()|[\\]\\\\]/.test(char)) {\n pattern += `\\\\${char}`;\n continue;\n }\n pattern += char;\n }\n if (optionalDeep) pattern += '(?:/.*)?';\n return new RegExp(`^${pattern}$`);\n}\n","import { CacheKey, Caching } from '@aomex/cache';\nimport { middleware, parseDuration, registerLifecycle } from '@aomex/common';\nimport { HttpError, type WebContext } from '@aomex/web';\nimport { i18n } from './i18n';\nimport { matchAnyPath, matchMethod } from './match';\nimport type {\n AbuseApi,\n AbuseBlockStrategy,\n AbuseHoneypotStrategy,\n AbuseHttpErrorStrategy,\n AbuseIpAbuseStrategy,\n AbuseMiddleware,\n AbuseOptions,\n AbuseStrategy,\n AbuseUserAbuseStrategy,\n InferIpAbuseReasons,\n InferUserAbuseReasons,\n} from './types';\n\nconst abuseKey = new CacheKey().key('abuse');\n\n/** 校验策略并按 reason 分桶;非法配置创建期抛错 */\nconst validateStrategies = (strategies: readonly AbuseStrategy[]) => {\n const userAbuseStrategies = new Map<string, AbuseUserAbuseStrategy>();\n const ipAbuseStrategies = new Map<string, AbuseIpAbuseStrategy>();\n\n for (const item of strategies) {\n if (!Number.isInteger(item.limit) || item.limit <= 0) {\n throw new Error(i18n.t('invalid_limit', { limit: String(item.limit) }));\n }\n const windowMs = parseDuration(item.window);\n if (windowMs <= 0) {\n throw new Error(i18n.t('invalid_window', { window: String(item.window) }));\n }\n if (item.strategy === 'honeypot') {\n if (item.paths.length === 0) {\n throw new Error(i18n.t('empty_honeypot_paths'));\n }\n } else if (item.strategy === 'http-error') {\n if (item.statusCodes.length === 0) {\n throw new Error(i18n.t('empty_http_error_status_codes'));\n }\n }\n if (item.strategy === 'user-abuse') {\n if (item.banFor !== undefined) {\n const banForMs = parseDuration(item.banFor);\n if (banForMs <= 0) {\n throw new Error(i18n.t('invalid_ban_for', { banFor: String(item.banFor) }));\n }\n }\n const reasonKey = String(item.reason);\n if (userAbuseStrategies.has(reasonKey)) {\n throw new Error(i18n.t('duplicate_user_abuse_reason', { reason: reasonKey }));\n }\n userAbuseStrategies.set(reasonKey, item);\n } else {\n const blockForMs = parseDuration(item.blockFor);\n if (blockForMs <= 0) {\n throw new Error(i18n.t('invalid_block_for', { blockFor: String(item.blockFor) }));\n }\n if (item.strategy === 'ip-abuse') {\n const reasonKey = String(item.reason);\n if (ipAbuseStrategies.has(reasonKey)) {\n throw new Error(i18n.t('duplicate_ip_abuse_reason', { reason: reasonKey }));\n }\n ipAbuseStrategies.set(reasonKey, item);\n }\n }\n }\n\n return { userAbuseStrategies, ipAbuseStrategies };\n};\n\n/**\n * 蜜罐路径 / 错误累计 / 业务滥用计数。\n *\n * - `honeypot` / `http-error`:按请求匹配计数,满额封 IP\n * - `ip-abuse`:业务上报 IP 滥用(如 logout token 未命中),满额封 IP\n * - `user-abuse`:业务上报,满额只触发 `onBanUser`(账号封禁由业务写库)\n *\n * 返回值既是中间件,也带 API(不挂到 `ctx`):\n * ```ts\n * const abuse = createAbuse({ store, strategies });\n * app.mount([abuse]);\n * await abuse.ipAbuse(ip, 'logout-miss'); // 路由内上报\n * await abuse.userAbuse(userId, 'order-probe');\n * ```\n */\nexport const createAbuse = <const S extends readonly AbuseStrategy[]>(\n options: AbuseOptions<S>,\n): AbuseMiddleware<InferUserAbuseReasons<S>, InferIpAbuseReasons<S>> => {\n const adapter = options.store;\n const caching = new Caching(adapter);\n const getBlockKey = (ip: string) => abuseKey.key('block', ip);\n const onBanUser = options.onBanUser;\n const onBlockIP = options.onBlockIP;\n const bypass = options.bypass ?? (() => false);\n const blockedError = options.blockedError;\n const throwBlocked = (ctx: WebContext): never => {\n if (blockedError) throw blockedError;\n return ctx.throw(403);\n };\n\n const bumpCount = async (countKey: Caching.Key, windowMs: number): Promise<number> => {\n const count = await caching.increment(countKey);\n if (count === 1 || (await caching.ttl(countKey)) === -1) {\n await caching.expire(countKey, Math.max(windowMs, 1));\n }\n return count;\n };\n\n /**\n * 封 IP:`setNX` 原子抢占,已封禁则跳过钩子;抢到则写入并触发 `onBlockIP`\n */\n const ensureBlocked = async (\n ip: string,\n reason: AbuseBlockStrategy,\n detail: { count: number; limit: number; blockFor: number },\n ): Promise<boolean> => {\n const created = await caching.setNX(getBlockKey(ip), reason, detail.blockFor);\n if (!created) return false;\n await onBlockIP?.(ip, reason, detail);\n return true;\n };\n\n const honeypotStrategies = options.strategies.filter(\n (item): item is AbuseHoneypotStrategy => item.strategy === 'honeypot',\n );\n const httpErrorStrategies = options.strategies.filter(\n (item): item is AbuseHttpErrorStrategy => item.strategy === 'http-error',\n );\n const { userAbuseStrategies, ipAbuseStrategies } = validateStrategies(\n options.strategies,\n );\n\n if (userAbuseStrategies.size > 0 && !onBanUser) {\n throw new Error(i18n.t('missing_on_ban_user'));\n }\n\n void registerLifecycle({\n onInit: () => adapter.connect(),\n onDestroy: () => adapter.disconnect(),\n });\n\n const api: AbuseApi<InferUserAbuseReasons<S>, InferIpAbuseReasons<S>> = {\n async userAbuse(id, reason) {\n const reasonKey = String(reason);\n const strategy = userAbuseStrategies.get(reasonKey);\n if (!strategy) {\n throw new Error(i18n.t('unknown_user_abuse_reason', { reason: reasonKey }));\n }\n const idKey = String(id);\n const countKey = abuseKey.key('count', 'user-abuse', reasonKey, idKey);\n const windowMs = parseDuration(strategy.window);\n const count = await bumpCount(countKey, windowMs);\n if (count < strategy.limit) return;\n\n // 无 IP 封禁键:hook 标记 setNX,避免窗口内重复 / 并发触发 onBanUser\n const hookKey = abuseKey.key('hook', 'user-abuse', reasonKey, idKey);\n const banFor =\n strategy.banFor === undefined ? undefined : parseDuration(strategy.banFor);\n const countTtl = await caching.ttl(countKey);\n const marked = await caching.setNX(\n hookKey,\n '1',\n Math.max(countTtl > 0 ? countTtl : windowMs, 1),\n );\n if (!marked) return;\n try {\n await onBanUser!(id, reason, { count, limit: strategy.limit, banFor });\n } catch (e) {\n // 回调失败则释放 hook,允许窗口内重试\n await caching.delete(hookKey);\n throw e;\n }\n },\n async ipAbuse(ip, reason) {\n const reasonKey = String(reason);\n const strategy = ipAbuseStrategies.get(reasonKey);\n if (!strategy) {\n throw new Error(i18n.t('unknown_ip_abuse_reason', { reason: reasonKey }));\n }\n const countKey = abuseKey.key('count', 'ip-abuse', reasonKey, ip);\n const count = await bumpCount(countKey, parseDuration(strategy.window));\n if (count < strategy.limit) return;\n\n await ensureBlocked(ip, 'ip-abuse', {\n count,\n limit: strategy.limit,\n blockFor: parseDuration(strategy.blockFor),\n });\n },\n async blockIP(ip, duration) {\n const blockFor = parseDuration(duration);\n if (blockFor <= 0) {\n throw new Error(i18n.t('invalid_block_for', { blockFor: String(duration) }));\n }\n await ensureBlocked(ip, 'manual', {\n count: 1,\n limit: 1,\n blockFor,\n });\n },\n async unblockIP(ip) {\n await caching.delete(getBlockKey(ip));\n },\n async isIPBlocked(ip) {\n return caching.exists(getBlockKey(ip));\n },\n };\n\n const md = middleware.web(async (ctx, next) => {\n if (await bypass(ctx)) return next();\n\n const ip = ctx.request.ip;\n if (!ip) return next();\n\n if (await caching.exists(getBlockKey(ip))) {\n return throwBlocked(ctx);\n }\n\n const request = ctx.request;\n\n for (let i = 0; i < honeypotStrategies.length; i += 1) {\n const strategy = honeypotStrategies[i]!;\n if (\n !matchMethod(request.method, strategy.methods) ||\n !matchAnyPath(request.pathname, request.search, strategy.paths)\n ) {\n continue;\n }\n\n const countKey = abuseKey.key('count', 'honeypot', i, ip);\n const count = await bumpCount(countKey, parseDuration(strategy.window));\n if (count < strategy.limit) continue;\n\n await ensureBlocked(ip, 'honeypot', {\n count,\n limit: strategy.limit,\n blockFor: parseDuration(strategy.blockFor),\n });\n return throwBlocked(ctx);\n }\n\n let statusCode: number;\n let thrown: HttpError | undefined;\n try {\n await next();\n statusCode = ctx.response.statusCode;\n } catch (e) {\n thrown = HttpError.from(e);\n statusCode = thrown.statusCode;\n }\n\n for (let i = 0; i < httpErrorStrategies.length; i += 1) {\n const strategy = httpErrorStrategies[i]!;\n if (\n !strategy.statusCodes.includes(statusCode) ||\n !matchMethod(request.method, strategy.methods) ||\n !matchAnyPath(request.pathname, request.search, strategy.paths)\n ) {\n continue;\n }\n\n const countKey = abuseKey.key('count', 'http-error', i, ip);\n const count = await bumpCount(countKey, parseDuration(strategy.window));\n if (count < strategy.limit) continue;\n\n await ensureBlocked(ip, 'http-error', {\n count,\n limit: strategy.limit,\n blockFor: parseDuration(strategy.blockFor),\n });\n }\n\n if (thrown) throw thrown;\n });\n\n return Object.assign(md, api) as AbuseMiddleware<\n InferUserAbuseReasons<S>,\n InferIpAbuseReasons<S>\n >;\n};\n"],"mappings":";;;;AAEA,MAAa,KAAK,KAAK,OAAO;CAC5B,2BAA2B;CAC3B,yBAAyB;CACzB,6BAA6B;CAC7B,2BAA2B;CAC3B,qBAAqB;CACrB,eAAe;CACf,gBAAgB;CAChB,mBAAmB;CACnB,iBAAiB;CACjB,sBAAsB;CACtB,+BAA+B;AACjC,CAAC;;ACXD,MAAa,KAAK,KAAK,UAAU,EAAE,CAAC,CAAC,OAAO;CAC1C,2BAA2B;CAC3B,yBAAyB;CACzB,6BAA6B;CAC7B,2BAA2B;CAC3B,qBAAqB;CACrB,eAAe;CACf,gBAAgB;CAChB,mBAAmB;CACnB,iBAAiB;CACjB,sBAAsB;CACtB,+BAA+B;AACjC,CAAC;;ACXD,MAAa,OAAO,WAAW;CAC7B;CACA;CACA,OAAO,SAAS,OAAO,IAAI,IAAI,aAAa,KAAK,MAAM,YAAY,GAAG,CAAC,CAAC;AAC1E,CAAC;;;;;;ACJD,SAAgB,UACd,UACA,QACA,SACS;CACT,IAAI,mBAAmB,QACrB,OAAO,QAAQ,KAAK,WAAW,MAAM;CAGvC,IAAI,CAAC,QAAQ,SAAS,GAAG,GACvB,OAAO,aAAa;CAItB,OADW,aAAa,OAChB,CAAC,CAAC,KAAK,QAAQ;AACzB;;;;;AAMA,SAAgB,aACd,UACA,QACA,OACS;CACT,IAAI,UAAU,KAAA,GAAW,OAAO;CAChC,OAAO,MAAM,MAAM,SAAS,UAAU,UAAU,QAAQ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AS,cAAc,GAAG,EAAE;GAC1D,MAAM,QAAQ,MAAM,UAAU,UAAU,cAAc,SAAS,MAAM,CAAC;GACtE,IAAI,QAAQ,SAAS,OAAO;GAE5B,MAAM,cAAc,IAAI,cAAc;IACpC;IACA,OAAO,SAAS;IAChB,UAAU,cAAc,SAAS,QAAQ;GAC3C,CAAC;EACH;EAEA,IAAI,QAAQ,MAAM;CACpB,CAAC;CAED,OAAO,OAAO,OAAO,IAAI,GAAG;AAI9B"}
package/package.json CHANGED
@@ -1,6 +1,41 @@
1
1
  {
2
2
  "name": "@aomex/abuse",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "4.3.0",
4
+ "description": "滥用计数与封禁(蜜罐路径 / HTTP 错误 / IP·用户滥用)",
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
+ "package.json",
24
+ "README.md",
25
+ "CHANGELOG.md"
26
+ ],
27
+ "publishConfig": {
28
+ "access": "public"
29
+ },
30
+ "peerDependencies": {
31
+ "@aomex/cache": "^4.0.0",
32
+ "@aomex/common": "^4.0.0",
33
+ "@aomex/web": "^4.0.0"
34
+ },
35
+ "devDependencies": {
36
+ "@aomex/cache": "4.3.0",
37
+ "@aomex/common": "4.3.0",
38
+ "@aomex/web": "4.3.0"
39
+ },
40
+ "scripts": {}
6
41
  }