@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
@@ -2568,6 +2568,20 @@ export interface IServerOptions {
2568
2568
  */
2569
2569
  apiTokens?: boolean | IApiTokens;
2570
2570
 
2571
+ /**
2572
+ * Audit log (DEV-4432): who created, changed, deleted or restored which record of the models a project names, and
2573
+ * which fields a change touched — names only, never values. Presence implies enabled — `true` / `{}` enable it with
2574
+ * the defaults, `{ enabled: false }` pre-configures. Absent: no collection or table, no route, no work per request.
2575
+ *
2576
+ * Logged are the models carrying `@Audited()` and those named in `auditLog.models`, written through `CrudService`
2577
+ * (`create()`, `update()`, `delete()` and their `Force` / `Raw` variants); a project logs further actions (restore)
2578
+ * with `CoreAuditLogService.record()`. Readable by admins (`GET /audit-log`).
2579
+ *
2580
+ * @see IAuditLog
2581
+ * @since 12.12.0
2582
+ */
2583
+ auditLog?: boolean | IAuditLog;
2584
+
2571
2585
  /**
2572
2586
  * Authentication system configuration
2573
2587
  *
@@ -3346,6 +3360,17 @@ export interface IServerOptions {
3346
3360
  */
3347
3361
  logExceptions?: boolean;
3348
3362
 
3363
+ /**
3364
+ * Mail outbox (DEV-4433): every mail of `EmailService` — the framework's auth mails included — is stored first and
3365
+ * delivered from the store; a failed delivery is retried with backoff up to `maxAttempts`, and with several replicas
3366
+ * exactly one delivers each mail. Presence implies enabled — `true` / `{}` enable it with the defaults,
3367
+ * `{ enabled: false }` pre-configures. Absent: mail is sent directly, as before.
3368
+ *
3369
+ * @see IMailOutbox
3370
+ * @since 12.12.0
3371
+ */
3372
+ mailOutbox?: boolean | IMailOutbox;
3373
+
3349
3374
  /**
3350
3375
  * Configuration for Mongoose
3351
3376
  */
@@ -3950,6 +3975,30 @@ export interface IServerOptions {
3950
3975
  path?: string;
3951
3976
  };
3952
3977
 
3978
+ /**
3979
+ * Rate limit for a project's routes, on top of `@nestjs/throttler` (DEV-4431): `@Throttle()` on a route or a
3980
+ * controller limits it per client IP, over the limit it answers 429 with `Retry-After`. Presence implies enabled —
3981
+ * `true` / `{}` enable it with the defaults, `{ enabled: false }` pre-configures. Absent: no guard, no storage, no
3982
+ * table — nothing changes.
3983
+ *
3984
+ * Counted per client IP as `request.ip` reports it, so `trustProxy` must name the proxies in front of the app.
3985
+ * The counters live in memory (default), in Redis (default when `redis` is configured) or in the project's database
3986
+ * (`storage: 'database'`, MongoDB or SQL, exact across replicas without Redis).
3987
+ *
3988
+ * @see IThrottler
3989
+ * @since 12.12.0
3990
+ *
3991
+ * @example
3992
+ * ```typescript
3993
+ * throttler: { storage: 'database' },
3994
+ *
3995
+ * // on the route
3996
+ * @Throttle({ default: { limit: 5, ttl: 60_000 } })
3997
+ * @Post('contact')
3998
+ * ```
3999
+ */
4000
+ throttler?: boolean | IThrottler;
4001
+
3953
4002
  /**
3954
4003
  * Express `trust proxy` setting — how far up the `X-Forwarded-For` chain this app believes.
3955
4004
  *
@@ -3985,7 +4034,7 @@ export interface IServerOptions {
3985
4034
  * — i.e. AFTER your `main.ts` runs. A configured value therefore takes precedence over an
3986
4035
  * `app.set('trust proxy', …)` of your own.
3987
4036
  *
3988
- * When this is unset and an IP-keyed rate limiter (`auth.rateLimit` / `betterAuth.rateLimit`) is
4037
+ * When this is unset and an IP-keyed rate limiter (`auth.rateLimit` / `betterAuth.rateLimit` / `throttler`) is
3989
4038
  * enabled, the framework logs a warning at boot naming the shared-bucket consequence.
3990
4039
  *
3991
4040
  * @default false (Express default — the forwarded chain is not trusted)
@@ -4273,6 +4322,222 @@ export interface IS3Config {
4273
4322
  stagingBucket?: string;
4274
4323
  }
4275
4324
 
4325
+ /**
4326
+ * One named throttler of `throttler.throttlers` — `@nestjs/throttler`'s `ThrottlerOptions` in the form a
4327
+ * configuration can carry (numbers, no functions).
4328
+ */
4329
+ export interface IThrottlerLimit {
4330
+ /**
4331
+ * How long a client stays refused once it went over the limit, in milliseconds.
4332
+ * @default the throttler's `ttl`
4333
+ */
4334
+ blockDuration?: number;
4335
+
4336
+ /** Requests a client may make per window */
4337
+ limit: number;
4338
+
4339
+ /**
4340
+ * Name `@Throttle()` / `@SkipThrottle()` address the throttler by (`@Throttle({ <name>: { limit, ttl } })`).
4341
+ * @default 'default'
4342
+ */
4343
+ name?: string;
4344
+
4345
+ /** Length of the window, in milliseconds (the unit of `@nestjs/throttler`) */
4346
+ ttl: number;
4347
+ }
4348
+
4349
+ /**
4350
+ * Rate limit for a project's routes (`throttler`, presence implies enabled). See
4351
+ * `src/core/modules/throttler/README.md`.
4352
+ *
4353
+ * @since 12.12.0
4354
+ */
4355
+ export interface IThrottler {
4356
+ /**
4357
+ * How long a client stays refused once it went over the `default` throttler's limit, in milliseconds.
4358
+ * @default the `ttl`
4359
+ */
4360
+ blockDuration?: number;
4361
+
4362
+ /**
4363
+ * Pre-configure without enabling.
4364
+ * @default true (when the object is present)
4365
+ */
4366
+ enabled?: boolean;
4367
+
4368
+ /**
4369
+ * Message of the 429 answer.
4370
+ * @default ErrorCode.RATE_LIMIT_EXCEEDED ('#LTNS_0020: Too many requests')
4371
+ */
4372
+ errorMessage?: string;
4373
+
4374
+ /** User agents never limited (`@nestjs/throttler`'s `ignoreUserAgents`) — from `config.env.ts` only */
4375
+ ignoreUserAgents?: RegExp[];
4376
+
4377
+ /**
4378
+ * Prefix length an IPv6 address is counted by, so a client cannot rotate addresses inside its own network.
4379
+ * @default 64
4380
+ */
4381
+ ipv6SubnetPrefix?: number;
4382
+
4383
+ /**
4384
+ * Requests per window of the `default` throttler. An invalid value (not a positive number) falls back to the
4385
+ * default with a warning.
4386
+ * @default 10
4387
+ */
4388
+ limit?: number;
4389
+
4390
+ /**
4391
+ * Which routes are limited:
4392
+ * - `'decorated'` — only routes whose method or controller carries `@Throttle()`; a route is limited by the
4393
+ * throttlers its decorator names. Turning the feature on changes no other route.
4394
+ * - `'all'` — every HTTP route and GraphQL operation, by every throttler, unless `@SkipThrottle()` exempts it
4395
+ * (the behaviour of a plain `ThrottlerModule`). Keep in mind that every client behind one NAT shares an address.
4396
+ * @default 'decorated'
4397
+ */
4398
+ routes?: 'all' | 'decorated';
4399
+
4400
+ /**
4401
+ * Send `X-RateLimit-Limit` / `-Remaining` / `-Reset` (and `Retry-After` on a refusal).
4402
+ * @default true
4403
+ */
4404
+ setHeaders?: boolean;
4405
+
4406
+ /**
4407
+ * Where the counters live:
4408
+ * - `'memory'` — in the process (`@nestjs/throttler`'s own storage); each replica counts for itself.
4409
+ * - `'redis'` — in Redis (`redis` must be configured); exact across replicas.
4410
+ * - `'database'` — in the project's database through the persistence layer (MongoDB or SQL, the table
4411
+ * `throttler_counters`); exact across replicas without Redis.
4412
+ *
4413
+ * An explicitly chosen storage that is not available stops the boot. While Redis or the database cannot be reached,
4414
+ * the counters fall back to memory (logged), never to "no limit".
4415
+ * @default 'redis' when `redis` is configured, otherwise 'memory'
4416
+ */
4417
+ storage?: 'database' | 'memory' | 'redis';
4418
+
4419
+ /**
4420
+ * Named throttlers. When given, they replace the `default` throttler built from `limit` / `ttl` / `blockDuration`
4421
+ * (name one of them `default` to keep `@Throttle({ default: … })` working).
4422
+ */
4423
+ throttlers?: IThrottlerLimit[];
4424
+
4425
+ /**
4426
+ * Window of the `default` throttler, in milliseconds. An invalid value falls back to the default with a warning.
4427
+ * @default 60000
4428
+ */
4429
+ ttl?: number;
4430
+ }
4431
+
4432
+ /**
4433
+ * Audit log (`auditLog`, presence implies enabled): who created, changed, deleted or restored which record, and which
4434
+ * fields a change touched — names only, never values. See `src/core/modules/audit-log/README.md`.
4435
+ *
4436
+ * @since 12.12.0
4437
+ */
4438
+ export interface IAuditLog {
4439
+ /**
4440
+ * Pre-configure without enabling.
4441
+ * @default true (when the object is present)
4442
+ */
4443
+ enabled?: boolean;
4444
+
4445
+ /**
4446
+ * Names of the models logged (as registered, e.g. `'Institution'`), in addition to every model class carrying
4447
+ * `@Audited()`. A model in neither is not logged.
4448
+ * @default []
4449
+ */
4450
+ models?: string[];
4451
+
4452
+ /**
4453
+ * Route prefix of the read endpoint (`GET /<path>`).
4454
+ * @default 'audit-log'
4455
+ */
4456
+ path?: string;
4457
+
4458
+ /**
4459
+ * Days an entry is kept; older entries are removed every hour (on one replica). `false` keeps them for good. An
4460
+ * invalid value (not a positive number) falls back to the default, never to "for good".
4461
+ * @default 365
4462
+ */
4463
+ retentionDays?: false | number;
4464
+
4465
+ /**
4466
+ * Roles that may read the log. ADMIN always may.
4467
+ * @default [RoleEnum.ADMIN]
4468
+ */
4469
+ roles?: string[];
4470
+ }
4471
+
4472
+ /**
4473
+ * Mail outbox (`mailOutbox`, presence implies enabled): every mail of `EmailService` — the framework's auth mails
4474
+ * included — is stored first and delivered from the store, retried with backoff on a failure, by exactly one replica.
4475
+ * See `src/core/modules/mail-outbox/README.md`.
4476
+ *
4477
+ * @since 12.12.0
4478
+ */
4479
+ export interface IMailOutbox {
4480
+ /**
4481
+ * Pre-configure without enabling.
4482
+ * @default true (when the object is present)
4483
+ */
4484
+ enabled?: boolean;
4485
+
4486
+ /**
4487
+ * How long one replica holds a mail it is delivering before another may take it over, in seconds. Keep it above the
4488
+ * SMTP timeouts: a mail taken over while the first send still runs is sent twice.
4489
+ * @default 900
4490
+ */
4491
+ lockSeconds?: number;
4492
+
4493
+ /**
4494
+ * Delivery attempts before a mail counts as failed for good.
4495
+ * @default 10
4496
+ */
4497
+ maxAttempts?: number;
4498
+
4499
+ /**
4500
+ * Upper bound of the delay between two attempts, in seconds.
4501
+ * @default 3600
4502
+ */
4503
+ maxRetryDelaySeconds?: number;
4504
+
4505
+ /**
4506
+ * Route prefix of the admin endpoints (`GET /<path>`, `POST /<path>/:id/retry`).
4507
+ * @default 'mail-outbox'
4508
+ */
4509
+ path?: string;
4510
+
4511
+ /**
4512
+ * How often each replica looks for due mails, in seconds. A new mail is sent at once; this is for retries.
4513
+ * @default 10
4514
+ */
4515
+ pollIntervalSeconds?: number;
4516
+
4517
+ /**
4518
+ * How long entries are kept (the purge runs every hour on one replica). A sent mail keeps only its metadata
4519
+ * (recipients, subject, times) — its content is removed when it was delivered. `false` keeps entries for good.
4520
+ */
4521
+ retention?: {
4522
+ /** Days a failed mail stays visible @default 30 */
4523
+ failedDays?: false | number;
4524
+ /** Days a sent mail's metadata stays @default 7 */
4525
+ sentDays?: false | number;
4526
+ };
4527
+
4528
+ /**
4529
+ * Delay before the second attempt, in seconds; doubled for every further attempt up to `maxRetryDelaySeconds`.
4530
+ * @default 30
4531
+ */
4532
+ retryDelaySeconds?: number;
4533
+
4534
+ /**
4535
+ * Roles that may list the outbox and retry a failed mail. ADMIN always may.
4536
+ * @default [RoleEnum.ADMIN]
4537
+ */
4538
+ roles?: string[];
4539
+ }
4540
+
4276
4541
  /**
4277
4542
  * Offline sync (`sync`, presence implies enabled). See `src/core/modules/sync/README.md`.
4278
4543
  *
@@ -5491,6 +5756,51 @@ export interface ICoreModuleOverrides {
5491
5756
  service?: Type<any>;
5492
5757
  };
5493
5758
 
5759
+ /**
5760
+ * Override the audit log's read endpoint and/or service (`auditLog` config).
5761
+ *
5762
+ * - `controller` must extend `CoreAuditLogController`
5763
+ * - `service` must extend `CoreAuditLogService` (e.g. to decide per record whether it is logged)
5764
+ *
5765
+ * @example
5766
+ * ```typescript
5767
+ * { auditLog: { service: AuditLogService } }
5768
+ * ```
5769
+ */
5770
+ auditLog?: {
5771
+ controller?: Type<any>;
5772
+ service?: Type<any>;
5773
+ };
5774
+
5775
+ /**
5776
+ * Override the mail outbox's admin endpoints and/or service (`mailOutbox` config).
5777
+ *
5778
+ * - `controller` must extend `CoreMailOutboxController`
5779
+ * - `service` must extend `CoreMailOutboxService` (e.g. to change the backoff)
5780
+ *
5781
+ * @example
5782
+ * ```typescript
5783
+ * { mailOutbox: { service: MailOutboxService } }
5784
+ * ```
5785
+ */
5786
+ mailOutbox?: {
5787
+ controller?: Type<any>;
5788
+ service?: Type<any>;
5789
+ };
5790
+
5791
+ /**
5792
+ * Override the rate limit guard (`throttler` config). `guard` must extend `CoreThrottlerGuard` (e.g. to count a
5793
+ * signed-in user by id instead of by IP: override `getTracker()`).
5794
+ *
5795
+ * @example
5796
+ * ```typescript
5797
+ * { throttler: { guard: ThrottlerGuard } }
5798
+ * ```
5799
+ */
5800
+ throttler?: {
5801
+ guard?: Type<any>;
5802
+ };
5803
+
5494
5804
  /**
5495
5805
  * Override the offline sync endpoints, the hint subscription and their service (`sync` config).
5496
5806
  *
@@ -0,0 +1,150 @@
1
+ /**
2
+ * How a write of `CrudService` reaches the audit log (`auditLog` config, DEV-4432) without the persistence layer or
3
+ * `CrudService` importing the module: the module registers itself here when it starts, and `CrudService.create()`,
4
+ * `update()` and `delete()` report every successful write of a logged model. Nothing is registered without an
5
+ * `auditLog` configuration — every report is then one `undefined` check, no work per request.
6
+ *
7
+ * Also holds the comparison `update()` uses to tell which fields a change touched, by NAME: the audit log never
8
+ * stores a value, so nothing a value carries (a password, an IBAN, a health record) can reach it.
9
+ *
10
+ * Import-free leaf (types only): every caller may import it without an import cycle.
11
+ */
12
+
13
+ /** What happened to the record. `restore` and any other action come from a project (`CoreAuditLogService.record()`) */
14
+ export type AuditAction = 'create' | 'delete' | 'restore' | 'update' | (string & {});
15
+
16
+ /** One logged write — names only, never values */
17
+ export interface AuditWrite {
18
+ action: AuditAction;
19
+ /** Names of the fields the write set or changed, sorted; empty for a delete */
20
+ fields: string[];
21
+ /** The model's registered name */
22
+ model: string;
23
+ /** The record's id */
24
+ recordId: string;
25
+ /** Who acted; `undefined` for system work (no user: cron, migration, seed) */
26
+ userId?: string;
27
+ }
28
+
29
+ export interface AuditLogListener {
30
+ /** Whether writes of the model are logged (`@Audited()` on its class, or named in `auditLog.models`) */
31
+ isAudited(model: string, modelClass?: Function): boolean;
32
+ /** Store one write; a failure is the caller's to log, never to throw on — the write has happened */
33
+ recordWrite(write: AuditWrite): Promise<void>;
34
+ }
35
+
36
+ let listener: AuditLogListener | undefined;
37
+
38
+ /** Set by the audit log module when it starts, cleared when it stops */
39
+ export function setAuditLogListener(value: AuditLogListener | undefined): void {
40
+ listener = value;
41
+ }
42
+
43
+ export function getAuditLogListener(): AuditLogListener | undefined {
44
+ return listener;
45
+ }
46
+
47
+ /**
48
+ * Bookkeeping fields every write touches or the store manages — never reported as changed: `updatedBy` is set on each
49
+ * update, `updatedAt` stamped by the store, the id never changes, and the sync columns are the store's.
50
+ */
51
+ export const AUDIT_IGNORED_FIELDS: ReadonlySet<string> = new Set([
52
+ '_id',
53
+ 'createdAt',
54
+ 'createdBy',
55
+ 'id',
56
+ 'syncAt',
57
+ 'syncSeq',
58
+ 'updatedAt',
59
+ 'updatedBy',
60
+ 'version',
61
+ ]);
62
+
63
+ /** Deeper than this, two values count as different: a self-referencing value must not hang the write */
64
+ const MAX_DEPTH = 20;
65
+
66
+ function normalize(value: unknown, depth: number): unknown {
67
+ if (value === undefined || value === null) {
68
+ return null;
69
+ }
70
+ if (depth > MAX_DEPTH) {
71
+ return { $deep: Math.random() };
72
+ }
73
+ if (value instanceof Date) {
74
+ return Number.isNaN(value.getTime()) ? 'Invalid Date' : value.toISOString();
75
+ }
76
+ // A SQL `bigint` column reads as a BigInt, which JSON.stringify refuses
77
+ if (typeof value === 'bigint') {
78
+ return { $bigint: value.toString() };
79
+ }
80
+ if (typeof value !== 'object') {
81
+ return value;
82
+ }
83
+ const object = value as Record<string, any>;
84
+ // An ObjectId (bson, Mongoose) compares by its hex string, so a stored id equals the same id given as a string
85
+ if (typeof object.toHexString === 'function') {
86
+ return object.toHexString();
87
+ }
88
+ if (typeof Buffer !== 'undefined' && Buffer.isBuffer(object)) {
89
+ return object.toString('base64');
90
+ }
91
+ if (Array.isArray(object)) {
92
+ return object.map((item) => normalize(item, depth + 1));
93
+ }
94
+ const plain = typeof object.toObject === 'function' ? object.toObject() : object;
95
+ return Object.fromEntries(
96
+ Object.keys(plain)
97
+ .filter((key) => plain[key] !== undefined)
98
+ .sort()
99
+ .map((key) => [key, normalize(plain[key], depth + 1)]),
100
+ );
101
+ }
102
+
103
+ /**
104
+ * A comparable form of a field's value: dates by instant, ObjectIds by hex, BigInts by their digits, objects with
105
+ * sorted keys. Only ever compared with another fingerprint in memory — it is never stored. Never throws: it runs inside
106
+ * the write it reports on, so a value it cannot read (a getter that throws) counts as changed instead.
107
+ */
108
+ export function auditFingerprint(value: unknown): string {
109
+ try {
110
+ return JSON.stringify(normalize(value, 0));
111
+ } catch {
112
+ return `{"$uncomparable":${Math.random()}}`;
113
+ }
114
+ }
115
+
116
+ /** The names of the fields an input sets (create), without bookkeeping fields and undefined values, sorted */
117
+ export function auditInputFields(input: Record<string, any> | null | undefined): string[] {
118
+ if (!input || typeof input !== 'object') {
119
+ return [];
120
+ }
121
+ return Object.keys(input)
122
+ .filter((key) => input[key] !== undefined && !AUDIT_IGNORED_FIELDS.has(key))
123
+ .sort();
124
+ }
125
+
126
+ /**
127
+ * The fingerprints of the stored values of the fields an update input names — taken BEFORE the input is merged into
128
+ * the stored record (`mergePlain()` merges into it).
129
+ */
130
+ export function auditSnapshot(
131
+ stored: Record<string, any> | null | undefined,
132
+ input: Record<string, any> | null | undefined,
133
+ ): Map<string, string> {
134
+ const snapshot = new Map<string, string>();
135
+ for (const key of auditInputFields(input)) {
136
+ snapshot.set(key, auditFingerprint(stored?.[key]));
137
+ }
138
+ return snapshot;
139
+ }
140
+
141
+ /** The names of the fields whose value differs between the snapshot and the record as written, sorted */
142
+ export function auditChangedFields(snapshot: Map<string, string>, written: Record<string, any>): string[] {
143
+ const changed: string[] = [];
144
+ for (const [key, before] of snapshot) {
145
+ if (auditFingerprint(written?.[key]) !== before) {
146
+ changed.push(key);
147
+ }
148
+ }
149
+ return changed.sort();
150
+ }
@@ -1,5 +1,6 @@
1
1
  import { ForbiddenException, Logger } from '@nestjs/common';
2
2
 
3
+ import { accessDeniedException } from '../../exceptions/access-denied.exception.js';
3
4
  import { ConfigService } from '../../services/config.service.js';
4
5
  import { RequestContext } from '../../services/request-context.service.js';
5
6
 
@@ -100,14 +101,15 @@ export function isTenantPolicyBypassed(modelName?: string): boolean {
100
101
  * Resolve tenant filter from RequestContext for read operations (queries, aggregates).
101
102
  *
102
103
  * Defense-in-depth: If a schema has tenantId but there is no valid tenant context,
103
- * throws ForbiddenException instead of returning unfiltered data (Safety Net).
104
+ * throws instead of returning unfiltered data (Safety Net) — 401 for a client operation without a user, 403 otherwise.
104
105
  *
105
106
  * @returns
106
107
  * - `undefined` → no filter should be applied (bypass active or plugin disabled)
107
108
  * - `{}` → empty filter (admin bypass without header — sees all data)
108
109
  * - `{ tenantId: string }` → filter by single validated tenant
109
110
  * - `{ tenantId: { $in: string[] } }` → filter by user's tenant memberships
110
- * @throws ForbiddenException when tenantId-schema is accessed without valid tenant context
111
+ * @throws when tenantId-schema is accessed without valid tenant context: UnauthorizedException (401) for a client
112
+ * operation without a user, ForbiddenException (403) for a signed-in caller and for server work
111
113
  */
112
114
  export function resolveTenantFilter(modelName?: string): Record<string, any> | undefined {
113
115
  if (isTenantPolicyBypassed(modelName)) return undefined;
@@ -127,9 +129,12 @@ export function resolveTenantFilter(modelName?: string): Record<string, any> | u
127
129
 
128
130
  // SAFETY NET: Schema has tenantId but no valid tenant context.
129
131
  // Throw instead of returning unfiltered data to prevent data leaks.
130
- throw new ForbiddenException(
131
- 'Tenant context required: this data is tenant-scoped but no valid tenant context was provided',
132
- );
132
+ const message = 'Tenant context required: this data is tenant-scoped but no valid tenant context was provided';
133
+ // A CLIENT operation without a user (an expired session, a public route) is answered 401: a tenant context comes
134
+ // from a membership, so signing in is the remedy, and a 403 kept a frontend with an expired session from signing
135
+ // out (it reads only 401 as "signed out"). A signed-in caller keeps the 403 — the same rule as every other
136
+ // permission layer (`accessDeniedException()`). Server work without a request keeps the 403 as well.
137
+ throw context?.fromRequest ? accessDeniedException(context.currentUser, message) : new ForbiddenException(message);
133
138
  }
134
139
 
135
140
  /**
@@ -85,12 +85,13 @@ export class CoreTrustProxyInitializer implements OnApplicationBootstrap, OnModu
85
85
  /**
86
86
  * Which IP-keyed limiters are on.
87
87
  *
88
- * Read from config rather than injected, so this provider stays free of import edges to the auth
89
- * and better-auth modules. Both follow "presence implies enabled". The AI limiter is deliberately
90
- * absent: it keys on the user id, so `trust proxy` does not affect it.
88
+ * Read from config rather than injected, so this provider stays free of import edges to the auth,
89
+ * better-auth and throttler modules. All three follow "presence implies enabled" (`throttler` also
90
+ * takes `true`). The AI limiter is deliberately absent: it keys on the user id, so `trust proxy`
91
+ * does not affect it.
91
92
  */
92
93
  protected enabledIpRateLimiters(): string[] {
93
- return (['auth.rateLimit', 'betterAuth.rateLimit'] as const).filter((path) => {
94
+ return (['auth.rateLimit', 'betterAuth.rateLimit', 'throttler'] as const).filter((path) => {
94
95
  const config = ConfigService.getFastButReadOnly<{ enabled?: boolean } | boolean>(path);
95
96
  if (config === undefined || config === null || config === false) {
96
97
  return false;