@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.
Files changed (128) 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/testing.md +8 -7
  5. package/CLAUDE.md +2 -1
  6. package/FRAMEWORK-API.md +15 -1
  7. package/dist/core/common/decorators/common-error.decorator.d.ts +1 -1
  8. package/dist/core/common/interfaces/server-options.interface.d.ts +54 -0
  9. package/dist/core/common/persistence/audit-log.registry.d.ts +19 -0
  10. package/dist/core/common/persistence/audit-log.registry.js +84 -0
  11. package/dist/core/common/persistence/audit-log.registry.js.map +1 -0
  12. package/dist/core/common/services/core-trust-proxy.initializer.js +1 -1
  13. package/dist/core/common/services/core-trust-proxy.initializer.js.map +1 -1
  14. package/dist/core/common/services/crud.service.d.ts +10 -0
  15. package/dist/core/common/services/crud.service.js +79 -24
  16. package/dist/core/common/services/crud.service.js.map +1 -1
  17. package/dist/core/common/services/email.service.d.ts +5 -0
  18. package/dist/core/common/services/email.service.js +82 -6
  19. package/dist/core/common/services/email.service.js.map +1 -1
  20. package/dist/core/common/services/leased-interval.d.ts +22 -0
  21. package/dist/core/common/services/leased-interval.js +81 -0
  22. package/dist/core/common/services/leased-interval.js.map +1 -0
  23. package/dist/core/common/services/mail-outbox.registry.d.ts +26 -0
  24. package/dist/core/common/services/mail-outbox.registry.js +8 -0
  25. package/dist/core/common/services/mail-outbox.registry.js.map +1 -0
  26. package/dist/core/modules/audit-log/audited.decorator.d.ts +2 -0
  27. package/dist/core/modules/audit-log/audited.decorator.js +10 -0
  28. package/dist/core/modules/audit-log/audited.decorator.js.map +1 -0
  29. package/dist/core/modules/audit-log/core-audit-log.constants.d.ts +13 -0
  30. package/dist/core/modules/audit-log/core-audit-log.constants.js +11 -0
  31. package/dist/core/modules/audit-log/core-audit-log.constants.js.map +1 -0
  32. package/dist/core/modules/audit-log/core-audit-log.controller.d.ts +9 -0
  33. package/dist/core/modules/audit-log/core-audit-log.controller.js +87 -0
  34. package/dist/core/modules/audit-log/core-audit-log.controller.js.map +1 -0
  35. package/dist/core/modules/audit-log/core-audit-log.models.d.ts +10 -0
  36. package/dist/core/modules/audit-log/core-audit-log.models.js +11 -0
  37. package/dist/core/modules/audit-log/core-audit-log.models.js.map +1 -0
  38. package/dist/core/modules/audit-log/core-audit-log.module.d.ts +13 -0
  39. package/dist/core/modules/audit-log/core-audit-log.module.js +41 -0
  40. package/dist/core/modules/audit-log/core-audit-log.module.js.map +1 -0
  41. package/dist/core/modules/audit-log/core-audit-log.service.d.ts +49 -0
  42. package/dist/core/modules/audit-log/core-audit-log.service.js +169 -0
  43. package/dist/core/modules/audit-log/core-audit-log.service.js.map +1 -0
  44. package/dist/core/modules/better-auth/core-better-auth-email-verification.service.js +4 -0
  45. package/dist/core/modules/better-auth/core-better-auth-email-verification.service.js.map +1 -1
  46. package/dist/core/modules/mail-outbox/core-mail-outbox.constants.d.ts +22 -0
  47. package/dist/core/modules/mail-outbox/core-mail-outbox.constants.js +23 -0
  48. package/dist/core/modules/mail-outbox/core-mail-outbox.constants.js.map +1 -0
  49. package/dist/core/modules/mail-outbox/core-mail-outbox.controller.d.ts +10 -0
  50. package/dist/core/modules/mail-outbox/core-mail-outbox.controller.js +80 -0
  51. package/dist/core/modules/mail-outbox/core-mail-outbox.controller.js.map +1 -0
  52. package/dist/core/modules/mail-outbox/core-mail-outbox.models.d.ts +17 -0
  53. package/dist/core/modules/mail-outbox/core-mail-outbox.models.js +17 -0
  54. package/dist/core/modules/mail-outbox/core-mail-outbox.models.js.map +1 -0
  55. package/dist/core/modules/mail-outbox/core-mail-outbox.module.d.ts +12 -0
  56. package/dist/core/modules/mail-outbox/core-mail-outbox.module.js +42 -0
  57. package/dist/core/modules/mail-outbox/core-mail-outbox.module.js.map +1 -0
  58. package/dist/core/modules/mail-outbox/core-mail-outbox.service.d.ts +59 -0
  59. package/dist/core/modules/mail-outbox/core-mail-outbox.service.js +280 -0
  60. package/dist/core/modules/mail-outbox/core-mail-outbox.service.js.map +1 -0
  61. package/dist/core/modules/migrate/cli/migrate-cli.js +20 -2
  62. package/dist/core/modules/migrate/cli/migrate-cli.js.map +1 -1
  63. package/dist/core/modules/throttler/core-throttler.config.d.ts +16 -0
  64. package/dist/core/modules/throttler/core-throttler.config.js +107 -0
  65. package/dist/core/modules/throttler/core-throttler.config.js.map +1 -0
  66. package/dist/core/modules/throttler/core-throttler.constants.d.ts +10 -0
  67. package/dist/core/modules/throttler/core-throttler.constants.js +11 -0
  68. package/dist/core/modules/throttler/core-throttler.constants.js.map +1 -0
  69. package/dist/core/modules/throttler/core-throttler.decorators.d.ts +1 -0
  70. package/dist/core/modules/throttler/core-throttler.decorators.js +2 -0
  71. package/dist/core/modules/throttler/core-throttler.decorators.js.map +1 -0
  72. package/dist/core/modules/throttler/core-throttler.guard.d.ts +15 -0
  73. package/dist/core/modules/throttler/core-throttler.guard.js +65 -0
  74. package/dist/core/modules/throttler/core-throttler.guard.js.map +1 -0
  75. package/dist/core/modules/throttler/core-throttler.models.d.ts +1 -0
  76. package/dist/core/modules/throttler/core-throttler.models.js +11 -0
  77. package/dist/core/modules/throttler/core-throttler.models.js.map +1 -0
  78. package/dist/core/modules/throttler/core-throttler.module.d.ts +12 -0
  79. package/dist/core/modules/throttler/core-throttler.module.js +71 -0
  80. package/dist/core/modules/throttler/core-throttler.module.js.map +1 -0
  81. package/dist/core/modules/throttler/core-throttler.storages.d.ts +43 -0
  82. package/dist/core/modules/throttler/core-throttler.storages.js +174 -0
  83. package/dist/core/modules/throttler/core-throttler.storages.js.map +1 -0
  84. package/dist/core/modules/user/core-user.service.js +2 -2
  85. package/dist/core/modules/user/core-user.service.js.map +1 -1
  86. package/dist/core.module.js +26 -0
  87. package/dist/core.module.js.map +1 -1
  88. package/dist/index.d.ts +21 -0
  89. package/dist/index.js +21 -0
  90. package/dist/index.js.map +1 -1
  91. package/docs/REQUEST-LIFECYCLE.md +7 -0
  92. package/docs/security-overrides.md +20 -8
  93. package/migration-guides/12.11.x-to-12.12.x.md +182 -0
  94. package/package.json +24 -23
  95. package/src/core/common/interfaces/server-options.interface.ts +311 -1
  96. package/src/core/common/persistence/audit-log.registry.ts +150 -0
  97. package/src/core/common/services/core-trust-proxy.initializer.ts +5 -4
  98. package/src/core/common/services/crud.service.ts +128 -33
  99. package/src/core/common/services/email.service.ts +101 -9
  100. package/src/core/common/services/leased-interval.ts +123 -0
  101. package/src/core/common/services/mail-outbox.registry.ts +53 -0
  102. package/src/core/modules/audit-log/README.md +95 -0
  103. package/src/core/modules/audit-log/audited.decorator.ts +27 -0
  104. package/src/core/modules/audit-log/core-audit-log.constants.ts +28 -0
  105. package/src/core/modules/audit-log/core-audit-log.controller.ts +77 -0
  106. package/src/core/modules/audit-log/core-audit-log.models.ts +34 -0
  107. package/src/core/modules/audit-log/core-audit-log.module.ts +54 -0
  108. package/src/core/modules/audit-log/core-audit-log.service.ts +270 -0
  109. package/src/core/modules/better-auth/core-better-auth-email-verification.service.ts +4 -0
  110. package/src/core/modules/mail-outbox/README.md +88 -0
  111. package/src/core/modules/mail-outbox/core-mail-outbox.constants.ts +42 -0
  112. package/src/core/modules/mail-outbox/core-mail-outbox.controller.ts +60 -0
  113. package/src/core/modules/mail-outbox/core-mail-outbox.models.ts +46 -0
  114. package/src/core/modules/mail-outbox/core-mail-outbox.module.ts +52 -0
  115. package/src/core/modules/mail-outbox/core-mail-outbox.service.ts +390 -0
  116. package/src/core/modules/migrate/README.md +4 -1
  117. package/src/core/modules/migrate/cli/migrate-cli.ts +30 -2
  118. package/src/core/modules/throttler/README.md +107 -0
  119. package/src/core/modules/throttler/core-throttler.config.ts +162 -0
  120. package/src/core/modules/throttler/core-throttler.constants.ts +33 -0
  121. package/src/core/modules/throttler/core-throttler.decorators.ts +14 -0
  122. package/src/core/modules/throttler/core-throttler.guard.ts +109 -0
  123. package/src/core/modules/throttler/core-throttler.models.ts +23 -0
  124. package/src/core/modules/throttler/core-throttler.module.ts +95 -0
  125. package/src/core/modules/throttler/core-throttler.storages.ts +299 -0
  126. package/src/core/modules/user/core-user.service.ts +3 -2
  127. package/src/core.module.ts +46 -0
  128. package/src/index.ts +36 -0
@@ -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
+ }