@seip/bluebird-js 0.0.1 → 0.1.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/.env_example +53 -53
- package/AGENTS.md +426 -403
- package/LICENSE +1 -1
- package/README.md +292 -285
- package/app/routes/api.js +50 -50
- package/app/routes/web.js +55 -53
- package/app/views/about.js +63 -0
- package/app/views/dashboard.js +147 -0
- package/app/views/index.js +80 -0
- package/app/views/layouts/main/view.js +81 -0
- package/app/views/legal/terms.html +19 -0
- package/app/views/login.js +80 -0
- package/core/app.d.ts +18 -18
- package/core/app.js +684 -644
- package/core/auth.d.ts +13 -13
- package/core/auth.js +326 -326
- package/core/cache.d.ts +17 -17
- package/core/cache.js +475 -475
- package/core/cli/doctor.js +287 -287
- package/core/cli/ecosystem.js +162 -162
- package/core/cli/init.js +779 -779
- package/core/cli/migrate.js +541 -541
- package/core/cli/model.js +66 -66
- package/core/cli/nginx.js +199 -199
- package/core/cli/route.js +120 -120
- package/core/cli/view.js +55 -36
- package/core/config.d.ts +3 -3
- package/core/config.js +111 -111
- package/core/csrf.d.ts +3 -3
- package/core/csrf.js +114 -114
- package/core/database.d.ts +15 -15
- package/core/database.js +636 -636
- package/core/debug.d.ts +3 -3
- package/core/debug.js +249 -249
- package/core/hash.d.ts +3 -3
- package/core/hash.js +194 -194
- package/core/html.d.ts +42 -0
- package/core/html.js +217 -0
- package/core/index.d.ts +1176 -1071
- package/core/logger.d.ts +3 -3
- package/core/logger.js +127 -124
- package/core/middleware.d.ts +3 -3
- package/core/middleware.js +28 -28
- package/core/model.d.ts +19 -19
- package/core/model.js +600 -600
- package/core/queue.d.ts +13 -13
- package/core/queue.js +172 -172
- package/core/ratelimit.d.ts +3 -3
- package/core/ratelimit.js +145 -145
- package/core/redis.d.ts +21 -21
- package/core/redis.js +230 -230
- package/core/render-cache.js +212 -0
- package/core/render.d.ts +3 -3
- package/core/render.js +199 -555
- package/core/router.d.ts +3 -3
- package/core/router.js +171 -171
- package/core/seo.d.ts +3 -3
- package/core/seo.js +106 -106
- package/core/swagger.d.ts +3 -3
- package/core/swagger.js +60 -60
- package/core/upload.d.ts +13 -13
- package/core/upload.js +102 -102
- package/core/util/colors.js +82 -82
- package/core/validate.d.ts +15 -15
- package/core/validate.js +364 -364
- package/core/view-loader.js +162 -0
- package/core/vite.d.ts +3 -3
- package/core/vite.js +145 -145
- package/core/ws.d.ts +13 -13
- package/core/ws.js +245 -245
- package/index.js +18 -18
- package/jsconfig.json +15 -15
- package/package.json +85 -86
- package/production.md +273 -273
- package/public/css/bluebird.min.css +1 -1
- package/public/js/bluebird-client.js +1780 -1662
- package/public/js/bluebird.min.js +1072 -1072
- package/app/views/about.html +0 -161
- package/app/views/dashboard.html +0 -140
- package/app/views/index.html +0 -150
- package/app/views/login.html +0 -144
package/core/queue.d.ts
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
import {
|
|
2
|
-
Queue,
|
|
3
|
-
QueueDispatchOptions,
|
|
4
|
-
QueueJob,
|
|
5
|
-
QueueHandler,
|
|
6
|
-
} from "./index.js";
|
|
7
|
-
export default Queue;
|
|
8
|
-
export {
|
|
9
|
-
Queue,
|
|
10
|
-
QueueDispatchOptions,
|
|
11
|
-
QueueJob,
|
|
12
|
-
QueueHandler,
|
|
13
|
-
};
|
|
1
|
+
import {
|
|
2
|
+
Queue,
|
|
3
|
+
QueueDispatchOptions,
|
|
4
|
+
QueueJob,
|
|
5
|
+
QueueHandler,
|
|
6
|
+
} from "./index.js";
|
|
7
|
+
export default Queue;
|
|
8
|
+
export {
|
|
9
|
+
Queue,
|
|
10
|
+
QueueDispatchOptions,
|
|
11
|
+
QueueJob,
|
|
12
|
+
QueueHandler,
|
|
13
|
+
};
|
package/core/queue.js
CHANGED
|
@@ -1,172 +1,172 @@
|
|
|
1
|
-
import fs from "node:fs";
|
|
2
|
-
import path from "node:path";
|
|
3
|
-
import { getRedisClient } from "./cache.js";
|
|
4
|
-
|
|
5
|
-
/**
|
|
6
|
-
* Lightweight background queue worker module with Redis and in-memory fallback.
|
|
7
|
-
*/
|
|
8
|
-
class QueueManager {
|
|
9
|
-
constructor() {
|
|
10
|
-
this.handlers = new Map();
|
|
11
|
-
this.memoryQueue = [];
|
|
12
|
-
this.isProcessing = false;
|
|
13
|
-
this.isWorkerRunning = false;
|
|
14
|
-
this.shouldStop = false;
|
|
15
|
-
this.redisPrefix = "bluebird:queue:";
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
/**
|
|
19
|
-
* Registers a job handler function.
|
|
20
|
-
* @param {string} jobName - Name of the job.
|
|
21
|
-
* @param {Function} handler - Async function(payload).
|
|
22
|
-
*/
|
|
23
|
-
process(jobName, handler) {
|
|
24
|
-
if (typeof handler !== "function") {
|
|
25
|
-
throw new Error(`Handler for job '${jobName}' must be a function.`);
|
|
26
|
-
}
|
|
27
|
-
this.handlers.set(jobName, handler);
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
/**
|
|
31
|
-
* Dispatches a new job to the queue.
|
|
32
|
-
* @param {string} jobName - Name of the job.
|
|
33
|
-
* @param {any} [payload={}] - Data payload to pass to the handler.
|
|
34
|
-
* @param {Object} [options={}] - Options (e.g. delayMs).
|
|
35
|
-
* @returns {Promise<boolean>}
|
|
36
|
-
*/
|
|
37
|
-
async dispatch(jobName, payload = {}, options = {}) {
|
|
38
|
-
const jobItem = {
|
|
39
|
-
id: `${Date.now()}_${Math.random().toString(36).substring(2, 9)}`,
|
|
40
|
-
name: jobName,
|
|
41
|
-
payload,
|
|
42
|
-
createdAt: new Date().toISOString(),
|
|
43
|
-
};
|
|
44
|
-
|
|
45
|
-
const redis = getRedisClient();
|
|
46
|
-
if (redis && redis.isReady) {
|
|
47
|
-
try {
|
|
48
|
-
await redis.lPush(`${this.redisPrefix}jobs`, JSON.stringify(jobItem));
|
|
49
|
-
return true;
|
|
50
|
-
} catch (err) {
|
|
51
|
-
console.error("[QUEUE ERROR] Failed to dispatch job to Redis:", err.message);
|
|
52
|
-
}
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
if (options.delayMs && options.delayMs > 0) {
|
|
56
|
-
setTimeout(() => {
|
|
57
|
-
this.memoryQueue.push(jobItem);
|
|
58
|
-
this.runMemoryWorker();
|
|
59
|
-
}, options.delayMs);
|
|
60
|
-
} else {
|
|
61
|
-
this.memoryQueue.push(jobItem);
|
|
62
|
-
setImmediate(() => this.runMemoryWorker());
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
return true;
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
/**
|
|
69
|
-
* Starts the worker processing loop for Redis and in-memory jobs.
|
|
70
|
-
* @returns {Promise<void>}
|
|
71
|
-
*/
|
|
72
|
-
async work() {
|
|
73
|
-
this.isWorkerRunning = true;
|
|
74
|
-
this.shouldStop = false;
|
|
75
|
-
|
|
76
|
-
const redis = getRedisClient();
|
|
77
|
-
if (redis && redis.isReady) {
|
|
78
|
-
while (!this.shouldStop) {
|
|
79
|
-
try {
|
|
80
|
-
const result = await redis.brPop(`${this.redisPrefix}jobs`, 2);
|
|
81
|
-
if (result && result.element) {
|
|
82
|
-
const job = JSON.parse(result.element);
|
|
83
|
-
const handler = this.handlers.get(job.name);
|
|
84
|
-
if (handler) {
|
|
85
|
-
await handler(job.payload);
|
|
86
|
-
} else {
|
|
87
|
-
console.warn(`[QUEUE WARN] No handler registered for job '${job.name}'.`);
|
|
88
|
-
}
|
|
89
|
-
}
|
|
90
|
-
} catch (err) {
|
|
91
|
-
if (!this.shouldStop) {
|
|
92
|
-
await new Promise((resolve) => setTimeout(resolve, 1000));
|
|
93
|
-
}
|
|
94
|
-
}
|
|
95
|
-
}
|
|
96
|
-
this.isWorkerRunning = false;
|
|
97
|
-
return;
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
await this.runMemoryWorker();
|
|
101
|
-
this.isWorkerRunning = false;
|
|
102
|
-
}
|
|
103
|
-
|
|
104
|
-
/**
|
|
105
|
-
* Stops the background worker loop.
|
|
106
|
-
*/
|
|
107
|
-
stop() {
|
|
108
|
-
this.shouldStop = true;
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
/**
|
|
112
|
-
* Executes in-memory queue jobs sequentially.
|
|
113
|
-
* @private
|
|
114
|
-
*/
|
|
115
|
-
async runMemoryWorker() {
|
|
116
|
-
if (this.isProcessing || this.memoryQueue.length === 0) return;
|
|
117
|
-
this.isProcessing = true;
|
|
118
|
-
|
|
119
|
-
while (this.memoryQueue.length > 0) {
|
|
120
|
-
const job = this.memoryQueue.shift();
|
|
121
|
-
if (!job) continue;
|
|
122
|
-
|
|
123
|
-
const handler = this.handlers.get(job.name);
|
|
124
|
-
if (!handler) {
|
|
125
|
-
console.warn(`[QUEUE WARN] No handler registered for job '${job.name}'.`);
|
|
126
|
-
continue;
|
|
127
|
-
}
|
|
128
|
-
|
|
129
|
-
try {
|
|
130
|
-
await handler(job.payload);
|
|
131
|
-
} catch (err) {
|
|
132
|
-
console.error(`[QUEUE ERROR] Error processing job '${job.name}' (${job.id}):`, err);
|
|
133
|
-
}
|
|
134
|
-
}
|
|
135
|
-
|
|
136
|
-
this.isProcessing = false;
|
|
137
|
-
}
|
|
138
|
-
|
|
139
|
-
/**
|
|
140
|
-
* Auto-loads all job definition files from app/jobs/ (or legacy backend/jobs/).
|
|
141
|
-
* @param {string} [jobsDir]
|
|
142
|
-
*/
|
|
143
|
-
async loadJobs(jobsDir) {
|
|
144
|
-
const targetDir =
|
|
145
|
-
jobsDir ||
|
|
146
|
-
(fs.existsSync(path.resolve(process.cwd(), "app/jobs"))
|
|
147
|
-
? path.resolve(process.cwd(), "app/jobs")
|
|
148
|
-
: path.resolve(process.cwd(), "backend/jobs"));
|
|
149
|
-
|
|
150
|
-
if (!fs.existsSync(targetDir)) return;
|
|
151
|
-
|
|
152
|
-
const files = fs
|
|
153
|
-
.readdirSync(targetDir)
|
|
154
|
-
.filter((f) => f.endsWith(".js") || f.endsWith(".mjs") || f.endsWith(".ts"));
|
|
155
|
-
|
|
156
|
-
for (const file of files) {
|
|
157
|
-
const fullPath = path.join(targetDir, file);
|
|
158
|
-
try {
|
|
159
|
-
const module = await import(`file://${fullPath}`);
|
|
160
|
-
if (typeof module.default === "function") {
|
|
161
|
-
const jobName = path.basename(file, path.extname(file));
|
|
162
|
-
this.process(jobName, module.default);
|
|
163
|
-
}
|
|
164
|
-
} catch (err) {
|
|
165
|
-
console.error(`[QUEUE ERROR] Failed to load job file '${file}':`, err.message);
|
|
166
|
-
}
|
|
167
|
-
}
|
|
168
|
-
}
|
|
169
|
-
}
|
|
170
|
-
|
|
171
|
-
export const Queue = new QueueManager();
|
|
172
|
-
export default Queue;
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { getRedisClient } from "./cache.js";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Lightweight background queue worker module with Redis and in-memory fallback.
|
|
7
|
+
*/
|
|
8
|
+
class QueueManager {
|
|
9
|
+
constructor() {
|
|
10
|
+
this.handlers = new Map();
|
|
11
|
+
this.memoryQueue = [];
|
|
12
|
+
this.isProcessing = false;
|
|
13
|
+
this.isWorkerRunning = false;
|
|
14
|
+
this.shouldStop = false;
|
|
15
|
+
this.redisPrefix = "bluebird:queue:";
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Registers a job handler function.
|
|
20
|
+
* @param {string} jobName - Name of the job.
|
|
21
|
+
* @param {Function} handler - Async function(payload).
|
|
22
|
+
*/
|
|
23
|
+
process(jobName, handler) {
|
|
24
|
+
if (typeof handler !== "function") {
|
|
25
|
+
throw new Error(`Handler for job '${jobName}' must be a function.`);
|
|
26
|
+
}
|
|
27
|
+
this.handlers.set(jobName, handler);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Dispatches a new job to the queue.
|
|
32
|
+
* @param {string} jobName - Name of the job.
|
|
33
|
+
* @param {any} [payload={}] - Data payload to pass to the handler.
|
|
34
|
+
* @param {Object} [options={}] - Options (e.g. delayMs).
|
|
35
|
+
* @returns {Promise<boolean>}
|
|
36
|
+
*/
|
|
37
|
+
async dispatch(jobName, payload = {}, options = {}) {
|
|
38
|
+
const jobItem = {
|
|
39
|
+
id: `${Date.now()}_${Math.random().toString(36).substring(2, 9)}`,
|
|
40
|
+
name: jobName,
|
|
41
|
+
payload,
|
|
42
|
+
createdAt: new Date().toISOString(),
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
const redis = getRedisClient();
|
|
46
|
+
if (redis && redis.isReady) {
|
|
47
|
+
try {
|
|
48
|
+
await redis.lPush(`${this.redisPrefix}jobs`, JSON.stringify(jobItem));
|
|
49
|
+
return true;
|
|
50
|
+
} catch (err) {
|
|
51
|
+
console.error("[QUEUE ERROR] Failed to dispatch job to Redis:", err.message);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
if (options.delayMs && options.delayMs > 0) {
|
|
56
|
+
setTimeout(() => {
|
|
57
|
+
this.memoryQueue.push(jobItem);
|
|
58
|
+
this.runMemoryWorker();
|
|
59
|
+
}, options.delayMs);
|
|
60
|
+
} else {
|
|
61
|
+
this.memoryQueue.push(jobItem);
|
|
62
|
+
setImmediate(() => this.runMemoryWorker());
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
return true;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Starts the worker processing loop for Redis and in-memory jobs.
|
|
70
|
+
* @returns {Promise<void>}
|
|
71
|
+
*/
|
|
72
|
+
async work() {
|
|
73
|
+
this.isWorkerRunning = true;
|
|
74
|
+
this.shouldStop = false;
|
|
75
|
+
|
|
76
|
+
const redis = getRedisClient();
|
|
77
|
+
if (redis && redis.isReady) {
|
|
78
|
+
while (!this.shouldStop) {
|
|
79
|
+
try {
|
|
80
|
+
const result = await redis.brPop(`${this.redisPrefix}jobs`, 2);
|
|
81
|
+
if (result && result.element) {
|
|
82
|
+
const job = JSON.parse(result.element);
|
|
83
|
+
const handler = this.handlers.get(job.name);
|
|
84
|
+
if (handler) {
|
|
85
|
+
await handler(job.payload);
|
|
86
|
+
} else {
|
|
87
|
+
console.warn(`[QUEUE WARN] No handler registered for job '${job.name}'.`);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
} catch (err) {
|
|
91
|
+
if (!this.shouldStop) {
|
|
92
|
+
await new Promise((resolve) => setTimeout(resolve, 1000));
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
this.isWorkerRunning = false;
|
|
97
|
+
return;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
await this.runMemoryWorker();
|
|
101
|
+
this.isWorkerRunning = false;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Stops the background worker loop.
|
|
106
|
+
*/
|
|
107
|
+
stop() {
|
|
108
|
+
this.shouldStop = true;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Executes in-memory queue jobs sequentially.
|
|
113
|
+
* @private
|
|
114
|
+
*/
|
|
115
|
+
async runMemoryWorker() {
|
|
116
|
+
if (this.isProcessing || this.memoryQueue.length === 0) return;
|
|
117
|
+
this.isProcessing = true;
|
|
118
|
+
|
|
119
|
+
while (this.memoryQueue.length > 0) {
|
|
120
|
+
const job = this.memoryQueue.shift();
|
|
121
|
+
if (!job) continue;
|
|
122
|
+
|
|
123
|
+
const handler = this.handlers.get(job.name);
|
|
124
|
+
if (!handler) {
|
|
125
|
+
console.warn(`[QUEUE WARN] No handler registered for job '${job.name}'.`);
|
|
126
|
+
continue;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
try {
|
|
130
|
+
await handler(job.payload);
|
|
131
|
+
} catch (err) {
|
|
132
|
+
console.error(`[QUEUE ERROR] Error processing job '${job.name}' (${job.id}):`, err);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
this.isProcessing = false;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* Auto-loads all job definition files from app/jobs/ (or legacy backend/jobs/).
|
|
141
|
+
* @param {string} [jobsDir]
|
|
142
|
+
*/
|
|
143
|
+
async loadJobs(jobsDir) {
|
|
144
|
+
const targetDir =
|
|
145
|
+
jobsDir ||
|
|
146
|
+
(fs.existsSync(path.resolve(process.cwd(), "app/jobs"))
|
|
147
|
+
? path.resolve(process.cwd(), "app/jobs")
|
|
148
|
+
: path.resolve(process.cwd(), "backend/jobs"));
|
|
149
|
+
|
|
150
|
+
if (!fs.existsSync(targetDir)) return;
|
|
151
|
+
|
|
152
|
+
const files = fs
|
|
153
|
+
.readdirSync(targetDir)
|
|
154
|
+
.filter((f) => f.endsWith(".js") || f.endsWith(".mjs") || f.endsWith(".ts"));
|
|
155
|
+
|
|
156
|
+
for (const file of files) {
|
|
157
|
+
const fullPath = path.join(targetDir, file);
|
|
158
|
+
try {
|
|
159
|
+
const module = await import(`file://${fullPath}`);
|
|
160
|
+
if (typeof module.default === "function") {
|
|
161
|
+
const jobName = path.basename(file, path.extname(file));
|
|
162
|
+
this.process(jobName, module.default);
|
|
163
|
+
}
|
|
164
|
+
} catch (err) {
|
|
165
|
+
console.error(`[QUEUE ERROR] Failed to load job file '${file}':`, err.message);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
export const Queue = new QueueManager();
|
|
172
|
+
export default Queue;
|
package/core/ratelimit.d.ts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { RateLimit, RateLimitOptions } from "./index.js";
|
|
2
|
-
export default RateLimit;
|
|
3
|
-
export { RateLimit, RateLimitOptions };
|
|
1
|
+
import { RateLimit, RateLimitOptions } from "./index.js";
|
|
2
|
+
export default RateLimit;
|
|
3
|
+
export { RateLimit, RateLimitOptions };
|
package/core/ratelimit.js
CHANGED
|
@@ -1,145 +1,145 @@
|
|
|
1
|
-
import { getRedisClient } from "./cache.js";
|
|
2
|
-
|
|
3
|
-
/**
|
|
4
|
-
* In-memory store for rate limiting buckets.
|
|
5
|
-
* Maps client key to { count: number, resetTime: number }.
|
|
6
|
-
* @type {Map<string, {count: number, resetTime: number}>}
|
|
7
|
-
*/
|
|
8
|
-
const memoryBuckets = new Map();
|
|
9
|
-
|
|
10
|
-
setInterval(() => {
|
|
11
|
-
if (memoryBuckets.size === 0) return;
|
|
12
|
-
const now = Date.now();
|
|
13
|
-
for (const [key, bucket] of memoryBuckets) {
|
|
14
|
-
if (bucket.resetTime <= now) {
|
|
15
|
-
memoryBuckets.delete(key);
|
|
16
|
-
}
|
|
17
|
-
}
|
|
18
|
-
}, 60000).unref();
|
|
19
|
-
|
|
20
|
-
/**
|
|
21
|
-
* Native zero-dependency Rate Limiter supporting in-memory and Redis backends.
|
|
22
|
-
*/
|
|
23
|
-
class RateLimit {
|
|
24
|
-
/**
|
|
25
|
-
* Creates an Express rate-limiting middleware.
|
|
26
|
-
* @param {Object} [options={}] - Rate limit configuration options.
|
|
27
|
-
* @param {number} [options.windowMs=60000] - Time window in milliseconds (default: 60s).
|
|
28
|
-
* @param {number} [options.max=100] - Maximum requests allowed per window (default: 100).
|
|
29
|
-
* @param {string} [options.message="Too many requests, please try again later."] - Error message when rate limited.
|
|
30
|
-
* @param {number} [options.statusCode=429] - HTTP status code when rate limited.
|
|
31
|
-
* @param {boolean} [options.headers=true] - Whether to send X-RateLimit-* and Retry-After headers.
|
|
32
|
-
* @param {"memory"|"redis"} [options.driver="memory"] - Storage backend.
|
|
33
|
-
* @param {Function} [options.keyGenerator] - Custom key generator: (req) => string.
|
|
34
|
-
* @param {Function} [options.skip] - Predicate to bypass rate limiting: (req) => boolean.
|
|
35
|
-
* @returns {Function} Express middleware function.
|
|
36
|
-
*/
|
|
37
|
-
static middleware(options = {}) {
|
|
38
|
-
const windowMs = options.windowMs ?? 60000;
|
|
39
|
-
const max = options.max ?? 100;
|
|
40
|
-
const message = options.message ?? "Too many requests, please try again later.";
|
|
41
|
-
const statusCode = options.statusCode ?? 429;
|
|
42
|
-
const sendHeaders = options.headers ?? true;
|
|
43
|
-
const driver = options.driver || "memory";
|
|
44
|
-
const keyGenerator =
|
|
45
|
-
typeof options.keyGenerator === "function"
|
|
46
|
-
? options.keyGenerator
|
|
47
|
-
: (req) => req.ip || req.socket?.remoteAddress || "unknown";
|
|
48
|
-
const skip = typeof options.skip === "function" ? options.skip : null;
|
|
49
|
-
|
|
50
|
-
return async (req, res, next) => {
|
|
51
|
-
if (skip && skip(req)) {
|
|
52
|
-
return next();
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
const clientKey = `rl:${keyGenerator(req)}`;
|
|
56
|
-
const now = Date.now();
|
|
57
|
-
let count = 0;
|
|
58
|
-
let resetTime = now + windowMs;
|
|
59
|
-
|
|
60
|
-
const redis = driver === "redis" ? getRedisClient() : null;
|
|
61
|
-
if (redis) {
|
|
62
|
-
try {
|
|
63
|
-
const ttlSeconds = Math.ceil(windowMs / 1000);
|
|
64
|
-
count = await redis.incr(clientKey);
|
|
65
|
-
if (count === 1) {
|
|
66
|
-
await redis.expire(clientKey, ttlSeconds);
|
|
67
|
-
} else {
|
|
68
|
-
const pttl = await redis.pTTL(clientKey);
|
|
69
|
-
if (pttl > 0) {
|
|
70
|
-
resetTime = now + pttl;
|
|
71
|
-
}
|
|
72
|
-
}
|
|
73
|
-
} catch {
|
|
74
|
-
const bucket = RateLimit._incrementMemory(clientKey, now, windowMs);
|
|
75
|
-
count = bucket.count;
|
|
76
|
-
resetTime = bucket.resetTime;
|
|
77
|
-
}
|
|
78
|
-
} else {
|
|
79
|
-
const bucket = RateLimit._incrementMemory(clientKey, now, windowMs);
|
|
80
|
-
count = bucket.count;
|
|
81
|
-
resetTime = bucket.resetTime;
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
const remaining = Math.max(0, max - count);
|
|
85
|
-
const resetSeconds = Math.ceil((resetTime - now) / 1000);
|
|
86
|
-
|
|
87
|
-
if (sendHeaders) {
|
|
88
|
-
res.setHeader("X-RateLimit-Limit", String(max));
|
|
89
|
-
res.setHeader("X-RateLimit-Remaining", String(remaining));
|
|
90
|
-
res.setHeader("X-RateLimit-Reset", String(Math.ceil(resetTime / 1000)));
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
if (count > max) {
|
|
94
|
-
if (sendHeaders) {
|
|
95
|
-
res.setHeader("Retry-After", String(Math.max(1, resetSeconds)));
|
|
96
|
-
}
|
|
97
|
-
const expectsHtml =
|
|
98
|
-
req.headers.accept?.includes("text/html") && !req.path.startsWith("/api");
|
|
99
|
-
if (expectsHtml) {
|
|
100
|
-
return res.status(statusCode).send(`<h1>${statusCode} Too Many Requests</h1><p>${message}</p>`);
|
|
101
|
-
}
|
|
102
|
-
return res.status(statusCode).json({
|
|
103
|
-
status: "error",
|
|
104
|
-
message,
|
|
105
|
-
retryAfter: Math.max(1, resetSeconds),
|
|
106
|
-
});
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
next();
|
|
110
|
-
};
|
|
111
|
-
}
|
|
112
|
-
|
|
113
|
-
/**
|
|
114
|
-
* Increments the counter for a client key in memory.
|
|
115
|
-
* @private
|
|
116
|
-
* @param {string} key
|
|
117
|
-
* @param {number} now
|
|
118
|
-
* @param {number} windowMs
|
|
119
|
-
* @returns {{count: number, resetTime: number}}
|
|
120
|
-
*/
|
|
121
|
-
static _incrementMemory(key, now, windowMs) {
|
|
122
|
-
let bucket = memoryBuckets.get(key);
|
|
123
|
-
if (!bucket || bucket.resetTime <= now) {
|
|
124
|
-
bucket = { count: 1, resetTime: now + windowMs };
|
|
125
|
-
if (memoryBuckets.size >= 50000) {
|
|
126
|
-
const oldestKey = memoryBuckets.keys().next().value;
|
|
127
|
-
if (oldestKey !== undefined) memoryBuckets.delete(oldestKey);
|
|
128
|
-
}
|
|
129
|
-
memoryBuckets.set(key, bucket);
|
|
130
|
-
} else {
|
|
131
|
-
bucket.count += 1;
|
|
132
|
-
}
|
|
133
|
-
return bucket;
|
|
134
|
-
}
|
|
135
|
-
|
|
136
|
-
/**
|
|
137
|
-
* Clears all rate limit buckets in memory.
|
|
138
|
-
*/
|
|
139
|
-
static reset() {
|
|
140
|
-
memoryBuckets.clear();
|
|
141
|
-
}
|
|
142
|
-
}
|
|
143
|
-
|
|
144
|
-
export { RateLimit };
|
|
145
|
-
export default RateLimit;
|
|
1
|
+
import { getRedisClient } from "./cache.js";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* In-memory store for rate limiting buckets.
|
|
5
|
+
* Maps client key to { count: number, resetTime: number }.
|
|
6
|
+
* @type {Map<string, {count: number, resetTime: number}>}
|
|
7
|
+
*/
|
|
8
|
+
const memoryBuckets = new Map();
|
|
9
|
+
|
|
10
|
+
setInterval(() => {
|
|
11
|
+
if (memoryBuckets.size === 0) return;
|
|
12
|
+
const now = Date.now();
|
|
13
|
+
for (const [key, bucket] of memoryBuckets) {
|
|
14
|
+
if (bucket.resetTime <= now) {
|
|
15
|
+
memoryBuckets.delete(key);
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
}, 60000).unref();
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Native zero-dependency Rate Limiter supporting in-memory and Redis backends.
|
|
22
|
+
*/
|
|
23
|
+
class RateLimit {
|
|
24
|
+
/**
|
|
25
|
+
* Creates an Express rate-limiting middleware.
|
|
26
|
+
* @param {Object} [options={}] - Rate limit configuration options.
|
|
27
|
+
* @param {number} [options.windowMs=60000] - Time window in milliseconds (default: 60s).
|
|
28
|
+
* @param {number} [options.max=100] - Maximum requests allowed per window (default: 100).
|
|
29
|
+
* @param {string} [options.message="Too many requests, please try again later."] - Error message when rate limited.
|
|
30
|
+
* @param {number} [options.statusCode=429] - HTTP status code when rate limited.
|
|
31
|
+
* @param {boolean} [options.headers=true] - Whether to send X-RateLimit-* and Retry-After headers.
|
|
32
|
+
* @param {"memory"|"redis"} [options.driver="memory"] - Storage backend.
|
|
33
|
+
* @param {Function} [options.keyGenerator] - Custom key generator: (req) => string.
|
|
34
|
+
* @param {Function} [options.skip] - Predicate to bypass rate limiting: (req) => boolean.
|
|
35
|
+
* @returns {Function} Express middleware function.
|
|
36
|
+
*/
|
|
37
|
+
static middleware(options = {}) {
|
|
38
|
+
const windowMs = options.windowMs ?? 60000;
|
|
39
|
+
const max = options.max ?? 100;
|
|
40
|
+
const message = options.message ?? "Too many requests, please try again later.";
|
|
41
|
+
const statusCode = options.statusCode ?? 429;
|
|
42
|
+
const sendHeaders = options.headers ?? true;
|
|
43
|
+
const driver = options.driver || "memory";
|
|
44
|
+
const keyGenerator =
|
|
45
|
+
typeof options.keyGenerator === "function"
|
|
46
|
+
? options.keyGenerator
|
|
47
|
+
: (req) => req.ip || req.socket?.remoteAddress || "unknown";
|
|
48
|
+
const skip = typeof options.skip === "function" ? options.skip : null;
|
|
49
|
+
|
|
50
|
+
return async (req, res, next) => {
|
|
51
|
+
if (skip && skip(req)) {
|
|
52
|
+
return next();
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const clientKey = `rl:${keyGenerator(req)}`;
|
|
56
|
+
const now = Date.now();
|
|
57
|
+
let count = 0;
|
|
58
|
+
let resetTime = now + windowMs;
|
|
59
|
+
|
|
60
|
+
const redis = driver === "redis" ? getRedisClient() : null;
|
|
61
|
+
if (redis) {
|
|
62
|
+
try {
|
|
63
|
+
const ttlSeconds = Math.ceil(windowMs / 1000);
|
|
64
|
+
count = await redis.incr(clientKey);
|
|
65
|
+
if (count === 1) {
|
|
66
|
+
await redis.expire(clientKey, ttlSeconds);
|
|
67
|
+
} else {
|
|
68
|
+
const pttl = await redis.pTTL(clientKey);
|
|
69
|
+
if (pttl > 0) {
|
|
70
|
+
resetTime = now + pttl;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
} catch {
|
|
74
|
+
const bucket = RateLimit._incrementMemory(clientKey, now, windowMs);
|
|
75
|
+
count = bucket.count;
|
|
76
|
+
resetTime = bucket.resetTime;
|
|
77
|
+
}
|
|
78
|
+
} else {
|
|
79
|
+
const bucket = RateLimit._incrementMemory(clientKey, now, windowMs);
|
|
80
|
+
count = bucket.count;
|
|
81
|
+
resetTime = bucket.resetTime;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
const remaining = Math.max(0, max - count);
|
|
85
|
+
const resetSeconds = Math.ceil((resetTime - now) / 1000);
|
|
86
|
+
|
|
87
|
+
if (sendHeaders) {
|
|
88
|
+
res.setHeader("X-RateLimit-Limit", String(max));
|
|
89
|
+
res.setHeader("X-RateLimit-Remaining", String(remaining));
|
|
90
|
+
res.setHeader("X-RateLimit-Reset", String(Math.ceil(resetTime / 1000)));
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
if (count > max) {
|
|
94
|
+
if (sendHeaders) {
|
|
95
|
+
res.setHeader("Retry-After", String(Math.max(1, resetSeconds)));
|
|
96
|
+
}
|
|
97
|
+
const expectsHtml =
|
|
98
|
+
req.headers.accept?.includes("text/html") && !req.path.startsWith("/api");
|
|
99
|
+
if (expectsHtml) {
|
|
100
|
+
return res.status(statusCode).send(`<h1>${statusCode} Too Many Requests</h1><p>${message}</p>`);
|
|
101
|
+
}
|
|
102
|
+
return res.status(statusCode).json({
|
|
103
|
+
status: "error",
|
|
104
|
+
message,
|
|
105
|
+
retryAfter: Math.max(1, resetSeconds),
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
next();
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Increments the counter for a client key in memory.
|
|
115
|
+
* @private
|
|
116
|
+
* @param {string} key
|
|
117
|
+
* @param {number} now
|
|
118
|
+
* @param {number} windowMs
|
|
119
|
+
* @returns {{count: number, resetTime: number}}
|
|
120
|
+
*/
|
|
121
|
+
static _incrementMemory(key, now, windowMs) {
|
|
122
|
+
let bucket = memoryBuckets.get(key);
|
|
123
|
+
if (!bucket || bucket.resetTime <= now) {
|
|
124
|
+
bucket = { count: 1, resetTime: now + windowMs };
|
|
125
|
+
if (memoryBuckets.size >= 50000) {
|
|
126
|
+
const oldestKey = memoryBuckets.keys().next().value;
|
|
127
|
+
if (oldestKey !== undefined) memoryBuckets.delete(oldestKey);
|
|
128
|
+
}
|
|
129
|
+
memoryBuckets.set(key, bucket);
|
|
130
|
+
} else {
|
|
131
|
+
bucket.count += 1;
|
|
132
|
+
}
|
|
133
|
+
return bucket;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* Clears all rate limit buckets in memory.
|
|
138
|
+
*/
|
|
139
|
+
static reset() {
|
|
140
|
+
memoryBuckets.clear();
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
export { RateLimit };
|
|
145
|
+
export default RateLimit;
|