@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.
@@ -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
  */
package/build/BaseCore.js CHANGED
@@ -59,9 +59,36 @@ const localLogger = new utils_1.Logger({ level: utils_1.LoggerLevels.ERROR });
59
59
  * - Database transaction management
60
60
  * - Calling gateway methods and transforming results
61
61
  * - Consistent error handling and OpResult wrapping
62
+ * - Optional IP-based rate limiting (via `checkRateLimit`)
62
63
  *
63
64
  * Cores are instantiated per-request and receive a full `BaseCorePropsInterface`
64
- * including the ApiContext, db, logger, auth config, etc.
65
+ * including the ApiContext, db, logger, auth config, and optional rate-limit config.
66
+ *
67
+ * Rate limiting runs two independent tiers, both must pass:
68
+ *
69
+ * Global tier — context.globalRateLimit, set once at app startup.
70
+ * Always counted when present; cannot be opted out.
71
+ * Guards the whole service from a flood regardless of
72
+ * which action the IP targets.
73
+ *
74
+ * Core-or-action tier — mutually exclusive; action rule replaces core rule:
75
+ * 1. CoreActionInterface.rateLimit (per-call override)
76
+ * 2. rateLimitOnAction[actionName] (per-action props)
77
+ * 3. config.rateLimit (core-level default)
78
+ * false at step 1 or 2 disables this tier for that
79
+ * action (only global applies). Raising an action limit
80
+ * above the core default works correctly because the
81
+ * core counter is not also running.
82
+ *
83
+ * To wire up: create one IpRateLimiter at app startup, set it on context.rateLimiter.
84
+ * To use a custom limiter: pass `rateLimiter` (any RateLimiterInterface).
85
+ * To disable: pass `rateLimiter: null`.
86
+ *
87
+ * Rule resolution order (first match wins):
88
+ * CoreActionInterface.rateLimit
89
+ * → BaseCorePropsInterface.rateLimitOnAction[actionName]
90
+ * → BaseCorePropsInterface.rateLimit
91
+ * → no limiting
65
92
  *
66
93
  * Subclasses typically override:
67
94
  * - `getValidators()` — to provide custom validation per action
@@ -295,37 +322,209 @@ class BaseCore {
295
322
  }
296
323
  }
297
324
  }
325
+ /**
326
+ * Returns the active rate-limiter for this request.
327
+ *
328
+ * Resolution order (first defined value wins):
329
+ * 1. config.rateLimiter — per-core override; null explicitly disables
330
+ * 2. context.rateLimiter — app-level singleton set at startup
331
+ * 3. null — no limiting
332
+ *
333
+ * The app-level instance on context is created once at startup (e.g. in
334
+ * your context factory alongside spaceGw, globalRateLimit, etc.) and shared
335
+ * across all cores in all requests. This avoids creating a new limiter
336
+ * object on every request while still allowing individual cores to swap
337
+ * in a custom implementation or disable limiting entirely via config.
338
+ */
339
+ getRateLimiter() {
340
+ // 1. Per-core explicit override (including null to disable for this core)
341
+ if (this.config.rateLimiter !== undefined) {
342
+ return this.config.rateLimiter ?? null;
343
+ }
344
+ // 2. App-level singleton from context
345
+ const contextLimiter = this.getContext().rateLimiter;
346
+ if (contextLimiter !== undefined) {
347
+ return contextLimiter ?? null;
348
+ }
349
+ // 3. Nothing configured — no limiting
350
+ return null;
351
+ }
352
+ /**
353
+ * Collects the rate-limit rules that apply to a single runAction call.
354
+ *
355
+ * Returns at most two entries: one for the global tier and one for the
356
+ * core-or-action tier. Both tiers are independent — each gets its own
357
+ * Redis counter and the request must pass both to proceed.
358
+ *
359
+ * ── Global tier ─────────────────────────────────────────────────────────
360
+ * Sourced from context.globalRateLimit. Always included when present —
361
+ * it cannot be opted out by core or action configuration. This is the
362
+ * service-wide flood guard: no single IP can saturate the service
363
+ * regardless of which action it targets.
364
+ *
365
+ * ── Core-or-action tier (mutually exclusive) ────────────────────────────
366
+ * Core and action rules are NOT additive. If an action-level rule exists
367
+ * it completely replaces the core rule for that action. This makes
368
+ * loosening or tightening a single action meaningful: raising the action
369
+ * limit actually raises it (the core counter will not block first), and
370
+ * lowering it tightens that specific action without affecting others.
371
+ *
372
+ * Resolution for the core-or-action tier (first defined value wins):
373
+ * 1. callOverride (CoreActionInterface.rateLimit)
374
+ * 2. rateLimitOnAction[actionName]
375
+ * 3. config.rateLimit (core-level default)
376
+ * 4. nothing — tier omitted
377
+ *
378
+ * false at step 1 or 2 explicitly disables this tier for the action
379
+ * so only the global counter applies. false never suppresses global.
380
+ *
381
+ * @param actionName Stable action key used for per-action lookup and as
382
+ * the Redis key segment when rule.action is not set.
383
+ * @param callOverride The rateLimit value passed directly to runAction().
384
+ */
385
+ collectRateLimitRules(actionName, callOverride) {
386
+ const collected = [];
387
+ // ── Global tier ──────────────────────────────────────────────────────────
388
+ // Always added when present. No opt-out — this is the service-wide guard.
389
+ const globalRule = this.getContext().globalRateLimit;
390
+ if (globalRule) {
391
+ collected.push({ rule: globalRule, scope: 'global' });
392
+ }
393
+ // ── Core-or-action tier ──────────────────────────────────────────────────
394
+ // Walk the resolution chain. The first defined value (including false) wins
395
+ // and stops the search — core and action are mutually exclusive so that a
396
+ // raised action limit is not silently capped by the core counter.
397
+ // Step 1: per-call override (highest priority)
398
+ let tierRule = callOverride;
399
+ // Step 2: per-action props (only when no call-site override was given)
400
+ if (tierRule === undefined && actionName && this.config.rateLimitOnAction) {
401
+ tierRule = this.config.rateLimitOnAction[actionName];
402
+ }
403
+ // Step 3: core-level default (only when no action-level rule was found)
404
+ if (tierRule === undefined && this.config.rateLimit) {
405
+ tierRule = this.config.rateLimit;
406
+ }
407
+ // false means "disable the core-or-action tier for this action" —
408
+ // only the global counter applies. Omitted entirely from collected.
409
+ if (tierRule !== undefined && tierRule !== false) {
410
+ collected.push({ rule: tierRule, scope: 'core-action' });
411
+ }
412
+ return collected;
413
+ }
414
+ /**
415
+ * Checks applicable rate-limit counters for the current request.
416
+ *
417
+ * Called at the very start of runAction(), before the DB transaction is
418
+ * opened and before any authentication, so auth endpoints are protected
419
+ * from brute-force without any DB or session overhead.
420
+ *
421
+ * Runs up to two independent counters in parallel (global + core-or-action).
422
+ * The request is blocked if either counter is exceeded.
423
+ *
424
+ * Returns an OpResult with code TOO_MANY_REQUESTS (429) on the first block
425
+ * found, or null when the request may proceed.
426
+ *
427
+ * Never throws — any error from the limiter is treated as "allow" to ensure
428
+ * Redis unavailability cannot take down an endpoint.
429
+ *
430
+ * Skipped entirely when:
431
+ * - No rules are collected for this action (collectRateLimitRules returns [])
432
+ * - No limiter is available (no context.rateLimiter, no config.rateLimiter)
433
+ * - sameRequest is true (nested calls within the same request are not
434
+ * re-counted — the outer call has already consumed the slot)
435
+ *
436
+ * Redis key format per tier:
437
+ * rl:{spaceId}:{scope}:{actionKey}:{ip}
438
+ * The scope segment ('global' or 'core-action') keeps the two counters in
439
+ * separate keys so they never interfere with each other.
440
+ *
441
+ * @param actionName Stable action identifier used as the Redis key segment
442
+ * and for per-action rule lookup.
443
+ * @param callOverride The rateLimit value passed to the current runAction call.
444
+ * @param doingWhat Human-readable description used in log messages.
445
+ */
446
+ async checkRateLimit(actionName, callOverride, doingWhat) {
447
+ const rules = this.collectRateLimitRules(actionName, callOverride);
448
+ if (rules.length === 0) {
449
+ // Nothing to check — skip limiter lookup entirely
450
+ return null;
451
+ }
452
+ const limiter = this.getRateLimiter();
453
+ if (!limiter) {
454
+ // No limiter available (no context.rateLimiter, no config.rateLimiter) — allow through
455
+ return null;
456
+ }
457
+ const context = this.getContext();
458
+ const ip = context.ipAddress || '';
459
+ const spaceId = context.spaceId || '';
460
+ // Stable key segment: prefer rule.action override, then actionName, then doingWhat
461
+ const actionKey = actionName || doingWhat;
462
+ this.logger.debug(`Checking ${rules.length} rate-limit counter(s) for action '${actionKey}' from IP '${ip}' in space '${spaceId}' on ${doingWhat}`);
463
+ // Run all counters in parallel — every applicable level is incremented on
464
+ // every request regardless of what the others return. This ensures counters
465
+ // stay accurate even when the request is ultimately blocked by another level.
466
+ const results = await Promise.all(rules.map(({ rule, scope }) => limiter.check({
467
+ // Scope prefix keeps counters for different levels in separate keys
468
+ action: `${scope}:${rule.action || actionKey}`,
469
+ ip,
470
+ spaceId,
471
+ limit: rule.limit,
472
+ windowSec: rule.windowSec,
473
+ })));
474
+ // Find the first blocked result and return it; allow if all passed
475
+ for (let i = 0; i < results.length; i++) {
476
+ const result = results[i];
477
+ const { scope } = rules[i];
478
+ if (result.blocked) {
479
+ const retryAfter = result.ttlSec > 0 ? ` Please try again in ${result.ttlSec} seconds.` : '';
480
+ const msg = `Too many requests.${retryAfter}`;
481
+ this.logger.log(`Rate limit blocked action '${actionKey}' for IP '${ip}' in space '${spaceId}' on ${doingWhat}: ${scope} counter exceeded (${result.count} requests in window)`);
482
+ const opResult = new api_helpers_1.OpResult({ code: api_helpers_1.OP_RESULT_CODES.TOO_MANY_REQUESTS });
483
+ opResult.addError('', msg, api_helpers_1.OP_RESULT_CODES.TOO_MANY_REQUESTS);
484
+ return opResult;
485
+ }
486
+ }
487
+ return null;
488
+ }
298
489
  /**
299
490
  * Core action runner. All public CRUD methods delegate to this.
300
491
  *
301
492
  * Execution flow:
302
- * 1. Detect same-request calls (skip transaction + auth for nested calls
303
- * within the same request, identified by matching requestId)
304
- * 2. Start DB transaction if `hasTransaction` is true
305
- * 3. Authenticate the request (if `doAuth` is true) OR verify the space
493
+ * 1. Detect same-request calls (skip transaction + auth + rate limiting for
494
+ * nested calls within the same request, identified by matching requestId)
495
+ * 2. Check IP rate limits if configured — all applicable counters (global,
496
+ * core, action) are checked in parallel; blocked if any is exceeded
497
+ * 3. Start DB transaction if `hasTransaction` is true
498
+ * 4. Authenticate the request (if `doAuth` is true) OR verify the space
306
499
  * (if `requireSpace` is not false) — space verification is a lighter
307
500
  * alternative to full auth for public-but-space-scoped operations
308
- * 4. Check role-based access if `roles` array is provided
309
- * 5. Run the validator function if provided — validator returns
501
+ * 5. Check role-based access if `roles` array is provided
502
+ * 6. Run the validator function if provided — validator returns
310
503
  * `[true, validatedItems]` on success or `[errorObj, {}]` on failure
311
- * 6. Execute the action handler with `(args, { ...actionOpt, validatedItems })`
312
- * 7. Commit or rollback the transaction via `checkResult()`
313
- * 8. On any exception: rollback, call `onException()` and the caller's
504
+ * 7. Execute the action handler with `(args, { ...actionOpt, validatedItems })`
505
+ * 8. Commit or rollback the transaction via `checkResult()`
506
+ * 9. On any exception: rollback, call `onException()` and the caller's
314
507
  * `onException` hook, then return an exceptionFailure result
315
508
  *
316
509
  * Same-request detection:
317
510
  * When a core method calls another core method on the same request
318
511
  * (e.g. create calling list to re-fetch results), it can pass
319
512
  * `args.requestId = context.requestId`. The inner call detects this,
320
- * skips starting a new transaction, skips auth, and skips committing —
321
- * the outer call owns the transaction lifecycle.
513
+ * skips starting a new transaction, skips auth, skips rate limiting,
514
+ * and skips committing — the outer call owns the transaction lifecycle.
515
+ *
516
+ * Rate limiting:
517
+ * Resolved via collectRateLimitRules() and checked via checkRateLimit().
518
+ * See BaseCorePropsInterface for the full rule resolution chain.
519
+ * Entirely skipped if no rateLimiter is configured.
322
520
  *
323
521
  * @param opt CoreActionInterface with all action configuration
324
522
  */
325
523
  async runAction(opt) {
326
- const { args, validate, doAuth, tryAuth, roles, action, hasTransaction, doingWhat, onException, shouldLogArgs, requireSpace, skipCheckResult, } = opt || {};
524
+ const { args, validate, doAuth, tryAuth, roles, action, hasTransaction, doingWhat, onException, shouldLogArgs, requireSpace, skipCheckResult, actionName, rateLimit: callRateLimit, } = opt || {};
327
525
  // Detect if this is a nested call within the same request.
328
- // If so, skip transaction management and auth to avoid double-wrapping.
526
+ // If so, skip transaction management, auth, and rate limiting to avoid
527
+ // double-wrapping and double-counting.
329
528
  const sameRequest = !!this.config.context.requestId && args?.requestId === this.config.context.requestId;
330
529
  if (shouldLogArgs == null || shouldLogArgs === true) {
331
530
  this.logger.debug(`The ${doingWhat} started:`, args);
@@ -351,6 +550,19 @@ class BaseCore {
351
550
  hasTransaction,
352
551
  };
353
552
  try {
553
+ // ── Step 1: Rate limiting ──────────────────────────────────────────────
554
+ // Checked before the DB transaction is opened and before authentication.
555
+ // Same-request nested calls are excluded — the outer call was already
556
+ // counted and we must not penalise legitimate internal fan-out.
557
+ if (!sameRequest) {
558
+ this.measureTool.addCheckpoint('Rate limit check: start');
559
+ const rateLimitResult = await this.checkRateLimit(actionName, callRateLimit, doingWhat ?? '');
560
+ this.measureTool.addCheckpoint('Rate limit check: end');
561
+ if (rateLimitResult !== null) {
562
+ // Request is blocked — return immediately, no transaction opened
563
+ return rateLimitResult;
564
+ }
565
+ }
354
566
  if (!sameRequest) {
355
567
  if (hasTransaction) {
356
568
  this.logger.debug(`Start DB transaction on ${step}`);
@@ -1113,6 +1325,7 @@ class BaseCore {
1113
1325
  context.accountId = tokenData.accountId;
1114
1326
  context.roleId = tokenData.roleId;
1115
1327
  context.userId = tokenData.userId;
1328
+ // TODO: update the isSuperAdmin
1116
1329
  context.isSuperAdmin = context.roleId === 'superadmin';
1117
1330
  // Header spaceId takes precedence over token spaceId
1118
1331
  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
+ }
@@ -0,0 +1,104 @@
1
+ "use strict";
2
+ /**
3
+ * IpRateLimiter
4
+ *
5
+ * A reusable Redis-backed sliding-window rate limiter keyed on (action, IP).
6
+ * Designed for auth endpoints where Redis is optional infrastructure: if the
7
+ * client is null (Redis not configured) the limiter silently allows all
8
+ * requests — it never throws and never blocks the caller.
9
+ *
10
+ * Usage:
11
+ * const limiter = new IpRateLimiter(redisClient, logger);
12
+ *
13
+ * const result = await limiter.check({
14
+ * action: 'signIn',
15
+ * ip: '1.2.3.4',
16
+ * spaceId: 'my-space',
17
+ * limit: 20,
18
+ * windowSec: 900,
19
+ * });
20
+ *
21
+ * if (result.blocked) {
22
+ * // return 429 / rate limit failure
23
+ * }
24
+ *
25
+ * Redis key format: rl:{spaceId}:{action}:{ip}
26
+ * Strategy: INCR + EXPIRE (atomic for the first hit via SET NX)
27
+ * Each key lives exactly `windowSec` seconds. On first
28
+ * hit the key is created with TTL = windowSec. Subsequent
29
+ * hits within the window increment the counter. When the
30
+ * window expires Redis deletes the key automatically.
31
+ *
32
+ * This is a fixed-window counter (not a true sliding window), which is the
33
+ * right trade-off here: it is O(1) per request, uses a single key, and the
34
+ * 2× burst risk at window boundaries is acceptable for auth rate-limiting
35
+ * where the window is measured in minutes, not milliseconds.
36
+ */
37
+ Object.defineProperty(exports, "__esModule", { value: true });
38
+ exports.IpRateLimiter = void 0;
39
+ class IpRateLimiter {
40
+ client;
41
+ logger;
42
+ constructor(redisClient, logger) {
43
+ this.client = redisClient;
44
+ this.logger = logger;
45
+ }
46
+ /**
47
+ * Check and increment the rate-limit counter for a given action + IP.
48
+ * Always resolves — never rejects.
49
+ */
50
+ async check(args) {
51
+ const { action, ip, spaceId, limit, windowSec } = args;
52
+ if (!this.client) {
53
+ // Redis not configured — allow the request, emit a single debug note
54
+ this.logger.log(`Rate limiter bypassed for action '${action}' from IP '${ip}' in space '${spaceId}': Redis client not available`);
55
+ return { blocked: false, count: 0, ttlSec: -1 };
56
+ }
57
+ if (!ip) {
58
+ // No IP to key on — allow but log so we notice misconfigured proxies
59
+ this.logger.log(`Rate limiter skipped for action '${action}' in space '${spaceId}': IP address not available`);
60
+ return { blocked: false, count: 0, ttlSec: -1 };
61
+ }
62
+ const key = `rl:${spaceId}:${action}:${ip}`;
63
+ try {
64
+ // INCR is atomic. If the key does not exist Redis creates it at 0 then
65
+ // increments to 1. We set the TTL only on the first hit (NX flag) so
66
+ // the window always starts from the very first request.
67
+ const count = await this.client.incr(key);
68
+ if (count === 1) {
69
+ // First hit in this window — set the expiry
70
+ await this.client.expire(key, windowSec);
71
+ }
72
+ const ttlSec = await this.client.ttl(key);
73
+ if (count > limit) {
74
+ this.logger.log(`Rate limit exceeded for action '${action}' from IP '${ip}' in space '${spaceId}': ${count}/${limit} requests, resets in ${ttlSec}s`);
75
+ return { blocked: true, count, ttlSec };
76
+ }
77
+ return { blocked: false, count, ttlSec };
78
+ }
79
+ catch (err) {
80
+ // Redis errors must never crash an auth request — log and allow
81
+ this.logger.error(`Rate limiter error for action '${action}' from IP '${ip}' in space '${spaceId}': ${err?.message} — request allowed`);
82
+ return { blocked: false, count: 0, ttlSec: -1 };
83
+ }
84
+ }
85
+ /**
86
+ * Manually reset the counter for a given action + IP.
87
+ * Useful after a successful sign-in to clear the failed-attempt counter.
88
+ * Silently no-ops if Redis is unavailable.
89
+ */
90
+ async reset(args) {
91
+ const { action, ip, spaceId } = args;
92
+ if (!this.client || !ip) {
93
+ return;
94
+ }
95
+ const key = `rl:${spaceId}:${action}:${ip}`;
96
+ try {
97
+ await this.client.del(key);
98
+ }
99
+ catch (err) {
100
+ this.logger.error(`Rate limiter reset failed for action '${action}' from IP '${ip}' in space '${spaceId}': ${err?.message}`);
101
+ }
102
+ }
103
+ }
104
+ exports.IpRateLimiter = IpRateLimiter;