@sdflc/backend-helpers 1.0.115 → 1.0.117
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/README.md +41 -0
- package/build/BaseCore.d.ts +22 -0
- package/build/BaseCore.js +46 -3
- package/build/esm/BaseCore.d.ts +22 -0
- package/build/esm/BaseCore.js +46 -3
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -34,6 +34,7 @@ A comprehensive backend framework for Node.js applications providing database ac
|
|
|
34
34
|
- [Action-level rules](#action-level-rules)
|
|
35
35
|
- [Per-call override](#per-call-override)
|
|
36
36
|
- [Disabling rate limiting](#disabling-rate-limiting)
|
|
37
|
+
- [Resetting a counter after success](#resetting-a-counter-after-success)
|
|
37
38
|
- [Custom limiter](#custom-limiter)
|
|
38
39
|
- [Database](#database)
|
|
39
40
|
- [Database class](#database-class)
|
|
@@ -1012,6 +1013,46 @@ super({
|
|
|
1012
1013
|
|
|
1013
1014
|
---
|
|
1014
1015
|
|
|
1016
|
+
### Resetting a counter after success
|
|
1017
|
+
|
|
1018
|
+
After a successful sensitive operation (e.g. sign-in), you can reset the IP rate-limit counter so a legitimate user who was briefly throttled is not stuck waiting for the window to expire.
|
|
1019
|
+
|
|
1020
|
+
Call `this.resetRateLimit(actionName)` from any `BaseCore` subclass. The `actionName` must match the value used in the `runAction` call that incremented the counter — either the `actionName` field or the `rule.action` override if one was set. The method silently no-ops when no limiter is configured or when Redis is unavailable.
|
|
1021
|
+
|
|
1022
|
+
```typescript
|
|
1023
|
+
public async signIn(args: any) {
|
|
1024
|
+
return this.runAction({
|
|
1025
|
+
args,
|
|
1026
|
+
actionName: 'signIn',
|
|
1027
|
+
rateLimit: { limit: 20, windowSec: 900 },
|
|
1028
|
+
action: async (args) => {
|
|
1029
|
+
// ... validate credentials ...
|
|
1030
|
+
|
|
1031
|
+
if (!passwordValid) {
|
|
1032
|
+
return this.failure(OP_RESULT_CODES.UNAUTHORIZED, 'Username/Password pair is invalid');
|
|
1033
|
+
}
|
|
1034
|
+
|
|
1035
|
+
// Successful sign-in — clear the failed-attempt counter so the user
|
|
1036
|
+
// is not stuck throttled until the 15-minute window expires.
|
|
1037
|
+
await this.resetRateLimit('signIn');
|
|
1038
|
+
|
|
1039
|
+
// ... issue cookies, return user ...
|
|
1040
|
+
},
|
|
1041
|
+
hasTransaction: false,
|
|
1042
|
+
doingWhat: 'signing in a user',
|
|
1043
|
+
});
|
|
1044
|
+
}
|
|
1045
|
+
```
|
|
1046
|
+
|
|
1047
|
+
The optional second argument controls which tier's counter is reset. It defaults to `'core-action'`, which covers rules set via `rateLimit` on `runAction` or `rateLimitOnAction` / `rateLimit` in props. Pass `'global'` to reset the global tier counter instead.
|
|
1048
|
+
|
|
1049
|
+
```typescript
|
|
1050
|
+
await this.resetRateLimit('signIn'); // resets the core-or-action counter (default)
|
|
1051
|
+
await this.resetRateLimit('signIn', 'global'); // resets the global counter
|
|
1052
|
+
```
|
|
1053
|
+
|
|
1054
|
+
---
|
|
1055
|
+
|
|
1015
1056
|
### Custom limiter
|
|
1016
1057
|
|
|
1017
1058
|
To use a different rate-limiting backend (e.g. in-memory for tests, DynamoDB for Lambda), implement `RateLimiterInterface` and pass it via `rateLimiter` in `createContextDefault` or in per-core props.
|
package/build/BaseCore.d.ts
CHANGED
|
@@ -103,6 +103,7 @@ declare class BaseCore {
|
|
|
103
103
|
* that will be merged into actionOpt for the action handler
|
|
104
104
|
*/
|
|
105
105
|
getValidators(): BaseCoreValidatorsInterface;
|
|
106
|
+
getLogger(): Logger;
|
|
106
107
|
/**
|
|
107
108
|
* Wraps data in a successful OpResult and returns its plain JS representation.
|
|
108
109
|
*
|
|
@@ -174,6 +175,27 @@ declare class BaseCore {
|
|
|
174
175
|
* in a custom implementation or disable limiting entirely via config.
|
|
175
176
|
*/
|
|
176
177
|
private getRateLimiter;
|
|
178
|
+
/**
|
|
179
|
+
* Resets the rate-limit counter for a specific action and the current IP.
|
|
180
|
+
*
|
|
181
|
+
* Useful after a successful sensitive operation (e.g. sign-in) to give a
|
|
182
|
+
* legitimate user a clean slate so they are not stuck waiting for the window
|
|
183
|
+
* to expire after being briefly throttled by failed attempts.
|
|
184
|
+
*
|
|
185
|
+
* Silently no-ops when:
|
|
186
|
+
* - No limiter is configured
|
|
187
|
+
* - The limiter does not know about this action / IP combination
|
|
188
|
+
* - Redis is unavailable (the limiter already handles this gracefully)
|
|
189
|
+
*
|
|
190
|
+
* The action key must match the one used in the rate-limit rule — either the
|
|
191
|
+
* `rule.action` override or the `actionName` / `doingWhat` fallback that was
|
|
192
|
+
* used when the counter was incremented. The scope prefix ('core-action' or
|
|
193
|
+
* 'global') is prepended automatically to match the stored key format.
|
|
194
|
+
*
|
|
195
|
+
* @param actionName The action key to reset (e.g. 'signIn', ACTIONS.CREATE)
|
|
196
|
+
* @param scope The tier scope — 'core-action' (default) or 'global'
|
|
197
|
+
*/
|
|
198
|
+
protected resetRateLimit(actionName: string, scope?: 'core-action' | 'global'): Promise<void>;
|
|
177
199
|
/**
|
|
178
200
|
* Collects the rate-limit rules that apply to a single runAction call.
|
|
179
201
|
*
|
package/build/BaseCore.js
CHANGED
|
@@ -12,6 +12,7 @@ const lodash_1 = require("lodash");
|
|
|
12
12
|
const commonValidators_1 = require("./commonValidators");
|
|
13
13
|
const constants_1 = require("./constants");
|
|
14
14
|
const userToken_1 = require("./userToken");
|
|
15
|
+
const OP_RESULT_TOO_MANY_REQUESTS = api_helpers_1.OP_RESULT_CODES.TOO_MANY_REQUESTS;
|
|
15
16
|
/**
|
|
16
17
|
* Default no-op validator — allows all operations through without checks.
|
|
17
18
|
* Used as the fallback for action types that do not define custom validation.
|
|
@@ -189,6 +190,9 @@ class BaseCore {
|
|
|
189
190
|
getValidators() {
|
|
190
191
|
return defaultValidators;
|
|
191
192
|
}
|
|
193
|
+
getLogger() {
|
|
194
|
+
return this.logger;
|
|
195
|
+
}
|
|
192
196
|
/**
|
|
193
197
|
* Wraps data in a successful OpResult and returns its plain JS representation.
|
|
194
198
|
*
|
|
@@ -349,6 +353,46 @@ class BaseCore {
|
|
|
349
353
|
// 3. Nothing configured — no limiting
|
|
350
354
|
return null;
|
|
351
355
|
}
|
|
356
|
+
/**
|
|
357
|
+
* Resets the rate-limit counter for a specific action and the current IP.
|
|
358
|
+
*
|
|
359
|
+
* Useful after a successful sensitive operation (e.g. sign-in) to give a
|
|
360
|
+
* legitimate user a clean slate so they are not stuck waiting for the window
|
|
361
|
+
* to expire after being briefly throttled by failed attempts.
|
|
362
|
+
*
|
|
363
|
+
* Silently no-ops when:
|
|
364
|
+
* - No limiter is configured
|
|
365
|
+
* - The limiter does not know about this action / IP combination
|
|
366
|
+
* - Redis is unavailable (the limiter already handles this gracefully)
|
|
367
|
+
*
|
|
368
|
+
* The action key must match the one used in the rate-limit rule — either the
|
|
369
|
+
* `rule.action` override or the `actionName` / `doingWhat` fallback that was
|
|
370
|
+
* used when the counter was incremented. The scope prefix ('core-action' or
|
|
371
|
+
* 'global') is prepended automatically to match the stored key format.
|
|
372
|
+
*
|
|
373
|
+
* @param actionName The action key to reset (e.g. 'signIn', ACTIONS.CREATE)
|
|
374
|
+
* @param scope The tier scope — 'core-action' (default) or 'global'
|
|
375
|
+
*/
|
|
376
|
+
async resetRateLimit(actionName, scope = 'core-action') {
|
|
377
|
+
const limiter = this.getRateLimiter();
|
|
378
|
+
if (!limiter) {
|
|
379
|
+
return;
|
|
380
|
+
}
|
|
381
|
+
const context = this.getContext();
|
|
382
|
+
const ip = context.ipAddress || '';
|
|
383
|
+
const spaceId = context.spaceId || '';
|
|
384
|
+
if (!ip) {
|
|
385
|
+
return;
|
|
386
|
+
}
|
|
387
|
+
// Key format must match what checkRateLimit wrote:
|
|
388
|
+
// rl:{spaceId}:{scope}:{actionKey}:{ip}
|
|
389
|
+
await limiter.reset({
|
|
390
|
+
action: `${scope}:${actionName}`,
|
|
391
|
+
ip,
|
|
392
|
+
spaceId,
|
|
393
|
+
});
|
|
394
|
+
this.logger.debug(`Rate-limit counter reset for action '${scope}:${actionName}' from IP '${ip}' in space '${spaceId}'`);
|
|
395
|
+
}
|
|
352
396
|
/**
|
|
353
397
|
* Collects the rate-limit rules that apply to a single runAction call.
|
|
354
398
|
*
|
|
@@ -479,8 +523,8 @@ class BaseCore {
|
|
|
479
523
|
const retryAfter = result.ttlSec > 0 ? ` Please try again in ${result.ttlSec} seconds.` : '';
|
|
480
524
|
const msg = `Too many requests.${retryAfter}`;
|
|
481
525
|
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:
|
|
483
|
-
opResult.addError('', msg,
|
|
526
|
+
const opResult = new api_helpers_1.OpResult({ code: OP_RESULT_TOO_MANY_REQUESTS });
|
|
527
|
+
opResult.addError('', msg, OP_RESULT_TOO_MANY_REQUESTS);
|
|
484
528
|
return opResult;
|
|
485
529
|
}
|
|
486
530
|
}
|
|
@@ -1325,7 +1369,6 @@ class BaseCore {
|
|
|
1325
1369
|
context.accountId = tokenData.accountId;
|
|
1326
1370
|
context.roleId = tokenData.roleId;
|
|
1327
1371
|
context.userId = tokenData.userId;
|
|
1328
|
-
// TODO: update the isSuperAdmin
|
|
1329
1372
|
context.isSuperAdmin = context.roleId === 'superadmin';
|
|
1330
1373
|
// Header spaceId takes precedence over token spaceId
|
|
1331
1374
|
context.spaceId = context.spaceId || tokenData.spaceId || '';
|
package/build/esm/BaseCore.d.ts
CHANGED
|
@@ -103,6 +103,7 @@ declare class BaseCore {
|
|
|
103
103
|
* that will be merged into actionOpt for the action handler
|
|
104
104
|
*/
|
|
105
105
|
getValidators(): BaseCoreValidatorsInterface;
|
|
106
|
+
getLogger(): Logger;
|
|
106
107
|
/**
|
|
107
108
|
* Wraps data in a successful OpResult and returns its plain JS representation.
|
|
108
109
|
*
|
|
@@ -174,6 +175,27 @@ declare class BaseCore {
|
|
|
174
175
|
* in a custom implementation or disable limiting entirely via config.
|
|
175
176
|
*/
|
|
176
177
|
private getRateLimiter;
|
|
178
|
+
/**
|
|
179
|
+
* Resets the rate-limit counter for a specific action and the current IP.
|
|
180
|
+
*
|
|
181
|
+
* Useful after a successful sensitive operation (e.g. sign-in) to give a
|
|
182
|
+
* legitimate user a clean slate so they are not stuck waiting for the window
|
|
183
|
+
* to expire after being briefly throttled by failed attempts.
|
|
184
|
+
*
|
|
185
|
+
* Silently no-ops when:
|
|
186
|
+
* - No limiter is configured
|
|
187
|
+
* - The limiter does not know about this action / IP combination
|
|
188
|
+
* - Redis is unavailable (the limiter already handles this gracefully)
|
|
189
|
+
*
|
|
190
|
+
* The action key must match the one used in the rate-limit rule — either the
|
|
191
|
+
* `rule.action` override or the `actionName` / `doingWhat` fallback that was
|
|
192
|
+
* used when the counter was incremented. The scope prefix ('core-action' or
|
|
193
|
+
* 'global') is prepended automatically to match the stored key format.
|
|
194
|
+
*
|
|
195
|
+
* @param actionName The action key to reset (e.g. 'signIn', ACTIONS.CREATE)
|
|
196
|
+
* @param scope The tier scope — 'core-action' (default) or 'global'
|
|
197
|
+
*/
|
|
198
|
+
protected resetRateLimit(actionName: string, scope?: 'core-action' | 'global'): Promise<void>;
|
|
177
199
|
/**
|
|
178
200
|
* Collects the rate-limit rules that apply to a single runAction call.
|
|
179
201
|
*
|
package/build/esm/BaseCore.js
CHANGED
|
@@ -6,6 +6,7 @@ import { castArray } from 'lodash';
|
|
|
6
6
|
import { validateGet, validateGetMany, validateRemove, validateRemoveMany } from './commonValidators';
|
|
7
7
|
import { ACTIONS, DEFAULT_ORDER_NO, DEFAULT_ORDER_NO_STEP, FIELDS, HEADERS, ID_TYPES, ORDER_BYS } from './constants';
|
|
8
8
|
import { getDefaultJwtAlgorithm, getDefaultJwtIssuer, verifyUserToken } from './userToken';
|
|
9
|
+
const OP_RESULT_TOO_MANY_REQUESTS = OP_RESULT_CODES.TOO_MANY_REQUESTS;
|
|
9
10
|
/**
|
|
10
11
|
* Default no-op validator — allows all operations through without checks.
|
|
11
12
|
* Used as the fallback for action types that do not define custom validation.
|
|
@@ -183,6 +184,9 @@ class BaseCore {
|
|
|
183
184
|
getValidators() {
|
|
184
185
|
return defaultValidators;
|
|
185
186
|
}
|
|
187
|
+
getLogger() {
|
|
188
|
+
return this.logger;
|
|
189
|
+
}
|
|
186
190
|
/**
|
|
187
191
|
* Wraps data in a successful OpResult and returns its plain JS representation.
|
|
188
192
|
*
|
|
@@ -343,6 +347,46 @@ class BaseCore {
|
|
|
343
347
|
// 3. Nothing configured — no limiting
|
|
344
348
|
return null;
|
|
345
349
|
}
|
|
350
|
+
/**
|
|
351
|
+
* Resets the rate-limit counter for a specific action and the current IP.
|
|
352
|
+
*
|
|
353
|
+
* Useful after a successful sensitive operation (e.g. sign-in) to give a
|
|
354
|
+
* legitimate user a clean slate so they are not stuck waiting for the window
|
|
355
|
+
* to expire after being briefly throttled by failed attempts.
|
|
356
|
+
*
|
|
357
|
+
* Silently no-ops when:
|
|
358
|
+
* - No limiter is configured
|
|
359
|
+
* - The limiter does not know about this action / IP combination
|
|
360
|
+
* - Redis is unavailable (the limiter already handles this gracefully)
|
|
361
|
+
*
|
|
362
|
+
* The action key must match the one used in the rate-limit rule — either the
|
|
363
|
+
* `rule.action` override or the `actionName` / `doingWhat` fallback that was
|
|
364
|
+
* used when the counter was incremented. The scope prefix ('core-action' or
|
|
365
|
+
* 'global') is prepended automatically to match the stored key format.
|
|
366
|
+
*
|
|
367
|
+
* @param actionName The action key to reset (e.g. 'signIn', ACTIONS.CREATE)
|
|
368
|
+
* @param scope The tier scope — 'core-action' (default) or 'global'
|
|
369
|
+
*/
|
|
370
|
+
async resetRateLimit(actionName, scope = 'core-action') {
|
|
371
|
+
const limiter = this.getRateLimiter();
|
|
372
|
+
if (!limiter) {
|
|
373
|
+
return;
|
|
374
|
+
}
|
|
375
|
+
const context = this.getContext();
|
|
376
|
+
const ip = context.ipAddress || '';
|
|
377
|
+
const spaceId = context.spaceId || '';
|
|
378
|
+
if (!ip) {
|
|
379
|
+
return;
|
|
380
|
+
}
|
|
381
|
+
// Key format must match what checkRateLimit wrote:
|
|
382
|
+
// rl:{spaceId}:{scope}:{actionKey}:{ip}
|
|
383
|
+
await limiter.reset({
|
|
384
|
+
action: `${scope}:${actionName}`,
|
|
385
|
+
ip,
|
|
386
|
+
spaceId,
|
|
387
|
+
});
|
|
388
|
+
this.logger.debug(`Rate-limit counter reset for action '${scope}:${actionName}' from IP '${ip}' in space '${spaceId}'`);
|
|
389
|
+
}
|
|
346
390
|
/**
|
|
347
391
|
* Collects the rate-limit rules that apply to a single runAction call.
|
|
348
392
|
*
|
|
@@ -473,8 +517,8 @@ class BaseCore {
|
|
|
473
517
|
const retryAfter = result.ttlSec > 0 ? ` Please try again in ${result.ttlSec} seconds.` : '';
|
|
474
518
|
const msg = `Too many requests.${retryAfter}`;
|
|
475
519
|
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:
|
|
477
|
-
opResult.addError('', msg,
|
|
520
|
+
const opResult = new OpResult({ code: OP_RESULT_TOO_MANY_REQUESTS });
|
|
521
|
+
opResult.addError('', msg, OP_RESULT_TOO_MANY_REQUESTS);
|
|
478
522
|
return opResult;
|
|
479
523
|
}
|
|
480
524
|
}
|
|
@@ -1319,7 +1363,6 @@ class BaseCore {
|
|
|
1319
1363
|
context.accountId = tokenData.accountId;
|
|
1320
1364
|
context.roleId = tokenData.roleId;
|
|
1321
1365
|
context.userId = tokenData.userId;
|
|
1322
|
-
// TODO: update the isSuperAdmin
|
|
1323
1366
|
context.isSuperAdmin = context.roleId === 'superadmin';
|
|
1324
1367
|
// Header spaceId takes precedence over token spaceId
|
|
1325
1368
|
context.spaceId = context.spaceId || tokenData.spaceId || '';
|