@sdflc/backend-helpers 1.0.113 → 1.0.114
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/build/BaseCore.d.ts +128 -12
- package/build/BaseCore.js +227 -14
- package/build/IpRateLimiter.d.ts +105 -0
- package/build/IpRateLimiter.js +104 -0
- package/build/apiContext.js +21 -8
- package/build/esm/BaseCore.d.ts +128 -12
- package/build/esm/BaseCore.js +227 -14
- package/build/esm/IpRateLimiter.d.ts +105 -0
- package/build/esm/IpRateLimiter.js +100 -0
- package/build/esm/apiContext.js +20 -7
- package/build/esm/index.d.ts +1 -0
- package/build/esm/index.js +1 -0
- package/build/esm/interfaces/ApiContext.d.ts +26 -0
- package/build/esm/interfaces/ApiContext.js +1 -0
- package/build/esm/interfaces/BaseCorePropsInterface.d.ts +59 -0
- package/build/esm/interfaces/CoreActionInterface.d.ts +40 -0
- package/build/esm/interfaces/CoreActionInterface.js +1 -0
- package/build/index.d.ts +1 -0
- package/build/index.js +1 -0
- package/build/interfaces/ApiContext.d.ts +26 -0
- package/build/interfaces/ApiContext.js +1 -0
- package/build/interfaces/BaseCorePropsInterface.d.ts +59 -0
- package/build/interfaces/CoreActionInterface.d.ts +40 -0
- package/build/interfaces/CoreActionInterface.js +1 -0
- package/package.json +2 -2
|
@@ -0,0 +1,100 @@
|
|
|
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
|
+
export class IpRateLimiter {
|
|
37
|
+
client;
|
|
38
|
+
logger;
|
|
39
|
+
constructor(redisClient, logger) {
|
|
40
|
+
this.client = redisClient;
|
|
41
|
+
this.logger = logger;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Check and increment the rate-limit counter for a given action + IP.
|
|
45
|
+
* Always resolves — never rejects.
|
|
46
|
+
*/
|
|
47
|
+
async check(args) {
|
|
48
|
+
const { action, ip, spaceId, limit, windowSec } = args;
|
|
49
|
+
if (!this.client) {
|
|
50
|
+
// Redis not configured — allow the request, emit a single debug note
|
|
51
|
+
this.logger.log(`Rate limiter bypassed for action '${action}' from IP '${ip}' in space '${spaceId}': Redis client not available`);
|
|
52
|
+
return { blocked: false, count: 0, ttlSec: -1 };
|
|
53
|
+
}
|
|
54
|
+
if (!ip) {
|
|
55
|
+
// No IP to key on — allow but log so we notice misconfigured proxies
|
|
56
|
+
this.logger.log(`Rate limiter skipped for action '${action}' in space '${spaceId}': IP address not available`);
|
|
57
|
+
return { blocked: false, count: 0, ttlSec: -1 };
|
|
58
|
+
}
|
|
59
|
+
const key = `rl:${spaceId}:${action}:${ip}`;
|
|
60
|
+
try {
|
|
61
|
+
// INCR is atomic. If the key does not exist Redis creates it at 0 then
|
|
62
|
+
// increments to 1. We set the TTL only on the first hit (NX flag) so
|
|
63
|
+
// the window always starts from the very first request.
|
|
64
|
+
const count = await this.client.incr(key);
|
|
65
|
+
if (count === 1) {
|
|
66
|
+
// First hit in this window — set the expiry
|
|
67
|
+
await this.client.expire(key, windowSec);
|
|
68
|
+
}
|
|
69
|
+
const ttlSec = await this.client.ttl(key);
|
|
70
|
+
if (count > limit) {
|
|
71
|
+
this.logger.log(`Rate limit exceeded for action '${action}' from IP '${ip}' in space '${spaceId}': ${count}/${limit} requests, resets in ${ttlSec}s`);
|
|
72
|
+
return { blocked: true, count, ttlSec };
|
|
73
|
+
}
|
|
74
|
+
return { blocked: false, count, ttlSec };
|
|
75
|
+
}
|
|
76
|
+
catch (err) {
|
|
77
|
+
// Redis errors must never crash an auth request — log and allow
|
|
78
|
+
this.logger.error(`Rate limiter error for action '${action}' from IP '${ip}' in space '${spaceId}': ${err?.message} — request allowed`);
|
|
79
|
+
return { blocked: false, count: 0, ttlSec: -1 };
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Manually reset the counter for a given action + IP.
|
|
84
|
+
* Useful after a successful sign-in to clear the failed-attempt counter.
|
|
85
|
+
* Silently no-ops if Redis is unavailable.
|
|
86
|
+
*/
|
|
87
|
+
async reset(args) {
|
|
88
|
+
const { action, ip, spaceId } = args;
|
|
89
|
+
if (!this.client || !ip) {
|
|
90
|
+
return;
|
|
91
|
+
}
|
|
92
|
+
const key = `rl:${spaceId}:${action}:${ip}`;
|
|
93
|
+
try {
|
|
94
|
+
await this.client.del(key);
|
|
95
|
+
}
|
|
96
|
+
catch (err) {
|
|
97
|
+
this.logger.error(`Rate limiter reset failed for action '${action}' from IP '${ip}' in space '${spaceId}': ${err?.message}`);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
}
|
package/build/esm/apiContext.js
CHANGED
|
@@ -3,6 +3,7 @@ import { camelCase } from 'lodash';
|
|
|
3
3
|
import { v4 } from 'uuid';
|
|
4
4
|
import check from 'check-types';
|
|
5
5
|
import { extractLanguages } from '@sdflc/utils';
|
|
6
|
+
import { IpRateLimiter } from './IpRateLimiter';
|
|
6
7
|
import { Database } from './Database';
|
|
7
8
|
import { HEADERS } from './constants';
|
|
8
9
|
import { resolveClientIp } from './resolveClientIp';
|
|
@@ -33,7 +34,11 @@ export const createApiContext = async (args) => {
|
|
|
33
34
|
return context;
|
|
34
35
|
};
|
|
35
36
|
export const createContextDefault = async (args) => {
|
|
36
|
-
const { knexConfig, isProduction, logger, doAuth, spaceGw, interserviceApiKey, jwtSecret, verifyTokenArgs, dbType, dbSchema, cores, gateways, req, res, extendContext, getCoreContext, getGatewayContext, authorizationToken, db: inDb,
|
|
37
|
+
const { knexConfig, isProduction, logger, doAuth, spaceGw, interserviceApiKey, jwtSecret, verifyTokenArgs, dbType, dbSchema, cores, gateways, req, res, extendContext, getCoreContext, getGatewayContext, authorizationToken, db: inDb,
|
|
38
|
+
// Rate limiting — both optional. If redisClient is provided and no custom
|
|
39
|
+
// rateLimiter is given, a built-in IpRateLimiter is constructed here once
|
|
40
|
+
// and shared across every core for the lifetime of this context.
|
|
41
|
+
redisClient, rateLimiter: inRateLimiter, globalRateLimit, } = args || {};
|
|
37
42
|
const headers = req.headers || { noHeadersSetup: true };
|
|
38
43
|
const cookies = req.cookies || { noCookiesSetup: true };
|
|
39
44
|
const authorization = (headers[HEADERS.AUTHORIZATION] || authorizationToken || '').replace('Bearer ', '');
|
|
@@ -57,6 +62,14 @@ export const createContextDefault = async (args) => {
|
|
|
57
62
|
dbSchema,
|
|
58
63
|
logger,
|
|
59
64
|
});
|
|
65
|
+
// Resolve the rate-limiter once here so every core shares the same instance
|
|
66
|
+
// for the lifetime of this context (i.e. the duration of a single request).
|
|
67
|
+
// Priority: explicit rateLimiter arg > auto-construct from redisClient > none.
|
|
68
|
+
// null is a valid explicit value meaning "disable rate limiting entirely".
|
|
69
|
+
let rateLimiter = inRateLimiter;
|
|
70
|
+
if (rateLimiter === undefined && redisClient != null) {
|
|
71
|
+
rateLimiter = new IpRateLimiter(redisClient, logger);
|
|
72
|
+
}
|
|
60
73
|
const sharedContext = {
|
|
61
74
|
spaceId,
|
|
62
75
|
apiKey,
|
|
@@ -69,12 +82,12 @@ export const createContextDefault = async (args) => {
|
|
|
69
82
|
requestedLang,
|
|
70
83
|
authorization,
|
|
71
84
|
fingerprint,
|
|
72
|
-
req,
|
|
73
|
-
res,
|
|
74
|
-
headers,
|
|
75
|
-
cookies,
|
|
76
85
|
authorizationToken,
|
|
77
86
|
isExternalDb: !!inDb,
|
|
87
|
+
// Rate limiting — undefined values are omitted so context stays clean when
|
|
88
|
+
// neither is configured.
|
|
89
|
+
...(rateLimiter !== undefined ? { rateLimiter } : {}),
|
|
90
|
+
...(globalRateLimit !== undefined ? { globalRateLimit } : {}),
|
|
78
91
|
};
|
|
79
92
|
return await createApiContext({
|
|
80
93
|
cores,
|
|
@@ -90,7 +103,7 @@ export const createContextDefault = async (args) => {
|
|
|
90
103
|
}
|
|
91
104
|
},
|
|
92
105
|
getCoreContext: async (args) => {
|
|
93
|
-
let extendCoreContext = {};
|
|
106
|
+
let extendCoreContext = {};
|
|
94
107
|
if (check.function(getCoreContext)) {
|
|
95
108
|
extendCoreContext = await getCoreContext(args);
|
|
96
109
|
}
|
|
@@ -108,7 +121,7 @@ export const createContextDefault = async (args) => {
|
|
|
108
121
|
};
|
|
109
122
|
},
|
|
110
123
|
getGatewayContext: async (args) => {
|
|
111
|
-
let extendGatewayContext = {};
|
|
124
|
+
let extendGatewayContext = {};
|
|
112
125
|
if (check.function(getGatewayContext)) {
|
|
113
126
|
extendGatewayContext = await getGatewayContext(args);
|
|
114
127
|
}
|
package/build/esm/index.d.ts
CHANGED
package/build/esm/index.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { RateLimiterInterface, RateLimitRule } from '../IpRateLimiter';
|
|
1
2
|
export interface ApiContext {
|
|
2
3
|
requestId: string;
|
|
3
4
|
cores: any;
|
|
@@ -25,5 +26,30 @@ export interface ApiContext {
|
|
|
25
26
|
roleId?: string;
|
|
26
27
|
userId?: string;
|
|
27
28
|
lang?: string;
|
|
29
|
+
/**
|
|
30
|
+
* App-level rate-limiter singleton. Created once at startup (e.g. in
|
|
31
|
+
* createContextDefault) and shared across every core in every request.
|
|
32
|
+
*
|
|
33
|
+
* BaseCore.getRateLimiter() reads this field when no per-core override is
|
|
34
|
+
* set in BaseCorePropsInterface.rateLimiter. Setting it to null on the
|
|
35
|
+
* context disables rate limiting for all cores that don't have their own
|
|
36
|
+
* override.
|
|
37
|
+
*
|
|
38
|
+
* Typed as RateLimiterInterface so any compatible implementation works —
|
|
39
|
+
* the built-in IpRateLimiter is the default but tests can swap in a no-op.
|
|
40
|
+
*/
|
|
41
|
+
rateLimiter?: RateLimiterInterface | null;
|
|
42
|
+
/**
|
|
43
|
+
* Service-wide rate-limit rule applied as a global tier on every runAction
|
|
44
|
+
* call across all cores. Runs independently alongside the core-or-action
|
|
45
|
+
* tier — both must pass. Cannot be opted out by per-core or per-action config.
|
|
46
|
+
*
|
|
47
|
+
* Set once at app startup via createContextDefault (or your own context
|
|
48
|
+
* factory). Leave unset to skip the global tier entirely.
|
|
49
|
+
*
|
|
50
|
+
* Example — cap every IP at 300 requests per minute across the whole service:
|
|
51
|
+
* globalRateLimit: { limit: 300, windowSec: 60 }
|
|
52
|
+
*/
|
|
53
|
+
globalRateLimit?: RateLimitRule;
|
|
28
54
|
[key: string]: any;
|
|
29
55
|
}
|
|
@@ -6,6 +6,16 @@ import { VerifyUserTokenArgs } from './VerifyUserTokenArgs';
|
|
|
6
6
|
import { ApiContext } from './ApiContext';
|
|
7
7
|
import { ID_TYPES } from '../constants';
|
|
8
8
|
import { BaseCoreDoAuthOnActionInterface } from './BaseCoreDoAuthOnActionInterface';
|
|
9
|
+
import { RateLimiterInterface, RateLimitRule } from '../IpRateLimiter';
|
|
10
|
+
/**
|
|
11
|
+
* Per-action rate-limit overrides. Each key maps to either:
|
|
12
|
+
* - A RateLimitRule object — use this rule for the action
|
|
13
|
+
* - false — explicitly disable rate limiting for the action
|
|
14
|
+
* even if a core-level default rule is configured
|
|
15
|
+
*
|
|
16
|
+
* Actions not listed here fall back to the core-level `rateLimit` default.
|
|
17
|
+
*/
|
|
18
|
+
export type BaseCoreRateLimitOnActionInterface = Partial<Record<'list' | 'get' | 'getMany' | 'create' | 'createMany' | 'update' | 'updateMany' | 'set' | 'remove' | 'removeMany', RateLimitRule | false>>;
|
|
9
19
|
export interface BaseCorePropsInterface {
|
|
10
20
|
/**
|
|
11
21
|
* Full request-scoped ApiContext. Required — cores use it to access
|
|
@@ -112,4 +122,53 @@ export interface BaseCorePropsInterface {
|
|
|
112
122
|
* Defaults to ID_TYPES.UNKNOWN if not set.
|
|
113
123
|
*/
|
|
114
124
|
idType?: ID_TYPES;
|
|
125
|
+
/**
|
|
126
|
+
* Per-core rate-limiter override. When set, BaseCore uses this instance
|
|
127
|
+
* instead of the app-level context.rateLimiter singleton. Typed structurally
|
|
128
|
+
* via RateLimiterInterface — any compatible implementation works.
|
|
129
|
+
*
|
|
130
|
+
* The normal path is to leave this unset and place one IpRateLimiter on
|
|
131
|
+
* context.rateLimiter at app startup so all cores share it automatically.
|
|
132
|
+
* Use this field only when a specific core needs a different limiter
|
|
133
|
+
* (e.g. a stricter in-memory limiter for a payment core in tests, or a
|
|
134
|
+
* no-op stub when integrating with an external rate-limiting proxy).
|
|
135
|
+
*
|
|
136
|
+
* Set to null to explicitly disable rate limiting for this core even when
|
|
137
|
+
* context.rateLimiter is configured.
|
|
138
|
+
*/
|
|
139
|
+
rateLimiter?: RateLimiterInterface | null;
|
|
140
|
+
/**
|
|
141
|
+
* Default rate-limit rule applied to every runAction call in this core
|
|
142
|
+
* unless overridden by rateLimitOnAction or CoreActionInterface.rateLimit.
|
|
143
|
+
*
|
|
144
|
+
* Example — limit all actions to 60 requests per minute:
|
|
145
|
+
* { limit: 60, windowSec: 60 }
|
|
146
|
+
*
|
|
147
|
+
* Omit to disable rate limiting at the core level (actions can still
|
|
148
|
+
* opt in individually via CoreActionInterface.rateLimit).
|
|
149
|
+
*/
|
|
150
|
+
rateLimit?: RateLimitRule;
|
|
151
|
+
/**
|
|
152
|
+
* Per-action rate-limit rules. An entry here replaces the core-level
|
|
153
|
+
* `rateLimit` rule for that specific action — core and action are
|
|
154
|
+
* mutually exclusive so a raised action limit is not silently capped
|
|
155
|
+
* by the core counter still running alongside it.
|
|
156
|
+
*
|
|
157
|
+
* The global counter (context.globalRateLimit) always runs independently
|
|
158
|
+
* and is never affected by entries here.
|
|
159
|
+
*
|
|
160
|
+
* Use a RateLimitRule to override the core default for an action.
|
|
161
|
+
* Use false to disable the core-or-action tier for that action entirely
|
|
162
|
+
* so only the global counter applies.
|
|
163
|
+
*
|
|
164
|
+
* Example — raise the limit for uploads, tighten sign-in, drop reads
|
|
165
|
+
* down to global-only:
|
|
166
|
+
* {
|
|
167
|
+
* list: false,
|
|
168
|
+
* get: false,
|
|
169
|
+
* create: { limit: 50, windowSec: 60 }, // replaces core rule
|
|
170
|
+
* update: { limit: 5, windowSec: 300 }, // tighter than core
|
|
171
|
+
* }
|
|
172
|
+
*/
|
|
173
|
+
rateLimitOnAction?: BaseCoreRateLimitOnActionInterface;
|
|
115
174
|
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { BaseCoreActionsInterface } from './BaseCoreActionsInterface';
|
|
2
|
+
import { RateLimitRule } from '../IpRateLimiter';
|
|
2
3
|
export interface CoreActionInterface {
|
|
3
4
|
args: any;
|
|
4
5
|
actionName?: string;
|
|
@@ -33,4 +34,43 @@ export interface CoreActionInterface {
|
|
|
33
34
|
* whether to commit or rollback the DB transaction.
|
|
34
35
|
*/
|
|
35
36
|
skipCheckResult?: boolean;
|
|
37
|
+
/**
|
|
38
|
+
* Action-scoped rate-limit rule for this specific runAction call.
|
|
39
|
+
*
|
|
40
|
+
* Overrides the core-or-action tier for this specific runAction call.
|
|
41
|
+
* Action and core rules are mutually exclusive — this rule replaces the
|
|
42
|
+
* core rule (config.rateLimit) for this call so that loosening or
|
|
43
|
+
* tightening the limit here has full effect without the core counter
|
|
44
|
+
* silently capping it.
|
|
45
|
+
*
|
|
46
|
+
* The global counter (context.globalRateLimit) always runs independently
|
|
47
|
+
* alongside this and is never affected by this field.
|
|
48
|
+
*
|
|
49
|
+
* Set to a RateLimitRule to apply or override the action-level limit.
|
|
50
|
+
* This takes precedence over rateLimitOnAction[actionName] when both
|
|
51
|
+
* are configured — only one core-or-action counter runs per request.
|
|
52
|
+
*
|
|
53
|
+
* Set to false to disable the core-or-action tier for this call entirely
|
|
54
|
+
* so only the global counter applies.
|
|
55
|
+
*
|
|
56
|
+
* Evaluated before the DB transaction is opened and before authentication,
|
|
57
|
+
* so auth endpoints are protected from brute-force attempts without any
|
|
58
|
+
* DB or session overhead.
|
|
59
|
+
*
|
|
60
|
+
* Same-request nested calls (sameRequest === true) always skip all rate
|
|
61
|
+
* limiting — the outer call has already consumed the counter slots.
|
|
62
|
+
*
|
|
63
|
+
* Example — tighten limits on a sensitive mutation:
|
|
64
|
+
* runAction({
|
|
65
|
+
* ...,
|
|
66
|
+
* rateLimit: { limit: 5, windowSec: 300 },
|
|
67
|
+
* })
|
|
68
|
+
*
|
|
69
|
+
* Example — disable the action-level counter for an internal helper:
|
|
70
|
+
* runAction({
|
|
71
|
+
* ...,
|
|
72
|
+
* rateLimit: false,
|
|
73
|
+
* })
|
|
74
|
+
*/
|
|
75
|
+
rateLimit?: RateLimitRule | false;
|
|
36
76
|
}
|
package/build/index.d.ts
CHANGED
package/build/index.js
CHANGED
|
@@ -38,3 +38,4 @@ __exportStar(require("./downloadHelpers"), exports);
|
|
|
38
38
|
__exportStar(require("./resolveClientIp"), exports);
|
|
39
39
|
__exportStar(require("./BaseRestApiCrudController"), exports);
|
|
40
40
|
__exportStar(require("./BaseExternalApiGateway"), exports);
|
|
41
|
+
__exportStar(require("./IpRateLimiter"), exports);
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { RateLimiterInterface, RateLimitRule } from '../IpRateLimiter';
|
|
1
2
|
export interface ApiContext {
|
|
2
3
|
requestId: string;
|
|
3
4
|
cores: any;
|
|
@@ -25,5 +26,30 @@ export interface ApiContext {
|
|
|
25
26
|
roleId?: string;
|
|
26
27
|
userId?: string;
|
|
27
28
|
lang?: string;
|
|
29
|
+
/**
|
|
30
|
+
* App-level rate-limiter singleton. Created once at startup (e.g. in
|
|
31
|
+
* createContextDefault) and shared across every core in every request.
|
|
32
|
+
*
|
|
33
|
+
* BaseCore.getRateLimiter() reads this field when no per-core override is
|
|
34
|
+
* set in BaseCorePropsInterface.rateLimiter. Setting it to null on the
|
|
35
|
+
* context disables rate limiting for all cores that don't have their own
|
|
36
|
+
* override.
|
|
37
|
+
*
|
|
38
|
+
* Typed as RateLimiterInterface so any compatible implementation works —
|
|
39
|
+
* the built-in IpRateLimiter is the default but tests can swap in a no-op.
|
|
40
|
+
*/
|
|
41
|
+
rateLimiter?: RateLimiterInterface | null;
|
|
42
|
+
/**
|
|
43
|
+
* Service-wide rate-limit rule applied as a global tier on every runAction
|
|
44
|
+
* call across all cores. Runs independently alongside the core-or-action
|
|
45
|
+
* tier — both must pass. Cannot be opted out by per-core or per-action config.
|
|
46
|
+
*
|
|
47
|
+
* Set once at app startup via createContextDefault (or your own context
|
|
48
|
+
* factory). Leave unset to skip the global tier entirely.
|
|
49
|
+
*
|
|
50
|
+
* Example — cap every IP at 300 requests per minute across the whole service:
|
|
51
|
+
* globalRateLimit: { limit: 300, windowSec: 60 }
|
|
52
|
+
*/
|
|
53
|
+
globalRateLimit?: RateLimitRule;
|
|
28
54
|
[key: string]: any;
|
|
29
55
|
}
|
|
@@ -6,6 +6,16 @@ import { VerifyUserTokenArgs } from './VerifyUserTokenArgs';
|
|
|
6
6
|
import { ApiContext } from './ApiContext';
|
|
7
7
|
import { ID_TYPES } from '../constants';
|
|
8
8
|
import { BaseCoreDoAuthOnActionInterface } from './BaseCoreDoAuthOnActionInterface';
|
|
9
|
+
import { RateLimiterInterface, RateLimitRule } from '../IpRateLimiter';
|
|
10
|
+
/**
|
|
11
|
+
* Per-action rate-limit overrides. Each key maps to either:
|
|
12
|
+
* - A RateLimitRule object — use this rule for the action
|
|
13
|
+
* - false — explicitly disable rate limiting for the action
|
|
14
|
+
* even if a core-level default rule is configured
|
|
15
|
+
*
|
|
16
|
+
* Actions not listed here fall back to the core-level `rateLimit` default.
|
|
17
|
+
*/
|
|
18
|
+
export type BaseCoreRateLimitOnActionInterface = Partial<Record<'list' | 'get' | 'getMany' | 'create' | 'createMany' | 'update' | 'updateMany' | 'set' | 'remove' | 'removeMany', RateLimitRule | false>>;
|
|
9
19
|
export interface BaseCorePropsInterface {
|
|
10
20
|
/**
|
|
11
21
|
* Full request-scoped ApiContext. Required — cores use it to access
|
|
@@ -112,4 +122,53 @@ export interface BaseCorePropsInterface {
|
|
|
112
122
|
* Defaults to ID_TYPES.UNKNOWN if not set.
|
|
113
123
|
*/
|
|
114
124
|
idType?: ID_TYPES;
|
|
125
|
+
/**
|
|
126
|
+
* Per-core rate-limiter override. When set, BaseCore uses this instance
|
|
127
|
+
* instead of the app-level context.rateLimiter singleton. Typed structurally
|
|
128
|
+
* via RateLimiterInterface — any compatible implementation works.
|
|
129
|
+
*
|
|
130
|
+
* The normal path is to leave this unset and place one IpRateLimiter on
|
|
131
|
+
* context.rateLimiter at app startup so all cores share it automatically.
|
|
132
|
+
* Use this field only when a specific core needs a different limiter
|
|
133
|
+
* (e.g. a stricter in-memory limiter for a payment core in tests, or a
|
|
134
|
+
* no-op stub when integrating with an external rate-limiting proxy).
|
|
135
|
+
*
|
|
136
|
+
* Set to null to explicitly disable rate limiting for this core even when
|
|
137
|
+
* context.rateLimiter is configured.
|
|
138
|
+
*/
|
|
139
|
+
rateLimiter?: RateLimiterInterface | null;
|
|
140
|
+
/**
|
|
141
|
+
* Default rate-limit rule applied to every runAction call in this core
|
|
142
|
+
* unless overridden by rateLimitOnAction or CoreActionInterface.rateLimit.
|
|
143
|
+
*
|
|
144
|
+
* Example — limit all actions to 60 requests per minute:
|
|
145
|
+
* { limit: 60, windowSec: 60 }
|
|
146
|
+
*
|
|
147
|
+
* Omit to disable rate limiting at the core level (actions can still
|
|
148
|
+
* opt in individually via CoreActionInterface.rateLimit).
|
|
149
|
+
*/
|
|
150
|
+
rateLimit?: RateLimitRule;
|
|
151
|
+
/**
|
|
152
|
+
* Per-action rate-limit rules. An entry here replaces the core-level
|
|
153
|
+
* `rateLimit` rule for that specific action — core and action are
|
|
154
|
+
* mutually exclusive so a raised action limit is not silently capped
|
|
155
|
+
* by the core counter still running alongside it.
|
|
156
|
+
*
|
|
157
|
+
* The global counter (context.globalRateLimit) always runs independently
|
|
158
|
+
* and is never affected by entries here.
|
|
159
|
+
*
|
|
160
|
+
* Use a RateLimitRule to override the core default for an action.
|
|
161
|
+
* Use false to disable the core-or-action tier for that action entirely
|
|
162
|
+
* so only the global counter applies.
|
|
163
|
+
*
|
|
164
|
+
* Example — raise the limit for uploads, tighten sign-in, drop reads
|
|
165
|
+
* down to global-only:
|
|
166
|
+
* {
|
|
167
|
+
* list: false,
|
|
168
|
+
* get: false,
|
|
169
|
+
* create: { limit: 50, windowSec: 60 }, // replaces core rule
|
|
170
|
+
* update: { limit: 5, windowSec: 300 }, // tighter than core
|
|
171
|
+
* }
|
|
172
|
+
*/
|
|
173
|
+
rateLimitOnAction?: BaseCoreRateLimitOnActionInterface;
|
|
115
174
|
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { BaseCoreActionsInterface } from './BaseCoreActionsInterface';
|
|
2
|
+
import { RateLimitRule } from '../IpRateLimiter';
|
|
2
3
|
export interface CoreActionInterface {
|
|
3
4
|
args: any;
|
|
4
5
|
actionName?: string;
|
|
@@ -33,4 +34,43 @@ export interface CoreActionInterface {
|
|
|
33
34
|
* whether to commit or rollback the DB transaction.
|
|
34
35
|
*/
|
|
35
36
|
skipCheckResult?: boolean;
|
|
37
|
+
/**
|
|
38
|
+
* Action-scoped rate-limit rule for this specific runAction call.
|
|
39
|
+
*
|
|
40
|
+
* Overrides the core-or-action tier for this specific runAction call.
|
|
41
|
+
* Action and core rules are mutually exclusive — this rule replaces the
|
|
42
|
+
* core rule (config.rateLimit) for this call so that loosening or
|
|
43
|
+
* tightening the limit here has full effect without the core counter
|
|
44
|
+
* silently capping it.
|
|
45
|
+
*
|
|
46
|
+
* The global counter (context.globalRateLimit) always runs independently
|
|
47
|
+
* alongside this and is never affected by this field.
|
|
48
|
+
*
|
|
49
|
+
* Set to a RateLimitRule to apply or override the action-level limit.
|
|
50
|
+
* This takes precedence over rateLimitOnAction[actionName] when both
|
|
51
|
+
* are configured — only one core-or-action counter runs per request.
|
|
52
|
+
*
|
|
53
|
+
* Set to false to disable the core-or-action tier for this call entirely
|
|
54
|
+
* so only the global counter applies.
|
|
55
|
+
*
|
|
56
|
+
* Evaluated before the DB transaction is opened and before authentication,
|
|
57
|
+
* so auth endpoints are protected from brute-force attempts without any
|
|
58
|
+
* DB or session overhead.
|
|
59
|
+
*
|
|
60
|
+
* Same-request nested calls (sameRequest === true) always skip all rate
|
|
61
|
+
* limiting — the outer call has already consumed the counter slots.
|
|
62
|
+
*
|
|
63
|
+
* Example — tighten limits on a sensitive mutation:
|
|
64
|
+
* runAction({
|
|
65
|
+
* ...,
|
|
66
|
+
* rateLimit: { limit: 5, windowSec: 300 },
|
|
67
|
+
* })
|
|
68
|
+
*
|
|
69
|
+
* Example — disable the action-level counter for an internal helper:
|
|
70
|
+
* runAction({
|
|
71
|
+
* ...,
|
|
72
|
+
* rateLimit: false,
|
|
73
|
+
* })
|
|
74
|
+
*/
|
|
75
|
+
rateLimit?: RateLimitRule | false;
|
|
36
76
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sdflc/backend-helpers",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.114",
|
|
4
4
|
"description": "Set of helper functions and classes to simplify building backend apps within @sdflc ecosystem",
|
|
5
5
|
"type": "commonjs",
|
|
6
6
|
"exports": {
|
|
@@ -58,7 +58,7 @@
|
|
|
58
58
|
"typescript": "^5.9.3"
|
|
59
59
|
},
|
|
60
60
|
"dependencies": {
|
|
61
|
-
"@sdflc/api-helpers": "^1.1.
|
|
61
|
+
"@sdflc/api-helpers": "^1.1.16",
|
|
62
62
|
"@sdflc/utils": "^1.0.28",
|
|
63
63
|
"bcrypt": "^6.0.0",
|
|
64
64
|
"bluebird": "^3.7.2",
|