@lenne.tech/nest-server 12.11.3 → 12.12.0
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/.claude/rules/architecture.md +3 -0
- package/.claude/rules/configurable-features.md +6 -0
- package/.claude/rules/package-management.md +6 -4
- package/.claude/rules/testing.md +8 -7
- package/CLAUDE.md +2 -1
- package/FRAMEWORK-API.md +15 -1
- package/dist/core/common/decorators/common-error.decorator.d.ts +1 -1
- package/dist/core/common/interfaces/server-options.interface.d.ts +54 -0
- package/dist/core/common/persistence/audit-log.registry.d.ts +19 -0
- package/dist/core/common/persistence/audit-log.registry.js +84 -0
- package/dist/core/common/persistence/audit-log.registry.js.map +1 -0
- package/dist/core/common/services/core-trust-proxy.initializer.js +1 -1
- package/dist/core/common/services/core-trust-proxy.initializer.js.map +1 -1
- package/dist/core/common/services/crud.service.d.ts +10 -0
- package/dist/core/common/services/crud.service.js +79 -24
- package/dist/core/common/services/crud.service.js.map +1 -1
- package/dist/core/common/services/email.service.d.ts +5 -0
- package/dist/core/common/services/email.service.js +82 -6
- package/dist/core/common/services/email.service.js.map +1 -1
- package/dist/core/common/services/leased-interval.d.ts +22 -0
- package/dist/core/common/services/leased-interval.js +81 -0
- package/dist/core/common/services/leased-interval.js.map +1 -0
- package/dist/core/common/services/mail-outbox.registry.d.ts +26 -0
- package/dist/core/common/services/mail-outbox.registry.js +8 -0
- package/dist/core/common/services/mail-outbox.registry.js.map +1 -0
- package/dist/core/modules/audit-log/audited.decorator.d.ts +2 -0
- package/dist/core/modules/audit-log/audited.decorator.js +10 -0
- package/dist/core/modules/audit-log/audited.decorator.js.map +1 -0
- package/dist/core/modules/audit-log/core-audit-log.constants.d.ts +13 -0
- package/dist/core/modules/audit-log/core-audit-log.constants.js +11 -0
- package/dist/core/modules/audit-log/core-audit-log.constants.js.map +1 -0
- package/dist/core/modules/audit-log/core-audit-log.controller.d.ts +9 -0
- package/dist/core/modules/audit-log/core-audit-log.controller.js +87 -0
- package/dist/core/modules/audit-log/core-audit-log.controller.js.map +1 -0
- package/dist/core/modules/audit-log/core-audit-log.models.d.ts +10 -0
- package/dist/core/modules/audit-log/core-audit-log.models.js +11 -0
- package/dist/core/modules/audit-log/core-audit-log.models.js.map +1 -0
- package/dist/core/modules/audit-log/core-audit-log.module.d.ts +13 -0
- package/dist/core/modules/audit-log/core-audit-log.module.js +41 -0
- package/dist/core/modules/audit-log/core-audit-log.module.js.map +1 -0
- package/dist/core/modules/audit-log/core-audit-log.service.d.ts +49 -0
- package/dist/core/modules/audit-log/core-audit-log.service.js +169 -0
- package/dist/core/modules/audit-log/core-audit-log.service.js.map +1 -0
- package/dist/core/modules/better-auth/core-better-auth-email-verification.service.js +4 -0
- package/dist/core/modules/better-auth/core-better-auth-email-verification.service.js.map +1 -1
- package/dist/core/modules/mail-outbox/core-mail-outbox.constants.d.ts +22 -0
- package/dist/core/modules/mail-outbox/core-mail-outbox.constants.js +23 -0
- package/dist/core/modules/mail-outbox/core-mail-outbox.constants.js.map +1 -0
- package/dist/core/modules/mail-outbox/core-mail-outbox.controller.d.ts +10 -0
- package/dist/core/modules/mail-outbox/core-mail-outbox.controller.js +80 -0
- package/dist/core/modules/mail-outbox/core-mail-outbox.controller.js.map +1 -0
- package/dist/core/modules/mail-outbox/core-mail-outbox.models.d.ts +17 -0
- package/dist/core/modules/mail-outbox/core-mail-outbox.models.js +17 -0
- package/dist/core/modules/mail-outbox/core-mail-outbox.models.js.map +1 -0
- package/dist/core/modules/mail-outbox/core-mail-outbox.module.d.ts +12 -0
- package/dist/core/modules/mail-outbox/core-mail-outbox.module.js +42 -0
- package/dist/core/modules/mail-outbox/core-mail-outbox.module.js.map +1 -0
- package/dist/core/modules/mail-outbox/core-mail-outbox.service.d.ts +59 -0
- package/dist/core/modules/mail-outbox/core-mail-outbox.service.js +280 -0
- package/dist/core/modules/mail-outbox/core-mail-outbox.service.js.map +1 -0
- package/dist/core/modules/migrate/cli/migrate-cli.js +20 -2
- package/dist/core/modules/migrate/cli/migrate-cli.js.map +1 -1
- package/dist/core/modules/throttler/core-throttler.config.d.ts +16 -0
- package/dist/core/modules/throttler/core-throttler.config.js +107 -0
- package/dist/core/modules/throttler/core-throttler.config.js.map +1 -0
- package/dist/core/modules/throttler/core-throttler.constants.d.ts +10 -0
- package/dist/core/modules/throttler/core-throttler.constants.js +11 -0
- package/dist/core/modules/throttler/core-throttler.constants.js.map +1 -0
- package/dist/core/modules/throttler/core-throttler.decorators.d.ts +1 -0
- package/dist/core/modules/throttler/core-throttler.decorators.js +2 -0
- package/dist/core/modules/throttler/core-throttler.decorators.js.map +1 -0
- package/dist/core/modules/throttler/core-throttler.guard.d.ts +15 -0
- package/dist/core/modules/throttler/core-throttler.guard.js +65 -0
- package/dist/core/modules/throttler/core-throttler.guard.js.map +1 -0
- package/dist/core/modules/throttler/core-throttler.models.d.ts +1 -0
- package/dist/core/modules/throttler/core-throttler.models.js +11 -0
- package/dist/core/modules/throttler/core-throttler.models.js.map +1 -0
- package/dist/core/modules/throttler/core-throttler.module.d.ts +12 -0
- package/dist/core/modules/throttler/core-throttler.module.js +71 -0
- package/dist/core/modules/throttler/core-throttler.module.js.map +1 -0
- package/dist/core/modules/throttler/core-throttler.storages.d.ts +43 -0
- package/dist/core/modules/throttler/core-throttler.storages.js +174 -0
- package/dist/core/modules/throttler/core-throttler.storages.js.map +1 -0
- package/dist/core/modules/user/core-user.service.js +2 -2
- package/dist/core/modules/user/core-user.service.js.map +1 -1
- package/dist/core.module.js +26 -0
- package/dist/core.module.js.map +1 -1
- package/dist/index.d.ts +21 -0
- package/dist/index.js +21 -0
- package/dist/index.js.map +1 -1
- package/docs/REQUEST-LIFECYCLE.md +7 -0
- package/docs/security-overrides.md +20 -8
- package/migration-guides/12.11.x-to-12.12.x.md +182 -0
- package/package.json +24 -23
- package/src/core/common/interfaces/server-options.interface.ts +311 -1
- package/src/core/common/persistence/audit-log.registry.ts +150 -0
- package/src/core/common/services/core-trust-proxy.initializer.ts +5 -4
- package/src/core/common/services/crud.service.ts +128 -33
- package/src/core/common/services/email.service.ts +101 -9
- package/src/core/common/services/leased-interval.ts +123 -0
- package/src/core/common/services/mail-outbox.registry.ts +53 -0
- package/src/core/modules/audit-log/README.md +95 -0
- package/src/core/modules/audit-log/audited.decorator.ts +27 -0
- package/src/core/modules/audit-log/core-audit-log.constants.ts +28 -0
- package/src/core/modules/audit-log/core-audit-log.controller.ts +77 -0
- package/src/core/modules/audit-log/core-audit-log.models.ts +34 -0
- package/src/core/modules/audit-log/core-audit-log.module.ts +54 -0
- package/src/core/modules/audit-log/core-audit-log.service.ts +270 -0
- package/src/core/modules/better-auth/core-better-auth-email-verification.service.ts +4 -0
- package/src/core/modules/mail-outbox/README.md +88 -0
- package/src/core/modules/mail-outbox/core-mail-outbox.constants.ts +42 -0
- package/src/core/modules/mail-outbox/core-mail-outbox.controller.ts +60 -0
- package/src/core/modules/mail-outbox/core-mail-outbox.models.ts +46 -0
- package/src/core/modules/mail-outbox/core-mail-outbox.module.ts +52 -0
- package/src/core/modules/mail-outbox/core-mail-outbox.service.ts +390 -0
- package/src/core/modules/migrate/README.md +4 -1
- package/src/core/modules/migrate/cli/migrate-cli.ts +30 -2
- package/src/core/modules/throttler/README.md +107 -0
- package/src/core/modules/throttler/core-throttler.config.ts +162 -0
- package/src/core/modules/throttler/core-throttler.constants.ts +33 -0
- package/src/core/modules/throttler/core-throttler.decorators.ts +14 -0
- package/src/core/modules/throttler/core-throttler.guard.ts +109 -0
- package/src/core/modules/throttler/core-throttler.models.ts +23 -0
- package/src/core/modules/throttler/core-throttler.module.ts +95 -0
- package/src/core/modules/throttler/core-throttler.storages.ts +299 -0
- package/src/core/modules/user/core-user.service.ts +3 -2
- package/src/core.module.ts +46 -0
- package/src/index.ts +36 -0
|
@@ -0,0 +1,299 @@
|
|
|
1
|
+
import { Logger, OnApplicationShutdown } from '@nestjs/common';
|
|
2
|
+
import { ThrottlerStorageService } from '@nestjs/throttler';
|
|
3
|
+
import type { ThrottlerStorage } from '@nestjs/throttler';
|
|
4
|
+
|
|
5
|
+
import type { DataStore, StoredRecord } from '../../common/persistence/data-store.interface.js';
|
|
6
|
+
import type { CoreRedisService } from '../../common/services/core-redis.service.js';
|
|
7
|
+
|
|
8
|
+
/** What `ThrottlerStorage.increment()` answers (`@nestjs/throttler`'s `ThrottlerStorageRecord`) */
|
|
9
|
+
export interface ThrottlerHit {
|
|
10
|
+
isBlocked: boolean;
|
|
11
|
+
/** Seconds until the client may send again; `0` while it is not blocked */
|
|
12
|
+
timeToBlockExpire: number;
|
|
13
|
+
/** Seconds until the window ends */
|
|
14
|
+
timeToExpire: number;
|
|
15
|
+
totalHits: number;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** A record of the database storage (`ThrottlerCounterSchema`) */
|
|
19
|
+
export interface ThrottlerCounterRecord {
|
|
20
|
+
blocked: boolean;
|
|
21
|
+
blockedUntil: Date;
|
|
22
|
+
expiresAt: Date;
|
|
23
|
+
hits: number;
|
|
24
|
+
key: string;
|
|
25
|
+
windowEndsAt: Date;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Milliseconds → whole seconds, at least 1 (a `Retry-After: 0` would tell the client to retry at once) */
|
|
29
|
+
function seconds(ms: number): number {
|
|
30
|
+
return Math.max(1, Math.ceil(ms / 1000));
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function time(value: Date | number | string | undefined): number {
|
|
34
|
+
return value === undefined || value === null ? 0 : new Date(value).getTime();
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* The part both shared storages have in common: while the shared store cannot be reached, the counters fall back to
|
|
39
|
+
* `@nestjs/throttler`'s own in-memory storage, and each transition is logged once. Neither of the alternatives is
|
|
40
|
+
* acceptable for a rate limit: letting the error escape answers every limited route with a 500 for the duration of an
|
|
41
|
+
* outage, and swallowing it into "allowed" switches the protection off exactly when somebody may be hammering the
|
|
42
|
+
* route. The cost of the fallback is the one of `storage: 'memory'`: each replica counts for itself meanwhile.
|
|
43
|
+
*/
|
|
44
|
+
export abstract class CoreSharedThrottlerStorage implements ThrottlerStorage, OnApplicationShutdown {
|
|
45
|
+
protected readonly fallback = new ThrottlerStorageService();
|
|
46
|
+
protected degraded = false;
|
|
47
|
+
protected readonly logger = new Logger(this.constructor.name);
|
|
48
|
+
|
|
49
|
+
/** Human-readable name of the shared store, for the log lines */
|
|
50
|
+
protected abstract readonly storeLabel: string;
|
|
51
|
+
|
|
52
|
+
async increment(
|
|
53
|
+
key: string,
|
|
54
|
+
ttl: number,
|
|
55
|
+
limit: number,
|
|
56
|
+
blockDuration: number,
|
|
57
|
+
throttlerName: string,
|
|
58
|
+
): Promise<ThrottlerHit> {
|
|
59
|
+
try {
|
|
60
|
+
const hit = await this.incrementShared(`${throttlerName}:${key}`, ttl, limit, blockDuration);
|
|
61
|
+
if (this.degraded) {
|
|
62
|
+
this.degraded = false;
|
|
63
|
+
this.logger.log(`Rate limit counters are shared through ${this.storeLabel} again`);
|
|
64
|
+
}
|
|
65
|
+
return hit;
|
|
66
|
+
} catch (error) {
|
|
67
|
+
if (!this.degraded) {
|
|
68
|
+
this.degraded = true;
|
|
69
|
+
this.logger.error(
|
|
70
|
+
`Rate limit counters unavailable in ${this.storeLabel}: ${(error as Error)?.message ?? error}. ` +
|
|
71
|
+
'Counting per replica in memory until it answers again.',
|
|
72
|
+
);
|
|
73
|
+
}
|
|
74
|
+
return this.fallback.increment(key, ttl, limit, blockDuration, throttlerName);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
onApplicationShutdown(): void {
|
|
79
|
+
this.fallback.onApplicationShutdown();
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** Count one hit of `key` (throttler name and client) in the shared store */
|
|
83
|
+
protected abstract incrementShared(
|
|
84
|
+
key: string,
|
|
85
|
+
ttl: number,
|
|
86
|
+
limit: number,
|
|
87
|
+
blockDuration: number,
|
|
88
|
+
): Promise<ThrottlerHit>;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* The database storage (`throttler.storage: 'database'`): the counters in the project's database through the
|
|
93
|
+
* persistence layer, so every replica counts against the same record — exact across replicas without Redis, on
|
|
94
|
+
* MongoDB and on SQL.
|
|
95
|
+
*
|
|
96
|
+
* A fixed window per throttler and client. Every step is ONE atomic statement of the store port (`updateOne` is
|
|
97
|
+
* MongoDB's `findOneAndUpdate`, on SQL one `UPDATE … RETURNING`), so two replicas never count on the strength of one
|
|
98
|
+
* read:
|
|
99
|
+
*
|
|
100
|
+
* 1. a live, unblocked window: `$inc` the hits;
|
|
101
|
+
* 2. a blocked client: answer the block without counting;
|
|
102
|
+
* 3. no record, an ended window or an ended block: start a new window — conditional on the state that was read, and
|
|
103
|
+
* an insert for a new client, whose unique `key` turns a concurrent second insert into a retry.
|
|
104
|
+
*
|
|
105
|
+
* Over the limit the record is blocked for `blockDuration`; after the block a new window begins, as in
|
|
106
|
+
* `@nestjs/throttler`'s own storage. The windows are measured with each replica's clock: replicas whose clocks differ by
|
|
107
|
+
* a few seconds end a window a few seconds apart, never count twice.
|
|
108
|
+
*/
|
|
109
|
+
export class CoreDatabaseThrottlerStorage extends CoreSharedThrottlerStorage {
|
|
110
|
+
protected readonly storeLabel = 'the database';
|
|
111
|
+
|
|
112
|
+
/** How often a step is retried when concurrent requests changed the record in between */
|
|
113
|
+
protected maxAttempts = 5;
|
|
114
|
+
|
|
115
|
+
constructor(protected readonly store: DataStore<ThrottlerCounterRecord>) {
|
|
116
|
+
super();
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
protected async incrementShared(
|
|
120
|
+
key: string,
|
|
121
|
+
ttl: number,
|
|
122
|
+
limit: number,
|
|
123
|
+
blockDuration: number,
|
|
124
|
+
): Promise<ThrottlerHit> {
|
|
125
|
+
for (let attempt = 0; attempt < this.maxAttempts; attempt++) {
|
|
126
|
+
const now = Date.now();
|
|
127
|
+
const nowDate = new Date(now);
|
|
128
|
+
|
|
129
|
+
const counted = await this.store.updateOne(
|
|
130
|
+
{ blocked: false, key, windowEndsAt: { $gt: nowDate } },
|
|
131
|
+
{ $inc: { hits: 1 } },
|
|
132
|
+
);
|
|
133
|
+
if (counted) {
|
|
134
|
+
return this.afterCount(counted, now, limit, blockDuration);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
const current = await this.store.findOne({ key });
|
|
138
|
+
if (current?.blocked && time(current.blockedUntil) > now) {
|
|
139
|
+
const remaining = time(current.blockedUntil) - now;
|
|
140
|
+
return {
|
|
141
|
+
isBlocked: true,
|
|
142
|
+
timeToBlockExpire: seconds(remaining),
|
|
143
|
+
timeToExpire: seconds(Math.max(remaining, time(current.windowEndsAt) - now)),
|
|
144
|
+
totalHits: Math.max(current.hits ?? 0, limit + 1),
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
const windowEndsAt = new Date(now + ttl);
|
|
149
|
+
const fresh = { blocked: false, blockedUntil: nowDate, expiresAt: windowEndsAt, hits: 1, windowEndsAt };
|
|
150
|
+
if (current) {
|
|
151
|
+
const renewed = await this.store.updateOne(
|
|
152
|
+
{
|
|
153
|
+
$or: [
|
|
154
|
+
{ blocked: false, windowEndsAt: { $lte: nowDate } },
|
|
155
|
+
{ blocked: true, blockedUntil: { $lte: nowDate } },
|
|
156
|
+
],
|
|
157
|
+
key,
|
|
158
|
+
},
|
|
159
|
+
{ $set: fresh },
|
|
160
|
+
);
|
|
161
|
+
if (renewed) {
|
|
162
|
+
return this.afterCount(renewed, now, limit, blockDuration);
|
|
163
|
+
}
|
|
164
|
+
continue;
|
|
165
|
+
}
|
|
166
|
+
try {
|
|
167
|
+
return await this.afterCount(await this.store.insert({ key, ...fresh }), now, limit, blockDuration);
|
|
168
|
+
} catch (error) {
|
|
169
|
+
if ((error as { code?: unknown })?.code !== 11000) {
|
|
170
|
+
throw error;
|
|
171
|
+
}
|
|
172
|
+
// Another replica created the record in between: count against it
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
throw new Error(`the counter ${key} kept changing under concurrent requests`);
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** The answer for a counted hit — and the block, when the hit went over the limit */
|
|
179
|
+
protected async afterCount(
|
|
180
|
+
record: StoredRecord<ThrottlerCounterRecord>,
|
|
181
|
+
now: number,
|
|
182
|
+
limit: number,
|
|
183
|
+
blockDuration: number,
|
|
184
|
+
): Promise<ThrottlerHit> {
|
|
185
|
+
const windowLeft = time(record.windowEndsAt) - now;
|
|
186
|
+
const hit: ThrottlerHit = {
|
|
187
|
+
isBlocked: false,
|
|
188
|
+
timeToBlockExpire: 0,
|
|
189
|
+
timeToExpire: seconds(windowLeft),
|
|
190
|
+
totalHits: record.hits,
|
|
191
|
+
};
|
|
192
|
+
if (record.hits <= limit) {
|
|
193
|
+
return hit;
|
|
194
|
+
}
|
|
195
|
+
if (blockDuration <= 0) {
|
|
196
|
+
// No block: refused until the window ends
|
|
197
|
+
return { ...hit, isBlocked: true, timeToBlockExpire: hit.timeToExpire };
|
|
198
|
+
}
|
|
199
|
+
const blockedUntil = new Date(now + blockDuration);
|
|
200
|
+
await this.store.updateOne(
|
|
201
|
+
{ blocked: false, key: record.key },
|
|
202
|
+
{
|
|
203
|
+
$set: {
|
|
204
|
+
blocked: true,
|
|
205
|
+
blockedUntil,
|
|
206
|
+
expiresAt: new Date(Math.max(time(record.windowEndsAt), blockedUntil.getTime())),
|
|
207
|
+
},
|
|
208
|
+
},
|
|
209
|
+
);
|
|
210
|
+
return { ...hit, isBlocked: true, timeToBlockExpire: seconds(blockDuration) };
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/**
|
|
215
|
+
* Atomic hit with block, in one round trip. Fixed window, the semantics of the database storage.
|
|
216
|
+
*
|
|
217
|
+
* ```
|
|
218
|
+
* KEYS[1] hits of the current window KEYS[2] block marker
|
|
219
|
+
* ARGV[1] window (ms) ARGV[2] limit ARGV[3] block duration (ms)
|
|
220
|
+
* ```
|
|
221
|
+
*
|
|
222
|
+
* Returns `[totalHits, windowMs, blocked, blockMs]`.
|
|
223
|
+
*/
|
|
224
|
+
const THROTTLER_HIT_SCRIPT = `
|
|
225
|
+
local ttl = tonumber(ARGV[1])
|
|
226
|
+
local limit = tonumber(ARGV[2])
|
|
227
|
+
local block = tonumber(ARGV[3])
|
|
228
|
+
local blockTtl = redis.call('PTTL', KEYS[2])
|
|
229
|
+
if blockTtl > 0 then
|
|
230
|
+
return {limit + 1, blockTtl, 1, blockTtl}
|
|
231
|
+
end
|
|
232
|
+
local hits = redis.call('INCR', KEYS[1])
|
|
233
|
+
local windowTtl = redis.call('PTTL', KEYS[1])
|
|
234
|
+
if hits == 1 or windowTtl < 0 then
|
|
235
|
+
redis.call('PEXPIRE', KEYS[1], ttl)
|
|
236
|
+
windowTtl = ttl
|
|
237
|
+
end
|
|
238
|
+
if hits > limit then
|
|
239
|
+
if block > 0 then
|
|
240
|
+
redis.call('SET', KEYS[2], '1', 'PX', block)
|
|
241
|
+
redis.call('DEL', KEYS[1])
|
|
242
|
+
return {hits, windowTtl, 1, block}
|
|
243
|
+
end
|
|
244
|
+
return {hits, windowTtl, 1, windowTtl}
|
|
245
|
+
end
|
|
246
|
+
return {hits, windowTtl, 0, 0}
|
|
247
|
+
`;
|
|
248
|
+
|
|
249
|
+
/** Name the script is registered under via ioredis `defineCommand` */
|
|
250
|
+
const THROTTLER_HIT_COMMAND = 'ltThrottlerHit';
|
|
251
|
+
|
|
252
|
+
/**
|
|
253
|
+
* The Redis storage (`throttler.storage: 'redis'`, the default when `redis` is configured): the counters in the
|
|
254
|
+
* shared Redis under `<keyPrefix>:throttler:…`, exact across replicas. Every key carries its window or block as TTL,
|
|
255
|
+
* so there is nothing to clean up.
|
|
256
|
+
*/
|
|
257
|
+
export class CoreRedisThrottlerStorage extends CoreSharedThrottlerStorage {
|
|
258
|
+
protected readonly storeLabel = 'Redis';
|
|
259
|
+
|
|
260
|
+
/** Clients the script is registered on (`defineCommand` is per connection) */
|
|
261
|
+
protected readonly prepared = new WeakSet<object>();
|
|
262
|
+
|
|
263
|
+
constructor(protected readonly redisService: CoreRedisService) {
|
|
264
|
+
super();
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
protected async incrementShared(
|
|
268
|
+
key: string,
|
|
269
|
+
ttl: number,
|
|
270
|
+
limit: number,
|
|
271
|
+
blockDuration: number,
|
|
272
|
+
): Promise<ThrottlerHit> {
|
|
273
|
+
const client = this.redisService.getClient() as any;
|
|
274
|
+
const args = [
|
|
275
|
+
this.redisService.key('throttler', key),
|
|
276
|
+
this.redisService.key('throttler', key, 'block'),
|
|
277
|
+
Math.max(1, Math.ceil(ttl)),
|
|
278
|
+
limit,
|
|
279
|
+
Math.max(0, Math.ceil(blockDuration)),
|
|
280
|
+
];
|
|
281
|
+
let result: [number, number, number, number];
|
|
282
|
+
if (typeof client.defineCommand === 'function') {
|
|
283
|
+
if (!this.prepared.has(client)) {
|
|
284
|
+
client.defineCommand(THROTTLER_HIT_COMMAND, { lua: THROTTLER_HIT_SCRIPT, numberOfKeys: 2 });
|
|
285
|
+
this.prepared.add(client);
|
|
286
|
+
}
|
|
287
|
+
result = await client[THROTTLER_HIT_COMMAND](...args);
|
|
288
|
+
} else {
|
|
289
|
+
result = await client.eval(THROTTLER_HIT_SCRIPT, 2, ...args);
|
|
290
|
+
}
|
|
291
|
+
const [totalHits, windowMs, blocked, blockMs] = result.map(Number);
|
|
292
|
+
return {
|
|
293
|
+
isBlocked: blocked === 1,
|
|
294
|
+
timeToBlockExpire: blocked === 1 ? seconds(blockMs) : 0,
|
|
295
|
+
timeToExpire: seconds(windowMs),
|
|
296
|
+
totalHits,
|
|
297
|
+
};
|
|
298
|
+
}
|
|
299
|
+
}
|
|
@@ -147,7 +147,8 @@ export abstract class CoreUserService<
|
|
|
147
147
|
// Distinguish between different error messages when saving
|
|
148
148
|
try {
|
|
149
149
|
if (!createdUser) {
|
|
150
|
-
|
|
150
|
+
// The audit log (`auditLog`) sees the write CrudService.create() would report — field names only
|
|
151
|
+
return await this.auditCreated(await this.dataStore.insert(fields), data.input, serviceOptions);
|
|
151
152
|
}
|
|
152
153
|
await createdUser.save();
|
|
153
154
|
} catch (error) {
|
|
@@ -159,7 +160,7 @@ export abstract class CoreUserService<
|
|
|
159
160
|
}
|
|
160
161
|
|
|
161
162
|
// Return created user
|
|
162
|
-
return createdUser;
|
|
163
|
+
return this.auditCreated(createdUser, data.input, serviceOptions);
|
|
163
164
|
},
|
|
164
165
|
{ input, serviceOptions },
|
|
165
166
|
);
|
package/src/core.module.ts
CHANGED
|
@@ -72,6 +72,7 @@ import { MailjetService } from './core/common/services/mailjet.service.js';
|
|
|
72
72
|
import { ModelDocService } from './core/common/services/model-doc.service.js';
|
|
73
73
|
import { TemplateService } from './core/common/services/template.service.js';
|
|
74
74
|
import { CoreAiModule } from './core/modules/ai/core-ai.module.js';
|
|
75
|
+
import { CoreAuditLogModule } from './core/modules/audit-log/core-audit-log.module.js';
|
|
75
76
|
import { isLegacyJwt } from './core/modules/better-auth/core-better-auth-token.helper.js';
|
|
76
77
|
import { CoreBetterAuthUserMapper } from './core/modules/better-auth/core-better-auth-user.mapper.js';
|
|
77
78
|
import { CoreBetterAuthModule } from './core/modules/better-auth/core-better-auth.module.js';
|
|
@@ -83,11 +84,14 @@ import { applyFileRoles, warnOnPresignedDownloadsWithRestrictedRoles } from './c
|
|
|
83
84
|
import { CoreHealthCheckModule } from './core/modules/health-check/core-health-check.module.js';
|
|
84
85
|
import { CoreHubModule } from './core/modules/hub/core-hub.module.js';
|
|
85
86
|
import { isHubEnabled, isHubQueriesEnabled } from './core/modules/hub/hub-config.helper.js';
|
|
87
|
+
import { CoreMailOutboxModule } from './core/modules/mail-outbox/core-mail-outbox.module.js';
|
|
86
88
|
import { CorePermissionsModule } from './core/modules/permissions/core-permissions.module.js';
|
|
87
89
|
import { CoreSystemSetupModule } from './core/modules/system-setup/core-system-setup.module.js';
|
|
88
90
|
import { CoreApiTokenModule } from './core/modules/api-token/core-api-token.module.js';
|
|
89
91
|
import { CoreSyncModule } from './core/modules/sync/core-sync.module.js';
|
|
90
92
|
import { CoreTenantModule } from './core/modules/tenant/core-tenant.module.js';
|
|
93
|
+
import { resolveThrottlerConfig } from './core/modules/throttler/core-throttler.config.js';
|
|
94
|
+
import { CoreThrottlerModule } from './core/modules/throttler/core-throttler.module.js';
|
|
91
95
|
|
|
92
96
|
/** Configuration warnings of `forRoot()`, through Nest's logger so log levels and a project's logger apply. */
|
|
93
97
|
const coreModuleLogger = new Logger('CoreModule');
|
|
@@ -355,6 +359,10 @@ export class CoreModule implements NestModule {
|
|
|
355
359
|
// combination has legitimate uses, it just should not be reached by accident.
|
|
356
360
|
warnOnPresignedDownloadsWithRestrictedRoles(config.s3, config.file);
|
|
357
361
|
|
|
362
|
+
// Rate limit for a project's routes (`throttler`, presence implies enabled). Resolved here so an explicit storage that
|
|
363
|
+
// cannot work stops the boot before anything connects.
|
|
364
|
+
const throttlerConfig = resolveThrottlerConfig(config);
|
|
365
|
+
|
|
358
366
|
// Check secrets
|
|
359
367
|
const jwtConfig = config.jwt;
|
|
360
368
|
if (jwtConfig?.secret && jwtConfig.secret && jwtConfig.refresh && jwtConfig.refresh.secret === jwtConfig.secret) {
|
|
@@ -487,6 +495,12 @@ export class CoreModule implements NestModule {
|
|
|
487
495
|
CorePersistenceModule.forFeature(FILE_METADATA_MODELS),
|
|
488
496
|
];
|
|
489
497
|
|
|
498
|
+
// The rate limit guard comes FIRST: global guards run in the order their modules are registered, and an over-limit
|
|
499
|
+
// client must be refused before authentication runs (also on a route that would answer it with 401)
|
|
500
|
+
if (throttlerConfig) {
|
|
501
|
+
imports.unshift(CoreThrottlerModule.forRoot({ config: throttlerConfig, guard: overrides?.throttler?.guard }));
|
|
502
|
+
}
|
|
503
|
+
|
|
490
504
|
if (isGraphQlEnabled && config.graphQl) {
|
|
491
505
|
imports.push(
|
|
492
506
|
GraphQLModule.forRootAsync<ApolloDriverConfig>(
|
|
@@ -718,6 +732,38 @@ export class CoreModule implements NestModule {
|
|
|
718
732
|
);
|
|
719
733
|
}
|
|
720
734
|
|
|
735
|
+
// Add CoreAuditLogModule when auditLog is configured (boolean shorthand, presence implies enabled). Without it there
|
|
736
|
+
// is no model, no route and no listener CrudService reports its writes to.
|
|
737
|
+
const auditLogConfig = config.auditLog;
|
|
738
|
+
if (
|
|
739
|
+
auditLogConfig === true ||
|
|
740
|
+
(typeof auditLogConfig === 'object' && auditLogConfig !== null && auditLogConfig.enabled !== false)
|
|
741
|
+
) {
|
|
742
|
+
imports.push(
|
|
743
|
+
CoreAuditLogModule.forRoot({
|
|
744
|
+
...overrides?.auditLog,
|
|
745
|
+
path: typeof auditLogConfig === 'object' ? auditLogConfig.path : undefined,
|
|
746
|
+
roles: typeof auditLogConfig === 'object' ? auditLogConfig.roles : undefined,
|
|
747
|
+
}),
|
|
748
|
+
);
|
|
749
|
+
}
|
|
750
|
+
|
|
751
|
+
// Add CoreMailOutboxModule when mailOutbox is configured (boolean shorthand, presence implies enabled). Without it
|
|
752
|
+
// EmailService sends directly, as before.
|
|
753
|
+
const mailOutboxConfig = config.mailOutbox;
|
|
754
|
+
if (
|
|
755
|
+
mailOutboxConfig === true ||
|
|
756
|
+
(typeof mailOutboxConfig === 'object' && mailOutboxConfig !== null && mailOutboxConfig.enabled !== false)
|
|
757
|
+
) {
|
|
758
|
+
imports.push(
|
|
759
|
+
CoreMailOutboxModule.forRoot({
|
|
760
|
+
...overrides?.mailOutbox,
|
|
761
|
+
path: typeof mailOutboxConfig === 'object' ? mailOutboxConfig.path : undefined,
|
|
762
|
+
roles: typeof mailOutboxConfig === 'object' ? mailOutboxConfig.roles : undefined,
|
|
763
|
+
}),
|
|
764
|
+
);
|
|
765
|
+
}
|
|
766
|
+
|
|
721
767
|
// Set exports
|
|
722
768
|
const exports: any[] = [
|
|
723
769
|
ConfigService,
|
package/src/index.ts
CHANGED
|
@@ -143,6 +143,7 @@ export * from './core/common/services/core-tenant-context.registry.js';
|
|
|
143
143
|
export * from './core/common/services/rate-limit-store.js';
|
|
144
144
|
export * from './core/common/services/crud.service.js';
|
|
145
145
|
export * from './core/common/services/email.service.js';
|
|
146
|
+
export * from './core/common/services/leased-interval.js';
|
|
146
147
|
export * from './core/common/services/mailjet.service.js';
|
|
147
148
|
export * from './core/common/services/model-doc.service.js';
|
|
148
149
|
export * from './core/common/services/model-registry.service.js';
|
|
@@ -180,6 +181,18 @@ export * from './core/modules/api-token/core-api-token.model.js';
|
|
|
180
181
|
export * from './core/modules/api-token/core-api-token.module.js';
|
|
181
182
|
export * from './core/modules/api-token/core-api-token.service.js';
|
|
182
183
|
|
|
184
|
+
// =====================================================================================================================
|
|
185
|
+
// Core - Modules - Audit log
|
|
186
|
+
// =====================================================================================================================
|
|
187
|
+
|
|
188
|
+
export * from './core/common/persistence/audit-log.registry.js';
|
|
189
|
+
export * from './core/modules/audit-log/audited.decorator.js';
|
|
190
|
+
export * from './core/modules/audit-log/core-audit-log.constants.js';
|
|
191
|
+
export * from './core/modules/audit-log/core-audit-log.controller.js';
|
|
192
|
+
export * from './core/modules/audit-log/core-audit-log.models.js';
|
|
193
|
+
export * from './core/modules/audit-log/core-audit-log.module.js';
|
|
194
|
+
export * from './core/modules/audit-log/core-audit-log.service.js';
|
|
195
|
+
|
|
183
196
|
// =====================================================================================================================
|
|
184
197
|
// Core - Modules - Auth
|
|
185
198
|
// =====================================================================================================================
|
|
@@ -266,6 +279,17 @@ export * from './core/modules/health-check/core-health-check.service.js';
|
|
|
266
279
|
|
|
267
280
|
export * from './core/modules/hub/index.js';
|
|
268
281
|
|
|
282
|
+
// =====================================================================================================================
|
|
283
|
+
// Core - Modules - Mail outbox
|
|
284
|
+
// =====================================================================================================================
|
|
285
|
+
|
|
286
|
+
export * from './core/common/services/mail-outbox.registry.js';
|
|
287
|
+
export * from './core/modules/mail-outbox/core-mail-outbox.constants.js';
|
|
288
|
+
export * from './core/modules/mail-outbox/core-mail-outbox.controller.js';
|
|
289
|
+
export * from './core/modules/mail-outbox/core-mail-outbox.models.js';
|
|
290
|
+
export * from './core/modules/mail-outbox/core-mail-outbox.module.js';
|
|
291
|
+
export * from './core/modules/mail-outbox/core-mail-outbox.service.js';
|
|
292
|
+
|
|
269
293
|
// =====================================================================================================================
|
|
270
294
|
// Core - Modules - Migrate
|
|
271
295
|
// =====================================================================================================================
|
|
@@ -310,6 +334,18 @@ export * from './core/modules/sync/core-sync-state.store.js';
|
|
|
310
334
|
export * from './core/modules/sync/interfaces/core-sync.interfaces.js';
|
|
311
335
|
export * from './core/modules/sync/models/core-sync-hint.model.js';
|
|
312
336
|
|
|
337
|
+
// =====================================================================================================================
|
|
338
|
+
// Core - Modules - Throttler (rate limit for a project's routes)
|
|
339
|
+
// =====================================================================================================================
|
|
340
|
+
|
|
341
|
+
export * from './core/modules/throttler/core-throttler.config.js';
|
|
342
|
+
export * from './core/modules/throttler/core-throttler.constants.js';
|
|
343
|
+
export * from './core/modules/throttler/core-throttler.decorators.js';
|
|
344
|
+
export * from './core/modules/throttler/core-throttler.guard.js';
|
|
345
|
+
export * from './core/modules/throttler/core-throttler.models.js';
|
|
346
|
+
export * from './core/modules/throttler/core-throttler.module.js';
|
|
347
|
+
export * from './core/modules/throttler/core-throttler.storages.js';
|
|
348
|
+
|
|
313
349
|
// =====================================================================================================================
|
|
314
350
|
// Core - Modules - Tus
|
|
315
351
|
// =====================================================================================================================
|