@bymax-one/nest-notification 1.4.10 → 1.4.12

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,59 @@ the entries that carry one, is the compatibility contract — read it, not the n
11
11
 
12
12
  ## [Unreleased]
13
13
 
14
+ ## [1.4.12] - 2026-11-17
15
+
16
+ ### Fixed
17
+
18
+ - **A send with no `html` part fails with its own error, not a `TypeError`.** When the transport or
19
+ the API rejected such a send, the code that removes secrets and echoed content from the error read
20
+ the missing part and threw a `TypeError` instead of the `SMTP send failed` or `Resend send failed`
21
+ error. `SmtpEmailProvider`, `ResendEmailProvider` and `EmailService` now treat a missing part as
22
+ nothing to echo against, and the declared values, the credentials and an echo of the text part are
23
+ removed as before. Only a caller that bypasses the `html: string` type reached it.
24
+ - **`pool: []` is refused.** `SmtpEmailProvider` took an empty array for the `pool` object and
25
+ behaved as if `{}` had been given; it now fails with the same `pool must be an object` as any
26
+ other value that is not one.
27
+
28
+ ## [1.4.11] - 2026-11-17
29
+
30
+ ### Added
31
+
32
+ - **`SmtpEmailProvider` can pool its connections, and closes with the application.** The new
33
+ option `pool` (`maxConnections` and `maxMessages`, each optional) turns Nodemailer's pooled mode
34
+ on, a limit left out keeping Nodemailer's default; without it the transport is configured as
35
+ before. The provider gains `close()`, which closes the transport it built (a send in flight on a
36
+ pooled transport finishes, one waiting for a connection fails, and a later `send()` builds a new
37
+ transport), and implements `onModuleDestroy`, so Nest closes it when the application closes. A
38
+ close that throws is logged as `[SMTP_CLOSE_FAILED]` with no text from the relay and is not
39
+ rethrown.
40
+
41
+ - **`otp.strictPurposes` refuses a purpose that nobody registered.** The limits of a recipient are
42
+ kept per `(tenant, recipient, purpose)` and a purpose with no `perPurpose` entry uses the
43
+ defaults, so a host that lets a caller choose the purpose lets the caller ask for a fresh
44
+ cooldown and attempt counter each time. With `strictPurposes: true`, `OtpService` refuses at every
45
+ operation, before any storage call, a purpose that is neither in
46
+ `NOTIFICATION_PURPOSES` nor a key of `perPurpose`, with `notification.invalid_scope_identifier`
47
+ (400) and the reason `not a registered purpose`, never the value. The option is a boolean
48
+ checked when the module starts and is off by default.
49
+
50
+ ### Documentation
51
+
52
+ - The README states how deep the audit metadata is kept, and a spec holds the number to the code.
53
+ - The README has a Production section: a bounded `ioredis` client and who closes it, the send
54
+ timeouts, the shutdown, and storing codes as digests.
55
+
56
+ #### Apply to a derived backend
57
+
58
+ `OtpChannelOptions` gains the optional `strictPurposes`, off by default, so a backend that does
59
+ not set it needs no change; one that sets it registers each purpose it uses that is not one of
60
+ the canonical purposes as a key of `perPurpose` (an empty object keeps the defaults).
61
+
62
+ `SmtpEmailProviderOptions` gains the optional `pool`, the exported `SmtpPoolOptions` type is new,
63
+ and `SmtpEmailProvider` gains `close()` and `onModuleDestroy()`. A backend that builds the
64
+ provider without `pool` needs no change; one that sets it should let Nest close the application,
65
+ or call `close()` itself.
66
+
14
67
  ## [1.4.10] - 2026-11-16
15
68
 
16
69
  ### Fixed
@@ -1268,7 +1321,9 @@ rejected at startup rather than failing on the first send.
1268
1321
 
1269
1322
  [1.0.4]: https://github.com/bymaxone/nest-notification/compare/v1.0.3...v1.0.4
1270
1323
  [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
1324
+ [Unreleased]: https://github.com/bymaxone/nest-notification/compare/v1.4.12...HEAD
1325
+ [1.4.12]: https://github.com/bymaxone/nest-notification/compare/v1.4.11...v1.4.12
1326
+ [1.4.11]: https://github.com/bymaxone/nest-notification/compare/v1.4.10...v1.4.11
1272
1327
  [1.4.10]: https://github.com/bymaxone/nest-notification/compare/v1.4.9...v1.4.10
1273
1328
  [1.4.9]: https://github.com/bymaxone/nest-notification/compare/v1.4.8...v1.4.9
1274
1329
  [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.33 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"
@@ -1078,6 +1101,9 @@ function collectEchoedExcerpts(fields, reference) {
1078
1101
  budget -= field.length;
1079
1102
  }
1080
1103
  }
1104
+ if (typeof reference !== "string") {
1105
+ return whole;
1106
+ }
1081
1107
  const units = examined.flatMap((field) => [...field.split("").map((c) => c.charCodeAt(0)), -1]);
1082
1108
  const reach = longestEchoFrom(units, reference);
1083
1109
  const excerpts = whole;
@@ -1671,7 +1697,7 @@ exports.EmailService = class EmailService {
1671
1697
  gatherRedactionValues(parts, declared, sendOptions) {
1672
1698
  return [
1673
1699
  ...collectEchoedExcerpts(parts, sendOptions.html),
1674
- ...sendOptions.text !== void 0 ? collectEchoedExcerpts(parts, sendOptions.text) : [],
1700
+ ...collectEchoedExcerpts(parts, sendOptions.text),
1675
1701
  ...declared ?? []
1676
1702
  ];
1677
1703
  }
@@ -2251,6 +2277,10 @@ exports.OtpService = class OtpService {
2251
2277
  assertIdentifies("OtpService", "tenantId", ref.tenantId);
2252
2278
  assertIdentifies("OtpService", "recipient", ref.recipient);
2253
2279
  assertPurpose("OtpService", ref.purpose);
2280
+ const otp = this.options.otp;
2281
+ if (otp?.strictPurposes === true) {
2282
+ assertRegisteredPurpose("OtpService", ref.purpose, otp.isRegisteredPurpose);
2283
+ }
2254
2284
  }
2255
2285
  /**
2256
2286
  * Returns the input with its recipient replaced by the value the OTP state is keyed on.
@@ -2913,15 +2943,6 @@ exports.NotificationAuditInterceptor = __decorateClass([
2913
2943
  __decorateParam(0, common.Inject(BYMAX_NOTIFICATION_OPTIONS)),
2914
2944
  __decorateParam(1, common.Inject(BYMAX_NOTIFICATION_AUDIT_SINK))
2915
2945
  ], 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
2946
  function maskEmail(address) {
2926
2947
  const at = address.lastIndexOf("@");
2927
2948
  if (at <= 0) {
@@ -3136,9 +3157,7 @@ exports.ResendEmailProvider = class ResendEmailProvider {
3136
3157
  */
3137
3158
  scrubSendError(message, options) {
3138
3159
  const values = collectEchoedExcerpts(message, options.html);
3139
- if (options.text !== void 0) {
3140
- values.push(...collectEchoedExcerpts(message, options.text));
3141
- }
3160
+ values.push(...collectEchoedExcerpts(message, options.text));
3142
3161
  if (options.redactValues) {
3143
3162
  values.push(...options.redactValues);
3144
3163
  }
@@ -3233,6 +3252,32 @@ function settleOrTimeout(call, timeoutMs) {
3233
3252
  });
3234
3253
  }
3235
3254
  var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "::1", "[::1]"]);
3255
+ function assertPool(pool) {
3256
+ if (pool === void 0) {
3257
+ return;
3258
+ }
3259
+ if (typeof pool !== "object" || pool === null || Array.isArray(pool)) {
3260
+ throw new Error("SmtpEmailProvider: pool must be an object");
3261
+ }
3262
+ for (const [name, value] of [
3263
+ ["maxConnections", pool.maxConnections],
3264
+ ["maxMessages", pool.maxMessages]
3265
+ ]) {
3266
+ if (value !== void 0 && !(Number.isInteger(value) && value >= 1)) {
3267
+ throw new Error(`SmtpEmailProvider: pool.${name} must be a positive integer`);
3268
+ }
3269
+ }
3270
+ }
3271
+ function poolConfig(pool) {
3272
+ if (pool === void 0) {
3273
+ return {};
3274
+ }
3275
+ return {
3276
+ pool: true,
3277
+ ...pool.maxConnections === void 0 ? {} : { maxConnections: pool.maxConnections },
3278
+ ...pool.maxMessages === void 0 ? {} : { maxMessages: pool.maxMessages }
3279
+ };
3280
+ }
3236
3281
  function areCredentialsComplete(credentials) {
3237
3282
  return Boolean(credentials.user) && Boolean(credentials.pass);
3238
3283
  }
@@ -3271,6 +3316,7 @@ exports.SmtpEmailProvider = class SmtpEmailProvider {
3271
3316
  `SmtpEmailProvider: sendTimeoutMs must be a positive integer of at most ${String(MAX_SEND_TIMEOUT_MS)}`
3272
3317
  );
3273
3318
  }
3319
+ assertPool(options.pool);
3274
3320
  __privateSet(this, _options2, options);
3275
3321
  }
3276
3322
  /**
@@ -3333,6 +3379,38 @@ exports.SmtpEmailProvider = class SmtpEmailProvider {
3333
3379
  }
3334
3380
  return { messageId: info.messageId };
3335
3381
  }
3382
+ /**
3383
+ * Closes the transport this provider built, so a pooled connection does not keep the process
3384
+ * alive. A send already in flight on a pooled transport finishes; one still waiting for a
3385
+ * connection fails with `Connection pool was closed`. Idempotent, and it never builds a transport
3386
+ * to close it. A `send()` after it builds a new transport, which the host has to close again if it
3387
+ * keeps the provider alive.
3388
+ *
3389
+ * A close that throws is logged as a fixed line and not rethrown, so one failure cannot stop the
3390
+ * other shutdown hooks of the application.
3391
+ */
3392
+ async close() {
3393
+ const pending = __privateGet(this, _transportPromise);
3394
+ __privateSet(this, _transportPromise, null);
3395
+ if (pending === null) {
3396
+ return;
3397
+ }
3398
+ let transport;
3399
+ try {
3400
+ transport = await pending;
3401
+ } catch {
3402
+ return;
3403
+ }
3404
+ try {
3405
+ transport.close?.();
3406
+ } catch {
3407
+ this.logger.warn("[SMTP_CLOSE_FAILED] The transport could not be closed.");
3408
+ }
3409
+ }
3410
+ /** Nest calls this when the application closes; it closes the transport. */
3411
+ async onModuleDestroy() {
3412
+ await this.close();
3413
+ }
3336
3414
  /**
3337
3415
  * Hands the payload to the transport, converting a transport failure into a plain
3338
3416
  * `Error` whose message has the SMTP password scrubbed out. The email body is
@@ -3405,9 +3483,7 @@ exports.SmtpEmailProvider = class SmtpEmailProvider {
3405
3483
  */
3406
3484
  scrubTransportError(message, payload, declaredValues) {
3407
3485
  const values = collectEchoedExcerpts(message, payload.html);
3408
- if (payload.text !== void 0) {
3409
- values.push(...collectEchoedExcerpts(message, payload.text));
3410
- }
3486
+ values.push(...collectEchoedExcerpts(message, payload.text));
3411
3487
  if (declaredValues) {
3412
3488
  values.push(...declaredValues);
3413
3489
  }
@@ -3537,31 +3613,37 @@ exports.SmtpEmailProvider = class SmtpEmailProvider {
3537
3613
  * Returns the cached transport, lazily importing `nodemailer` on first use.
3538
3614
  * Concurrent first calls share one in-flight initialization promise so the dynamic
3539
3615
  * 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.
3616
+ * a later call can retry instead of being permanently bricked. It is dropped only while
3617
+ * it is still the cached build: `close()` may have taken it, and a newer send may have
3618
+ * started a build of its own, which a late failure here must not clear.
3541
3619
  *
3542
3620
  * @returns The initialized transport.
3543
3621
  * @throws Error When the configuration is incomplete or `nodemailer` is missing.
3544
3622
  */
3545
3623
  getTransport() {
3546
- __privateGet(this, _transportPromise) ?? __privateSet(this, _transportPromise, this.createTransport());
3547
- return __privateGet(this, _transportPromise);
3624
+ const cached = __privateGet(this, _transportPromise);
3625
+ if (cached !== null) {
3626
+ return cached;
3627
+ }
3628
+ const build = this.createTransport();
3629
+ __privateSet(this, _transportPromise, build);
3630
+ build.catch(() => {
3631
+ if (__privateGet(this, _transportPromise) === build) {
3632
+ __privateSet(this, _transportPromise, null);
3633
+ }
3634
+ });
3635
+ return build;
3548
3636
  }
3549
3637
  /**
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.
3638
+ * Builds a fresh transport.
3552
3639
  *
3553
3640
  * @returns The initialized transport.
3554
3641
  * @throws Error When the configuration is incomplete or `nodemailer` is missing.
3555
3642
  */
3556
3643
  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
- }
3644
+ const config = this.buildTransportConfig();
3645
+ const nodemailer = await this.loadNodemailer();
3646
+ return this.instantiate(nodemailer, config);
3565
3647
  }
3566
3648
  /**
3567
3649
  * Calls into Nodemailer to build the transport, scrubbing the password out of a
@@ -3633,7 +3715,8 @@ exports.SmtpEmailProvider = class SmtpEmailProvider {
3633
3715
  tls: options.tls,
3634
3716
  connectionTimeout: options.connectionTimeout ?? DEFAULT_CONNECTION_TIMEOUT_MS,
3635
3717
  greetingTimeout: options.greetingTimeout ?? DEFAULT_GREETING_TIMEOUT_MS,
3636
- socketTimeout: options.socketTimeout ?? DEFAULT_SOCKET_TIMEOUT_MS
3718
+ socketTimeout: options.socketTimeout ?? DEFAULT_SOCKET_TIMEOUT_MS,
3719
+ ...poolConfig(options.pool)
3637
3720
  };
3638
3721
  }
3639
3722
  /**
@@ -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"
@@ -1076,6 +1099,9 @@ function collectEchoedExcerpts(fields, reference) {
1076
1099
  budget -= field.length;
1077
1100
  }
1078
1101
  }
1102
+ if (typeof reference !== "string") {
1103
+ return whole;
1104
+ }
1079
1105
  const units = examined.flatMap((field) => [...field.split("").map((c) => c.charCodeAt(0)), -1]);
1080
1106
  const reach = longestEchoFrom(units, reference);
1081
1107
  const excerpts = whole;
@@ -1669,7 +1695,7 @@ var EmailService = class {
1669
1695
  gatherRedactionValues(parts, declared, sendOptions) {
1670
1696
  return [
1671
1697
  ...collectEchoedExcerpts(parts, sendOptions.html),
1672
- ...sendOptions.text !== void 0 ? collectEchoedExcerpts(parts, sendOptions.text) : [],
1698
+ ...collectEchoedExcerpts(parts, sendOptions.text),
1673
1699
  ...declared ?? []
1674
1700
  ];
1675
1701
  }
@@ -2249,6 +2275,10 @@ var OtpService = class {
2249
2275
  assertIdentifies("OtpService", "tenantId", ref.tenantId);
2250
2276
  assertIdentifies("OtpService", "recipient", ref.recipient);
2251
2277
  assertPurpose("OtpService", ref.purpose);
2278
+ const otp = this.options.otp;
2279
+ if (otp?.strictPurposes === true) {
2280
+ assertRegisteredPurpose("OtpService", ref.purpose, otp.isRegisteredPurpose);
2281
+ }
2252
2282
  }
2253
2283
  /**
2254
2284
  * Returns the input with its recipient replaced by the value the OTP state is keyed on.
@@ -2911,15 +2941,6 @@ NotificationAuditInterceptor = __decorateClass([
2911
2941
  __decorateParam(0, Inject(BYMAX_NOTIFICATION_OPTIONS)),
2912
2942
  __decorateParam(1, Inject(BYMAX_NOTIFICATION_AUDIT_SINK))
2913
2943
  ], 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
2944
  function maskEmail(address) {
2924
2945
  const at = address.lastIndexOf("@");
2925
2946
  if (at <= 0) {
@@ -3134,9 +3155,7 @@ var ResendEmailProvider = class {
3134
3155
  */
3135
3156
  scrubSendError(message, options) {
3136
3157
  const values = collectEchoedExcerpts(message, options.html);
3137
- if (options.text !== void 0) {
3138
- values.push(...collectEchoedExcerpts(message, options.text));
3139
- }
3158
+ values.push(...collectEchoedExcerpts(message, options.text));
3140
3159
  if (options.redactValues) {
3141
3160
  values.push(...options.redactValues);
3142
3161
  }
@@ -3231,6 +3250,32 @@ function settleOrTimeout(call, timeoutMs) {
3231
3250
  });
3232
3251
  }
3233
3252
  var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "::1", "[::1]"]);
3253
+ function assertPool(pool) {
3254
+ if (pool === void 0) {
3255
+ return;
3256
+ }
3257
+ if (typeof pool !== "object" || pool === null || Array.isArray(pool)) {
3258
+ throw new Error("SmtpEmailProvider: pool must be an object");
3259
+ }
3260
+ for (const [name, value] of [
3261
+ ["maxConnections", pool.maxConnections],
3262
+ ["maxMessages", pool.maxMessages]
3263
+ ]) {
3264
+ if (value !== void 0 && !(Number.isInteger(value) && value >= 1)) {
3265
+ throw new Error(`SmtpEmailProvider: pool.${name} must be a positive integer`);
3266
+ }
3267
+ }
3268
+ }
3269
+ function poolConfig(pool) {
3270
+ if (pool === void 0) {
3271
+ return {};
3272
+ }
3273
+ return {
3274
+ pool: true,
3275
+ ...pool.maxConnections === void 0 ? {} : { maxConnections: pool.maxConnections },
3276
+ ...pool.maxMessages === void 0 ? {} : { maxMessages: pool.maxMessages }
3277
+ };
3278
+ }
3234
3279
  function areCredentialsComplete(credentials) {
3235
3280
  return Boolean(credentials.user) && Boolean(credentials.pass);
3236
3281
  }
@@ -3269,6 +3314,7 @@ var SmtpEmailProvider = class {
3269
3314
  `SmtpEmailProvider: sendTimeoutMs must be a positive integer of at most ${String(MAX_SEND_TIMEOUT_MS)}`
3270
3315
  );
3271
3316
  }
3317
+ assertPool(options.pool);
3272
3318
  __privateSet(this, _options2, options);
3273
3319
  }
3274
3320
  /**
@@ -3331,6 +3377,38 @@ var SmtpEmailProvider = class {
3331
3377
  }
3332
3378
  return { messageId: info.messageId };
3333
3379
  }
3380
+ /**
3381
+ * Closes the transport this provider built, so a pooled connection does not keep the process
3382
+ * alive. A send already in flight on a pooled transport finishes; one still waiting for a
3383
+ * connection fails with `Connection pool was closed`. Idempotent, and it never builds a transport
3384
+ * to close it. A `send()` after it builds a new transport, which the host has to close again if it
3385
+ * keeps the provider alive.
3386
+ *
3387
+ * A close that throws is logged as a fixed line and not rethrown, so one failure cannot stop the
3388
+ * other shutdown hooks of the application.
3389
+ */
3390
+ async close() {
3391
+ const pending = __privateGet(this, _transportPromise);
3392
+ __privateSet(this, _transportPromise, null);
3393
+ if (pending === null) {
3394
+ return;
3395
+ }
3396
+ let transport;
3397
+ try {
3398
+ transport = await pending;
3399
+ } catch {
3400
+ return;
3401
+ }
3402
+ try {
3403
+ transport.close?.();
3404
+ } catch {
3405
+ this.logger.warn("[SMTP_CLOSE_FAILED] The transport could not be closed.");
3406
+ }
3407
+ }
3408
+ /** Nest calls this when the application closes; it closes the transport. */
3409
+ async onModuleDestroy() {
3410
+ await this.close();
3411
+ }
3334
3412
  /**
3335
3413
  * Hands the payload to the transport, converting a transport failure into a plain
3336
3414
  * `Error` whose message has the SMTP password scrubbed out. The email body is
@@ -3403,9 +3481,7 @@ var SmtpEmailProvider = class {
3403
3481
  */
3404
3482
  scrubTransportError(message, payload, declaredValues) {
3405
3483
  const values = collectEchoedExcerpts(message, payload.html);
3406
- if (payload.text !== void 0) {
3407
- values.push(...collectEchoedExcerpts(message, payload.text));
3408
- }
3484
+ values.push(...collectEchoedExcerpts(message, payload.text));
3409
3485
  if (declaredValues) {
3410
3486
  values.push(...declaredValues);
3411
3487
  }
@@ -3535,31 +3611,37 @@ var SmtpEmailProvider = class {
3535
3611
  * Returns the cached transport, lazily importing `nodemailer` on first use.
3536
3612
  * Concurrent first calls share one in-flight initialization promise so the dynamic
3537
3613
  * 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.
3614
+ * a later call can retry instead of being permanently bricked. It is dropped only while
3615
+ * it is still the cached build: `close()` may have taken it, and a newer send may have
3616
+ * started a build of its own, which a late failure here must not clear.
3539
3617
  *
3540
3618
  * @returns The initialized transport.
3541
3619
  * @throws Error When the configuration is incomplete or `nodemailer` is missing.
3542
3620
  */
3543
3621
  getTransport() {
3544
- __privateGet(this, _transportPromise) ?? __privateSet(this, _transportPromise, this.createTransport());
3545
- return __privateGet(this, _transportPromise);
3622
+ const cached = __privateGet(this, _transportPromise);
3623
+ if (cached !== null) {
3624
+ return cached;
3625
+ }
3626
+ const build = this.createTransport();
3627
+ __privateSet(this, _transportPromise, build);
3628
+ build.catch(() => {
3629
+ if (__privateGet(this, _transportPromise) === build) {
3630
+ __privateSet(this, _transportPromise, null);
3631
+ }
3632
+ });
3633
+ return build;
3546
3634
  }
3547
3635
  /**
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.
3636
+ * Builds a fresh transport.
3550
3637
  *
3551
3638
  * @returns The initialized transport.
3552
3639
  * @throws Error When the configuration is incomplete or `nodemailer` is missing.
3553
3640
  */
3554
3641
  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
- }
3642
+ const config = this.buildTransportConfig();
3643
+ const nodemailer = await this.loadNodemailer();
3644
+ return this.instantiate(nodemailer, config);
3563
3645
  }
3564
3646
  /**
3565
3647
  * Calls into Nodemailer to build the transport, scrubbing the password out of a
@@ -3631,7 +3713,8 @@ var SmtpEmailProvider = class {
3631
3713
  tls: options.tls,
3632
3714
  connectionTimeout: options.connectionTimeout ?? DEFAULT_CONNECTION_TIMEOUT_MS,
3633
3715
  greetingTimeout: options.greetingTimeout ?? DEFAULT_GREETING_TIMEOUT_MS,
3634
- socketTimeout: options.socketTimeout ?? DEFAULT_SOCKET_TIMEOUT_MS
3716
+ socketTimeout: options.socketTimeout ?? DEFAULT_SOCKET_TIMEOUT_MS,
3717
+ ...poolConfig(options.pool)
3635
3718
  };
3636
3719
  }
3637
3720
  /**
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.12",
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",