@sdflc/backend-helpers 1.0.114 → 1.0.116

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 CHANGED
@@ -1,6 +1,6 @@
1
1
  # @sdflc/backend-helpers
2
2
 
3
- A comprehensive backend framework for Node.js applications providing database access, authentication, caching, GraphQL resolver helpers, REST controllers, CLI utilities, and migration tools.
3
+ A comprehensive backend framework for Node.js applications providing database access, authentication, caching, IP-based rate limiting, GraphQL resolver helpers, REST controllers, CLI utilities, and migration tools.
4
4
 
5
5
  ---
6
6
 
@@ -26,6 +26,16 @@ A comprehensive backend framework for Node.js applications providing database ac
26
26
  - [BaseController](#basecontroller)
27
27
  - [BaseRestApiCrudController](#baserestapicrudcontroller)
28
28
  - [BaseExternalApiGateway](#baseexternalapigatewayx)
29
+ - [IP rate limiting](#ip-rate-limiting)
30
+ - [How it works](#how-it-works)
31
+ - [Setup](#setup)
32
+ - [Global tier](#global-tier)
33
+ - [Core-level rules](#core-level-rules)
34
+ - [Action-level rules](#action-level-rules)
35
+ - [Per-call override](#per-call-override)
36
+ - [Disabling rate limiting](#disabling-rate-limiting)
37
+ - [Resetting a counter after success](#resetting-a-counter-after-success)
38
+ - [Custom limiter](#custom-limiter)
29
39
  - [Database](#database)
30
40
  - [Database class](#database-class)
31
41
  - [DataCache and custom loaders](#datacache-and-custom-loaders)
@@ -74,9 +84,9 @@ Application layer → GraphQL resolvers / REST controllers / CLI
74
84
  transform inputs before passing them to cores.
75
85
 
76
86
  Business layer → Core classes (BaseCore subclasses)
77
- Manage transactions, handle request-level authentication
78
- and validation, enforce business rules, normalise
79
- responses into a consistent OpResult shape.
87
+ Manage transactions, handle request-level authentication,
88
+ validation, IP rate limiting, enforce business rules,
89
+ and normalise responses into a consistent OpResult shape.
80
90
 
81
91
  Data layer → Gateway classes (BaseGateway subclasses)
82
92
  Perform CRUD operations on database tables, run complex
@@ -269,6 +279,8 @@ export const redisClient = config.redisHost
269
279
 
270
280
  > The client is created but **not connected** — call `await redisClient.connect()` during app or CLI startup. This allows the client to be created early and connected at a controlled point.
271
281
 
282
+ The same `redisClient` instance is used for both DataLoader caching (via gateways) and IP rate limiting (via `createContextDefault`). Pass it once — the library routes it to both uses automatically.
283
+
272
284
  ---
273
285
 
274
286
  ### Knex handle
@@ -300,7 +312,7 @@ export default knex({
300
312
 
301
313
  ### Context
302
314
 
303
- The context factory creates a fresh `ApiContext` for every request. All gateways and cores are instantiated here. The same factory is used by GraphQL, REST, and CLI — this is the single source of truth for how cores and gateways are wired together.
315
+ The context factory creates a fresh `ApiContext` for every request. All gateways and cores are instantiated here. The same factory is used by GraphQL, REST, and CLI.
304
316
 
305
317
  ```typescript
306
318
  // src/context.ts
@@ -331,6 +343,12 @@ export const createContext = async (args: any) => {
331
343
  ignoreExpiration: false,
332
344
  ignoreNotBefore: false,
333
345
  },
346
+ // Pass redisClient to enable IP rate limiting automatically.
347
+ // An IpRateLimiter instance is constructed once here and shared
348
+ // across all cores for the lifetime of this request.
349
+ redisClient,
350
+ // Optional: cap every IP at 300 requests per minute across all cores.
351
+ globalRateLimit: { limit: 300, windowSec: 60 },
334
352
  // Provide extra props to every gateway constructor
335
353
  getGatewayContext: () => ({
336
354
  redisClient,
@@ -349,6 +367,16 @@ export const createContext = async (args: any) => {
349
367
  };
350
368
  ```
351
369
 
370
+ #### `createContextDefault` options
371
+
372
+ All options from the original factory plus the new rate-limiting options:
373
+
374
+ | Option | Type | Description |
375
+ | ----------------- | ------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
376
+ | `redisClient` | `any \| null` | Redis client for the built-in `IpRateLimiter`. If provided and no `rateLimiter` is set, an `IpRateLimiter` is constructed automatically and placed on `context.rateLimiter`. |
377
+ | `rateLimiter` | `RateLimiterInterface \| null` | Custom rate-limiter instance. Overrides `redisClient`. Set to `null` to disable rate limiting explicitly. |
378
+ | `globalRateLimit` | `RateLimitRule` | Service-wide rule applied as the global tier to every `runAction` call across all cores. |
379
+
352
380
  ---
353
381
 
354
382
  ### Express app
@@ -440,12 +468,7 @@ const configureApp = async (app: any) => {
440
468
 
441
469
  await apolloServer.start();
442
470
 
443
- app.use(
444
- config.graphqlUrl,
445
- cors(corsOptions),
446
- express.json(),
447
- expressMiddleware(apolloServer, { context: createContext }),
448
- );
471
+ app.use(config.graphqlUrl, cors(corsOptions), expressMiddleware(apolloServer, { context: createContext }));
449
472
 
450
473
  // 404 handler
451
474
  app.use((req: any, res: any) => {
@@ -492,18 +515,36 @@ export default configureApp;
492
515
 
493
516
  The request context object shared across all layers. Created once per request — or once per CLI invocation.
494
517
 
495
- | Field | Type | Description |
496
- | ------------- | --------------------- | ------------------------------------------------- |
497
- | `requestId` | `string` | UUID generated per request |
498
- | `cores` | `Record<string, any>` | All registered core instances (camelCase keys) |
499
- | `gateways` | `Record<string, any>` | All registered gateway instances (camelCase keys) |
500
- | `db` | `Database` | Shared database instance |
501
- | `userId` | `string?` | Populated after successful authentication |
502
- | `accountId` | `string?` | Populated after successful authentication |
503
- | `roleId` | `string?` | Populated after successful authentication |
504
- | `spaceId` | `string?` | From request headers or JWT token |
505
- | `lang` | `string?` | Resolved language for the request |
506
- | `req` / `res` | `any` | Express request/response objects |
518
+ | Field | Type | Description |
519
+ | -------------------- | ----------------------- | ----------------------------------------------------------------------------------------------- |
520
+ | `requestId` | `string` | UUID generated per request |
521
+ | `cores` | `Record<string, any>` | All registered core instances (camelCase keys) |
522
+ | `gateways` | `Record<string, any>` | All registered gateway instances (camelCase keys) |
523
+ | `usedKeyPrefixes` | `Record<string, any>` | Tracks gateway key prefixes to detect collisions |
524
+ | `db` | `Database` | Shared database instance |
525
+ | `req` / `res` | `any` | Express request/response objects |
526
+ | `headers` | `Record<string, any>` | Raw request headers |
527
+ | `cookies` | `Record<string, any>` | Parsed request cookies |
528
+ | `spaceId` | `string?` | From request headers or JWT token |
529
+ | `apiKey` | `string?` | From `x-api-key` header |
530
+ | `managementApiKey` | `string?` | From management API key header |
531
+ | `ipAddress` | `string?` | Client IP address — used by the rate limiter |
532
+ | `authorization` | `string?` | Bearer token stripped from Authorization header |
533
+ | `fingerprint` | `string?` | CSRF fingerprint from cookie or header |
534
+ | `acceptLanguage` | `string?` | Raw `Accept-Language` header value |
535
+ | `languages` | `string[]?` | Parsed language preference list |
536
+ | `requestedLang` | `string?` | Resolved language for the request (default `'en'`) |
537
+ | `userAgent` | `string?` | `User-Agent` header |
538
+ | `referer` | `string?` | `Referer` header |
539
+ | `authorizationToken` | `string?` | Raw authorization token passed explicitly |
540
+ | `isExternalDb` | `boolean?` | True when a pre-built `db` was passed in |
541
+ | `userId` | `string?` | Populated after successful authentication |
542
+ | `accountId` | `string?` | Populated after successful authentication |
543
+ | `roleId` | `string?` | Populated after successful authentication |
544
+ | `isSuperAdmin` | `boolean?` | True when `roleId === 'superadmin'` |
545
+ | `lang` | `string?` | Resolved language from token or header |
546
+ | `rateLimiter` | `RateLimiterInterface?` | App-level rate-limiter singleton — set by `createContextDefault` when `redisClient` is provided |
547
+ | `globalRateLimit` | `RateLimitRule?` | Service-wide rate-limit rule applied to all cores |
507
548
 
508
549
  ---
509
550
 
@@ -553,60 +594,17 @@ class NoteCore extends AppCore {
553
594
  remove: 'removing a note',
554
595
  removeMany: 'removing multiple notes',
555
596
  },
597
+ // Rate limiting — tighten create, leave reads unrestricted
598
+ rateLimit: { limit: 60, windowSec: 60 },
599
+ rateLimitOnAction: {
600
+ list: false,
601
+ get: false,
602
+ create: { limit: 10, windowSec: 60 },
603
+ },
556
604
  });
557
605
  }
558
606
 
559
- public getValidators(): BaseCoreValidatorsInterface {
560
- return {
561
- ...super.getValidators(),
562
- ...validators,
563
- };
564
- }
565
-
566
- // Scope all list queries to the current user
567
- public async beforeList(args: any, opt?: BaseCoreActionsInterface): Promise<any> {
568
- const { filter } = args || {};
569
- const { userId } = this.getContext();
570
-
571
- if (!userId) {
572
- return OpResult.ok([]);
573
- }
574
-
575
- return { ...args, filter: { ...filter, userId } };
576
- }
577
-
578
- // Enforce ownership — return null so core responds with NOT_FOUND
579
- public async afterGet(item: any, opt?: BaseCoreActionsInterface): Promise<any> {
580
- if (!item) return item;
581
-
582
- if (item.userId !== this.getContext().userId) {
583
- return null;
584
- }
585
-
586
- return this.processItemOnOut(item, opt);
587
- }
588
-
589
- // Inject userId on create
590
- public async beforeCreate(params: any, opt?: BaseCoreActionsInterface): Promise<any> {
591
- return { ...params, userId: this.getContext().userId };
592
- }
593
-
594
- // Inject userId into where clause to prevent cross-user updates
595
- public async beforeUpdate(params: any, opt?: BaseCoreActionsInterface): Promise<any> {
596
- const { args } = opt || {};
597
- const { where } = args || {};
598
-
599
- if (where) {
600
- where.userId = this.getContext().userId;
601
- }
602
-
603
- return params;
604
- }
605
-
606
- // Prevent removing other users' notes
607
- public async beforeRemove(where: any, opt?: BaseCoreActionsInterface): Promise<any> {
608
- return { ...where, userId: this.getContext().userId };
609
- }
607
+ // ... validators, hooks, etc.
610
608
  }
611
609
 
612
610
  export { NoteCore };
@@ -866,6 +864,218 @@ await gw.chargeCard(1000, 'usd');
866
864
 
867
865
  ---
868
866
 
867
+ ## IP rate limiting
868
+
869
+ ### How it works
870
+
871
+ Rate limiting is built into `BaseCore` and runs automatically on every `runAction` call — before the database transaction is opened and before authentication. This protects auth endpoints from brute-force without any DB overhead.
872
+
873
+ The implementation uses two independent tiers, both of which must pass for a request to proceed. Each tier maintains its own Redis counter keyed on `(space, scope, action, ip)`.
874
+
875
+ **Global tier** — a service-wide ceiling applied to every core and every action. Cannot be opted out by core or action configuration. Guards the whole service from a flood regardless of which endpoint is targeted.
876
+
877
+ **Core-or-action tier** — a more specific limit scoped to a core or a single action. Core and action rules are **mutually exclusive**: an action rule replaces the core rule for that action so that loosening a limit actually raises it — the core counter will not silently block first.
878
+
879
+ Resolution for the core-or-action tier (first defined value wins):
880
+
881
+ 1. `CoreActionInterface.rateLimit` — per-call override in `runAction()`
882
+ 2. `BaseCorePropsInterface.rateLimitOnAction[actionName]` — per-action props
883
+ 3. `BaseCorePropsInterface.rateLimit` — core-level default
884
+ 4. Nothing — tier is skipped
885
+
886
+ Using `false` at steps 1 or 2 disables the core-or-action tier for that action entirely so only the global tier applies. `false` never suppresses the global tier.
887
+
888
+ Blocked requests receive `OP_RESULT_CODES.TOO_MANY_REQUESTS` (429) with a human-readable message including the time until the window resets.
889
+
890
+ Redis errors are swallowed silently — the limiter allows requests through rather than taking down an endpoint. If Redis is not configured, rate limiting is completely skipped with zero overhead.
891
+
892
+ ---
893
+
894
+ ### Setup
895
+
896
+ The minimum to enable rate limiting is passing `redisClient` to `createContextDefault`. An `IpRateLimiter` instance is constructed once per request context and shared across all cores automatically — no per-core wiring needed.
897
+
898
+ ```typescript
899
+ // src/context.ts
900
+ export const createContext = async (args: any) => {
901
+ return createContextDefault({
902
+ // ...existing options...
903
+ redisClient, // enables rate limiting
904
+ globalRateLimit: { limit: 300, windowSec: 60 }, // optional service-wide cap
905
+ });
906
+ };
907
+ ```
908
+
909
+ That is the only change needed to get rate limiting running across all cores. Per-core and per-action rules are additive on top.
910
+
911
+ ---
912
+
913
+ ### Global tier
914
+
915
+ Set `globalRateLimit` on the context to cap every IP across all cores and all actions. This is the flood guard — it runs regardless of what the core or action configures.
916
+
917
+ ```typescript
918
+ createContextDefault({
919
+ redisClient,
920
+ globalRateLimit: { limit: 500, windowSec: 60 }, // 500 req/min per IP, service-wide
921
+ });
922
+ ```
923
+
924
+ The global tier has no opt-out. If you need an endpoint to be completely unmetered, do not set `globalRateLimit`.
925
+
926
+ ---
927
+
928
+ ### Core-level rules
929
+
930
+ Add `rateLimit` to a core's constructor props to apply a default rule to every action in that core. Individual actions can override or disable it via `rateLimitOnAction`.
931
+
932
+ ```typescript
933
+ class AuthCore extends AppCore {
934
+ constructor(props: BaseCorePropsInterface) {
935
+ super({
936
+ ...props,
937
+ rateLimit: { limit: 30, windowSec: 60 }, // 30 req/min for all auth actions
938
+ rateLimitOnAction: {
939
+ list: false, // no core-tier limit for list
940
+ get: false, // no core-tier limit for get
941
+ create: { limit: 5, windowSec: 300 }, // tighter for sign-up (replaces core rule)
942
+ },
943
+ });
944
+ }
945
+ }
946
+ ```
947
+
948
+ `rateLimitOnAction` values:
949
+
950
+ | Value | Effect |
951
+ | --------------- | -------------------------------------------------------------- |
952
+ | `RateLimitRule` | Replaces the core rule for this action (action wins) |
953
+ | `false` | Disables the core-or-action tier for this action (global only) |
954
+ | `undefined` | Falls back to the core-level `rateLimit` default |
955
+
956
+ ---
957
+
958
+ ### Action-level rules
959
+
960
+ Pass `rateLimit` directly to `runAction()` for a one-off rule on a specific call. This is the highest-priority override and replaces any `rateLimitOnAction` or `rateLimit` configured in props for that call.
961
+
962
+ ```typescript
963
+ return this.runAction({
964
+ args,
965
+ doAuth: true,
966
+ hasTransaction: true,
967
+ actionName: 'signIn',
968
+ rateLimit: { limit: 5, windowSec: 300 }, // 5 attempts per 5 minutes
969
+ doingWhat: 'signing in',
970
+ action: async (args, opt) => {
971
+ /* ... */
972
+ },
973
+ });
974
+ ```
975
+
976
+ ---
977
+
978
+ ### Disabling rate limiting
979
+
980
+ Set `rateLimit: false` at the call site or in `rateLimitOnAction` to disable the core-or-action tier for a specific action. The global tier still runs.
981
+
982
+ ```typescript
983
+ // Disable core-tier for an internal helper action:
984
+ return this.runAction({
985
+ args,
986
+ rateLimit: false,
987
+ hasTransaction: false,
988
+ doingWhat: 'fetching internal config',
989
+ action: async (args, opt) => {
990
+ /* ... */
991
+ },
992
+ });
993
+
994
+ // Disable core-tier for specific actions in props:
995
+ super({
996
+ ...props,
997
+ rateLimit: { limit: 60, windowSec: 60 },
998
+ rateLimitOnAction: {
999
+ list: false, // reads are unrestricted at core tier
1000
+ get: false,
1001
+ },
1002
+ });
1003
+ ```
1004
+
1005
+ To disable rate limiting entirely for a core (including ignoring `context.rateLimiter`), pass `rateLimiter: null` in the core's props:
1006
+
1007
+ ```typescript
1008
+ super({
1009
+ ...props,
1010
+ rateLimiter: null, // this core is completely exempt from rate limiting
1011
+ });
1012
+ ```
1013
+
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
+
1056
+ ### Custom limiter
1057
+
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.
1059
+
1060
+ ```typescript
1061
+ import { RateLimiterInterface, RateLimitCheckArgs, RateLimitResult } from '@sdflc/backend-helpers';
1062
+
1063
+ class NoOpRateLimiter implements RateLimiterInterface {
1064
+ async check(_args: RateLimitCheckArgs): Promise<RateLimitResult> {
1065
+ return { blocked: false, count: 0, ttlSec: -1 };
1066
+ }
1067
+ async reset(_args: Pick<RateLimitCheckArgs, 'action' | 'ip' | 'spaceId'>): Promise<void> {}
1068
+ }
1069
+
1070
+ // In tests — disable all rate limiting:
1071
+ createContextDefault({
1072
+ rateLimiter: new NoOpRateLimiter(),
1073
+ // no redisClient needed
1074
+ });
1075
+ ```
1076
+
1077
+ ---
1078
+
869
1079
  ## Database
870
1080
 
871
1081
  ### Database class
@@ -1154,14 +1364,6 @@ import knexHandle from '../../knexHandle';
1154
1364
  import { logger } from '../../logger';
1155
1365
  import { redisClient } from '../../redisClient';
1156
1366
 
1157
- /**
1158
- * Builds a synthetic context for CLI commands.
1159
- *
1160
- * CLI commands do not have an HTTP request, so we construct a minimal req
1161
- * object with the headers that createContextDefault reads for space/auth
1162
- * resolution. Since CLI commands typically run with elevated access, we
1163
- * bypass JWT auth by providing the interservice API key directly.
1164
- */
1165
1367
  const getContext = () =>
1166
1368
  createContext({
1167
1369
  res: {},
@@ -1176,10 +1378,7 @@ const getContext = () =>
1176
1378
  },
1177
1379
  });
1178
1380
 
1179
- // ─── Commands ────────────────────────────────────────────────────────────────
1180
-
1181
1381
  const resetDb = () => {
1182
- // dbReset is a standalone helper — does not need a context
1183
1382
  dbReset(knexHandle, config).then(() => knexHandle.destroy());
1184
1383
  };
1185
1384
 
@@ -1199,7 +1398,6 @@ const syncExternalData = async () => {
1199
1398
  const context = await getContext();
1200
1399
 
1201
1400
  try {
1202
- // Connect Redis if available — some core operations use it for locking
1203
1401
  if (redisClient) {
1204
1402
  await redisClient.connect();
1205
1403
  }
@@ -1216,8 +1414,6 @@ const syncExternalData = async () => {
1216
1414
  }
1217
1415
  };
1218
1416
 
1219
- // ─── Command registration ─────────────────────────────────────────────────────
1220
-
1221
1417
  yargs(process.argv.splice(2))
1222
1418
  .command('reset', 'Wipes the database, runs all migrations, and seeds', () => {}, resetDb)
1223
1419
  .command('recalculate', 'Recalculates all stats and derived data', () => {}, recalculateStats)
@@ -1229,15 +1425,15 @@ yargs(process.argv.splice(2))
1229
1425
 
1230
1426
  ### Key points
1231
1427
 
1232
- **Context reuse** — the same `createContext()` factory used by GraphQL and REST is used here. The CLI passes a synthetic `req` object with hardcoded headers to simulate a trusted system-level request. This means all authentication, gateway initialisation, and Redis/db wiring happens identically regardless of whether the caller is an HTTP client or a terminal.
1428
+ **Context reuse** — the same `createContext()` factory used by GraphQL and REST is used here with a synthetic `req` object. All authentication, gateway initialisation, Redis, and rate-limiting wiring happens identically.
1233
1429
 
1234
- **Interservice API key** — CLI commands typically bypass JWT auth by providing the `interserviceApiKey` in the synthetic headers. `BaseCore.authenticate()` recognises this key and grants access without a user token.
1430
+ **Interservice API key** — CLI commands bypass JWT auth by providing `interserviceApiKey` in the synthetic headers.
1235
1431
 
1236
- **Redis** — if a core operation requires Redis (e.g. for distributed locking or cache warming), connect `redisClient` before calling the core method. The `redisClient` is `null` when `REDIS_HOST` is not configured, so always check before connecting.
1432
+ **Redis** — connect `redisClient` before calling core methods that require it. Rate limiting is also active for CLI calls if `redisClient` is configured — this is usually desirable but can be bypassed by passing `rateLimiter: null` to `createContextDefault` in your CLI's `createContext` factory if needed.
1237
1433
 
1238
- **Process exit** — CLI commands should call `process.exit(0)` in a `finally` block to ensure the Node.js process terminates cleanly after all async operations complete. Without it, open database connections and Redis clients can keep the process alive indefinitely.
1434
+ **Process exit** — CLI commands should call `process.exit(0)` in a `finally` block to close open database connections and Redis clients cleanly.
1239
1435
 
1240
- **Database reset** — `dbReset` is a standalone helper that operates directly on a Knex handle without going through the context or any core. It is appropriate for destructive operations like wiping and re-migrating the database.
1436
+ **Database reset** — `dbReset` operates directly on a Knex handle without going through the context.
1241
1437
 
1242
1438
  ---
1243
1439
 
@@ -1424,31 +1620,29 @@ ORDER_BYS.DESC; // 'desc'
1424
1620
 
1425
1621
  ## Interfaces reference
1426
1622
 
1427
- | Interface | Description |
1428
- | ----------------------------------------- | ------------------------------------------------------------------- |
1429
- | `ApiContext` | Request context object shape |
1430
- | `ApiContextInterface` | Arguments for `createApiContext()` |
1431
- | `BaseCorePropsInterface` | Constructor props for `BaseCore` subclasses |
1432
- | `BaseGatewayPropsInterface` | Constructor props for `BaseGateway` subclasses |
1433
- | `BaseExternalApiGatewayPropsInterface` | Constructor props for `BaseExternalApiGateway` |
1434
- | `BaseRestApiCrudControllerPropsInterface` | Constructor props for `BaseRestApiCrudController` |
1435
- | `BuildDefaultResolvers` | Arguments for `buildDefaultResolvers()` |
1436
- | `BuildConfigOptions` | Options for `buildConfig()` |
1437
- | `DatabaseOptions` | Options for `Database` constructor |
1438
- | `DatabaseReadInterface` | Arguments for `Database.read()` |
1439
- | `CacheInterface` | Config for `DataCache` (without request context) |
1440
- | `DataCachePropsInterface` | Full props for `DataCache` including request context |
1441
- | `LoaderInterface` | Interface for custom loaders (`load`, `loadMany`, `clear`, `prime`) |
1442
- | `CreateUserTokenArgs` | Options for `createUserToken()` |
1443
- | `VerifyUserTokenArgs` | Options for `verifyUserToken()` |
1444
- | `UserTokenParams` | JWT payload structure |
1445
- | `DownloadFileArgs` | Arguments for `downloadFile()` |
1446
- | `DbFieldAddDefaultInterface` | Options for `dbFieldAddDefaults()` |
1447
- | `ListArgsInterface` | Standard list operation arguments |
1448
- | `CoreActionInterface` | Arguments for `BaseCore.runAction()` including `tryAuth` |
1449
-
1450
- ---
1451
-
1452
- ## License
1453
-
1454
- MIT
1623
+ | Interface | Description |
1624
+ | ----------------------------------------- | -------------------------------------------------------------------------------- |
1625
+ | `ApiContext` | Request context object shape |
1626
+ | `ApiContextInterface` | Arguments for `createApiContext()` |
1627
+ | `BaseCorePropsInterface` | Constructor props for `BaseCore` subclasses |
1628
+ | `BaseCoreRateLimitOnActionInterface` | Per-action rate-limit rule map used in `BaseCorePropsInterface` |
1629
+ | `BaseGatewayPropsInterface` | Constructor props for `BaseGateway` subclasses |
1630
+ | `BaseExternalApiGatewayPropsInterface` | Constructor props for `BaseExternalApiGateway` |
1631
+ | `BaseRestApiCrudControllerPropsInterface` | Constructor props for `BaseRestApiCrudController` |
1632
+ | `BuildDefaultResolvers` | Arguments for `buildDefaultResolvers()` |
1633
+ | `BuildConfigOptions` | Options for `buildConfig()` |
1634
+ | `DatabaseOptions` | Options for `Database` constructor |
1635
+ | `DatabaseReadInterface` | Arguments for `Database.read()` |
1636
+ | `CacheInterface` | Config for `DataCache` (without request context) |
1637
+ | `DataCachePropsInterface` | Full props for `DataCache` including request context |
1638
+ | `LoaderInterface` | Interface for custom loaders (`load`, `loadMany`, `clear`, `prime`) |
1639
+ | `RateLimitRule` | Rate-limit rule shape: `{ limit, windowSec, action? }` |
1640
+ | `RateLimiterInterface` | Structural interface for custom rate-limiter implementations |
1641
+ | `IpRateLimiter` | Built-in Redis-backed rate limiter; constructed automatically from `redisClient` |
1642
+ | `CoreActionInterface` | Arguments for `BaseCore.runAction()` including `tryAuth` and `rateLimit` |
1643
+ | `CreateUserTokenArgs` | Options for `createUserToken()` |
1644
+ | `VerifyUserTokenArgs` | Options for `verifyUserToken()` |
1645
+ | `UserTokenParams` | JWT payload structure |
1646
+ | `DownloadFileArgs` | Arguments for `downloadFile()` |
1647
+ | `DbFieldAddDefaultInterface` | Options for `dbFieldAddDefaults()` |
1648
+ | `ListArgsInterface` | Standard list operation arguments |
@@ -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: api_helpers_1.OP_RESULT_CODES.TOO_MANY_REQUESTS });
483
- opResult.addError('', msg, api_helpers_1.OP_RESULT_CODES.TOO_MANY_REQUESTS);
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 || '';
@@ -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
  *
@@ -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: OP_RESULT_CODES.TOO_MANY_REQUESTS });
477
- opResult.addError('', msg, OP_RESULT_CODES.TOO_MANY_REQUESTS);
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 || '';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sdflc/backend-helpers",
3
- "version": "1.0.114",
3
+ "version": "1.0.116",
4
4
  "description": "Set of helper functions and classes to simplify building backend apps within @sdflc ecosystem",
5
5
  "type": "commonjs",
6
6
  "exports": {
@@ -29,7 +29,7 @@
29
29
  "postversion": "git push && git push --tags"
30
30
  },
31
31
  "author": "Sergey Demidenko",
32
- "license": "ISC",
32
+ "license": "MIT",
33
33
  "devDependencies": {
34
34
  "@eslint/js": "^10.0.1",
35
35
  "@types/bcrypt": "^6.0.0",