@sdflc/backend-helpers 1.0.113 → 1.0.115

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.
@@ -1,14 +1,15 @@
1
1
  "use strict";
2
+ // ./src/apiContext.ts
2
3
  var __importDefault = (this && this.__importDefault) || function (mod) {
3
4
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
5
  };
5
6
  Object.defineProperty(exports, "__esModule", { value: true });
6
7
  exports.createContextDefault = exports.createApiContext = void 0;
7
- // ./src/apiContext.ts
8
8
  const lodash_1 = require("lodash");
9
9
  const uuid_1 = require("uuid");
10
10
  const check_types_1 = __importDefault(require("check-types"));
11
11
  const utils_1 = require("@sdflc/utils");
12
+ const IpRateLimiter_1 = require("./IpRateLimiter");
12
13
  const Database_1 = require("./Database");
13
14
  const constants_1 = require("./constants");
14
15
  const resolveClientIp_1 = require("./resolveClientIp");
@@ -40,7 +41,11 @@ const createApiContext = async (args) => {
40
41
  };
41
42
  exports.createApiContext = createApiContext;
42
43
  const createContextDefault = async (args) => {
43
- const { knexConfig, isProduction, logger, doAuth, spaceGw, interserviceApiKey, jwtSecret, verifyTokenArgs, dbType, dbSchema, cores, gateways, req, res, extendContext, getCoreContext, getGatewayContext, authorizationToken, db: inDb, } = args || {};
44
+ const { knexConfig, isProduction, logger, doAuth, spaceGw, interserviceApiKey, jwtSecret, verifyTokenArgs, dbType, dbSchema, cores, gateways, req, res, extendContext, getCoreContext, getGatewayContext, authorizationToken, db: inDb,
45
+ // Rate limiting — both optional. If redisClient is provided and no custom
46
+ // rateLimiter is given, a built-in IpRateLimiter is constructed here once
47
+ // and shared across every core for the lifetime of this context.
48
+ redisClient, rateLimiter: inRateLimiter, globalRateLimit, } = args || {};
44
49
  const headers = req.headers || { noHeadersSetup: true };
45
50
  const cookies = req.cookies || { noCookiesSetup: true };
46
51
  const authorization = (headers[constants_1.HEADERS.AUTHORIZATION] || authorizationToken || '').replace('Bearer ', '');
@@ -64,6 +69,14 @@ const createContextDefault = async (args) => {
64
69
  dbSchema,
65
70
  logger,
66
71
  });
72
+ // Resolve the rate-limiter once here so every core shares the same instance
73
+ // for the lifetime of this context (i.e. the duration of a single request).
74
+ // Priority: explicit rateLimiter arg > auto-construct from redisClient > none.
75
+ // null is a valid explicit value meaning "disable rate limiting entirely".
76
+ let rateLimiter = inRateLimiter;
77
+ if (rateLimiter === undefined && redisClient != null) {
78
+ rateLimiter = new IpRateLimiter_1.IpRateLimiter(redisClient, logger);
79
+ }
67
80
  const sharedContext = {
68
81
  spaceId,
69
82
  apiKey,
@@ -76,12 +89,12 @@ const createContextDefault = async (args) => {
76
89
  requestedLang,
77
90
  authorization,
78
91
  fingerprint,
79
- req,
80
- res,
81
- headers,
82
- cookies,
83
92
  authorizationToken,
84
93
  isExternalDb: !!inDb,
94
+ // Rate limiting — undefined values are omitted so context stays clean when
95
+ // neither is configured.
96
+ ...(rateLimiter !== undefined ? { rateLimiter } : {}),
97
+ ...(globalRateLimit !== undefined ? { globalRateLimit } : {}),
85
98
  };
86
99
  return await (0, exports.createApiContext)({
87
100
  cores,
@@ -97,7 +110,7 @@ const createContextDefault = async (args) => {
97
110
  }
98
111
  },
99
112
  getCoreContext: async (args) => {
100
- let extendCoreContext = {}; // fixed typo: extendCoreConext → extendCoreContext
113
+ let extendCoreContext = {};
101
114
  if (check_types_1.default.function(getCoreContext)) {
102
115
  extendCoreContext = await getCoreContext(args);
103
116
  }
@@ -115,7 +128,7 @@ const createContextDefault = async (args) => {
115
128
  };
116
129
  },
117
130
  getGatewayContext: async (args) => {
118
- let extendGatewayContext = {}; // fixed typo: extendGatewayConext → extendGatewayContext
131
+ let extendGatewayContext = {};
119
132
  if (check_types_1.default.function(getGatewayContext)) {
120
133
  extendGatewayContext = await getGatewayContext(args);
121
134
  }
@@ -13,9 +13,36 @@ import { BaseCorePropsInterface, BaseCoreActionsInterface, CoreActionInterface,
13
13
  * - Database transaction management
14
14
  * - Calling gateway methods and transforming results
15
15
  * - Consistent error handling and OpResult wrapping
16
+ * - Optional IP-based rate limiting (via `checkRateLimit`)
16
17
  *
17
18
  * Cores are instantiated per-request and receive a full `BaseCorePropsInterface`
18
- * including the ApiContext, db, logger, auth config, etc.
19
+ * including the ApiContext, db, logger, auth config, and optional rate-limit config.
20
+ *
21
+ * Rate limiting runs two independent tiers, both must pass:
22
+ *
23
+ * Global tier — context.globalRateLimit, set once at app startup.
24
+ * Always counted when present; cannot be opted out.
25
+ * Guards the whole service from a flood regardless of
26
+ * which action the IP targets.
27
+ *
28
+ * Core-or-action tier — mutually exclusive; action rule replaces core rule:
29
+ * 1. CoreActionInterface.rateLimit (per-call override)
30
+ * 2. rateLimitOnAction[actionName] (per-action props)
31
+ * 3. config.rateLimit (core-level default)
32
+ * false at step 1 or 2 disables this tier for that
33
+ * action (only global applies). Raising an action limit
34
+ * above the core default works correctly because the
35
+ * core counter is not also running.
36
+ *
37
+ * To wire up: create one IpRateLimiter at app startup, set it on context.rateLimiter.
38
+ * To use a custom limiter: pass `rateLimiter` (any RateLimiterInterface).
39
+ * To disable: pass `rateLimiter: null`.
40
+ *
41
+ * Rule resolution order (first match wins):
42
+ * CoreActionInterface.rateLimit
43
+ * → BaseCorePropsInterface.rateLimitOnAction[actionName]
44
+ * → BaseCorePropsInterface.rateLimit
45
+ * → no limiting
19
46
  *
20
47
  * Subclasses typically override:
21
48
  * - `getValidators()` — to provide custom validation per action
@@ -132,30 +159,119 @@ declare class BaseCore {
132
159
  * the transaction closed (e.g. after a manual rollback-and-retry pattern).
133
160
  */
134
161
  checkResult(args: any): Promise<void>;
162
+ /**
163
+ * Returns the active rate-limiter for this request.
164
+ *
165
+ * Resolution order (first defined value wins):
166
+ * 1. config.rateLimiter — per-core override; null explicitly disables
167
+ * 2. context.rateLimiter — app-level singleton set at startup
168
+ * 3. null — no limiting
169
+ *
170
+ * The app-level instance on context is created once at startup (e.g. in
171
+ * your context factory alongside spaceGw, globalRateLimit, etc.) and shared
172
+ * across all cores in all requests. This avoids creating a new limiter
173
+ * object on every request while still allowing individual cores to swap
174
+ * in a custom implementation or disable limiting entirely via config.
175
+ */
176
+ private getRateLimiter;
177
+ /**
178
+ * Collects the rate-limit rules that apply to a single runAction call.
179
+ *
180
+ * Returns at most two entries: one for the global tier and one for the
181
+ * core-or-action tier. Both tiers are independent — each gets its own
182
+ * Redis counter and the request must pass both to proceed.
183
+ *
184
+ * ── Global tier ─────────────────────────────────────────────────────────
185
+ * Sourced from context.globalRateLimit. Always included when present —
186
+ * it cannot be opted out by core or action configuration. This is the
187
+ * service-wide flood guard: no single IP can saturate the service
188
+ * regardless of which action it targets.
189
+ *
190
+ * ── Core-or-action tier (mutually exclusive) ────────────────────────────
191
+ * Core and action rules are NOT additive. If an action-level rule exists
192
+ * it completely replaces the core rule for that action. This makes
193
+ * loosening or tightening a single action meaningful: raising the action
194
+ * limit actually raises it (the core counter will not block first), and
195
+ * lowering it tightens that specific action without affecting others.
196
+ *
197
+ * Resolution for the core-or-action tier (first defined value wins):
198
+ * 1. callOverride (CoreActionInterface.rateLimit)
199
+ * 2. rateLimitOnAction[actionName]
200
+ * 3. config.rateLimit (core-level default)
201
+ * 4. nothing — tier omitted
202
+ *
203
+ * false at step 1 or 2 explicitly disables this tier for the action
204
+ * so only the global counter applies. false never suppresses global.
205
+ *
206
+ * @param actionName Stable action key used for per-action lookup and as
207
+ * the Redis key segment when rule.action is not set.
208
+ * @param callOverride The rateLimit value passed directly to runAction().
209
+ */
210
+ private collectRateLimitRules;
211
+ /**
212
+ * Checks applicable rate-limit counters for the current request.
213
+ *
214
+ * Called at the very start of runAction(), before the DB transaction is
215
+ * opened and before any authentication, so auth endpoints are protected
216
+ * from brute-force without any DB or session overhead.
217
+ *
218
+ * Runs up to two independent counters in parallel (global + core-or-action).
219
+ * The request is blocked if either counter is exceeded.
220
+ *
221
+ * Returns an OpResult with code TOO_MANY_REQUESTS (429) on the first block
222
+ * found, or null when the request may proceed.
223
+ *
224
+ * Never throws — any error from the limiter is treated as "allow" to ensure
225
+ * Redis unavailability cannot take down an endpoint.
226
+ *
227
+ * Skipped entirely when:
228
+ * - No rules are collected for this action (collectRateLimitRules returns [])
229
+ * - No limiter is available (no context.rateLimiter, no config.rateLimiter)
230
+ * - sameRequest is true (nested calls within the same request are not
231
+ * re-counted — the outer call has already consumed the slot)
232
+ *
233
+ * Redis key format per tier:
234
+ * rl:{spaceId}:{scope}:{actionKey}:{ip}
235
+ * The scope segment ('global' or 'core-action') keeps the two counters in
236
+ * separate keys so they never interfere with each other.
237
+ *
238
+ * @param actionName Stable action identifier used as the Redis key segment
239
+ * and for per-action rule lookup.
240
+ * @param callOverride The rateLimit value passed to the current runAction call.
241
+ * @param doingWhat Human-readable description used in log messages.
242
+ */
243
+ private checkRateLimit;
135
244
  /**
136
245
  * Core action runner. All public CRUD methods delegate to this.
137
246
  *
138
247
  * Execution flow:
139
- * 1. Detect same-request calls (skip transaction + auth for nested calls
140
- * within the same request, identified by matching requestId)
141
- * 2. Start DB transaction if `hasTransaction` is true
142
- * 3. Authenticate the request (if `doAuth` is true) OR verify the space
248
+ * 1. Detect same-request calls (skip transaction + auth + rate limiting for
249
+ * nested calls within the same request, identified by matching requestId)
250
+ * 2. Check IP rate limits if configured — all applicable counters (global,
251
+ * core, action) are checked in parallel; blocked if any is exceeded
252
+ * 3. Start DB transaction if `hasTransaction` is true
253
+ * 4. Authenticate the request (if `doAuth` is true) OR verify the space
143
254
  * (if `requireSpace` is not false) — space verification is a lighter
144
255
  * alternative to full auth for public-but-space-scoped operations
145
- * 4. Check role-based access if `roles` array is provided
146
- * 5. Run the validator function if provided — validator returns
256
+ * 5. Check role-based access if `roles` array is provided
257
+ * 6. Run the validator function if provided — validator returns
147
258
  * `[true, validatedItems]` on success or `[errorObj, {}]` on failure
148
- * 6. Execute the action handler with `(args, { ...actionOpt, validatedItems })`
149
- * 7. Commit or rollback the transaction via `checkResult()`
150
- * 8. On any exception: rollback, call `onException()` and the caller's
259
+ * 7. Execute the action handler with `(args, { ...actionOpt, validatedItems })`
260
+ * 8. Commit or rollback the transaction via `checkResult()`
261
+ * 9. On any exception: rollback, call `onException()` and the caller's
151
262
  * `onException` hook, then return an exceptionFailure result
152
263
  *
153
264
  * Same-request detection:
154
265
  * When a core method calls another core method on the same request
155
266
  * (e.g. create calling list to re-fetch results), it can pass
156
267
  * `args.requestId = context.requestId`. The inner call detects this,
157
- * skips starting a new transaction, skips auth, and skips committing —
158
- * the outer call owns the transaction lifecycle.
268
+ * skips starting a new transaction, skips auth, skips rate limiting,
269
+ * and skips committing — the outer call owns the transaction lifecycle.
270
+ *
271
+ * Rate limiting:
272
+ * Resolved via collectRateLimitRules() and checked via checkRateLimit().
273
+ * See BaseCorePropsInterface for the full rule resolution chain.
274
+ * Entirely skipped if no rateLimiter is configured.
159
275
  *
160
276
  * @param opt CoreActionInterface with all action configuration
161
277
  */
@@ -53,9 +53,36 @@ const localLogger = new Logger({ level: LoggerLevels.ERROR });
53
53
  * - Database transaction management
54
54
  * - Calling gateway methods and transforming results
55
55
  * - Consistent error handling and OpResult wrapping
56
+ * - Optional IP-based rate limiting (via `checkRateLimit`)
56
57
  *
57
58
  * Cores are instantiated per-request and receive a full `BaseCorePropsInterface`
58
- * including the ApiContext, db, logger, auth config, etc.
59
+ * including the ApiContext, db, logger, auth config, and optional rate-limit config.
60
+ *
61
+ * Rate limiting runs two independent tiers, both must pass:
62
+ *
63
+ * Global tier — context.globalRateLimit, set once at app startup.
64
+ * Always counted when present; cannot be opted out.
65
+ * Guards the whole service from a flood regardless of
66
+ * which action the IP targets.
67
+ *
68
+ * Core-or-action tier — mutually exclusive; action rule replaces core rule:
69
+ * 1. CoreActionInterface.rateLimit (per-call override)
70
+ * 2. rateLimitOnAction[actionName] (per-action props)
71
+ * 3. config.rateLimit (core-level default)
72
+ * false at step 1 or 2 disables this tier for that
73
+ * action (only global applies). Raising an action limit
74
+ * above the core default works correctly because the
75
+ * core counter is not also running.
76
+ *
77
+ * To wire up: create one IpRateLimiter at app startup, set it on context.rateLimiter.
78
+ * To use a custom limiter: pass `rateLimiter` (any RateLimiterInterface).
79
+ * To disable: pass `rateLimiter: null`.
80
+ *
81
+ * Rule resolution order (first match wins):
82
+ * CoreActionInterface.rateLimit
83
+ * → BaseCorePropsInterface.rateLimitOnAction[actionName]
84
+ * → BaseCorePropsInterface.rateLimit
85
+ * → no limiting
59
86
  *
60
87
  * Subclasses typically override:
61
88
  * - `getValidators()` — to provide custom validation per action
@@ -289,37 +316,209 @@ class BaseCore {
289
316
  }
290
317
  }
291
318
  }
319
+ /**
320
+ * Returns the active rate-limiter for this request.
321
+ *
322
+ * Resolution order (first defined value wins):
323
+ * 1. config.rateLimiter — per-core override; null explicitly disables
324
+ * 2. context.rateLimiter — app-level singleton set at startup
325
+ * 3. null — no limiting
326
+ *
327
+ * The app-level instance on context is created once at startup (e.g. in
328
+ * your context factory alongside spaceGw, globalRateLimit, etc.) and shared
329
+ * across all cores in all requests. This avoids creating a new limiter
330
+ * object on every request while still allowing individual cores to swap
331
+ * in a custom implementation or disable limiting entirely via config.
332
+ */
333
+ getRateLimiter() {
334
+ // 1. Per-core explicit override (including null to disable for this core)
335
+ if (this.config.rateLimiter !== undefined) {
336
+ return this.config.rateLimiter ?? null;
337
+ }
338
+ // 2. App-level singleton from context
339
+ const contextLimiter = this.getContext().rateLimiter;
340
+ if (contextLimiter !== undefined) {
341
+ return contextLimiter ?? null;
342
+ }
343
+ // 3. Nothing configured — no limiting
344
+ return null;
345
+ }
346
+ /**
347
+ * Collects the rate-limit rules that apply to a single runAction call.
348
+ *
349
+ * Returns at most two entries: one for the global tier and one for the
350
+ * core-or-action tier. Both tiers are independent — each gets its own
351
+ * Redis counter and the request must pass both to proceed.
352
+ *
353
+ * ── Global tier ─────────────────────────────────────────────────────────
354
+ * Sourced from context.globalRateLimit. Always included when present —
355
+ * it cannot be opted out by core or action configuration. This is the
356
+ * service-wide flood guard: no single IP can saturate the service
357
+ * regardless of which action it targets.
358
+ *
359
+ * ── Core-or-action tier (mutually exclusive) ────────────────────────────
360
+ * Core and action rules are NOT additive. If an action-level rule exists
361
+ * it completely replaces the core rule for that action. This makes
362
+ * loosening or tightening a single action meaningful: raising the action
363
+ * limit actually raises it (the core counter will not block first), and
364
+ * lowering it tightens that specific action without affecting others.
365
+ *
366
+ * Resolution for the core-or-action tier (first defined value wins):
367
+ * 1. callOverride (CoreActionInterface.rateLimit)
368
+ * 2. rateLimitOnAction[actionName]
369
+ * 3. config.rateLimit (core-level default)
370
+ * 4. nothing — tier omitted
371
+ *
372
+ * false at step 1 or 2 explicitly disables this tier for the action
373
+ * so only the global counter applies. false never suppresses global.
374
+ *
375
+ * @param actionName Stable action key used for per-action lookup and as
376
+ * the Redis key segment when rule.action is not set.
377
+ * @param callOverride The rateLimit value passed directly to runAction().
378
+ */
379
+ collectRateLimitRules(actionName, callOverride) {
380
+ const collected = [];
381
+ // ── Global tier ──────────────────────────────────────────────────────────
382
+ // Always added when present. No opt-out — this is the service-wide guard.
383
+ const globalRule = this.getContext().globalRateLimit;
384
+ if (globalRule) {
385
+ collected.push({ rule: globalRule, scope: 'global' });
386
+ }
387
+ // ── Core-or-action tier ──────────────────────────────────────────────────
388
+ // Walk the resolution chain. The first defined value (including false) wins
389
+ // and stops the search — core and action are mutually exclusive so that a
390
+ // raised action limit is not silently capped by the core counter.
391
+ // Step 1: per-call override (highest priority)
392
+ let tierRule = callOverride;
393
+ // Step 2: per-action props (only when no call-site override was given)
394
+ if (tierRule === undefined && actionName && this.config.rateLimitOnAction) {
395
+ tierRule = this.config.rateLimitOnAction[actionName];
396
+ }
397
+ // Step 3: core-level default (only when no action-level rule was found)
398
+ if (tierRule === undefined && this.config.rateLimit) {
399
+ tierRule = this.config.rateLimit;
400
+ }
401
+ // false means "disable the core-or-action tier for this action" —
402
+ // only the global counter applies. Omitted entirely from collected.
403
+ if (tierRule !== undefined && tierRule !== false) {
404
+ collected.push({ rule: tierRule, scope: 'core-action' });
405
+ }
406
+ return collected;
407
+ }
408
+ /**
409
+ * Checks applicable rate-limit counters for the current request.
410
+ *
411
+ * Called at the very start of runAction(), before the DB transaction is
412
+ * opened and before any authentication, so auth endpoints are protected
413
+ * from brute-force without any DB or session overhead.
414
+ *
415
+ * Runs up to two independent counters in parallel (global + core-or-action).
416
+ * The request is blocked if either counter is exceeded.
417
+ *
418
+ * Returns an OpResult with code TOO_MANY_REQUESTS (429) on the first block
419
+ * found, or null when the request may proceed.
420
+ *
421
+ * Never throws — any error from the limiter is treated as "allow" to ensure
422
+ * Redis unavailability cannot take down an endpoint.
423
+ *
424
+ * Skipped entirely when:
425
+ * - No rules are collected for this action (collectRateLimitRules returns [])
426
+ * - No limiter is available (no context.rateLimiter, no config.rateLimiter)
427
+ * - sameRequest is true (nested calls within the same request are not
428
+ * re-counted — the outer call has already consumed the slot)
429
+ *
430
+ * Redis key format per tier:
431
+ * rl:{spaceId}:{scope}:{actionKey}:{ip}
432
+ * The scope segment ('global' or 'core-action') keeps the two counters in
433
+ * separate keys so they never interfere with each other.
434
+ *
435
+ * @param actionName Stable action identifier used as the Redis key segment
436
+ * and for per-action rule lookup.
437
+ * @param callOverride The rateLimit value passed to the current runAction call.
438
+ * @param doingWhat Human-readable description used in log messages.
439
+ */
440
+ async checkRateLimit(actionName, callOverride, doingWhat) {
441
+ const rules = this.collectRateLimitRules(actionName, callOverride);
442
+ if (rules.length === 0) {
443
+ // Nothing to check — skip limiter lookup entirely
444
+ return null;
445
+ }
446
+ const limiter = this.getRateLimiter();
447
+ if (!limiter) {
448
+ // No limiter available (no context.rateLimiter, no config.rateLimiter) — allow through
449
+ return null;
450
+ }
451
+ const context = this.getContext();
452
+ const ip = context.ipAddress || '';
453
+ const spaceId = context.spaceId || '';
454
+ // Stable key segment: prefer rule.action override, then actionName, then doingWhat
455
+ const actionKey = actionName || doingWhat;
456
+ this.logger.debug(`Checking ${rules.length} rate-limit counter(s) for action '${actionKey}' from IP '${ip}' in space '${spaceId}' on ${doingWhat}`);
457
+ // Run all counters in parallel — every applicable level is incremented on
458
+ // every request regardless of what the others return. This ensures counters
459
+ // stay accurate even when the request is ultimately blocked by another level.
460
+ const results = await Promise.all(rules.map(({ rule, scope }) => limiter.check({
461
+ // Scope prefix keeps counters for different levels in separate keys
462
+ action: `${scope}:${rule.action || actionKey}`,
463
+ ip,
464
+ spaceId,
465
+ limit: rule.limit,
466
+ windowSec: rule.windowSec,
467
+ })));
468
+ // Find the first blocked result and return it; allow if all passed
469
+ for (let i = 0; i < results.length; i++) {
470
+ const result = results[i];
471
+ const { scope } = rules[i];
472
+ if (result.blocked) {
473
+ const retryAfter = result.ttlSec > 0 ? ` Please try again in ${result.ttlSec} seconds.` : '';
474
+ const msg = `Too many requests.${retryAfter}`;
475
+ this.logger.log(`Rate limit blocked action '${actionKey}' for IP '${ip}' in space '${spaceId}' on ${doingWhat}: ${scope} counter exceeded (${result.count} requests in window)`);
476
+ const opResult = new OpResult({ code: OP_RESULT_CODES.TOO_MANY_REQUESTS });
477
+ opResult.addError('', msg, OP_RESULT_CODES.TOO_MANY_REQUESTS);
478
+ return opResult;
479
+ }
480
+ }
481
+ return null;
482
+ }
292
483
  /**
293
484
  * Core action runner. All public CRUD methods delegate to this.
294
485
  *
295
486
  * Execution flow:
296
- * 1. Detect same-request calls (skip transaction + auth for nested calls
297
- * within the same request, identified by matching requestId)
298
- * 2. Start DB transaction if `hasTransaction` is true
299
- * 3. Authenticate the request (if `doAuth` is true) OR verify the space
487
+ * 1. Detect same-request calls (skip transaction + auth + rate limiting for
488
+ * nested calls within the same request, identified by matching requestId)
489
+ * 2. Check IP rate limits if configured — all applicable counters (global,
490
+ * core, action) are checked in parallel; blocked if any is exceeded
491
+ * 3. Start DB transaction if `hasTransaction` is true
492
+ * 4. Authenticate the request (if `doAuth` is true) OR verify the space
300
493
  * (if `requireSpace` is not false) — space verification is a lighter
301
494
  * alternative to full auth for public-but-space-scoped operations
302
- * 4. Check role-based access if `roles` array is provided
303
- * 5. Run the validator function if provided — validator returns
495
+ * 5. Check role-based access if `roles` array is provided
496
+ * 6. Run the validator function if provided — validator returns
304
497
  * `[true, validatedItems]` on success or `[errorObj, {}]` on failure
305
- * 6. Execute the action handler with `(args, { ...actionOpt, validatedItems })`
306
- * 7. Commit or rollback the transaction via `checkResult()`
307
- * 8. On any exception: rollback, call `onException()` and the caller's
498
+ * 7. Execute the action handler with `(args, { ...actionOpt, validatedItems })`
499
+ * 8. Commit or rollback the transaction via `checkResult()`
500
+ * 9. On any exception: rollback, call `onException()` and the caller's
308
501
  * `onException` hook, then return an exceptionFailure result
309
502
  *
310
503
  * Same-request detection:
311
504
  * When a core method calls another core method on the same request
312
505
  * (e.g. create calling list to re-fetch results), it can pass
313
506
  * `args.requestId = context.requestId`. The inner call detects this,
314
- * skips starting a new transaction, skips auth, and skips committing —
315
- * the outer call owns the transaction lifecycle.
507
+ * skips starting a new transaction, skips auth, skips rate limiting,
508
+ * and skips committing — the outer call owns the transaction lifecycle.
509
+ *
510
+ * Rate limiting:
511
+ * Resolved via collectRateLimitRules() and checked via checkRateLimit().
512
+ * See BaseCorePropsInterface for the full rule resolution chain.
513
+ * Entirely skipped if no rateLimiter is configured.
316
514
  *
317
515
  * @param opt CoreActionInterface with all action configuration
318
516
  */
319
517
  async runAction(opt) {
320
- const { args, validate, doAuth, tryAuth, roles, action, hasTransaction, doingWhat, onException, shouldLogArgs, requireSpace, skipCheckResult, } = opt || {};
518
+ const { args, validate, doAuth, tryAuth, roles, action, hasTransaction, doingWhat, onException, shouldLogArgs, requireSpace, skipCheckResult, actionName, rateLimit: callRateLimit, } = opt || {};
321
519
  // Detect if this is a nested call within the same request.
322
- // If so, skip transaction management and auth to avoid double-wrapping.
520
+ // If so, skip transaction management, auth, and rate limiting to avoid
521
+ // double-wrapping and double-counting.
323
522
  const sameRequest = !!this.config.context.requestId && args?.requestId === this.config.context.requestId;
324
523
  if (shouldLogArgs == null || shouldLogArgs === true) {
325
524
  this.logger.debug(`The ${doingWhat} started:`, args);
@@ -345,6 +544,19 @@ class BaseCore {
345
544
  hasTransaction,
346
545
  };
347
546
  try {
547
+ // ── Step 1: Rate limiting ──────────────────────────────────────────────
548
+ // Checked before the DB transaction is opened and before authentication.
549
+ // Same-request nested calls are excluded — the outer call was already
550
+ // counted and we must not penalise legitimate internal fan-out.
551
+ if (!sameRequest) {
552
+ this.measureTool.addCheckpoint('Rate limit check: start');
553
+ const rateLimitResult = await this.checkRateLimit(actionName, callRateLimit, doingWhat ?? '');
554
+ this.measureTool.addCheckpoint('Rate limit check: end');
555
+ if (rateLimitResult !== null) {
556
+ // Request is blocked — return immediately, no transaction opened
557
+ return rateLimitResult;
558
+ }
559
+ }
348
560
  if (!sameRequest) {
349
561
  if (hasTransaction) {
350
562
  this.logger.debug(`Start DB transaction on ${step}`);
@@ -1107,6 +1319,7 @@ class BaseCore {
1107
1319
  context.accountId = tokenData.accountId;
1108
1320
  context.roleId = tokenData.roleId;
1109
1321
  context.userId = tokenData.userId;
1322
+ // TODO: update the isSuperAdmin
1110
1323
  context.isSuperAdmin = context.roleId === 'superadmin';
1111
1324
  // Header spaceId takes precedence over token spaceId
1112
1325
  context.spaceId = context.spaceId || tokenData.spaceId || '';
@@ -0,0 +1,105 @@
1
+ /**
2
+ * IpRateLimiter
3
+ *
4
+ * A reusable Redis-backed sliding-window rate limiter keyed on (action, IP).
5
+ * Designed for auth endpoints where Redis is optional infrastructure: if the
6
+ * client is null (Redis not configured) the limiter silently allows all
7
+ * requests — it never throws and never blocks the caller.
8
+ *
9
+ * Usage:
10
+ * const limiter = new IpRateLimiter(redisClient, logger);
11
+ *
12
+ * const result = await limiter.check({
13
+ * action: 'signIn',
14
+ * ip: '1.2.3.4',
15
+ * spaceId: 'my-space',
16
+ * limit: 20,
17
+ * windowSec: 900,
18
+ * });
19
+ *
20
+ * if (result.blocked) {
21
+ * // return 429 / rate limit failure
22
+ * }
23
+ *
24
+ * Redis key format: rl:{spaceId}:{action}:{ip}
25
+ * Strategy: INCR + EXPIRE (atomic for the first hit via SET NX)
26
+ * Each key lives exactly `windowSec` seconds. On first
27
+ * hit the key is created with TTL = windowSec. Subsequent
28
+ * hits within the window increment the counter. When the
29
+ * window expires Redis deletes the key automatically.
30
+ *
31
+ * This is a fixed-window counter (not a true sliding window), which is the
32
+ * right trade-off here: it is O(1) per request, uses a single key, and the
33
+ * 2× burst risk at window boundaries is acceptable for auth rate-limiting
34
+ * where the window is measured in minutes, not milliseconds.
35
+ */
36
+ /**
37
+ * A single rate-limit rule. Embed this in core props or per-action config
38
+ * to declaratively attach limiting without touching runAction call sites.
39
+ *
40
+ * Set `action` to override the Redis key segment; if omitted, BaseCore uses
41
+ * the CoreActionInterface.actionName (or doingWhat as fallback) so the key
42
+ * is always stable across deploys and language changes.
43
+ */
44
+ export interface RateLimitRule {
45
+ /** Maximum number of requests allowed within the window. */
46
+ limit: number;
47
+ /** Window length in seconds. */
48
+ windowSec: number;
49
+ /**
50
+ * Optional explicit action key for the Redis counter.
51
+ * When omitted, BaseCore fills this from actionName / doingWhat at call time.
52
+ */
53
+ action?: string;
54
+ }
55
+ export interface RateLimitCheckArgs {
56
+ /** Short label for the action being rate-limited, e.g. 'signIn', 'signUp' */
57
+ action: string;
58
+ /** Client IP address */
59
+ ip: string;
60
+ /** Space ID so different spaces get independent counters */
61
+ spaceId: string;
62
+ /** Maximum number of requests allowed within the window */
63
+ limit: number;
64
+ /** Window length in seconds */
65
+ windowSec: number;
66
+ }
67
+ export interface RateLimitResult {
68
+ /** True when the caller should be blocked */
69
+ blocked: boolean;
70
+ /** How many hits have been recorded in the current window (0 if Redis unavailable) */
71
+ count: number;
72
+ /** How many seconds remain in the current window (-1 if Redis unavailable) */
73
+ ttlSec: number;
74
+ }
75
+ export interface RateLimiterLogger {
76
+ log(message: string, ...args: any[]): void;
77
+ error(message: string, ...args: any[]): void;
78
+ }
79
+ /**
80
+ * Structural interface for any rate-limiter implementation.
81
+ * BaseCore accepts anything that satisfies this shape — callers are not
82
+ * required to use IpRateLimiter specifically. Duck-typed to avoid coupling
83
+ * across package versions, consistent with how spaceGw is typed in
84
+ * BaseCorePropsInterface.
85
+ */
86
+ export interface RateLimiterInterface {
87
+ check(args: RateLimitCheckArgs): Promise<RateLimitResult>;
88
+ reset(args: Pick<RateLimitCheckArgs, 'action' | 'ip' | 'spaceId'>): Promise<void>;
89
+ }
90
+ export declare class IpRateLimiter implements RateLimiterInterface {
91
+ private readonly client;
92
+ private readonly logger;
93
+ constructor(redisClient: any | null, logger: RateLimiterLogger);
94
+ /**
95
+ * Check and increment the rate-limit counter for a given action + IP.
96
+ * Always resolves — never rejects.
97
+ */
98
+ check(args: RateLimitCheckArgs): Promise<RateLimitResult>;
99
+ /**
100
+ * Manually reset the counter for a given action + IP.
101
+ * Useful after a successful sign-in to clear the failed-attempt counter.
102
+ * Silently no-ops if Redis is unavailable.
103
+ */
104
+ reset(args: Pick<RateLimitCheckArgs, 'action' | 'ip' | 'spaceId'>): Promise<void>;
105
+ }