@bymax-one/nest-notification 1.4.10 โ†’ 1.4.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -11,6 +11,45 @@ the entries that carry one, is the compatibility contract โ€” read it, not the n
11
11
 
12
12
  ## [Unreleased]
13
13
 
14
+ ## [1.4.11] - 2026-11-17
15
+
16
+ ### Added
17
+
18
+ - **`SmtpEmailProvider` can pool its connections, and closes with the application.** The new
19
+ option `pool` (`maxConnections` and `maxMessages`, each optional) turns Nodemailer's pooled mode
20
+ on, a limit left out keeping Nodemailer's default; without it the transport is configured as
21
+ before. The provider gains `close()`, which closes the transport it built (a send in flight on a
22
+ pooled transport finishes, one waiting for a connection fails, and a later `send()` builds a new
23
+ transport), and implements `onModuleDestroy`, so Nest closes it when the application closes. A
24
+ close that throws is logged as `[SMTP_CLOSE_FAILED]` with no text from the relay and is not
25
+ rethrown.
26
+
27
+ - **`otp.strictPurposes` refuses a purpose that nobody registered.** The limits of a recipient are
28
+ kept per `(tenant, recipient, purpose)` and a purpose with no `perPurpose` entry uses the
29
+ defaults, so a host that lets a caller choose the purpose lets the caller ask for a fresh
30
+ cooldown and attempt counter each time. With `strictPurposes: true`, `OtpService` refuses at every
31
+ operation, before any storage call, a purpose that is neither in
32
+ `NOTIFICATION_PURPOSES` nor a key of `perPurpose`, with `notification.invalid_scope_identifier`
33
+ (400) and the reason `not a registered purpose`, never the value. The option is a boolean
34
+ checked when the module starts and is off by default.
35
+
36
+ ### Documentation
37
+
38
+ - The README states how deep the audit metadata is kept, and a spec holds the number to the code.
39
+ - The README has a Production section: a bounded `ioredis` client and who closes it, the send
40
+ timeouts, the shutdown, and storing codes as digests.
41
+
42
+ #### Apply to a derived backend
43
+
44
+ `OtpChannelOptions` gains the optional `strictPurposes`, off by default, so a backend that does
45
+ not set it needs no change; one that sets it registers each purpose it uses that is not one of
46
+ the canonical purposes as a key of `perPurpose` (an empty object keeps the defaults).
47
+
48
+ `SmtpEmailProviderOptions` gains the optional `pool`, the exported `SmtpPoolOptions` type is new,
49
+ and `SmtpEmailProvider` gains `close()` and `onModuleDestroy()`. A backend that builds the
50
+ provider without `pool` needs no change; one that sets it should let Nest close the application,
51
+ or call `close()` itself.
52
+
14
53
  ## [1.4.10] - 2026-11-16
15
54
 
16
55
  ### Fixed
@@ -1268,7 +1307,8 @@ rejected at startup rather than failing on the first send.
1268
1307
 
1269
1308
  [1.0.4]: https://github.com/bymaxone/nest-notification/compare/v1.0.3...v1.0.4
1270
1309
  [1.0.3]: https://github.com/bymaxone/nest-notification/compare/v1.0.2...v1.0.3
1271
- [Unreleased]: https://github.com/bymaxone/nest-notification/compare/v1.4.10...HEAD
1310
+ [Unreleased]: https://github.com/bymaxone/nest-notification/compare/v1.4.11...HEAD
1311
+ [1.4.11]: https://github.com/bymaxone/nest-notification/compare/v1.4.10...v1.4.11
1272
1312
  [1.4.10]: https://github.com/bymaxone/nest-notification/compare/v1.4.9...v1.4.10
1273
1313
  [1.4.9]: https://github.com/bymaxone/nest-notification/compare/v1.4.8...v1.4.9
1274
1314
  [1.4.8]: https://github.com/bymaxone/nest-notification/compare/v1.4.7...v1.4.8
package/README.md CHANGED
@@ -382,7 +382,7 @@ BymaxNotificationModule.forRoot({
382
382
 
383
383
  To capture HTTP-level `sent` / `failed` entries automatically, apply `NotificationAuditInterceptor` with `@UseInterceptors(...)` on a controller or handler, or wire it globally.
384
384
 
385
- **Control characters are escaped before your repository sees an entry.** An entry carries values a caller chose (a recipient, a user id, an error text, a template name), and a line feed in one of them starts a second record in a log or a store that writes lines. Every string of an entry, and every key and string value of its `metadata`, reaches `create` with the C0 and C1 controls, the Unicode line and paragraph separators and the bidirectional controls written as visible sequences (`\n`, `\r`, `\t`, `\uXXXX`); a backslash is left as it is, so a key that escapes to the text of an earlier key takes a `#2`, `#3` suffix instead of replacing it. Metadata nested too deep, a cycle, and a value that is not a plain object, an array or a primitive arrive as `[depth limit]`, `[circular]` or `[non-plain value]`. The module does this for every writer it wires, and the `BYMAX_NOTIFICATION_LOG_REPOSITORY` token still resolves to your own repository. A host that builds `OtpService`, `EmailService` or `NotificationAuditInterceptor` itself, with `new`, bypasses the wiring and has its own repository's `create` escape the strings of the entry the same way. The length of a value is not bounded here. The failure lines the library logs from text it did not write (the reason an SMTP relay or the Resend API gives, and the error a template renderer throws at startup) carry it with the same escape; the error those providers throw keeps the text as it came, and is yours to escape if you log it.
385
+ **Control characters are escaped before your repository sees an entry.** An entry carries values a caller chose (a recipient, a user id, an error text, a template name), and a line feed in one of them starts a second record in a log or a store that writes lines. Every string of an entry, and every key and string value of its `metadata`, reaches `create` with the C0 and C1 controls, the Unicode line and paragraph separators and the bidirectional controls written as visible sequences (`\n`, `\r`, `\t`, `\uXXXX`); a backslash is left as it is, so a key that escapes to the text of an earlier key takes a `#2`, `#3` suffix instead of replacing it. Metadata is kept down to 3 levels of nesting below the `metadata` object; a subtree deeper than that arrives as `[depth limit]`, a cycle as `[circular]`, and a value that is not a plain object, an array or a primitive as `[non-plain value]`. The module does this for every writer it wires, and the `BYMAX_NOTIFICATION_LOG_REPOSITORY` token still resolves to your own repository. A host that builds `OtpService`, `EmailService` or `NotificationAuditInterceptor` itself, with `new`, bypasses the wiring and has its own repository's `create` escape the strings of the entry the same way. The length of a value is not bounded here. The failure lines the library logs from text it did not write (the reason an SMTP relay or the Resend API gives, and the error a template renderer throws at startup) carry it with the same escape; the error those providers throw keeps the text as it came, and is yours to escape if you log it.
386
386
 
387
387
  ### 7. Frontend Integration (React)
388
388
 
@@ -435,6 +435,42 @@ if (error.code === NOTIFICATION_ERROR_CODES.OTP_MAX_ATTEMPTS_EXCEEDED) {
435
435
 
436
436
  ---
437
437
 
438
+ ## ๐Ÿญ Production
439
+
440
+ What the library leaves to you, and what to set before real traffic. The option tables are in the Configuration section and in [`docs/smtp-provider.md`](./docs/smtp-provider.md); nothing here restates a default.
441
+
442
+ ### The Redis client is yours: bound it, and close it
443
+
444
+ `RedisOtpStorage` uses the client you give it. It never connects it, configures it or quits it. A client with no bounds turns a Redis outage into requests that hang. With a connect timeout, a command timeout and a bounded retry policy, the same outage reaches the caller as the library's `503`: a command that fails because the server cannot be reached is answered as unavailable.
445
+
446
+ ```typescript
447
+ import Redis from 'ioredis'
448
+ import { RedisOtpStorage } from '@bymax-one/nest-notification'
449
+
450
+ const client = new Redis(process.env.REDIS_URL!, {
451
+ connectTimeout: 5_000,
452
+ commandTimeout: 2_000,
453
+ maxRetriesPerRequest: 1,
454
+ retryStrategy: (attempt) => Math.min(attempt * 200, 2_000)
455
+ })
456
+
457
+ const storage = new RedisOtpStorage({ redisClient: client })
458
+ ```
459
+
460
+ Close the client in your own shutdown hook, after Nest has closed the application, so no OTP operation is still running when its connection goes.
461
+
462
+ ### Bound every send
463
+
464
+ `ResendEmailProvider` takes `timeoutMs` and `SmtpEmailProvider` takes `sendTimeoutMs`, plus the phase timeouts, each with its default in the option tables. A send that times out fails with `EMAIL_SEND_FAILED`, and **may still have been delivered**: make the job that retries it idempotent, as the Apply note of 1.4.9 says.
465
+
466
+ ### Shut down cleanly
467
+
468
+ Call `app.enableShutdownHooks()`, or close the application yourself, and Nest calls `onModuleDestroy` on the providers. `SmtpEmailProvider` closes its transport there. That matters once you set `pool`: a pool keeps sockets to the relay open, and without a close they keep the process alive. `close()` is also public and idempotent. A send already in flight on a pooled transport finishes; one still waiting for a connection fails with `Connection pool was closed`. A `send()` after `close()` builds a new transport, which you have to close again if you keep the provider alive. A failing close is logged as `[SMTP_CLOSE_FAILED]` with no text from the relay and does not stop the other hooks.
469
+
470
+ ### Store codes as digests
471
+
472
+ Without `otp.codeSecret`, codes are stored in plaintext and the startup warning `BYMAX_NOTIFICATION_PLAINTEXT_OTP_CODES` says so. In production set it to a secret of at least 32 bytes; see [Stored codes are keyed digests](#stored-codes-are-keyed-digests-when-you-set-otpcodesecret).
473
+
438
474
  ## โš™๏ธ Configuration
439
475
 
440
476
  Configure via `forRoot(options)` or `forRootAsync({ useFactory })`. **At least one channel must be configured**, and configuring a channel the library does not implement throws at startup rather than failing on the first send. The full reference is in [`docs/technical_specification.md` ยง4](./docs/technical_specification.md); the most-used options:
@@ -461,6 +497,7 @@ Configure via `forRoot(options)` or `forRootAsync({ useFactory })`. **At least o
461
497
  | `otp` | `consumeOnVerify` | `false` | `true` deletes the code when `verify()` succeeds, once however many verifications run together (needs `IOtpStorage.deleteIfCode`); otherwise the entry is marked validated until `consume()` or its TTL. |
462
498
  | `otp` | `resendCooldownSeconds` | `60` | Anti-resend window (atomic `SET NX EX`). |
463
499
  | `otp` | `perPurpose` | `{}` | Per-purpose overrides of the above. |
500
+ | `otp` | `strictPurposes` | `false` | `true` refuses a purpose that is neither in `NOTIFICATION_PURPOSES` nor a key of `perPurpose`, before any storage call. |
464
501
  | `audit` | `repository` | โ€” (required) | Any `INotificationLogRepository`. |
465
502
  | `audit` | `swallowErrors` | `true` | Keep audit failures out of the delivery path. A swallowed failure logs `BYMAX_NOTIFICATION_AUDIT_WRITE_FAILED`, at most once a minute per channel. |
466
503
  | `audit` | `maskRecipient` | identity | Minimize recipient PII before persisting. |
@@ -587,7 +624,7 @@ The recipient is normalized before it is hashed. Surrounding whitespace is trimm
587
624
 
588
625
  ### Purposes are yours
589
626
 
590
- A purpose names a flow (`email_verification`, `password_reset`): 1 to 64 characters from `A-Z a-z 0-9 : _ -`. Every OTP operation and both reference storages refuse anything else with `notification.invalid_scope_identifier` (HTTP 400), and a `perPurpose` key outside that set stops the module at startup. The refusal never carries the value. The limits of a recipient are kept per `(tenant, recipient, purpose)`, and a purpose with no `perPurpose` entry uses the defaults, so a caller who can choose the purpose can ask for a fresh cooldown and a fresh attempt counter each time. Purposes are yours: a literal from `NOTIFICATION_PURPOSES` or your own list, never taken from the request.
627
+ A purpose names a flow (`email_verification`, `password_reset`): 1 to 64 characters from `A-Z a-z 0-9 : _ -`. Every OTP operation and both reference storages refuse anything else with `notification.invalid_scope_identifier` (HTTP 400), and a `perPurpose` key outside that set stops the module at startup. The refusal never carries the value. The limits of a recipient are kept per `(tenant, recipient, purpose)`, and a purpose with no `perPurpose` entry uses the defaults, so a caller who can choose the purpose can ask for a fresh cooldown and a fresh attempt counter each time. Purposes are yours: a literal from `NOTIFICATION_PURPOSES` or your own list, never taken from the request. If a purpose can still reach the service from outside, set `otp.strictPurposes: true`: a purpose that is neither in `NOTIFICATION_PURPOSES` nor a key of `perPurpose` is then refused the same way (`reason: 'not a registered purpose'`), so your own flows are registered with `perPurpose: { my_flow: {} }`.
591
628
 
592
629
  ### Attempt ceilings and cooldowns are atomic
593
630
 
@@ -667,7 +704,7 @@ A one-time password is a credential, so every behavior is pinned so that a regre
667
704
  | Coverage | **100%** line/branch/function/statement per file (`pnpm test:cov:all`) |
668
705
  | Mutation | Stryker score **100%** (`break: 100`), no survivors |
669
706
  | Lint | ESLint flat config + `eslint-plugin-security`, zero warnings |
670
- | Bundle budgets | server < 34.61 KB ยท shared < 4 KB ยท react < 8 KB ยท testing < 4.5 KB brotli (`pnpm size`) |
707
+ | Bundle budgets | server < 35.34 KB ยท shared < 4 KB ยท react < 8 KB ยท testing < 4.5 KB brotli (`pnpm size`) |
671
708
  | Prisma-free | `pnpm check:no-prisma` โ€” the library never imports `@prisma/client` |
672
709
  | Export map | `pnpm check:exports` โ€” `attw` against the packed tarball, ESM and CJS |
673
710
  | Supply chain | published with npm provenance (OIDC), CodeQL + OpenSSF Scorecard |
@@ -53,6 +53,15 @@ var DEFAULT_EMAIL_OPTIONS = {
53
53
  var DEFAULT_AUDIT_OPTIONS = {
54
54
  swallowErrors: true
55
55
  };
56
+
57
+ // src/server/constants/notification-purposes.ts
58
+ var NOTIFICATION_PURPOSES = {
59
+ EMAIL_VERIFICATION: "email_verification",
60
+ PASSWORD_RESET: "password_reset",
61
+ MFA_OOB: "mfa_oob",
62
+ PHONE_VERIFICATION: "phone_verification",
63
+ MAGIC_LINK: "magic_link"
64
+ };
56
65
  var CODE_DIGEST_PREFIX = "hmac-sha256:v1:";
57
66
  var MIN_CODE_SECRET_BYTES = 32;
58
67
  var CONTEXT = "bymax-notification:otp-code:v1\0";
@@ -104,6 +113,10 @@ function resolveOtp(otp) {
104
113
  );
105
114
  const perPurpose = Object.fromEntries(entries);
106
115
  const perPurposeMap = new Map(entries);
116
+ const registered = /* @__PURE__ */ new Set([
117
+ ...Object.values(NOTIFICATION_PURPOSES),
118
+ ...perPurposeMap.keys()
119
+ ]);
107
120
  return {
108
121
  defaultLength: base.length,
109
122
  defaultCodeType: base.codeType,
@@ -113,7 +126,9 @@ function resolveOtp(otp) {
113
126
  consumeOnVerify: otp.consumeOnVerify ?? DEFAULT_OTP_OPTIONS.consumeOnVerify,
114
127
  ...otp.codeSecret !== void 0 ? { digestCode: createCodeDigester(otp.codeSecret) } : {},
115
128
  perPurpose,
116
- resolveForPurpose: (purpose) => perPurposeMap.get(purpose) ?? base
129
+ resolveForPurpose: (purpose) => perPurposeMap.get(purpose) ?? base,
130
+ strictPurposes: otp.strictPurposes ?? false,
131
+ isRegisteredPurpose: (purpose) => registered.has(purpose)
117
132
  };
118
133
  }
119
134
  function resolveAudit(options) {
@@ -416,6 +431,11 @@ function purposeProblem(value) {
416
431
  }
417
432
  return PURPOSE_CHARACTERS.test(value) ? void 0 : "contains a character outside A-Z a-z 0-9 : _ -";
418
433
  }
434
+ function assertRegisteredPurpose(owner, value, isRegistered) {
435
+ if (!isRegistered(value)) {
436
+ throw refuse(owner, "purpose", "not a registered purpose");
437
+ }
438
+ }
419
439
  function assertPurpose(owner, value) {
420
440
  const problem = purposeProblem(value);
421
441
  if (problem !== void 0) {
@@ -525,6 +545,9 @@ function validateOtpOptions(otp) {
525
545
  );
526
546
  }
527
547
  }
548
+ if (otp.strictPurposes !== void 0 && typeof otp.strictPurposes !== "boolean") {
549
+ throw new Error("[BymaxNotificationModule] options.otp.strictPurposes must be a boolean");
550
+ }
528
551
  if (otp.resendCooldownSeconds !== void 0 && otp.resendCooldownSeconds < 0) {
529
552
  throw new Error(
530
553
  "[BymaxNotificationModule] options.otp.resendCooldownSeconds must be 0 or greater"
@@ -2251,6 +2274,10 @@ exports.OtpService = class OtpService {
2251
2274
  assertIdentifies("OtpService", "tenantId", ref.tenantId);
2252
2275
  assertIdentifies("OtpService", "recipient", ref.recipient);
2253
2276
  assertPurpose("OtpService", ref.purpose);
2277
+ const otp = this.options.otp;
2278
+ if (otp?.strictPurposes === true) {
2279
+ assertRegisteredPurpose("OtpService", ref.purpose, otp.isRegisteredPurpose);
2280
+ }
2254
2281
  }
2255
2282
  /**
2256
2283
  * Returns the input with its recipient replaced by the value the OTP state is keyed on.
@@ -2913,15 +2940,6 @@ exports.NotificationAuditInterceptor = __decorateClass([
2913
2940
  __decorateParam(0, common.Inject(BYMAX_NOTIFICATION_OPTIONS)),
2914
2941
  __decorateParam(1, common.Inject(BYMAX_NOTIFICATION_AUDIT_SINK))
2915
2942
  ], exports.NotificationAuditInterceptor);
2916
-
2917
- // src/server/constants/notification-purposes.ts
2918
- var NOTIFICATION_PURPOSES = {
2919
- EMAIL_VERIFICATION: "email_verification",
2920
- PASSWORD_RESET: "password_reset",
2921
- MFA_OOB: "mfa_oob",
2922
- PHONE_VERIFICATION: "phone_verification",
2923
- MAGIC_LINK: "magic_link"
2924
- };
2925
2943
  function maskEmail(address) {
2926
2944
  const at = address.lastIndexOf("@");
2927
2945
  if (at <= 0) {
@@ -3233,6 +3251,32 @@ function settleOrTimeout(call, timeoutMs) {
3233
3251
  });
3234
3252
  }
3235
3253
  var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "::1", "[::1]"]);
3254
+ function assertPool(pool) {
3255
+ if (pool === void 0) {
3256
+ return;
3257
+ }
3258
+ if (typeof pool !== "object" || pool === null) {
3259
+ throw new Error("SmtpEmailProvider: pool must be an object");
3260
+ }
3261
+ for (const [name, value] of [
3262
+ ["maxConnections", pool.maxConnections],
3263
+ ["maxMessages", pool.maxMessages]
3264
+ ]) {
3265
+ if (value !== void 0 && !(Number.isInteger(value) && value >= 1)) {
3266
+ throw new Error(`SmtpEmailProvider: pool.${name} must be a positive integer`);
3267
+ }
3268
+ }
3269
+ }
3270
+ function poolConfig(pool) {
3271
+ if (pool === void 0) {
3272
+ return {};
3273
+ }
3274
+ return {
3275
+ pool: true,
3276
+ ...pool.maxConnections === void 0 ? {} : { maxConnections: pool.maxConnections },
3277
+ ...pool.maxMessages === void 0 ? {} : { maxMessages: pool.maxMessages }
3278
+ };
3279
+ }
3236
3280
  function areCredentialsComplete(credentials) {
3237
3281
  return Boolean(credentials.user) && Boolean(credentials.pass);
3238
3282
  }
@@ -3271,6 +3315,7 @@ exports.SmtpEmailProvider = class SmtpEmailProvider {
3271
3315
  `SmtpEmailProvider: sendTimeoutMs must be a positive integer of at most ${String(MAX_SEND_TIMEOUT_MS)}`
3272
3316
  );
3273
3317
  }
3318
+ assertPool(options.pool);
3274
3319
  __privateSet(this, _options2, options);
3275
3320
  }
3276
3321
  /**
@@ -3333,6 +3378,38 @@ exports.SmtpEmailProvider = class SmtpEmailProvider {
3333
3378
  }
3334
3379
  return { messageId: info.messageId };
3335
3380
  }
3381
+ /**
3382
+ * Closes the transport this provider built, so a pooled connection does not keep the process
3383
+ * alive. A send already in flight on a pooled transport finishes; one still waiting for a
3384
+ * connection fails with `Connection pool was closed`. Idempotent, and it never builds a transport
3385
+ * to close it. A `send()` after it builds a new transport, which the host has to close again if it
3386
+ * keeps the provider alive.
3387
+ *
3388
+ * A close that throws is logged as a fixed line and not rethrown, so one failure cannot stop the
3389
+ * other shutdown hooks of the application.
3390
+ */
3391
+ async close() {
3392
+ const pending = __privateGet(this, _transportPromise);
3393
+ __privateSet(this, _transportPromise, null);
3394
+ if (pending === null) {
3395
+ return;
3396
+ }
3397
+ let transport;
3398
+ try {
3399
+ transport = await pending;
3400
+ } catch {
3401
+ return;
3402
+ }
3403
+ try {
3404
+ transport.close?.();
3405
+ } catch {
3406
+ this.logger.warn("[SMTP_CLOSE_FAILED] The transport could not be closed.");
3407
+ }
3408
+ }
3409
+ /** Nest calls this when the application closes; it closes the transport. */
3410
+ async onModuleDestroy() {
3411
+ await this.close();
3412
+ }
3336
3413
  /**
3337
3414
  * Hands the payload to the transport, converting a transport failure into a plain
3338
3415
  * `Error` whose message has the SMTP password scrubbed out. The email body is
@@ -3537,31 +3614,37 @@ exports.SmtpEmailProvider = class SmtpEmailProvider {
3537
3614
  * Returns the cached transport, lazily importing `nodemailer` on first use.
3538
3615
  * Concurrent first calls share one in-flight initialization promise so the dynamic
3539
3616
  * import and creation run exactly once; a failed init is dropped from the cache so
3540
- * a later call can retry instead of being permanently bricked.
3617
+ * a later call can retry instead of being permanently bricked. It is dropped only while
3618
+ * it is still the cached build: `close()` may have taken it, and a newer send may have
3619
+ * started a build of its own, which a late failure here must not clear.
3541
3620
  *
3542
3621
  * @returns The initialized transport.
3543
3622
  * @throws Error When the configuration is incomplete or `nodemailer` is missing.
3544
3623
  */
3545
3624
  getTransport() {
3546
- __privateGet(this, _transportPromise) ?? __privateSet(this, _transportPromise, this.createTransport());
3547
- return __privateGet(this, _transportPromise);
3625
+ const cached = __privateGet(this, _transportPromise);
3626
+ if (cached !== null) {
3627
+ return cached;
3628
+ }
3629
+ const build = this.createTransport();
3630
+ __privateSet(this, _transportPromise, build);
3631
+ build.catch(() => {
3632
+ if (__privateGet(this, _transportPromise) === build) {
3633
+ __privateSet(this, _transportPromise, null);
3634
+ }
3635
+ });
3636
+ return build;
3548
3637
  }
3549
3638
  /**
3550
- * Builds a fresh transport, resetting the cached promise on any failure so the
3551
- * provider is not permanently bricked by a transient init error.
3639
+ * Builds a fresh transport.
3552
3640
  *
3553
3641
  * @returns The initialized transport.
3554
3642
  * @throws Error When the configuration is incomplete or `nodemailer` is missing.
3555
3643
  */
3556
3644
  async createTransport() {
3557
- try {
3558
- const config = this.buildTransportConfig();
3559
- const nodemailer = await this.loadNodemailer();
3560
- return this.instantiate(nodemailer, config);
3561
- } catch (error) {
3562
- __privateSet(this, _transportPromise, null);
3563
- throw error;
3564
- }
3645
+ const config = this.buildTransportConfig();
3646
+ const nodemailer = await this.loadNodemailer();
3647
+ return this.instantiate(nodemailer, config);
3565
3648
  }
3566
3649
  /**
3567
3650
  * Calls into Nodemailer to build the transport, scrubbing the password out of a
@@ -3633,7 +3716,8 @@ exports.SmtpEmailProvider = class SmtpEmailProvider {
3633
3716
  tls: options.tls,
3634
3717
  connectionTimeout: options.connectionTimeout ?? DEFAULT_CONNECTION_TIMEOUT_MS,
3635
3718
  greetingTimeout: options.greetingTimeout ?? DEFAULT_GREETING_TIMEOUT_MS,
3636
- socketTimeout: options.socketTimeout ?? DEFAULT_SOCKET_TIMEOUT_MS
3719
+ socketTimeout: options.socketTimeout ?? DEFAULT_SOCKET_TIMEOUT_MS,
3720
+ ...poolConfig(options.pool)
3637
3721
  };
3638
3722
  }
3639
3723
  /**
@@ -1,4 +1,4 @@
1
- import { ModuleMetadata, FactoryProvider, DynamicModule, OnModuleInit, NestInterceptor, ExecutionContext, CallHandler, HttpStatus, HttpException } from '@nestjs/common';
1
+ import { ModuleMetadata, FactoryProvider, DynamicModule, OnModuleInit, NestInterceptor, ExecutionContext, CallHandler, OnModuleDestroy, HttpStatus, HttpException } from '@nestjs/common';
2
2
  import { Observable } from 'rxjs';
3
3
 
4
4
  /**
@@ -598,6 +598,15 @@ interface OtpChannelOptions {
598
598
  codeSecret?: string;
599
599
  /** Per-purpose overrides of the defaults above. */
600
600
  perPurpose?: Record<string, Partial<OtpPurposeConfig>>;
601
+ /**
602
+ * When `true`, an OTP operation whose purpose is neither one of the five in
603
+ * `NOTIFICATION_PURPOSES` nor a key of `perPurpose` is refused with
604
+ * `INVALID_SCOPE_IDENTIFIER`, before any storage call. A purpose is part of the scope the limits
605
+ * are kept on, so a host that lets a caller choose it lets the caller ask for a fresh cooldown and
606
+ * attempt counter each time; this closes that without the host checking the purpose itself.
607
+ * Default: `false`.
608
+ */
609
+ strictPurposes?: boolean;
601
610
  }
602
611
  /**
603
612
  * SMS channel configuration.
@@ -805,6 +814,10 @@ interface ResolvedOtpOptions {
805
814
  perPurpose: Record<string, OtpPurposeConfig>;
806
815
  /** Effective config for a purpose: the resolved `perPurpose[purpose]`, or the OTP defaults. */
807
816
  resolveForPurpose(purpose: string): OtpPurposeConfig;
817
+ /** Whether an operation whose purpose is not registered is refused. */
818
+ strictPurposes: boolean;
819
+ /** Whether `purpose` is one of the canonical purposes or a key of `perPurpose`. */
820
+ isRegisteredPurpose(purpose: string): boolean;
808
821
  }
809
822
  /** Resolved audit section โ€” always present; the no-op sink obeys these settings too. */
810
823
  interface ResolvedAuditOptions {
@@ -1835,26 +1848,11 @@ declare class ResendEmailProvider implements IEmailProvider {
1835
1848
  }
1836
1849
 
1837
1850
  /**
1838
- * @fileoverview Reference `IEmailProvider` adapter speaking SMTP through Nodemailer.
1851
+ * @fileoverview The option types of `SmtpEmailProvider` and the shapes it exchanges with
1852
+ * Nodemailer. Types only; the provider re-exports the public ones, so an import from
1853
+ * `./smtp-email.provider` keeps working.
1839
1854
  * @layer infrastructure
1840
- *
1841
- * SMTP is the protocol every relay, Postfix, corporate gateway, SES-via-SMTP and
1842
- * mail-capture server (Mailpit, MailHog) understands, so this adapter serves both
1843
- * production delivery and the end-to-end tests a consumer needs to exercise its
1844
- * email flows.
1845
- *
1846
- * `nodemailer` is an OPTIONAL peer dependency: it is loaded lazily via a dynamic
1847
- * `import()` the first time `send()` runs, so a consumer who picks a different
1848
- * transport never has to install it. The adapter forward-declares the slim shape it
1849
- * needs instead of importing `nodemailer` at compile time, keeping the library free
1850
- * of a hard dependency on its types.
1851
- *
1852
- * Security: the email body (`html` / `text`) may carry OTP codes or PII โ€” it is
1853
- * NEVER logged. The SMTP password is held in an ECMAScript private field so it
1854
- * cannot be walked by a serializer, and is scrubbed from any transport error before
1855
- * that error is logged or re-thrown.
1856
1855
  */
1857
-
1858
1856
  /** TLS knobs forwarded to the transport, for relays using a private CA. */
1859
1857
  interface SmtpTlsOptions {
1860
1858
  /**
@@ -1934,7 +1932,46 @@ interface SmtpEmailProviderOptions {
1934
1932
  * message was not sent. The connection is left open: `socketTimeout` reaps it once the relay goes idle; a relay that keeps sending holds it until the relay ends the connection or the process exits.
1935
1933
  */
1936
1934
  sendTimeoutMs?: number;
1935
+ /**
1936
+ * Keeps connections to the relay open and reuses them, instead of one connection per send.
1937
+ * Setting it, even to `{}`, turns Nodemailer's pooled mode on; each limit left out keeps
1938
+ * Nodemailer's own default. Each is an integer of at least `1`.
1939
+ *
1940
+ * A pool holds sockets open, so close it with {@link SmtpEmailProvider.close} when the application
1941
+ * stops; Nest does that for you when the application closes. `sendTimeoutMs` also covers the wait
1942
+ * for a free connection.
1943
+ */
1944
+ pool?: SmtpPoolOptions;
1945
+ }
1946
+ /** The limits of a pooled transport; each left out keeps Nodemailer's default. */
1947
+ interface SmtpPoolOptions {
1948
+ /** Most connections open to the relay at once. An integer of at least `1`. */
1949
+ maxConnections?: number;
1950
+ /** Most messages sent over one connection before it is replaced. An integer of at least `1`. */
1951
+ maxMessages?: number;
1937
1952
  }
1953
+
1954
+ /**
1955
+ * @fileoverview Reference `IEmailProvider` adapter speaking SMTP through Nodemailer.
1956
+ * @layer infrastructure
1957
+ *
1958
+ * SMTP is the protocol every relay, Postfix, corporate gateway, SES-via-SMTP and
1959
+ * mail-capture server (Mailpit, MailHog) understands, so this adapter serves both
1960
+ * production delivery and the end-to-end tests a consumer needs to exercise its
1961
+ * email flows.
1962
+ *
1963
+ * `nodemailer` is an OPTIONAL peer dependency: it is loaded lazily via a dynamic
1964
+ * `import()` the first time `send()` runs, so a consumer who picks a different
1965
+ * transport never has to install it. The adapter forward-declares the slim shape it
1966
+ * needs instead of importing `nodemailer` at compile time, keeping the library free
1967
+ * of a hard dependency on its types.
1968
+ *
1969
+ * Security: the email body (`html` / `text`) may carry OTP codes or PII โ€” it is
1970
+ * NEVER logged. The SMTP password is held in an ECMAScript private field so it
1971
+ * cannot be walked by a serializer, and is scrubbed from any transport error before
1972
+ * that error is logged or re-thrown.
1973
+ */
1974
+
1938
1975
  /**
1939
1976
  * Reference {@link IEmailProvider} speaking SMTP.
1940
1977
  *
@@ -1961,7 +1998,7 @@ interface SmtpEmailProviderOptions {
1961
1998
  * @remarks `EmailSendOptions.tags` are not forwarded: SMTP has no tag facility.
1962
1999
  * They still reach the audit log through `EmailService`.
1963
2000
  */
1964
- declare class SmtpEmailProvider implements IEmailProvider {
2001
+ declare class SmtpEmailProvider implements IEmailProvider, OnModuleDestroy {
1965
2002
  #private;
1966
2003
  readonly name = "smtp";
1967
2004
  private readonly logger;
@@ -1997,6 +2034,19 @@ declare class SmtpEmailProvider implements IEmailProvider {
1997
2034
  * comes back. `EmailService` maps any thrown `Error` to `EMAIL_SEND_FAILED`.
1998
2035
  */
1999
2036
  send(options: EmailSendOptions): Promise<EmailSendResult>;
2037
+ /**
2038
+ * Closes the transport this provider built, so a pooled connection does not keep the process
2039
+ * alive. A send already in flight on a pooled transport finishes; one still waiting for a
2040
+ * connection fails with `Connection pool was closed`. Idempotent, and it never builds a transport
2041
+ * to close it. A `send()` after it builds a new transport, which the host has to close again if it
2042
+ * keeps the provider alive.
2043
+ *
2044
+ * A close that throws is logged as a fixed line and not rethrown, so one failure cannot stop the
2045
+ * other shutdown hooks of the application.
2046
+ */
2047
+ close(): Promise<void>;
2048
+ /** Nest calls this when the application closes; it closes the transport. */
2049
+ onModuleDestroy(): Promise<void>;
2000
2050
  /**
2001
2051
  * Hands the payload to the transport, converting a transport failure into a plain
2002
2052
  * `Error` whose message has the SMTP password scrubbed out. The email body is
@@ -2122,15 +2172,16 @@ declare class SmtpEmailProvider implements IEmailProvider {
2122
2172
  * Returns the cached transport, lazily importing `nodemailer` on first use.
2123
2173
  * Concurrent first calls share one in-flight initialization promise so the dynamic
2124
2174
  * import and creation run exactly once; a failed init is dropped from the cache so
2125
- * a later call can retry instead of being permanently bricked.
2175
+ * a later call can retry instead of being permanently bricked. It is dropped only while
2176
+ * it is still the cached build: `close()` may have taken it, and a newer send may have
2177
+ * started a build of its own, which a late failure here must not clear.
2126
2178
  *
2127
2179
  * @returns The initialized transport.
2128
2180
  * @throws Error When the configuration is incomplete or `nodemailer` is missing.
2129
2181
  */
2130
2182
  private getTransport;
2131
2183
  /**
2132
- * Builds a fresh transport, resetting the cached promise on any failure so the
2133
- * provider is not permanently bricked by a transient init error.
2184
+ * Builds a fresh transport.
2134
2185
  *
2135
2186
  * @returns The initialized transport.
2136
2187
  * @throws Error When the configuration is incomplete or `nodemailer` is missing.
@@ -3046,4 +3097,4 @@ declare const DEFAULT_TTLS: {
3046
3097
  };
3047
3098
 
3048
3099
  export { BYMAX_NOTIFICATION_EMAIL_PROVIDER, BYMAX_NOTIFICATION_LOG_REPOSITORY, BYMAX_NOTIFICATION_OPTIONS, BYMAX_NOTIFICATION_OTP_STORAGE, BYMAX_NOTIFICATION_PUSH_PROVIDER, BYMAX_NOTIFICATION_SMS_PROVIDER, BYMAX_NOTIFICATION_TEMPLATE_RENDERER, BymaxNotificationModule, CANONICAL_EMAIL_TEMPLATES, DEFAULT_TTLS, DefaultTemplateRenderer, EmailService, InMemoryOtpStorage, NOTIFICATION_ERROR_CODES, NOTIFICATION_ERROR_DEFINITIONS, NOTIFICATION_PURPOSES, NoOpEmailProvider, NoOpNotificationLogRepository, NotificationAuditInterceptor, NotificationException, NotificationService, OtpService, RedisOtpStorage, ResendEmailProvider, SmtpEmailProvider, cooldownExpiresAt, formatCooldown, generateOtpCode, hashTenantRecipient, safeCompare, toRetryAfterHeader };
3049
- export type { AuditOptions, BymaxNotificationModuleAsyncOptions, BymaxNotificationModuleOptions, BymaxNotificationModuleOptionsFactory, CanonicalEmailTemplate, CanonicalNotificationPurpose, ConsumeAttemptResult, DefaultTemplateRendererOptions, DispatchInput, DispatchResult, EmailAttachment, EmailChannelOptions, EmailDispatchPayload, EmailSendInput, EmailSendOptions, EmailSendResult, EmailSendTemplateInput, GlobalOptions, IEmailProvider, IEmailTemplateRenderer, INotificationLogRepository, IOtpStorage, IPushProvider, ISmsProvider, InMemoryStorageSize, MissingVariableMode, NotificationChannel, NotificationErrorCode, NotificationErrorDefinition, NotificationErrorKey, NotificationErrorResponse, NotificationExceptionOptions, NotificationLogEntry, NotificationLogVerb, NotificationRequest, OtpChannelOptions, OtpConsumeInput, OtpDispatchPayload, OtpEntry, OtpGenerateInput, OtpGenerateResult, OtpPurpose, OtpPurposeConfig, OtpStatusInput, OtpStatusResult, OtpVerifyInput, OtpVerifyResult, PushChannelOptions, PushSendOptions, PushSendResult, RedisLike, RedisOtpStorageOptions, RenderedEmail, ResendEmailProviderOptions, ResolvedAuditOptions, ResolvedEmailOptions, ResolvedGlobalOptions, ResolvedNotificationOptions, ResolvedOtpOptions, SmsChannelOptions, SmsSendOptions, SmsSendResult, SmtpCredentials, SmtpEmailProviderOptions, SmtpTlsOptions, TemplateDefinition };
3100
+ export type { AuditOptions, BymaxNotificationModuleAsyncOptions, BymaxNotificationModuleOptions, BymaxNotificationModuleOptionsFactory, CanonicalEmailTemplate, CanonicalNotificationPurpose, ConsumeAttemptResult, DefaultTemplateRendererOptions, DispatchInput, DispatchResult, EmailAttachment, EmailChannelOptions, EmailDispatchPayload, EmailSendInput, EmailSendOptions, EmailSendResult, EmailSendTemplateInput, GlobalOptions, IEmailProvider, IEmailTemplateRenderer, INotificationLogRepository, IOtpStorage, IPushProvider, ISmsProvider, InMemoryStorageSize, MissingVariableMode, NotificationChannel, NotificationErrorCode, NotificationErrorDefinition, NotificationErrorKey, NotificationErrorResponse, NotificationExceptionOptions, NotificationLogEntry, NotificationLogVerb, NotificationRequest, OtpChannelOptions, OtpConsumeInput, OtpDispatchPayload, OtpEntry, OtpGenerateInput, OtpGenerateResult, OtpPurpose, OtpPurposeConfig, OtpStatusInput, OtpStatusResult, OtpVerifyInput, OtpVerifyResult, PushChannelOptions, PushSendOptions, PushSendResult, RedisLike, RedisOtpStorageOptions, RenderedEmail, ResendEmailProviderOptions, ResolvedAuditOptions, ResolvedEmailOptions, ResolvedGlobalOptions, ResolvedNotificationOptions, ResolvedOtpOptions, SmsChannelOptions, SmsSendOptions, SmsSendResult, SmtpCredentials, SmtpEmailProviderOptions, SmtpPoolOptions, SmtpTlsOptions, TemplateDefinition };
@@ -1,4 +1,4 @@
1
- import { ModuleMetadata, FactoryProvider, DynamicModule, OnModuleInit, NestInterceptor, ExecutionContext, CallHandler, HttpStatus, HttpException } from '@nestjs/common';
1
+ import { ModuleMetadata, FactoryProvider, DynamicModule, OnModuleInit, NestInterceptor, ExecutionContext, CallHandler, OnModuleDestroy, HttpStatus, HttpException } from '@nestjs/common';
2
2
  import { Observable } from 'rxjs';
3
3
 
4
4
  /**
@@ -598,6 +598,15 @@ interface OtpChannelOptions {
598
598
  codeSecret?: string;
599
599
  /** Per-purpose overrides of the defaults above. */
600
600
  perPurpose?: Record<string, Partial<OtpPurposeConfig>>;
601
+ /**
602
+ * When `true`, an OTP operation whose purpose is neither one of the five in
603
+ * `NOTIFICATION_PURPOSES` nor a key of `perPurpose` is refused with
604
+ * `INVALID_SCOPE_IDENTIFIER`, before any storage call. A purpose is part of the scope the limits
605
+ * are kept on, so a host that lets a caller choose it lets the caller ask for a fresh cooldown and
606
+ * attempt counter each time; this closes that without the host checking the purpose itself.
607
+ * Default: `false`.
608
+ */
609
+ strictPurposes?: boolean;
601
610
  }
602
611
  /**
603
612
  * SMS channel configuration.
@@ -805,6 +814,10 @@ interface ResolvedOtpOptions {
805
814
  perPurpose: Record<string, OtpPurposeConfig>;
806
815
  /** Effective config for a purpose: the resolved `perPurpose[purpose]`, or the OTP defaults. */
807
816
  resolveForPurpose(purpose: string): OtpPurposeConfig;
817
+ /** Whether an operation whose purpose is not registered is refused. */
818
+ strictPurposes: boolean;
819
+ /** Whether `purpose` is one of the canonical purposes or a key of `perPurpose`. */
820
+ isRegisteredPurpose(purpose: string): boolean;
808
821
  }
809
822
  /** Resolved audit section โ€” always present; the no-op sink obeys these settings too. */
810
823
  interface ResolvedAuditOptions {
@@ -1835,26 +1848,11 @@ declare class ResendEmailProvider implements IEmailProvider {
1835
1848
  }
1836
1849
 
1837
1850
  /**
1838
- * @fileoverview Reference `IEmailProvider` adapter speaking SMTP through Nodemailer.
1851
+ * @fileoverview The option types of `SmtpEmailProvider` and the shapes it exchanges with
1852
+ * Nodemailer. Types only; the provider re-exports the public ones, so an import from
1853
+ * `./smtp-email.provider` keeps working.
1839
1854
  * @layer infrastructure
1840
- *
1841
- * SMTP is the protocol every relay, Postfix, corporate gateway, SES-via-SMTP and
1842
- * mail-capture server (Mailpit, MailHog) understands, so this adapter serves both
1843
- * production delivery and the end-to-end tests a consumer needs to exercise its
1844
- * email flows.
1845
- *
1846
- * `nodemailer` is an OPTIONAL peer dependency: it is loaded lazily via a dynamic
1847
- * `import()` the first time `send()` runs, so a consumer who picks a different
1848
- * transport never has to install it. The adapter forward-declares the slim shape it
1849
- * needs instead of importing `nodemailer` at compile time, keeping the library free
1850
- * of a hard dependency on its types.
1851
- *
1852
- * Security: the email body (`html` / `text`) may carry OTP codes or PII โ€” it is
1853
- * NEVER logged. The SMTP password is held in an ECMAScript private field so it
1854
- * cannot be walked by a serializer, and is scrubbed from any transport error before
1855
- * that error is logged or re-thrown.
1856
1855
  */
1857
-
1858
1856
  /** TLS knobs forwarded to the transport, for relays using a private CA. */
1859
1857
  interface SmtpTlsOptions {
1860
1858
  /**
@@ -1934,7 +1932,46 @@ interface SmtpEmailProviderOptions {
1934
1932
  * message was not sent. The connection is left open: `socketTimeout` reaps it once the relay goes idle; a relay that keeps sending holds it until the relay ends the connection or the process exits.
1935
1933
  */
1936
1934
  sendTimeoutMs?: number;
1935
+ /**
1936
+ * Keeps connections to the relay open and reuses them, instead of one connection per send.
1937
+ * Setting it, even to `{}`, turns Nodemailer's pooled mode on; each limit left out keeps
1938
+ * Nodemailer's own default. Each is an integer of at least `1`.
1939
+ *
1940
+ * A pool holds sockets open, so close it with {@link SmtpEmailProvider.close} when the application
1941
+ * stops; Nest does that for you when the application closes. `sendTimeoutMs` also covers the wait
1942
+ * for a free connection.
1943
+ */
1944
+ pool?: SmtpPoolOptions;
1945
+ }
1946
+ /** The limits of a pooled transport; each left out keeps Nodemailer's default. */
1947
+ interface SmtpPoolOptions {
1948
+ /** Most connections open to the relay at once. An integer of at least `1`. */
1949
+ maxConnections?: number;
1950
+ /** Most messages sent over one connection before it is replaced. An integer of at least `1`. */
1951
+ maxMessages?: number;
1937
1952
  }
1953
+
1954
+ /**
1955
+ * @fileoverview Reference `IEmailProvider` adapter speaking SMTP through Nodemailer.
1956
+ * @layer infrastructure
1957
+ *
1958
+ * SMTP is the protocol every relay, Postfix, corporate gateway, SES-via-SMTP and
1959
+ * mail-capture server (Mailpit, MailHog) understands, so this adapter serves both
1960
+ * production delivery and the end-to-end tests a consumer needs to exercise its
1961
+ * email flows.
1962
+ *
1963
+ * `nodemailer` is an OPTIONAL peer dependency: it is loaded lazily via a dynamic
1964
+ * `import()` the first time `send()` runs, so a consumer who picks a different
1965
+ * transport never has to install it. The adapter forward-declares the slim shape it
1966
+ * needs instead of importing `nodemailer` at compile time, keeping the library free
1967
+ * of a hard dependency on its types.
1968
+ *
1969
+ * Security: the email body (`html` / `text`) may carry OTP codes or PII โ€” it is
1970
+ * NEVER logged. The SMTP password is held in an ECMAScript private field so it
1971
+ * cannot be walked by a serializer, and is scrubbed from any transport error before
1972
+ * that error is logged or re-thrown.
1973
+ */
1974
+
1938
1975
  /**
1939
1976
  * Reference {@link IEmailProvider} speaking SMTP.
1940
1977
  *
@@ -1961,7 +1998,7 @@ interface SmtpEmailProviderOptions {
1961
1998
  * @remarks `EmailSendOptions.tags` are not forwarded: SMTP has no tag facility.
1962
1999
  * They still reach the audit log through `EmailService`.
1963
2000
  */
1964
- declare class SmtpEmailProvider implements IEmailProvider {
2001
+ declare class SmtpEmailProvider implements IEmailProvider, OnModuleDestroy {
1965
2002
  #private;
1966
2003
  readonly name = "smtp";
1967
2004
  private readonly logger;
@@ -1997,6 +2034,19 @@ declare class SmtpEmailProvider implements IEmailProvider {
1997
2034
  * comes back. `EmailService` maps any thrown `Error` to `EMAIL_SEND_FAILED`.
1998
2035
  */
1999
2036
  send(options: EmailSendOptions): Promise<EmailSendResult>;
2037
+ /**
2038
+ * Closes the transport this provider built, so a pooled connection does not keep the process
2039
+ * alive. A send already in flight on a pooled transport finishes; one still waiting for a
2040
+ * connection fails with `Connection pool was closed`. Idempotent, and it never builds a transport
2041
+ * to close it. A `send()` after it builds a new transport, which the host has to close again if it
2042
+ * keeps the provider alive.
2043
+ *
2044
+ * A close that throws is logged as a fixed line and not rethrown, so one failure cannot stop the
2045
+ * other shutdown hooks of the application.
2046
+ */
2047
+ close(): Promise<void>;
2048
+ /** Nest calls this when the application closes; it closes the transport. */
2049
+ onModuleDestroy(): Promise<void>;
2000
2050
  /**
2001
2051
  * Hands the payload to the transport, converting a transport failure into a plain
2002
2052
  * `Error` whose message has the SMTP password scrubbed out. The email body is
@@ -2122,15 +2172,16 @@ declare class SmtpEmailProvider implements IEmailProvider {
2122
2172
  * Returns the cached transport, lazily importing `nodemailer` on first use.
2123
2173
  * Concurrent first calls share one in-flight initialization promise so the dynamic
2124
2174
  * import and creation run exactly once; a failed init is dropped from the cache so
2125
- * a later call can retry instead of being permanently bricked.
2175
+ * a later call can retry instead of being permanently bricked. It is dropped only while
2176
+ * it is still the cached build: `close()` may have taken it, and a newer send may have
2177
+ * started a build of its own, which a late failure here must not clear.
2126
2178
  *
2127
2179
  * @returns The initialized transport.
2128
2180
  * @throws Error When the configuration is incomplete or `nodemailer` is missing.
2129
2181
  */
2130
2182
  private getTransport;
2131
2183
  /**
2132
- * Builds a fresh transport, resetting the cached promise on any failure so the
2133
- * provider is not permanently bricked by a transient init error.
2184
+ * Builds a fresh transport.
2134
2185
  *
2135
2186
  * @returns The initialized transport.
2136
2187
  * @throws Error When the configuration is incomplete or `nodemailer` is missing.
@@ -3046,4 +3097,4 @@ declare const DEFAULT_TTLS: {
3046
3097
  };
3047
3098
 
3048
3099
  export { BYMAX_NOTIFICATION_EMAIL_PROVIDER, BYMAX_NOTIFICATION_LOG_REPOSITORY, BYMAX_NOTIFICATION_OPTIONS, BYMAX_NOTIFICATION_OTP_STORAGE, BYMAX_NOTIFICATION_PUSH_PROVIDER, BYMAX_NOTIFICATION_SMS_PROVIDER, BYMAX_NOTIFICATION_TEMPLATE_RENDERER, BymaxNotificationModule, CANONICAL_EMAIL_TEMPLATES, DEFAULT_TTLS, DefaultTemplateRenderer, EmailService, InMemoryOtpStorage, NOTIFICATION_ERROR_CODES, NOTIFICATION_ERROR_DEFINITIONS, NOTIFICATION_PURPOSES, NoOpEmailProvider, NoOpNotificationLogRepository, NotificationAuditInterceptor, NotificationException, NotificationService, OtpService, RedisOtpStorage, ResendEmailProvider, SmtpEmailProvider, cooldownExpiresAt, formatCooldown, generateOtpCode, hashTenantRecipient, safeCompare, toRetryAfterHeader };
3049
- export type { AuditOptions, BymaxNotificationModuleAsyncOptions, BymaxNotificationModuleOptions, BymaxNotificationModuleOptionsFactory, CanonicalEmailTemplate, CanonicalNotificationPurpose, ConsumeAttemptResult, DefaultTemplateRendererOptions, DispatchInput, DispatchResult, EmailAttachment, EmailChannelOptions, EmailDispatchPayload, EmailSendInput, EmailSendOptions, EmailSendResult, EmailSendTemplateInput, GlobalOptions, IEmailProvider, IEmailTemplateRenderer, INotificationLogRepository, IOtpStorage, IPushProvider, ISmsProvider, InMemoryStorageSize, MissingVariableMode, NotificationChannel, NotificationErrorCode, NotificationErrorDefinition, NotificationErrorKey, NotificationErrorResponse, NotificationExceptionOptions, NotificationLogEntry, NotificationLogVerb, NotificationRequest, OtpChannelOptions, OtpConsumeInput, OtpDispatchPayload, OtpEntry, OtpGenerateInput, OtpGenerateResult, OtpPurpose, OtpPurposeConfig, OtpStatusInput, OtpStatusResult, OtpVerifyInput, OtpVerifyResult, PushChannelOptions, PushSendOptions, PushSendResult, RedisLike, RedisOtpStorageOptions, RenderedEmail, ResendEmailProviderOptions, ResolvedAuditOptions, ResolvedEmailOptions, ResolvedGlobalOptions, ResolvedNotificationOptions, ResolvedOtpOptions, SmsChannelOptions, SmsSendOptions, SmsSendResult, SmtpCredentials, SmtpEmailProviderOptions, SmtpTlsOptions, TemplateDefinition };
3100
+ export type { AuditOptions, BymaxNotificationModuleAsyncOptions, BymaxNotificationModuleOptions, BymaxNotificationModuleOptionsFactory, CanonicalEmailTemplate, CanonicalNotificationPurpose, ConsumeAttemptResult, DefaultTemplateRendererOptions, DispatchInput, DispatchResult, EmailAttachment, EmailChannelOptions, EmailDispatchPayload, EmailSendInput, EmailSendOptions, EmailSendResult, EmailSendTemplateInput, GlobalOptions, IEmailProvider, IEmailTemplateRenderer, INotificationLogRepository, IOtpStorage, IPushProvider, ISmsProvider, InMemoryStorageSize, MissingVariableMode, NotificationChannel, NotificationErrorCode, NotificationErrorDefinition, NotificationErrorKey, NotificationErrorResponse, NotificationExceptionOptions, NotificationLogEntry, NotificationLogVerb, NotificationRequest, OtpChannelOptions, OtpConsumeInput, OtpDispatchPayload, OtpEntry, OtpGenerateInput, OtpGenerateResult, OtpPurpose, OtpPurposeConfig, OtpStatusInput, OtpStatusResult, OtpVerifyInput, OtpVerifyResult, PushChannelOptions, PushSendOptions, PushSendResult, RedisLike, RedisOtpStorageOptions, RenderedEmail, ResendEmailProviderOptions, ResolvedAuditOptions, ResolvedEmailOptions, ResolvedGlobalOptions, ResolvedNotificationOptions, ResolvedOtpOptions, SmsChannelOptions, SmsSendOptions, SmsSendResult, SmtpCredentials, SmtpEmailProviderOptions, SmtpPoolOptions, SmtpTlsOptions, TemplateDefinition };
@@ -51,6 +51,15 @@ var DEFAULT_EMAIL_OPTIONS = {
51
51
  var DEFAULT_AUDIT_OPTIONS = {
52
52
  swallowErrors: true
53
53
  };
54
+
55
+ // src/server/constants/notification-purposes.ts
56
+ var NOTIFICATION_PURPOSES = {
57
+ EMAIL_VERIFICATION: "email_verification",
58
+ PASSWORD_RESET: "password_reset",
59
+ MFA_OOB: "mfa_oob",
60
+ PHONE_VERIFICATION: "phone_verification",
61
+ MAGIC_LINK: "magic_link"
62
+ };
54
63
  var CODE_DIGEST_PREFIX = "hmac-sha256:v1:";
55
64
  var MIN_CODE_SECRET_BYTES = 32;
56
65
  var CONTEXT = "bymax-notification:otp-code:v1\0";
@@ -102,6 +111,10 @@ function resolveOtp(otp) {
102
111
  );
103
112
  const perPurpose = Object.fromEntries(entries);
104
113
  const perPurposeMap = new Map(entries);
114
+ const registered = /* @__PURE__ */ new Set([
115
+ ...Object.values(NOTIFICATION_PURPOSES),
116
+ ...perPurposeMap.keys()
117
+ ]);
105
118
  return {
106
119
  defaultLength: base.length,
107
120
  defaultCodeType: base.codeType,
@@ -111,7 +124,9 @@ function resolveOtp(otp) {
111
124
  consumeOnVerify: otp.consumeOnVerify ?? DEFAULT_OTP_OPTIONS.consumeOnVerify,
112
125
  ...otp.codeSecret !== void 0 ? { digestCode: createCodeDigester(otp.codeSecret) } : {},
113
126
  perPurpose,
114
- resolveForPurpose: (purpose) => perPurposeMap.get(purpose) ?? base
127
+ resolveForPurpose: (purpose) => perPurposeMap.get(purpose) ?? base,
128
+ strictPurposes: otp.strictPurposes ?? false,
129
+ isRegisteredPurpose: (purpose) => registered.has(purpose)
115
130
  };
116
131
  }
117
132
  function resolveAudit(options) {
@@ -414,6 +429,11 @@ function purposeProblem(value) {
414
429
  }
415
430
  return PURPOSE_CHARACTERS.test(value) ? void 0 : "contains a character outside A-Z a-z 0-9 : _ -";
416
431
  }
432
+ function assertRegisteredPurpose(owner, value, isRegistered) {
433
+ if (!isRegistered(value)) {
434
+ throw refuse(owner, "purpose", "not a registered purpose");
435
+ }
436
+ }
417
437
  function assertPurpose(owner, value) {
418
438
  const problem = purposeProblem(value);
419
439
  if (problem !== void 0) {
@@ -523,6 +543,9 @@ function validateOtpOptions(otp) {
523
543
  );
524
544
  }
525
545
  }
546
+ if (otp.strictPurposes !== void 0 && typeof otp.strictPurposes !== "boolean") {
547
+ throw new Error("[BymaxNotificationModule] options.otp.strictPurposes must be a boolean");
548
+ }
526
549
  if (otp.resendCooldownSeconds !== void 0 && otp.resendCooldownSeconds < 0) {
527
550
  throw new Error(
528
551
  "[BymaxNotificationModule] options.otp.resendCooldownSeconds must be 0 or greater"
@@ -2249,6 +2272,10 @@ var OtpService = class {
2249
2272
  assertIdentifies("OtpService", "tenantId", ref.tenantId);
2250
2273
  assertIdentifies("OtpService", "recipient", ref.recipient);
2251
2274
  assertPurpose("OtpService", ref.purpose);
2275
+ const otp = this.options.otp;
2276
+ if (otp?.strictPurposes === true) {
2277
+ assertRegisteredPurpose("OtpService", ref.purpose, otp.isRegisteredPurpose);
2278
+ }
2252
2279
  }
2253
2280
  /**
2254
2281
  * Returns the input with its recipient replaced by the value the OTP state is keyed on.
@@ -2911,15 +2938,6 @@ NotificationAuditInterceptor = __decorateClass([
2911
2938
  __decorateParam(0, Inject(BYMAX_NOTIFICATION_OPTIONS)),
2912
2939
  __decorateParam(1, Inject(BYMAX_NOTIFICATION_AUDIT_SINK))
2913
2940
  ], NotificationAuditInterceptor);
2914
-
2915
- // src/server/constants/notification-purposes.ts
2916
- var NOTIFICATION_PURPOSES = {
2917
- EMAIL_VERIFICATION: "email_verification",
2918
- PASSWORD_RESET: "password_reset",
2919
- MFA_OOB: "mfa_oob",
2920
- PHONE_VERIFICATION: "phone_verification",
2921
- MAGIC_LINK: "magic_link"
2922
- };
2923
2941
  function maskEmail(address) {
2924
2942
  const at = address.lastIndexOf("@");
2925
2943
  if (at <= 0) {
@@ -3231,6 +3249,32 @@ function settleOrTimeout(call, timeoutMs) {
3231
3249
  });
3232
3250
  }
3233
3251
  var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "::1", "[::1]"]);
3252
+ function assertPool(pool) {
3253
+ if (pool === void 0) {
3254
+ return;
3255
+ }
3256
+ if (typeof pool !== "object" || pool === null) {
3257
+ throw new Error("SmtpEmailProvider: pool must be an object");
3258
+ }
3259
+ for (const [name, value] of [
3260
+ ["maxConnections", pool.maxConnections],
3261
+ ["maxMessages", pool.maxMessages]
3262
+ ]) {
3263
+ if (value !== void 0 && !(Number.isInteger(value) && value >= 1)) {
3264
+ throw new Error(`SmtpEmailProvider: pool.${name} must be a positive integer`);
3265
+ }
3266
+ }
3267
+ }
3268
+ function poolConfig(pool) {
3269
+ if (pool === void 0) {
3270
+ return {};
3271
+ }
3272
+ return {
3273
+ pool: true,
3274
+ ...pool.maxConnections === void 0 ? {} : { maxConnections: pool.maxConnections },
3275
+ ...pool.maxMessages === void 0 ? {} : { maxMessages: pool.maxMessages }
3276
+ };
3277
+ }
3234
3278
  function areCredentialsComplete(credentials) {
3235
3279
  return Boolean(credentials.user) && Boolean(credentials.pass);
3236
3280
  }
@@ -3269,6 +3313,7 @@ var SmtpEmailProvider = class {
3269
3313
  `SmtpEmailProvider: sendTimeoutMs must be a positive integer of at most ${String(MAX_SEND_TIMEOUT_MS)}`
3270
3314
  );
3271
3315
  }
3316
+ assertPool(options.pool);
3272
3317
  __privateSet(this, _options2, options);
3273
3318
  }
3274
3319
  /**
@@ -3331,6 +3376,38 @@ var SmtpEmailProvider = class {
3331
3376
  }
3332
3377
  return { messageId: info.messageId };
3333
3378
  }
3379
+ /**
3380
+ * Closes the transport this provider built, so a pooled connection does not keep the process
3381
+ * alive. A send already in flight on a pooled transport finishes; one still waiting for a
3382
+ * connection fails with `Connection pool was closed`. Idempotent, and it never builds a transport
3383
+ * to close it. A `send()` after it builds a new transport, which the host has to close again if it
3384
+ * keeps the provider alive.
3385
+ *
3386
+ * A close that throws is logged as a fixed line and not rethrown, so one failure cannot stop the
3387
+ * other shutdown hooks of the application.
3388
+ */
3389
+ async close() {
3390
+ const pending = __privateGet(this, _transportPromise);
3391
+ __privateSet(this, _transportPromise, null);
3392
+ if (pending === null) {
3393
+ return;
3394
+ }
3395
+ let transport;
3396
+ try {
3397
+ transport = await pending;
3398
+ } catch {
3399
+ return;
3400
+ }
3401
+ try {
3402
+ transport.close?.();
3403
+ } catch {
3404
+ this.logger.warn("[SMTP_CLOSE_FAILED] The transport could not be closed.");
3405
+ }
3406
+ }
3407
+ /** Nest calls this when the application closes; it closes the transport. */
3408
+ async onModuleDestroy() {
3409
+ await this.close();
3410
+ }
3334
3411
  /**
3335
3412
  * Hands the payload to the transport, converting a transport failure into a plain
3336
3413
  * `Error` whose message has the SMTP password scrubbed out. The email body is
@@ -3535,31 +3612,37 @@ var SmtpEmailProvider = class {
3535
3612
  * Returns the cached transport, lazily importing `nodemailer` on first use.
3536
3613
  * Concurrent first calls share one in-flight initialization promise so the dynamic
3537
3614
  * import and creation run exactly once; a failed init is dropped from the cache so
3538
- * a later call can retry instead of being permanently bricked.
3615
+ * a later call can retry instead of being permanently bricked. It is dropped only while
3616
+ * it is still the cached build: `close()` may have taken it, and a newer send may have
3617
+ * started a build of its own, which a late failure here must not clear.
3539
3618
  *
3540
3619
  * @returns The initialized transport.
3541
3620
  * @throws Error When the configuration is incomplete or `nodemailer` is missing.
3542
3621
  */
3543
3622
  getTransport() {
3544
- __privateGet(this, _transportPromise) ?? __privateSet(this, _transportPromise, this.createTransport());
3545
- return __privateGet(this, _transportPromise);
3623
+ const cached = __privateGet(this, _transportPromise);
3624
+ if (cached !== null) {
3625
+ return cached;
3626
+ }
3627
+ const build = this.createTransport();
3628
+ __privateSet(this, _transportPromise, build);
3629
+ build.catch(() => {
3630
+ if (__privateGet(this, _transportPromise) === build) {
3631
+ __privateSet(this, _transportPromise, null);
3632
+ }
3633
+ });
3634
+ return build;
3546
3635
  }
3547
3636
  /**
3548
- * Builds a fresh transport, resetting the cached promise on any failure so the
3549
- * provider is not permanently bricked by a transient init error.
3637
+ * Builds a fresh transport.
3550
3638
  *
3551
3639
  * @returns The initialized transport.
3552
3640
  * @throws Error When the configuration is incomplete or `nodemailer` is missing.
3553
3641
  */
3554
3642
  async createTransport() {
3555
- try {
3556
- const config = this.buildTransportConfig();
3557
- const nodemailer = await this.loadNodemailer();
3558
- return this.instantiate(nodemailer, config);
3559
- } catch (error) {
3560
- __privateSet(this, _transportPromise, null);
3561
- throw error;
3562
- }
3643
+ const config = this.buildTransportConfig();
3644
+ const nodemailer = await this.loadNodemailer();
3645
+ return this.instantiate(nodemailer, config);
3563
3646
  }
3564
3647
  /**
3565
3648
  * Calls into Nodemailer to build the transport, scrubbing the password out of a
@@ -3631,7 +3714,8 @@ var SmtpEmailProvider = class {
3631
3714
  tls: options.tls,
3632
3715
  connectionTimeout: options.connectionTimeout ?? DEFAULT_CONNECTION_TIMEOUT_MS,
3633
3716
  greetingTimeout: options.greetingTimeout ?? DEFAULT_GREETING_TIMEOUT_MS,
3634
- socketTimeout: options.socketTimeout ?? DEFAULT_SOCKET_TIMEOUT_MS
3717
+ socketTimeout: options.socketTimeout ?? DEFAULT_SOCKET_TIMEOUT_MS,
3718
+ ...poolConfig(options.pool)
3635
3719
  };
3636
3720
  }
3637
3721
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bymax-one/nest-notification",
3
- "version": "1.4.10",
3
+ "version": "1.4.11",
4
4
  "description": "Multi-channel notification library for NestJS โ€” email, OTP, SMS, push โ€” with pluggable providers and storage, multi-tenant by design, zero runtime dependencies.",
5
5
  "author": "Bymax One <support@bymax.one>",
6
6
  "license": "MIT",