@terreno/api 57.12.0 → 57.14.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/dist/index.d.ts +1 -0
- package/dist/index.js +5 -3
- package/dist/rateLimit/middleware.d.ts +8 -0
- package/dist/rateLimit/middleware.js +3 -2
- package/dist/rateLimit/routeRateLimit.d.ts +26 -0
- package/dist/rateLimit/routeRateLimit.js +69 -0
- package/package.json +3 -3
- package/src/index.ts +4 -0
- package/src/rateLimit/middleware.ts +1 -1
- package/src/rateLimit/routeRateLimit.test.ts +83 -0
- package/src/rateLimit/routeRateLimit.ts +94 -0
package/dist/index.d.ts
CHANGED
|
@@ -65,6 +65,7 @@ export * from "./orgs/orgsApp";
|
|
|
65
65
|
export * from "./permissions";
|
|
66
66
|
export * from "./plugins";
|
|
67
67
|
export * from "./populate";
|
|
68
|
+
export { createRouteRateLimitMiddleware, type RouteRateLimitOptions, } from "./rateLimit/routeRateLimit";
|
|
68
69
|
export type { RateLimitLimits, RateLimitOptions, RateLimitRedisClient, RateLimitStore, } from "./rateLimit/types";
|
|
69
70
|
export { DEFAULT_API_MAX, DEFAULT_AUTH_MAX, DEFAULT_WINDOW_MS, } from "./rateLimit/types";
|
|
70
71
|
export * from "./rbac/access";
|
package/dist/index.js
CHANGED
|
@@ -14,9 +14,9 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
|
14
14
|
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
15
|
};
|
|
16
16
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
-
exports.
|
|
18
|
-
exports.
|
|
19
|
-
exports.z = void 0;
|
|
17
|
+
exports.terrenoDefaultRoles = exports.READ_ONLY_ROLE_PERMISSIONS = exports.organizationOperatorRole = exports.expandRolePermissions = exports.createRbacRoleModel = exports.ORG_ADMIN_PERMISSION_BUNDLE = exports.membershipOrgAdminPermissionSource = exports.MEMBERSHIP_ORG_ADMIN_PERMISSION_SOURCE_NAME = exports.backfillAdmins = exports.recordRbacAudit = exports.createRbacAuditModel = exports.assertAllowed = exports.DEFAULT_WINDOW_MS = exports.DEFAULT_AUTH_MAX = exports.DEFAULT_API_MAX = exports.createRouteRateLimitMiddleware = exports.notificationsBeforeSend = exports.NotificationsApp = exports.getNotificationService = exports.createNotificationService = exports.configureNotificationService = exports.getAllMCPTools = exports.generateToolsForEntry = exports.generateAllTools = exports.resolveMcpServiceTokensOption = exports.MAX_ACTIVE_MCP_SERVICE_TOKENS = exports.addMcpServiceTokenRoutes = exports.mountMCPServer = exports.generateToolDescription = exports.generateInputSchema = exports.updateMCPRegistryOptions = exports.registerMCPTool = exports.registerMCPModel = exports.getMCPRegistry = exports.clearMCPRegistry = exports.extractUserFromHeaders = exports.publicFrameworkModelName = exports.FRAMEWORK_MODEL_PUBLIC_NAMES = exports.resetAuditRecorderForTests = exports.recordAuditEvent = exports.persistEnqueuedAuditEvent = exports.maybeRecordAdminAudit = exports.isAuditRecorderInstalled = exports.flushAuditRecorderForTests = exports.persistRbacAuditToAuditEvent = exports.createCloudTasksAuditEnqueue = exports.auditEnqueueFromEnv = exports.AUDIT_SECRET_HEADER = exports.createAuditEventModel = exports.AuditApp = void 0;
|
|
18
|
+
exports.twilioSignature = exports.stripeSignature = exports.sendgridEventSignature = exports.hmacSignature = exports.createMemoryIdempotencyStore = exports.stripAdminBodyFields = exports.scrubAdminFields = exports.adminBodyFieldsToStrip = exports.SYSTEM_FIELD_PATHS = exports.nestDottedFieldDescriptions = exports.modelDescriptionToOpenApiSpec = exports.modelDescriptionToAdminFields = exports.fieldDescriptionToZodType = exports.fieldDescriptionToOpenApiProperty = exports.fieldDescriptionToAdminMeta = exports.describeModelForRouter = exports.describeModel = exports.getSocketUser = exports.createSocketAuthMiddleware = exports.createLegacyJwtValidator = exports.createBetterAuthValidator = exports.startSessionRevalidationSweep = exports.runSessionRevalidationSweep = exports.revalidateSocketSession = exports.reresolveSyncRoomsForSocket = exports.loadFullUserForSocket = exports.DEFAULT_SESSION_REVALIDATION_INTERVAL_MS = exports.updateRealtimeRegistryOptions = exports.registerRealtime = exports.getRealtimeRegistry = exports.findRegistryEntryByRoutePath = exports.findRegistryEntryByCollection = exports.clearRealtimeRegistry = exports.RealtimeApp = exports.MAX_QUERY_SUBSCRIPTIONS = exports.MAX_MODEL_SUBSCRIPTIONS = exports.MAX_DOCUMENT_SUBSCRIPTIONS = exports.installRealtimeSocketHandlers = exports.removeQuerySubscription = exports.removeAllSocketQueries = exports.getQuerySubscriptionsForCollection = exports.computeQueryId = exports.clearQueryStore = exports.addQuerySubscription = exports.matchesQuery = exports.stopChangeStreamWatcher = exports.startChangeStreamWatcher = exports.emitSyncDeltaForChange = exports.emitPayloadToAuthorizedRoom = exports.rbacRouter = void 0;
|
|
19
|
+
exports.z = exports.WebhooksApp = void 0;
|
|
20
20
|
__exportStar(require("./actions"), exports);
|
|
21
21
|
__exportStar(require("./adminTypes"), exports);
|
|
22
22
|
__exportStar(require("./api"), exports);
|
|
@@ -116,6 +116,8 @@ __exportStar(require("./orgs/orgsApp"), exports);
|
|
|
116
116
|
__exportStar(require("./permissions"), exports);
|
|
117
117
|
__exportStar(require("./plugins"), exports);
|
|
118
118
|
__exportStar(require("./populate"), exports);
|
|
119
|
+
var routeRateLimit_1 = require("./rateLimit/routeRateLimit");
|
|
120
|
+
Object.defineProperty(exports, "createRouteRateLimitMiddleware", { enumerable: true, get: function () { return routeRateLimit_1.createRouteRateLimitMiddleware; } });
|
|
119
121
|
var types_1 = require("./rateLimit/types");
|
|
120
122
|
Object.defineProperty(exports, "DEFAULT_API_MAX", { enumerable: true, get: function () { return types_1.DEFAULT_API_MAX; } });
|
|
121
123
|
Object.defineProperty(exports, "DEFAULT_AUTH_MAX", { enumerable: true, get: function () { return types_1.DEFAULT_AUTH_MAX; } });
|
|
@@ -1,3 +1,11 @@
|
|
|
1
1
|
import type { NextFunction, Request, Response } from "express";
|
|
2
2
|
import type { RateLimitOptions, RateLimitStore } from "./types";
|
|
3
|
+
export declare const setRateLimitExceededHeaders: ({ max, remaining, resetAt, now, windowMs, res, }: {
|
|
4
|
+
max: number;
|
|
5
|
+
remaining: number;
|
|
6
|
+
resetAt: number;
|
|
7
|
+
now: number;
|
|
8
|
+
windowMs: number;
|
|
9
|
+
res: Response;
|
|
10
|
+
}) => void;
|
|
3
11
|
export declare const createRateLimitMiddleware: (store: RateLimitStore, options?: RateLimitOptions) => ((req: Request, res: Response, next: NextFunction) => Promise<void>);
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.createRateLimitMiddleware = void 0;
|
|
3
|
+
exports.createRateLimitMiddleware = exports.setRateLimitExceededHeaders = void 0;
|
|
4
4
|
const luxon_1 = require("luxon");
|
|
5
5
|
const errors_1 = require("../errors");
|
|
6
6
|
const policies_1 = require("./policies");
|
|
@@ -15,6 +15,7 @@ const setRateLimitExceededHeaders = ({ max, remaining, resetAt, now, windowMs, r
|
|
|
15
15
|
res.setHeader("RateLimit", `limit=${max}, remaining=${remaining}, reset=${retryAfter}`);
|
|
16
16
|
res.setHeader("RateLimit-Policy", `${max};w=${windowSec}`);
|
|
17
17
|
};
|
|
18
|
+
exports.setRateLimitExceededHeaders = setRateLimitExceededHeaders;
|
|
18
19
|
const createRateLimitMiddleware = (store, options = {}) => {
|
|
19
20
|
const windowMs = options.limits?.windowMs ?? types_1.DEFAULT_WINDOW_MS;
|
|
20
21
|
const authMax = options.limits?.authMax ?? types_1.DEFAULT_AUTH_MAX;
|
|
@@ -36,7 +37,7 @@ const createRateLimitMiddleware = (store, options = {}) => {
|
|
|
36
37
|
next();
|
|
37
38
|
return;
|
|
38
39
|
}
|
|
39
|
-
setRateLimitExceededHeaders({
|
|
40
|
+
(0, exports.setRateLimitExceededHeaders)({
|
|
40
41
|
max,
|
|
41
42
|
now,
|
|
42
43
|
remaining: result.remaining,
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import type { NextFunction, Request, Response } from "express";
|
|
2
|
+
import type { RateLimitOptions, RateLimitStore } from "./types";
|
|
3
|
+
export interface RouteRateLimitOptions {
|
|
4
|
+
/** Bucket namespace so separate route limits never share counters. */
|
|
5
|
+
name: string;
|
|
6
|
+
/** Requests allowed per key in each window. */
|
|
7
|
+
max: number;
|
|
8
|
+
windowMs: number;
|
|
9
|
+
/** Shared backing store. Defaults to `memory` (per process). */
|
|
10
|
+
store?: RateLimitOptions["store"];
|
|
11
|
+
/**
|
|
12
|
+
* Bucket key. `ip` (default) uses `req.ip`, so set Express `trust proxy` behind a load
|
|
13
|
+
* balancer. `user` keys by authenticated user id and falls back to IP.
|
|
14
|
+
*/
|
|
15
|
+
keyBy?: "ip" | "user";
|
|
16
|
+
/** Test-only clock. */
|
|
17
|
+
now?: () => number;
|
|
18
|
+
/** Test-only store override. */
|
|
19
|
+
storeImpl?: RateLimitStore;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Express middleware enforcing a fixed-window limit on a single route, independent of the
|
|
23
|
+
* global `TerrenoApp` `rateLimit` buckets. Use it for expensive or abuse-prone endpoints
|
|
24
|
+
* such as uploads.
|
|
25
|
+
*/
|
|
26
|
+
export declare const createRouteRateLimitMiddleware: (options: RouteRateLimitOptions) => ((req: Request, res: Response, next: NextFunction) => Promise<void>);
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.createRouteRateLimitMiddleware = void 0;
|
|
4
|
+
const luxon_1 = require("luxon");
|
|
5
|
+
const errors_1 = require("../errors");
|
|
6
|
+
const createStore_1 = require("./createStore");
|
|
7
|
+
const middleware_1 = require("./middleware");
|
|
8
|
+
const requestIp = (req) => {
|
|
9
|
+
return req.ip || req.socket?.remoteAddress || "unknown";
|
|
10
|
+
};
|
|
11
|
+
const routeRateLimitKey = (req, keyBy) => {
|
|
12
|
+
if (keyBy === "user") {
|
|
13
|
+
const user = req.user;
|
|
14
|
+
const userId = user?.id ?? (user?._id != null ? String(user._id) : undefined);
|
|
15
|
+
if (userId) {
|
|
16
|
+
return `user:${userId}`;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
return `ip:${requestIp(req)}`;
|
|
20
|
+
};
|
|
21
|
+
/**
|
|
22
|
+
* Express middleware enforcing a fixed-window limit on a single route, independent of the
|
|
23
|
+
* global `TerrenoApp` `rateLimit` buckets. Use it for expensive or abuse-prone endpoints
|
|
24
|
+
* such as uploads.
|
|
25
|
+
*/
|
|
26
|
+
const createRouteRateLimitMiddleware = (options) => {
|
|
27
|
+
if (!options.name) {
|
|
28
|
+
throw new errors_1.APIError({ status: 500, title: "Route rate limit requires a name" });
|
|
29
|
+
}
|
|
30
|
+
if (!(options.max > 0) || !(options.windowMs > 0)) {
|
|
31
|
+
throw new errors_1.APIError({
|
|
32
|
+
status: 500,
|
|
33
|
+
title: "Route rate limit max and windowMs must be positive",
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
const store = (0, createStore_1.createRateLimitStore)({ store: options.store, storeImpl: options.storeImpl });
|
|
37
|
+
const keyBy = options.keyBy ?? "ip";
|
|
38
|
+
const nowFn = options.now ?? (() => luxon_1.DateTime.now().toMillis());
|
|
39
|
+
const { max, windowMs } = options;
|
|
40
|
+
return async (req, res, next) => {
|
|
41
|
+
const key = `route:${options.name}:${routeRateLimitKey(req, keyBy)}`;
|
|
42
|
+
const now = nowFn();
|
|
43
|
+
try {
|
|
44
|
+
const result = await store.consume({ key, max, now, windowMs });
|
|
45
|
+
if (result.allowed) {
|
|
46
|
+
next();
|
|
47
|
+
return;
|
|
48
|
+
}
|
|
49
|
+
(0, middleware_1.setRateLimitExceededHeaders)({
|
|
50
|
+
max,
|
|
51
|
+
now,
|
|
52
|
+
remaining: result.remaining,
|
|
53
|
+
res,
|
|
54
|
+
resetAt: result.resetAt,
|
|
55
|
+
windowMs,
|
|
56
|
+
});
|
|
57
|
+
next(new errors_1.APIError({
|
|
58
|
+
code: "rate-limit-exceeded",
|
|
59
|
+
disableExternalErrorTracking: true,
|
|
60
|
+
status: 429,
|
|
61
|
+
title: "Too many requests",
|
|
62
|
+
}));
|
|
63
|
+
}
|
|
64
|
+
catch (error) {
|
|
65
|
+
next(error);
|
|
66
|
+
}
|
|
67
|
+
};
|
|
68
|
+
};
|
|
69
|
+
exports.createRouteRateLimitMiddleware = createRouteRateLimitMiddleware;
|
package/package.json
CHANGED
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
"@modelcontextprotocol/node": "^2.0.0",
|
|
12
12
|
"@modelcontextprotocol/server": "^2.0.0",
|
|
13
13
|
"@sentry/bun": "^10.39.0",
|
|
14
|
-
"@terreno/test": "57.
|
|
14
|
+
"@terreno/test": "57.14.0",
|
|
15
15
|
"@thream/socketio-jwt": "^3.1.4",
|
|
16
16
|
"@types/qs": "^6.14.0",
|
|
17
17
|
"ajv": "8.20.0",
|
|
@@ -48,7 +48,7 @@
|
|
|
48
48
|
"devDependencies": {
|
|
49
49
|
"@biomejs/biome": "^2.3.6",
|
|
50
50
|
"@modelcontextprotocol/client": "^2.0.0",
|
|
51
|
-
"@terreno/syncdb": "57.
|
|
51
|
+
"@terreno/syncdb": "57.14.0",
|
|
52
52
|
"@types/bun": "^1.4.0",
|
|
53
53
|
"@types/cors": "^2.8.17",
|
|
54
54
|
"@types/express": "^5.0.6",
|
|
@@ -132,5 +132,5 @@
|
|
|
132
132
|
"updateSnapshot": "bun test --update-snapshots"
|
|
133
133
|
},
|
|
134
134
|
"types": "dist/index.d.ts",
|
|
135
|
-
"version": "57.
|
|
135
|
+
"version": "57.14.0"
|
|
136
136
|
}
|
package/src/index.ts
CHANGED
|
@@ -133,6 +133,10 @@ export * from "./orgs/orgsApp";
|
|
|
133
133
|
export * from "./permissions";
|
|
134
134
|
export * from "./plugins";
|
|
135
135
|
export * from "./populate";
|
|
136
|
+
export {
|
|
137
|
+
createRouteRateLimitMiddleware,
|
|
138
|
+
type RouteRateLimitOptions,
|
|
139
|
+
} from "./rateLimit/routeRateLimit";
|
|
136
140
|
export type {
|
|
137
141
|
RateLimitLimits,
|
|
138
142
|
RateLimitOptions,
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import {describe, expect, it} from "bun:test";
|
|
2
|
+
import express from "express";
|
|
3
|
+
import supertest from "supertest";
|
|
4
|
+
|
|
5
|
+
import {apiErrorMiddleware} from "../errors";
|
|
6
|
+
import {createMemoryRateLimitStore} from "./memoryStore";
|
|
7
|
+
import {createRouteRateLimitMiddleware, type RouteRateLimitOptions} from "./routeRateLimit";
|
|
8
|
+
|
|
9
|
+
const buildApp = (
|
|
10
|
+
options: Partial<RouteRateLimitOptions> & {userId?: string} = {}
|
|
11
|
+
): express.Application => {
|
|
12
|
+
const {userId, ...limitOptions} = options;
|
|
13
|
+
const app = express();
|
|
14
|
+
app.set("trust proxy", true);
|
|
15
|
+
app.use((req, _res, next) => {
|
|
16
|
+
if (userId) {
|
|
17
|
+
(req as unknown as {user: {id: string}}).user = {id: userId};
|
|
18
|
+
}
|
|
19
|
+
next();
|
|
20
|
+
});
|
|
21
|
+
app.post(
|
|
22
|
+
"/upload",
|
|
23
|
+
createRouteRateLimitMiddleware({max: 1, name: "upload", windowMs: 60_000, ...limitOptions}),
|
|
24
|
+
(_req, res) => {
|
|
25
|
+
res.json({ok: true});
|
|
26
|
+
}
|
|
27
|
+
);
|
|
28
|
+
app.use(apiErrorMiddleware);
|
|
29
|
+
return app;
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
describe("createRouteRateLimitMiddleware", () => {
|
|
33
|
+
it("allows max requests per IP then returns 429 with Retry-After", async () => {
|
|
34
|
+
const app = buildApp();
|
|
35
|
+
await supertest(app).post("/upload").set("X-Forwarded-For", "1.1.1.1").expect(200);
|
|
36
|
+
const res = await supertest(app).post("/upload").set("X-Forwarded-For", "1.1.1.1").expect(429);
|
|
37
|
+
expect(res.headers["retry-after"]).toBe("60");
|
|
38
|
+
expect(res.headers["ratelimit-policy"]).toBe("1;w=60");
|
|
39
|
+
expect(res.body.title).toBe("Too many requests");
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
it("keeps separate buckets per IP", async () => {
|
|
43
|
+
const app = buildApp();
|
|
44
|
+
await supertest(app).post("/upload").set("X-Forwarded-For", "1.1.1.1").expect(200);
|
|
45
|
+
await supertest(app).post("/upload").set("X-Forwarded-For", "2.2.2.2").expect(200);
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
it("resets after the window elapses", async () => {
|
|
49
|
+
let now = 1_000_000;
|
|
50
|
+
const app = buildApp({now: () => now});
|
|
51
|
+
await supertest(app).post("/upload").expect(200);
|
|
52
|
+
await supertest(app).post("/upload").expect(429);
|
|
53
|
+
now += 60_000;
|
|
54
|
+
await supertest(app).post("/upload").expect(200);
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
it("keys by user when keyBy is user", async () => {
|
|
58
|
+
const storeImpl = createMemoryRateLimitStore();
|
|
59
|
+
const appA = buildApp({keyBy: "user", storeImpl, userId: "a"});
|
|
60
|
+
const appB = buildApp({keyBy: "user", storeImpl, userId: "b"});
|
|
61
|
+
await supertest(appA).post("/upload").set("X-Forwarded-For", "1.1.1.1").expect(200);
|
|
62
|
+
await supertest(appB).post("/upload").set("X-Forwarded-For", "1.1.1.1").expect(200);
|
|
63
|
+
await supertest(appA).post("/upload").set("X-Forwarded-For", "2.2.2.2").expect(429);
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
it("namespaces buckets by name", async () => {
|
|
67
|
+
const storeImpl = createMemoryRateLimitStore();
|
|
68
|
+
await supertest(buildApp({name: "one", storeImpl}))
|
|
69
|
+
.post("/upload")
|
|
70
|
+
.expect(200);
|
|
71
|
+
await supertest(buildApp({name: "two", storeImpl}))
|
|
72
|
+
.post("/upload")
|
|
73
|
+
.expect(200);
|
|
74
|
+
await supertest(buildApp({name: "one", storeImpl}))
|
|
75
|
+
.post("/upload")
|
|
76
|
+
.expect(429);
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
it("rejects invalid configuration", () => {
|
|
80
|
+
expect(() => createRouteRateLimitMiddleware({max: 0, name: "x", windowMs: 1000})).toThrow();
|
|
81
|
+
expect(() => createRouteRateLimitMiddleware({max: 1, name: "", windowMs: 1000})).toThrow();
|
|
82
|
+
});
|
|
83
|
+
});
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import type {NextFunction, Request, Response} from "express";
|
|
2
|
+
import {DateTime} from "luxon";
|
|
3
|
+
|
|
4
|
+
import {APIError} from "../errors";
|
|
5
|
+
import {createRateLimitStore} from "./createStore";
|
|
6
|
+
import {setRateLimitExceededHeaders} from "./middleware";
|
|
7
|
+
import type {RateLimitOptions, RateLimitStore} from "./types";
|
|
8
|
+
|
|
9
|
+
export interface RouteRateLimitOptions {
|
|
10
|
+
/** Bucket namespace so separate route limits never share counters. */
|
|
11
|
+
name: string;
|
|
12
|
+
/** Requests allowed per key in each window. */
|
|
13
|
+
max: number;
|
|
14
|
+
windowMs: number;
|
|
15
|
+
/** Shared backing store. Defaults to `memory` (per process). */
|
|
16
|
+
store?: RateLimitOptions["store"];
|
|
17
|
+
/**
|
|
18
|
+
* Bucket key. `ip` (default) uses `req.ip`, so set Express `trust proxy` behind a load
|
|
19
|
+
* balancer. `user` keys by authenticated user id and falls back to IP.
|
|
20
|
+
*/
|
|
21
|
+
keyBy?: "ip" | "user";
|
|
22
|
+
/** Test-only clock. */
|
|
23
|
+
now?: () => number;
|
|
24
|
+
/** Test-only store override. */
|
|
25
|
+
storeImpl?: RateLimitStore;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const requestIp = (req: Request): string => {
|
|
29
|
+
return req.ip || req.socket?.remoteAddress || "unknown";
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
const routeRateLimitKey = (req: Request, keyBy: "ip" | "user"): string => {
|
|
33
|
+
if (keyBy === "user") {
|
|
34
|
+
const user = req.user as {_id?: unknown; id?: string} | undefined;
|
|
35
|
+
const userId = user?.id ?? (user?._id != null ? String(user._id) : undefined);
|
|
36
|
+
if (userId) {
|
|
37
|
+
return `user:${userId}`;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
return `ip:${requestIp(req)}`;
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Express middleware enforcing a fixed-window limit on a single route, independent of the
|
|
45
|
+
* global `TerrenoApp` `rateLimit` buckets. Use it for expensive or abuse-prone endpoints
|
|
46
|
+
* such as uploads.
|
|
47
|
+
*/
|
|
48
|
+
export const createRouteRateLimitMiddleware = (
|
|
49
|
+
options: RouteRateLimitOptions
|
|
50
|
+
): ((req: Request, res: Response, next: NextFunction) => Promise<void>) => {
|
|
51
|
+
if (!options.name) {
|
|
52
|
+
throw new APIError({status: 500, title: "Route rate limit requires a name"});
|
|
53
|
+
}
|
|
54
|
+
if (!(options.max > 0) || !(options.windowMs > 0)) {
|
|
55
|
+
throw new APIError({
|
|
56
|
+
status: 500,
|
|
57
|
+
title: "Route rate limit max and windowMs must be positive",
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
const store = createRateLimitStore({store: options.store, storeImpl: options.storeImpl});
|
|
61
|
+
const keyBy = options.keyBy ?? "ip";
|
|
62
|
+
const nowFn = options.now ?? ((): number => DateTime.now().toMillis());
|
|
63
|
+
const {max, windowMs} = options;
|
|
64
|
+
|
|
65
|
+
return async (req: Request, res: Response, next: NextFunction): Promise<void> => {
|
|
66
|
+
const key = `route:${options.name}:${routeRateLimitKey(req, keyBy)}`;
|
|
67
|
+
const now = nowFn();
|
|
68
|
+
try {
|
|
69
|
+
const result = await store.consume({key, max, now, windowMs});
|
|
70
|
+
if (result.allowed) {
|
|
71
|
+
next();
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
setRateLimitExceededHeaders({
|
|
75
|
+
max,
|
|
76
|
+
now,
|
|
77
|
+
remaining: result.remaining,
|
|
78
|
+
res,
|
|
79
|
+
resetAt: result.resetAt,
|
|
80
|
+
windowMs,
|
|
81
|
+
});
|
|
82
|
+
next(
|
|
83
|
+
new APIError({
|
|
84
|
+
code: "rate-limit-exceeded",
|
|
85
|
+
disableExternalErrorTracking: true,
|
|
86
|
+
status: 429,
|
|
87
|
+
title: "Too many requests",
|
|
88
|
+
})
|
|
89
|
+
);
|
|
90
|
+
} catch (error) {
|
|
91
|
+
next(error);
|
|
92
|
+
}
|
|
93
|
+
};
|
|
94
|
+
};
|