@lenne.tech/nest-server 12.11.2 → 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.
Files changed (137) hide show
  1. package/.claude/rules/architecture.md +3 -0
  2. package/.claude/rules/configurable-features.md +6 -0
  3. package/.claude/rules/package-management.md +6 -4
  4. package/.claude/rules/role-system.md +8 -0
  5. package/.claude/rules/testing.md +8 -7
  6. package/CLAUDE.md +2 -1
  7. package/FRAMEWORK-API.md +15 -1
  8. package/dist/core/common/decorators/common-error.decorator.d.ts +1 -1
  9. package/dist/core/common/interfaces/server-options.interface.d.ts +54 -0
  10. package/dist/core/common/persistence/audit-log.registry.d.ts +19 -0
  11. package/dist/core/common/persistence/audit-log.registry.js +84 -0
  12. package/dist/core/common/persistence/audit-log.registry.js.map +1 -0
  13. package/dist/core/common/persistence/policies/tenant.policy.js +3 -1
  14. package/dist/core/common/persistence/policies/tenant.policy.js.map +1 -1
  15. package/dist/core/common/services/core-trust-proxy.initializer.js +1 -1
  16. package/dist/core/common/services/core-trust-proxy.initializer.js.map +1 -1
  17. package/dist/core/common/services/crud.service.d.ts +10 -0
  18. package/dist/core/common/services/crud.service.js +79 -24
  19. package/dist/core/common/services/crud.service.js.map +1 -1
  20. package/dist/core/common/services/email.service.d.ts +5 -0
  21. package/dist/core/common/services/email.service.js +82 -6
  22. package/dist/core/common/services/email.service.js.map +1 -1
  23. package/dist/core/common/services/leased-interval.d.ts +22 -0
  24. package/dist/core/common/services/leased-interval.js +81 -0
  25. package/dist/core/common/services/leased-interval.js.map +1 -0
  26. package/dist/core/common/services/mail-outbox.registry.d.ts +26 -0
  27. package/dist/core/common/services/mail-outbox.registry.js +8 -0
  28. package/dist/core/common/services/mail-outbox.registry.js.map +1 -0
  29. package/dist/core/modules/audit-log/audited.decorator.d.ts +2 -0
  30. package/dist/core/modules/audit-log/audited.decorator.js +10 -0
  31. package/dist/core/modules/audit-log/audited.decorator.js.map +1 -0
  32. package/dist/core/modules/audit-log/core-audit-log.constants.d.ts +13 -0
  33. package/dist/core/modules/audit-log/core-audit-log.constants.js +11 -0
  34. package/dist/core/modules/audit-log/core-audit-log.constants.js.map +1 -0
  35. package/dist/core/modules/audit-log/core-audit-log.controller.d.ts +9 -0
  36. package/dist/core/modules/audit-log/core-audit-log.controller.js +87 -0
  37. package/dist/core/modules/audit-log/core-audit-log.controller.js.map +1 -0
  38. package/dist/core/modules/audit-log/core-audit-log.models.d.ts +10 -0
  39. package/dist/core/modules/audit-log/core-audit-log.models.js +11 -0
  40. package/dist/core/modules/audit-log/core-audit-log.models.js.map +1 -0
  41. package/dist/core/modules/audit-log/core-audit-log.module.d.ts +13 -0
  42. package/dist/core/modules/audit-log/core-audit-log.module.js +41 -0
  43. package/dist/core/modules/audit-log/core-audit-log.module.js.map +1 -0
  44. package/dist/core/modules/audit-log/core-audit-log.service.d.ts +49 -0
  45. package/dist/core/modules/audit-log/core-audit-log.service.js +169 -0
  46. package/dist/core/modules/audit-log/core-audit-log.service.js.map +1 -0
  47. package/dist/core/modules/better-auth/core-better-auth-email-verification.service.js +4 -0
  48. package/dist/core/modules/better-auth/core-better-auth-email-verification.service.js.map +1 -1
  49. package/dist/core/modules/mail-outbox/core-mail-outbox.constants.d.ts +22 -0
  50. package/dist/core/modules/mail-outbox/core-mail-outbox.constants.js +23 -0
  51. package/dist/core/modules/mail-outbox/core-mail-outbox.constants.js.map +1 -0
  52. package/dist/core/modules/mail-outbox/core-mail-outbox.controller.d.ts +10 -0
  53. package/dist/core/modules/mail-outbox/core-mail-outbox.controller.js +80 -0
  54. package/dist/core/modules/mail-outbox/core-mail-outbox.controller.js.map +1 -0
  55. package/dist/core/modules/mail-outbox/core-mail-outbox.models.d.ts +17 -0
  56. package/dist/core/modules/mail-outbox/core-mail-outbox.models.js +17 -0
  57. package/dist/core/modules/mail-outbox/core-mail-outbox.models.js.map +1 -0
  58. package/dist/core/modules/mail-outbox/core-mail-outbox.module.d.ts +12 -0
  59. package/dist/core/modules/mail-outbox/core-mail-outbox.module.js +42 -0
  60. package/dist/core/modules/mail-outbox/core-mail-outbox.module.js.map +1 -0
  61. package/dist/core/modules/mail-outbox/core-mail-outbox.service.d.ts +59 -0
  62. package/dist/core/modules/mail-outbox/core-mail-outbox.service.js +280 -0
  63. package/dist/core/modules/mail-outbox/core-mail-outbox.service.js.map +1 -0
  64. package/dist/core/modules/migrate/cli/migrate-cli.js +20 -2
  65. package/dist/core/modules/migrate/cli/migrate-cli.js.map +1 -1
  66. package/dist/core/modules/throttler/core-throttler.config.d.ts +16 -0
  67. package/dist/core/modules/throttler/core-throttler.config.js +107 -0
  68. package/dist/core/modules/throttler/core-throttler.config.js.map +1 -0
  69. package/dist/core/modules/throttler/core-throttler.constants.d.ts +10 -0
  70. package/dist/core/modules/throttler/core-throttler.constants.js +11 -0
  71. package/dist/core/modules/throttler/core-throttler.constants.js.map +1 -0
  72. package/dist/core/modules/throttler/core-throttler.decorators.d.ts +1 -0
  73. package/dist/core/modules/throttler/core-throttler.decorators.js +2 -0
  74. package/dist/core/modules/throttler/core-throttler.decorators.js.map +1 -0
  75. package/dist/core/modules/throttler/core-throttler.guard.d.ts +15 -0
  76. package/dist/core/modules/throttler/core-throttler.guard.js +65 -0
  77. package/dist/core/modules/throttler/core-throttler.guard.js.map +1 -0
  78. package/dist/core/modules/throttler/core-throttler.models.d.ts +1 -0
  79. package/dist/core/modules/throttler/core-throttler.models.js +11 -0
  80. package/dist/core/modules/throttler/core-throttler.models.js.map +1 -0
  81. package/dist/core/modules/throttler/core-throttler.module.d.ts +12 -0
  82. package/dist/core/modules/throttler/core-throttler.module.js +71 -0
  83. package/dist/core/modules/throttler/core-throttler.module.js.map +1 -0
  84. package/dist/core/modules/throttler/core-throttler.storages.d.ts +43 -0
  85. package/dist/core/modules/throttler/core-throttler.storages.js +174 -0
  86. package/dist/core/modules/throttler/core-throttler.storages.js.map +1 -0
  87. package/dist/core/modules/user/core-user.service.js +2 -2
  88. package/dist/core/modules/user/core-user.service.js.map +1 -1
  89. package/dist/core.module.js +26 -0
  90. package/dist/core.module.js.map +1 -1
  91. package/dist/index.d.ts +21 -0
  92. package/dist/index.js +21 -0
  93. package/dist/index.js.map +1 -1
  94. package/docs/REQUEST-LIFECYCLE.md +10 -3
  95. package/docs/security-overrides.md +20 -8
  96. package/migration-guides/12.11.2-to-12.11.3.md +96 -0
  97. package/migration-guides/12.11.x-to-12.12.x.md +182 -0
  98. package/package.json +28 -27
  99. package/src/core/common/interfaces/server-options.interface.ts +311 -1
  100. package/src/core/common/persistence/audit-log.registry.ts +150 -0
  101. package/src/core/common/persistence/policies/tenant.policy.ts +10 -5
  102. package/src/core/common/services/core-trust-proxy.initializer.ts +5 -4
  103. package/src/core/common/services/crud.service.ts +128 -33
  104. package/src/core/common/services/email.service.ts +101 -9
  105. package/src/core/common/services/leased-interval.ts +123 -0
  106. package/src/core/common/services/mail-outbox.registry.ts +53 -0
  107. package/src/core/modules/audit-log/README.md +95 -0
  108. package/src/core/modules/audit-log/audited.decorator.ts +27 -0
  109. package/src/core/modules/audit-log/core-audit-log.constants.ts +28 -0
  110. package/src/core/modules/audit-log/core-audit-log.controller.ts +77 -0
  111. package/src/core/modules/audit-log/core-audit-log.models.ts +34 -0
  112. package/src/core/modules/audit-log/core-audit-log.module.ts +54 -0
  113. package/src/core/modules/audit-log/core-audit-log.service.ts +270 -0
  114. package/src/core/modules/better-auth/README.md +18 -0
  115. package/src/core/modules/better-auth/core-better-auth-email-verification.service.ts +4 -0
  116. package/src/core/modules/mail-outbox/README.md +88 -0
  117. package/src/core/modules/mail-outbox/core-mail-outbox.constants.ts +42 -0
  118. package/src/core/modules/mail-outbox/core-mail-outbox.controller.ts +60 -0
  119. package/src/core/modules/mail-outbox/core-mail-outbox.models.ts +46 -0
  120. package/src/core/modules/mail-outbox/core-mail-outbox.module.ts +52 -0
  121. package/src/core/modules/mail-outbox/core-mail-outbox.service.ts +390 -0
  122. package/src/core/modules/migrate/README.md +4 -1
  123. package/src/core/modules/migrate/cli/migrate-cli.ts +30 -2
  124. package/src/core/modules/system-setup/README.md +4 -0
  125. package/src/core/modules/tenant/INTEGRATION-CHECKLIST.md +3 -3
  126. package/src/core/modules/tenant/README.md +4 -4
  127. package/src/core/modules/throttler/README.md +107 -0
  128. package/src/core/modules/throttler/core-throttler.config.ts +162 -0
  129. package/src/core/modules/throttler/core-throttler.constants.ts +33 -0
  130. package/src/core/modules/throttler/core-throttler.decorators.ts +14 -0
  131. package/src/core/modules/throttler/core-throttler.guard.ts +109 -0
  132. package/src/core/modules/throttler/core-throttler.models.ts +23 -0
  133. package/src/core/modules/throttler/core-throttler.module.ts +95 -0
  134. package/src/core/modules/throttler/core-throttler.storages.ts +299 -0
  135. package/src/core/modules/user/core-user.service.ts +3 -2
  136. package/src/core.module.ts +46 -0
  137. package/src/index.ts +36 -0
@@ -0,0 +1,107 @@
1
+ # Throttler (rate limit for a project's routes)
2
+
3
+ Protects a project's own routes — a contact form, an application form, any public endpoint — against abuse, on top
4
+ of [`@nestjs/throttler`](https://github.com/nestjs/throttler). Over the limit a route answers **429** with
5
+ `Retry-After` and `#LTNS_0020: Too many requests`.
6
+
7
+ The framework's own sign-in routes have their own limits (`auth.rateLimit`, `betterAuth.rateLimit`); this module is
8
+ for the routes a project writes.
9
+
10
+ ## Switching it on
11
+
12
+ ```typescript
13
+ // config.env.ts
14
+ throttler: {}, // defaults: memory (Redis when `redis` is configured)
15
+ throttler: { storage: 'database' }, // counters in the project's database, exact across replicas
16
+ trustProxy: 1, // REQUIRED behind a reverse proxy — see below
17
+ ```
18
+
19
+ ```typescript
20
+ import { SkipThrottle, Throttle } from '@lenne.tech/nest-server';
21
+
22
+ @Controller('contact')
23
+ export class ContactController {
24
+ @Post()
25
+ @Roles(RoleEnum.S_EVERYONE)
26
+ @Throttle({ default: { limit: 5, ttl: 60_000 } }) // 5 requests per minute and client
27
+ async send(@Body() input: ContactInput) { … }
28
+ }
29
+ ```
30
+
31
+ Absent `throttler`: no guard, no storage, no table — nothing changes. `{ enabled: false }` pre-configures.
32
+
33
+ Import the decorators from `@lenne.tech/nest-server` (re-exported): in a pnpm project a package that is only a
34
+ dependency of the framework cannot be imported directly, and the re-export guarantees the metadata reaches the copy
35
+ the guard reads. Do **not** import `ThrottlerModule` yourself — `CoreModule` provides its tokens.
36
+
37
+ ## Which routes are limited
38
+
39
+ | `routes` | Limited |
40
+ | ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
41
+ | `'decorated'` (default) | only routes whose method or controller carries `@Throttle()`, by the throttlers it names. `@Throttle({ default: {} })` uses the configured limit |
42
+ | `'all'` | every HTTP route and GraphQL operation by every throttler, unless `@SkipThrottle()` exempts it — the behaviour of a plain `ThrottlerModule` |
43
+
44
+ `'decorated'` is the default because a global per-IP limit throttles every user behind one NAT (an office, a school)
45
+ on every route the moment the feature is switched on.
46
+
47
+ ## Storages
48
+
49
+ | `storage` | Where | Across replicas |
50
+ | ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------ |
51
+ | `'memory'` (default without Redis) | `@nestjs/throttler`'s in-process storage | each replica counts for itself |
52
+ | `'redis'` (default with `redis`) | the shared Redis, `<keyPrefix>:throttler:…`, keys expire with their window | exact |
53
+ | `'database'` | the framework model `CoreThrottlerCounter` (collection `throttlerCounters`, table `throttler_counters`), following `database` like every model — MongoDB, PostgreSQL, MySQL, MariaDB | exact, without Redis |
54
+
55
+ An explicitly chosen storage that cannot work (`'redis'` without `redis`, `'database'` with `database: false`, an
56
+ unknown name) **stops the boot**. While Redis or the database cannot be reached, the counters fall back to memory
57
+ (logged once per transition) — never to "no limit", never to a 500.
58
+
59
+ The database and Redis storages count a fixed window per throttler and client with ONE atomic statement per step;
60
+ over the limit the client is blocked for `blockDuration` (default: the `ttl`), then a new window begins. The memory
61
+ storage is `@nestjs/throttler`'s own (a sliding window). Expired counter rows are reclaimed by MongoDB's TTL index and
62
+ the SQL expiry sweep; nothing relies on them for correctness.
63
+
64
+ ## Counted per client IP — `trustProxy` matters
65
+
66
+ The tracker is `request.ip`, which Express derives from `X-Forwarded-For` only as far as `trustProxy` allows. Behind
67
+ Caddy, nginx or an ingress without `trustProxy`, every request arrives from the proxy and **all clients share one
68
+ bucket** — the boot warns about exactly that. Trusting more hops than exist lets a client pick a fresh bucket per
69
+ request. IPv6 addresses are counted by their /64 (`ipv6SubnetPrefix`).
70
+
71
+ ## Order with the role guards
72
+
73
+ The rate limit guard is registered as the **first** global guard, so an over-limit client is refused before
74
+ authentication runs — a brute force against a protected route gets 429, not an endless series of 401. It resolves the
75
+ request like the role guards (`resolveGuardRequest()`), so GraphQL operations are limited too, over HTTP and over the
76
+ WebSocket. Every request is counted, also one that carries no address: a GraphQL operation over the WebSocket per
77
+ signed-in user (else by the address of the upgrade request), an HTTP request whose client already closed the connection
78
+ — Node forgets the address with the socket — per user, else in one shared bucket. Only a call without any request (a
79
+ request-less agent call) is not counted; subscription events run no guards.
80
+
81
+ ## Configuration
82
+
83
+ | Key | Default | Meaning |
84
+ | ------------------ | --------------------------------------- | ----------------------------------------------------------------------------------- |
85
+ | `limit` | `10` | requests per window of the `default` throttler |
86
+ | `ttl` | `60000` | window in milliseconds (the unit of `@nestjs/throttler`) |
87
+ | `blockDuration` | `ttl` | how long an over-limit client stays refused (ms) |
88
+ | `throttlers` | — | named throttlers `{ name, limit, ttl, blockDuration }`, replacing the `default` one |
89
+ | `routes` | `'decorated'` | see above |
90
+ | `storage` | `'redis'` with `redis`, else `'memory'` | see above |
91
+ | `setHeaders` | `true` | `X-RateLimit-Limit` / `-Remaining` / `-Reset` |
92
+ | `errorMessage` | `ErrorCode.RATE_LIMIT_EXCEEDED` | message of the 429 |
93
+ | `ipv6SubnetPrefix` | `64` | prefix an IPv6 client is counted by |
94
+ | `ignoreUserAgents` | — | `RegExp[]` never limited (`config.env.ts` only) |
95
+
96
+ An invalid number (not positive) falls back to its default with a warning — never to "no limit".
97
+
98
+ ## Extending
99
+
100
+ Override the guard with `CoreModule.forRoot(env, { throttler: { guard: MyThrottlerGuard } })`, where
101
+ `MyThrottlerGuard extends CoreThrottlerGuard` — e.g. `getTracker()` to count a signed-in user by id.
102
+
103
+ ## Tests
104
+
105
+ - `tests/unit/throttler.spec.ts` — configuration, the guard on a real Express app, the database storage's state machine
106
+ - `tests/throttler.e2e-spec.ts` — every storage on the assembled stack, MongoDB and PostgreSQL, two replicas sharing a
107
+ store
@@ -0,0 +1,162 @@
1
+ import { Logger } from '@nestjs/common';
2
+
3
+ import type { IServerOptions, IThrottler, IThrottlerLimit } from '../../common/interfaces/server-options.interface.js';
4
+ import { ErrorCode } from '../error-code/error-codes.js';
5
+ import { THROTTLER_DEFAULTS, THROTTLER_STORAGE_KINDS } from './core-throttler.constants.js';
6
+
7
+ const logger = new Logger('CoreThrottler');
8
+
9
+ /** Where the counters live */
10
+ export type ThrottlerStorageKind = (typeof THROTTLER_STORAGE_KINDS)[number];
11
+
12
+ /** `throttler` with every default applied — what `CoreThrottlerModule` registers */
13
+ export interface ResolvedThrottlerConfig {
14
+ errorMessage: string;
15
+ ignoreUserAgents?: RegExp[];
16
+ ipv6SubnetPrefix?: number;
17
+ routes: 'all' | 'decorated';
18
+ setHeaders: boolean;
19
+ storage: ThrottlerStorageKind;
20
+ throttlers: Array<Required<Pick<IThrottlerLimit, 'limit' | 'name' | 'ttl'>> & Pick<IThrottlerLimit, 'blockDuration'>>;
21
+ }
22
+
23
+ /**
24
+ * Whether `throttler` switches the rate limit on: `true`, or an object without `enabled: false` (presence implies
25
+ * enabled). Absent, `null`, `false` and `{ enabled: false }` leave everything as it was.
26
+ */
27
+ export function isThrottlerEnabled(config: IServerOptions['throttler']): boolean {
28
+ if (config === undefined || config === null || config === false) {
29
+ return false;
30
+ }
31
+ return config === true || (typeof config === 'object' && config.enabled !== false);
32
+ }
33
+
34
+ /** Whether `redis` is configured and enabled — the rule `CoreRedisService` applies */
35
+ export function isRedisConfigured(redis: IServerOptions['redis']): boolean {
36
+ if (redis === undefined || redis === null || redis === false) {
37
+ return false;
38
+ }
39
+ return redis === true || (typeof redis === 'object' && redis.enabled !== false);
40
+ }
41
+
42
+ /** A positive finite number, or `undefined` */
43
+ function positive(value: unknown): number | undefined {
44
+ const number = typeof value === 'string' && value.trim() !== '' ? Number(value) : value;
45
+ return typeof number === 'number' && Number.isFinite(number) && number > 0 ? number : undefined;
46
+ }
47
+
48
+ /**
49
+ * A number of `throttler` that must be positive: an invalid value falls back to the default with a warning. Never to
50
+ * "no limit" — a typo in an environment variable must not switch the protection off — and never to `0`, which
51
+ * `@nestjs/throttler` would read as "refuse every request".
52
+ */
53
+ function positiveOrDefault(value: unknown, fallback: number, label: string): number {
54
+ if (value === undefined || value === null) {
55
+ return fallback;
56
+ }
57
+ const number = positive(value);
58
+ if (number === undefined) {
59
+ logger.warn(`${label} must be a positive number, got ${JSON.stringify(value)} — using ${fallback}`);
60
+ return fallback;
61
+ }
62
+ return number;
63
+ }
64
+
65
+ /**
66
+ * The storage the configuration asks for. Unset: Redis when `redis` is configured, memory otherwise. An explicit
67
+ * choice that cannot work stops the boot — counting in a store the operator does not believe in is worse than not
68
+ * starting (the rule of `file.storage`).
69
+ */
70
+ export function resolveThrottlerStorage(
71
+ config: IThrottler,
72
+ server: Pick<IServerOptions, 'database' | 'redis'>,
73
+ ): ThrottlerStorageKind {
74
+ const storage = config.storage;
75
+ if (storage === undefined || storage === null) {
76
+ return isRedisConfigured(server.redis) ? 'redis' : 'memory';
77
+ }
78
+ if (!THROTTLER_STORAGE_KINDS.includes(storage)) {
79
+ throw new Error(
80
+ `throttler.storage must be one of ${THROTTLER_STORAGE_KINDS.map((kind) => `'${kind}'`).join(', ')}, ` +
81
+ `got ${JSON.stringify(storage)}`,
82
+ );
83
+ }
84
+ if (storage === 'redis' && !isRedisConfigured(server.redis)) {
85
+ throw new Error("throttler.storage is 'redis', but `redis` is not configured");
86
+ }
87
+ if (storage === 'database' && server.database === false) {
88
+ throw new Error("throttler.storage is 'database', but `database` is false — the service has no database");
89
+ }
90
+ return storage;
91
+ }
92
+
93
+ /**
94
+ * `throttler` with every default applied, or `undefined` when it does not switch the rate limit on.
95
+ *
96
+ * Numbers arrive from `NSC__THROTTLER__*` too, where the reader converts only digits: an invalid one is reported and
97
+ * replaced by its default.
98
+ */
99
+ export function resolveThrottlerConfig(server: Partial<IServerOptions>): ResolvedThrottlerConfig | undefined {
100
+ if (!isThrottlerEnabled(server.throttler)) {
101
+ return undefined;
102
+ }
103
+ const config: IThrottler = typeof server.throttler === 'object' ? (server.throttler as IThrottler) : {};
104
+
105
+ const routes = config.routes === undefined || config.routes === null ? THROTTLER_DEFAULTS.routes : config.routes;
106
+ if (routes !== 'all' && routes !== 'decorated') {
107
+ throw new Error(`throttler.routes must be 'all' or 'decorated', got ${JSON.stringify(routes)}`);
108
+ }
109
+
110
+ let throttlers: ResolvedThrottlerConfig['throttlers'];
111
+ if (Array.isArray(config.throttlers) && config.throttlers.length) {
112
+ const names = new Set<string>();
113
+ throttlers = config.throttlers.map((entry, index) => {
114
+ const name = typeof entry?.name === 'string' && entry.name.trim() ? entry.name.trim() : THROTTLER_DEFAULTS.name;
115
+ if (names.has(name)) {
116
+ throw new Error(`throttler.throttlers: the name "${name}" is used twice`);
117
+ }
118
+ names.add(name);
119
+ const label = `throttler.throttlers[${index}]`;
120
+ const ttl = positiveOrDefault(entry?.ttl, THROTTLER_DEFAULTS.ttl, `${label}.ttl`);
121
+ return {
122
+ blockDuration:
123
+ entry?.blockDuration === undefined
124
+ ? undefined
125
+ : positiveOrDefault(entry.blockDuration, ttl, `${label}.blockDuration`),
126
+ limit: positiveOrDefault(entry?.limit, THROTTLER_DEFAULTS.limit, `${label}.limit`),
127
+ name,
128
+ ttl,
129
+ };
130
+ });
131
+ } else {
132
+ const ttl = positiveOrDefault(config.ttl, THROTTLER_DEFAULTS.ttl, 'throttler.ttl');
133
+ throttlers = [
134
+ {
135
+ blockDuration:
136
+ config.blockDuration === undefined
137
+ ? undefined
138
+ : positiveOrDefault(config.blockDuration, ttl, 'throttler.blockDuration'),
139
+ limit: positiveOrDefault(config.limit, THROTTLER_DEFAULTS.limit, 'throttler.limit'),
140
+ name: THROTTLER_DEFAULTS.name,
141
+ ttl,
142
+ },
143
+ ];
144
+ }
145
+
146
+ const ipv6SubnetPrefix = positive(config.ipv6SubnetPrefix);
147
+ return {
148
+ errorMessage:
149
+ typeof config.errorMessage === 'string' && config.errorMessage.trim()
150
+ ? config.errorMessage
151
+ : ErrorCode.RATE_LIMIT_EXCEEDED,
152
+ ignoreUserAgents: Array.isArray(config.ignoreUserAgents)
153
+ ? config.ignoreUserAgents.filter((pattern) => pattern instanceof RegExp)
154
+ : undefined,
155
+ ipv6SubnetPrefix:
156
+ ipv6SubnetPrefix !== undefined && ipv6SubnetPrefix <= 128 ? Math.floor(ipv6SubnetPrefix) : undefined,
157
+ routes,
158
+ setHeaders: config.setHeaders !== false,
159
+ storage: resolveThrottlerStorage(config, server),
160
+ throttlers,
161
+ };
162
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Constants of the rate limit for a project's routes (`throttler` config, DEV-4431).
3
+ *
4
+ * Import-free leaf: the module, the guard, the storages and the configuration helper read it without importing each
5
+ * other (see `.claude/rules/architecture.md` → "DI Token Placement (SWC-Safe)").
6
+ */
7
+
8
+ /** The framework model of the database storage (`throttler.storage: 'database'`) */
9
+ export const THROTTLER_COUNTER_MODEL = 'CoreThrottlerCounter';
10
+
11
+ /** Its collection on MongoDB; a SQL source keeps it as the table `throttler_counters` */
12
+ export const THROTTLER_COUNTER_COLLECTION = 'throttlerCounters';
13
+
14
+ /**
15
+ * The metadata key `@Throttle()` writes per throttler name (`THROTTLER:LIMIT` + name). `@nestjs/throttler` does not
16
+ * export its constants; `tests/unit/throttler.spec.ts` pins this value against what the decorator writes.
17
+ */
18
+ export const THROTTLER_LIMIT_METADATA = 'THROTTLER:LIMIT';
19
+
20
+ /** Defaults of `throttler` */
21
+ export const THROTTLER_DEFAULTS = {
22
+ /** Requests per window of the `default` throttler */
23
+ limit: 10,
24
+ /** Name of the throttler built from `limit` / `ttl` / `blockDuration` */
25
+ name: 'default',
26
+ /** Which routes are limited */
27
+ routes: 'decorated' as const,
28
+ /** Window of the `default` throttler in milliseconds (the unit of `@nestjs/throttler`) */
29
+ ttl: 60_000,
30
+ };
31
+
32
+ /** The storages a project can choose (`throttler.storage`) */
33
+ export const THROTTLER_STORAGE_KINDS = ['database', 'memory', 'redis'] as const;
@@ -0,0 +1,14 @@
1
+ /**
2
+ * `@nestjs/throttler`'s route decorators, re-exported so a project marks its routes from `@lenne.tech/nest-server`:
3
+ * in a pnpm project a package that is only a dependency of the framework cannot be imported directly, and the
4
+ * re-export guarantees the decorators write the metadata of the very copy the framework's guard reads.
5
+ *
6
+ * @example
7
+ * ```typescript
8
+ * import { SkipThrottle, Throttle } from '@lenne.tech/nest-server';
9
+ *
10
+ * @Throttle({ default: { limit: 5, ttl: 60_000 } })
11
+ * @Post('contact')
12
+ * ```
13
+ */
14
+ export { SkipThrottle, Throttle } from '@nestjs/throttler';
@@ -0,0 +1,109 @@
1
+ import { ExecutionContext, Injectable } from '@nestjs/common';
2
+ import { GqlExecutionContext } from '@nestjs/graphql';
3
+ import { normalizeIp, ThrottlerGuard } from '@nestjs/throttler';
4
+
5
+ import { resolveGuardRequest } from '../../common/helpers/execution-context-request.helper.js';
6
+ import { THROTTLER_LIMIT_METADATA } from './core-throttler.constants.js';
7
+
8
+ /**
9
+ * Whether `@Throttle()` names the throttler `name` on the route's method or controller — what `routes: 'decorated'`
10
+ * limits. `@Throttle()` writes its metadata for every key it names, also for `@Throttle({ default: {} })` (the
11
+ * throttler's own limits), so presence is the test, not a value.
12
+ */
13
+ export function isThrottleDecorated(context: ExecutionContext, name: string): boolean {
14
+ const key = THROTTLER_LIMIT_METADATA + name;
15
+ const handler = context.getHandler?.();
16
+ const controller = context.getClass?.();
17
+ return (!!handler && Reflect.hasMetadata(key, handler)) || (!!controller && Reflect.hasMetadata(key, controller));
18
+ }
19
+
20
+ /**
21
+ * The rate limit guard of the `throttler` configuration (DEV-4431): `@nestjs/throttler`'s `ThrottlerGuard`, adapted to
22
+ * the framework.
23
+ *
24
+ * - **Every transport resolves its request like the role guards do** (`resolveGuardRequest()`): REST, GraphQL over
25
+ * HTTP, and agent function / MCP calls that run inside a request. `ThrottlerGuard` itself reads
26
+ * `switchToHttp()`, which on a GraphQL context yields the resolver root.
27
+ * - **Counted per client IP** as `request.ip` reports it, which follows `trustProxy`; an IPv6 address by its subnet
28
+ * (`ipv6SubnetPrefix`, default /64), so a client cannot rotate through its own network.
29
+ * - **Every request is counted, also one without an address** (`trackerOf()`). A GraphQL operation over the WebSocket
30
+ * carries no `request.ip`: it is counted per signed-in user, else by the address of the WebSocket's upgrade request.
31
+ * An HTTP request whose client already closed the connection has lost its address (Node forgets it with the
32
+ * socket): it is counted by its user, else in one shared bucket. Letting such a request through would let a client
33
+ * that closes every connection right after sending call a limited route without limit.
34
+ * - **Only a call without any request is not counted** — a request-less agent call (a durable run, stdio). The role
35
+ * guards still decide whether it is allowed at all. GraphQL subscription events run no guards.
36
+ *
37
+ * Registered as the first global guard of the application when `throttler` is configured, so an over-limit client is
38
+ * refused before authentication runs — also on a route that would answer it with 401.
39
+ *
40
+ * Extend it and register the subclass with `CoreModule.forRoot(env, { throttler: { guard } })` to count differently,
41
+ * e.g. a signed-in user by id (`getTracker()`).
42
+ */
43
+ @Injectable()
44
+ export class CoreThrottlerGuard extends ThrottlerGuard {
45
+ /** The request-like object of the context, or `undefined` when it carries none */
46
+ protected requestOf(context: ExecutionContext): any {
47
+ return resolveGuardRequest(context, (ctx) => GqlExecutionContext.create(ctx).getContext());
48
+ }
49
+
50
+ /** The address the request is counted by, or `undefined` when there is none */
51
+ protected addressOf(req: any): string | undefined {
52
+ const address = req?.ip ?? req?.socket?.remoteAddress;
53
+ return typeof address === 'string' && address ? address : undefined;
54
+ }
55
+
56
+ protected override async shouldSkip(context: ExecutionContext): Promise<boolean> {
57
+ // Only a call without any request has nothing to count by; a request without an address is counted (trackerOf)
58
+ return !this.requestOf(context);
59
+ }
60
+
61
+ /**
62
+ * What a request is counted by — never nothing:
63
+ *
64
+ * 1. its client address (`request.ip`, following `trustProxy`), the subnet for IPv6;
65
+ * 2. without one, its signed-in user — a GraphQL operation over the WebSocket, whose handshake authenticated it, or
66
+ * an HTTP request whose client closed the connection;
67
+ * 3. the address of the WebSocket's upgrade request (subscription auth switched off);
68
+ * 4. one bucket shared by every request left: a client that closes its connections right after sending counts
69
+ * against that bucket instead of passing uncounted.
70
+ */
71
+ protected trackerOf(req: any): string {
72
+ const address = this.addressOf(req);
73
+ if (address) {
74
+ return normalizeIp(address, this.ipv6SubnetPrefix);
75
+ }
76
+ const userId = req?.user?.id;
77
+ if ((typeof userId === 'string' && userId) || typeof userId === 'number') {
78
+ return `user:${userId}`;
79
+ }
80
+ const upgradeAddress = this.addressOf(req?.request);
81
+ if (upgradeAddress) {
82
+ return normalizeIp(upgradeAddress, this.ipv6SubnetPrefix);
83
+ }
84
+ return 'unknown';
85
+ }
86
+
87
+ protected override getRequestResponse(context: ExecutionContext): {
88
+ req: Record<string, any>;
89
+ res: Record<string, any>;
90
+ } {
91
+ const req = this.requestOf(context);
92
+ let res = req?.res;
93
+ if (!res && context.getType() === 'http') {
94
+ res = context.switchToHttp().getResponse();
95
+ }
96
+ return { req, res };
97
+ }
98
+
99
+ protected override async getTracker(req: Record<string, any>): Promise<string> {
100
+ return this.trackerOf(req);
101
+ }
102
+
103
+ /** A context without a response (an agent call) gets no headers, instead of a crash */
104
+ protected override setResponseHeader(res: any, name: string, value: number | string): void {
105
+ if (res) {
106
+ super.setResponseHeader(res, name, value);
107
+ }
108
+ }
109
+ }
@@ -0,0 +1,23 @@
1
+ import { createSchema } from '../../common/persistence/mongo/mongoose-compat.js';
2
+ import { THROTTLER_COUNTER_COLLECTION } from './core-throttler.constants.js';
3
+
4
+ /**
5
+ * The counters of the database storage (`throttler.storage: 'database'`) as a framework model: registered with
6
+ * `CorePersistenceModule.forFeature()` only when that storage is chosen, it follows `database` like every other model —
7
+ * a collection on MongoDB, the table `throttler_counters` on SQL.
8
+ *
9
+ * One record per throttler and client (`key`): the hits of the current window, its end, and a block once the client
10
+ * went over the limit. Every reader decides by `windowEndsAt` / `blockedUntil` itself; MongoDB's TTL index and the SQL
11
+ * expiry sweep only reclaim the space of records nobody asks for any more.
12
+ */
13
+ export const ThrottlerCounterSchema = createSchema(
14
+ {
15
+ blocked: { type: Boolean },
16
+ blockedUntil: { type: Date },
17
+ expiresAt: { index: { expireAfterSeconds: 0 }, type: Date },
18
+ hits: { type: Number },
19
+ key: { index: { unique: true }, type: String },
20
+ windowEndsAt: { type: Date },
21
+ },
22
+ { collection: THROTTLER_COUNTER_COLLECTION, versionKey: false },
23
+ );
@@ -0,0 +1,95 @@
1
+ import { DynamicModule, ExecutionContext, Module, Provider, Type } from '@nestjs/common';
2
+ import { APP_GUARD } from '@nestjs/core';
3
+ import { getOptionsToken, getStorageToken, ThrottlerStorageService } from '@nestjs/throttler';
4
+ import type { ThrottlerModuleOptions, ThrottlerOptions } from '@nestjs/throttler';
5
+
6
+ import { CorePersistenceModule } from '../../common/persistence/core-persistence.module.js';
7
+ import type { DataStore } from '../../common/persistence/data-store.interface.js';
8
+ import { getStoreToken } from '../../common/persistence/persistence.tokens.js';
9
+ import { CoreRedisService } from '../../common/services/core-redis.service.js';
10
+ import type { ResolvedThrottlerConfig } from './core-throttler.config.js';
11
+ import { THROTTLER_COUNTER_MODEL } from './core-throttler.constants.js';
12
+ import { CoreThrottlerGuard, isThrottleDecorated } from './core-throttler.guard.js';
13
+ import { ThrottlerCounterSchema } from './core-throttler.models.js';
14
+ import {
15
+ CoreDatabaseThrottlerStorage,
16
+ CoreRedisThrottlerStorage,
17
+ type ThrottlerCounterRecord,
18
+ } from './core-throttler.storages.js';
19
+
20
+ /** Options of `CoreThrottlerModule.forRoot()` */
21
+ export interface CoreThrottlerModuleOptions {
22
+ /** `throttler` with its defaults applied (`resolveThrottlerConfig()`) */
23
+ config: ResolvedThrottlerConfig;
24
+ /** Custom guard (must extend CoreThrottlerGuard) */
25
+ guard?: Type<CoreThrottlerGuard>;
26
+ }
27
+
28
+ /**
29
+ * `@nestjs/throttler`'s module options from the resolved configuration. With `routes: 'decorated'` every throttler
30
+ * skips the routes whose `@Throttle()` does not name it, so turning the feature on limits nothing but what a project
31
+ * marked.
32
+ */
33
+ export function buildThrottlerModuleOptions(config: ResolvedThrottlerConfig): Exclude<ThrottlerModuleOptions, any[]> {
34
+ const throttlers: ThrottlerOptions[] = config.throttlers.map((throttler) => ({
35
+ ...(throttler.blockDuration === undefined ? {} : { blockDuration: throttler.blockDuration }),
36
+ limit: throttler.limit,
37
+ name: throttler.name,
38
+ ttl: throttler.ttl,
39
+ ...(config.routes === 'decorated'
40
+ ? { skipIf: (context: ExecutionContext) => !isThrottleDecorated(context, throttler.name) }
41
+ : {}),
42
+ }));
43
+ return {
44
+ errorMessage: config.errorMessage,
45
+ ...(config.ignoreUserAgents?.length ? { ignoreUserAgents: config.ignoreUserAgents } : {}),
46
+ ...(config.ipv6SubnetPrefix === undefined ? {} : { ipv6SubnetPrefix: config.ipv6SubnetPrefix }),
47
+ setHeaders: config.setHeaders,
48
+ throttlers,
49
+ };
50
+ }
51
+
52
+ /**
53
+ * Rate limit for a project's routes (`throttler` config, DEV-4431), on top of `@nestjs/throttler`.
54
+ *
55
+ * Registered automatically by `CoreModule.forRoot()` when `throttler` is configured — as the first import, so its guard
56
+ * is the first global guard. Provides `@nestjs/throttler`'s option and storage tokens itself (a project must not import
57
+ * `ThrottlerModule` next to it), the guard as `APP_GUARD`, and — only for `storage: 'database'` — the counter model,
58
+ * which follows `database` like every other model.
59
+ */
60
+ @Module({})
61
+ export class CoreThrottlerModule {
62
+ static forRoot(options: CoreThrottlerModuleOptions): DynamicModule {
63
+ const { config } = options;
64
+ const storageProvider: Provider =
65
+ config.storage === 'database'
66
+ ? {
67
+ inject: [getStoreToken(THROTTLER_COUNTER_MODEL)],
68
+ provide: getStorageToken(),
69
+ useFactory: (store: DataStore<ThrottlerCounterRecord>) => new CoreDatabaseThrottlerStorage(store),
70
+ }
71
+ : config.storage === 'redis'
72
+ ? {
73
+ inject: [CoreRedisService],
74
+ provide: getStorageToken(),
75
+ useFactory: (redisService: CoreRedisService) => new CoreRedisThrottlerStorage(redisService),
76
+ }
77
+ : { provide: getStorageToken(), useFactory: () => new ThrottlerStorageService() };
78
+
79
+ return {
80
+ exports: [getOptionsToken(), getStorageToken()],
81
+ // Global, as ThrottlerModule is: a project's own guard subclass or service may inject the storage
82
+ global: true,
83
+ imports:
84
+ config.storage === 'database'
85
+ ? [CorePersistenceModule.forFeature([{ name: THROTTLER_COUNTER_MODEL, schema: ThrottlerCounterSchema }])]
86
+ : [],
87
+ module: CoreThrottlerModule,
88
+ providers: [
89
+ { provide: getOptionsToken(), useValue: buildThrottlerModuleOptions(config) },
90
+ storageProvider,
91
+ { provide: APP_GUARD, useClass: options.guard ?? CoreThrottlerGuard },
92
+ ],
93
+ };
94
+ }
95
+ }