ayiin 2.0.39 → 2.0.40

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/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import Methods from "./methods";
2
- export type { DurationInput, RateLimitStore, RateLimiterOptions, } from "./types";
2
+ export type { DurationInput, FloodwaitPlaceholder, RateLimitStore, RateLimiterOptions, } from "./types";
3
3
  export default class Ayiin extends Methods {
4
4
  version: string;
5
5
  constructor();
@@ -3,4 +3,5 @@ import { RateLimiterOptions } from "../types";
3
3
  import Tools from "./tools";
4
4
  export declare class Limiter extends Tools {
5
5
  createRateLimit: (options: RateLimiterOptions) => RequestHandler;
6
+ private formatMessage;
6
7
  }
@@ -57,43 +57,63 @@ class Limiter extends tools_1.default {
57
57
  const blockedUntil = new Date(blockedUntilStr).getTime();
58
58
  const remainingMs = blockedUntil - now;
59
59
  if (remainingMs > 0) {
60
- return res.status(429).json({
61
- success: false,
62
- error: `Floodwait aktif untuk ${options.keyPrefix}. Tunggu ${this.formatRemainingTime(remainingMs)}.`,
63
- });
60
+ const msg = options.messageFormat
61
+ ? this.formatMessage(options.messageFormat, {
62
+ api: options.keyPrefix,
63
+ remainMs: remainingMs,
64
+ remain: this.formatRemainingTime(remainingMs),
65
+ limit: options.limit,
66
+ })
67
+ : `[FloodWait] - Silakan coba lagi dalam ${this.formatRemainingTime(remainingMs)}.`;
68
+ return res.status(429).json({ success: false, error: msg });
64
69
  }
65
70
  }
66
71
  const rateKey = `${options.keyPrefix}:rate:${userId}`;
67
72
  const hits = await store.incr(rateKey);
68
73
  const windowMs = this.toMilliseconds(options.windowMs);
69
- const baseFloodwaitMs = this.toMilliseconds(options.floodwaitMs);
70
- const levelTtlMs = this.toMilliseconds(options.levelTtl ?? { hours: 24 });
74
+ const refreshAtMs = this.toMilliseconds(options.refreshAt ?? { hours: 24 });
71
75
  if (hits === 1) {
72
76
  await store.expire(rateKey, windowMs);
73
77
  }
74
78
  if (hits > options.limit) {
75
- let floodwaitMs = baseFloodwaitMs;
76
- if (options.levels && options.levels.length > 0) {
77
- let level = parseInt((await store.get(levelKey)) ?? "0", 10);
78
- level += 1;
79
- // simpan level dengan TTL (reset otomatis setelah levelTtlMs)
80
- await store.set(levelKey, level.toString(), levelTtlMs);
81
- // pilih durasi floodwait dari config levels
82
- const idx = Math.min(level - 1, options.levels.length - 1);
83
- const levelDuration = options.levels[idx];
84
- if (levelDuration) {
85
- floodwaitMs = this.toMilliseconds(levelDuration);
86
- }
79
+ let floodwaitMs;
80
+ let level;
81
+ if (Array.isArray(options.floodwaitMs)) {
82
+ // escalation mode
83
+ level = parseInt((await store.get(levelKey)) ?? "0", 10) + 1;
84
+ await store.set(levelKey, level.toString(), refreshAtMs);
85
+ const idx = Math.min(level - 1, options.floodwaitMs.length - 1);
86
+ const floodwait = options.floodwaitMs[idx];
87
+ floodwaitMs = this.toMilliseconds(floodwait ?? options.floodwaitMs[0]);
88
+ }
89
+ else {
90
+ // fixed mode
91
+ floodwaitMs = this.toMilliseconds(options.floodwaitMs);
87
92
  }
88
93
  const untilDate = new Date(now + floodwaitMs).toISOString();
89
94
  await store.set(floodKey, untilDate, floodwaitMs);
90
- return res.status(429).json({
91
- success: false,
92
- error: `Terlalu banyak request ${options.keyPrefix}. Floodwait aktif selama ${this.formatRemainingTime(floodwaitMs)}.`,
93
- });
95
+ const msg = options.messageFormat
96
+ ? this.formatMessage(options.messageFormat, {
97
+ api: options.keyPrefix,
98
+ remainMs: floodwaitMs,
99
+ remain: this.formatRemainingTime(floodwaitMs),
100
+ level,
101
+ limit: options.limit,
102
+ })
103
+ : `[FloodWait] - Terlalu banyak permintaan. Silakan coba lagi dalam ${this.formatRemainingTime(floodwaitMs)}.`;
104
+ return res.status(429).json({ success: false, error: msg });
94
105
  }
95
106
  next();
96
107
  };
97
108
  };
109
+ // internal formatter
110
+ formatMessage(template, ctx) {
111
+ return template
112
+ .replace("%(api)s", ctx.api)
113
+ .replace("%(remainMs)s", ctx.remainMs.toString())
114
+ .replace("%(remain)s", ctx.remain)
115
+ .replace("%(level)s", ctx.level?.toString() ?? "1")
116
+ .replace("%(limit)s", ctx.limit?.toString() ?? "");
117
+ }
98
118
  }
99
119
  exports.Limiter = Limiter;
package/dist/types.d.ts CHANGED
@@ -1,4 +1,10 @@
1
1
  import { Request, Response } from "express";
2
+ export interface RateLimitStore {
3
+ get(key: string): Promise<string | undefined>;
4
+ set(key: string, value: string, ttlMs?: number): Promise<void>;
5
+ incr(key: string): Promise<number>;
6
+ expire(key: string, ttlMs: number): Promise<void>;
7
+ }
2
8
  export interface DurationInput {
3
9
  hours?: number;
4
10
  minutes?: number;
@@ -8,15 +14,10 @@ export interface RateLimiterOptions {
8
14
  keyPrefix: string;
9
15
  limit: number;
10
16
  windowMs: DurationInput;
11
- floodwaitMs: DurationInput;
17
+ floodwaitMs: DurationInput | DurationInput[];
12
18
  identifyUser?: (req: Request, res: Response) => string | Response<any, Record<string, any>>;
13
19
  store?: RateLimitStore;
14
- levels?: DurationInput[];
15
- levelTtl?: DurationInput;
16
- }
17
- export interface RateLimitStore {
18
- get(key: string): Promise<string | undefined>;
19
- set(key: string, value: string, ttlMs?: number): Promise<void>;
20
- incr(key: string): Promise<number>;
21
- expire(key: string, ttlMs: number): Promise<void>;
20
+ refreshAt?: DurationInput;
21
+ messageFormat?: string extends FloodwaitPlaceholder ? string : never;
22
22
  }
23
+ export type FloodwaitPlaceholder = "%(api)s" | "%(remainMs)s" | "%(remain)s" | "%(level)s" | "%(limit)s";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ayiin",
3
- "version": "2.0.39",
3
+ "version": "2.0.40",
4
4
  "description": "Library Pribadi Yang Gak Ada Isinya",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",