@bymax-one/nest-notification 1.4.9 → 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.
@@ -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 {
@@ -1227,7 +1240,7 @@ declare class OtpService implements OnModuleInit {
1227
1240
  * consumer-supplied {@link IOtpStorage} is not required to, and a blank scope would
1228
1241
  * then be shared by every caller that sent one.
1229
1242
  *
1230
- * @throws NotificationException `INVALID_SCOPE_IDENTIFIER` when either is blank.
1243
+ * @throws NotificationException `INVALID_SCOPE_IDENTIFIER` when either is blank or the purpose is not a plain name.
1231
1244
  */
1232
1245
  private assertScope;
1233
1246
  /**
@@ -1463,7 +1476,12 @@ declare class NotificationAuditInterceptor implements NestInterceptor {
1463
1476
  private buildEntry;
1464
1477
  /** Extracts the (unmasked) recipient from the dispatch payload. */
1465
1478
  private extractRecipient;
1466
- /** Extracts the audit `purpose`: the OTP purpose, or the email template name. */
1479
+ /**
1480
+ * Extracts the audit `purpose`: the OTP purpose, or the email template name. The interceptor sees
1481
+ * the payload before the service refuses it and audits a refused call too, so an OTP purpose that
1482
+ * is not a plain name is left out of the entry: a control character in it would forge a log
1483
+ * record and its length is unbounded.
1484
+ */
1467
1485
  private extractPurpose;
1468
1486
  }
1469
1487
 
@@ -1688,13 +1706,18 @@ declare class DefaultTemplateRenderer implements IEmailTemplateRenderer {
1688
1706
  /** Replaces every `{{path}}` placeholder, escaping only when `escape` is `true`. */
1689
1707
  private interpolate;
1690
1708
  /**
1691
- * Builds a variable resolver for one render call. Lookups go through a `Map`
1692
- * built from own enumerable entries (never bracket indexing) so neither flat
1693
- * nor nested resolution can reach inherited/prototype keys.
1709
+ * Builds a variable resolver for one render call. A key resolves only when the object holds it as
1710
+ * an own enumerable property, so neither flat nor nested resolution can reach inherited or
1711
+ * prototype keys, and only the property that is named is read.
1694
1712
  */
1695
1713
  private buildResolver;
1696
1714
  /** Walks a dotted path through own enumerable keys, stopping at any non-object. */
1697
1715
  private resolveNested;
1716
+ /**
1717
+ * The value of `key` when `object` holds it as an own enumerable property, otherwise `undefined`.
1718
+ * Called through `Object.prototype` so an object without a prototype works too.
1719
+ */
1720
+ private ownValue;
1698
1721
  /**
1699
1722
  * Validates a registered template shape, throwing on the offending key. The
1700
1723
  * optional `text` body, when present, must be a string — a non-string `text`
@@ -1825,26 +1848,11 @@ declare class ResendEmailProvider implements IEmailProvider {
1825
1848
  }
1826
1849
 
1827
1850
  /**
1828
- * @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.
1829
1854
  * @layer infrastructure
1830
- *
1831
- * SMTP is the protocol every relay, Postfix, corporate gateway, SES-via-SMTP and
1832
- * mail-capture server (Mailpit, MailHog) understands, so this adapter serves both
1833
- * production delivery and the end-to-end tests a consumer needs to exercise its
1834
- * email flows.
1835
- *
1836
- * `nodemailer` is an OPTIONAL peer dependency: it is loaded lazily via a dynamic
1837
- * `import()` the first time `send()` runs, so a consumer who picks a different
1838
- * transport never has to install it. The adapter forward-declares the slim shape it
1839
- * needs instead of importing `nodemailer` at compile time, keeping the library free
1840
- * of a hard dependency on its types.
1841
- *
1842
- * Security: the email body (`html` / `text`) may carry OTP codes or PII — it is
1843
- * NEVER logged. The SMTP password is held in an ECMAScript private field so it
1844
- * cannot be walked by a serializer, and is scrubbed from any transport error before
1845
- * that error is logged or re-thrown.
1846
1855
  */
1847
-
1848
1856
  /** TLS knobs forwarded to the transport, for relays using a private CA. */
1849
1857
  interface SmtpTlsOptions {
1850
1858
  /**
@@ -1924,7 +1932,46 @@ interface SmtpEmailProviderOptions {
1924
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.
1925
1933
  */
1926
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;
1927
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;
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
+
1928
1975
  /**
1929
1976
  * Reference {@link IEmailProvider} speaking SMTP.
1930
1977
  *
@@ -1951,7 +1998,7 @@ interface SmtpEmailProviderOptions {
1951
1998
  * @remarks `EmailSendOptions.tags` are not forwarded: SMTP has no tag facility.
1952
1999
  * They still reach the audit log through `EmailService`.
1953
2000
  */
1954
- declare class SmtpEmailProvider implements IEmailProvider {
2001
+ declare class SmtpEmailProvider implements IEmailProvider, OnModuleDestroy {
1955
2002
  #private;
1956
2003
  readonly name = "smtp";
1957
2004
  private readonly logger;
@@ -1987,6 +2034,19 @@ declare class SmtpEmailProvider implements IEmailProvider {
1987
2034
  * comes back. `EmailService` maps any thrown `Error` to `EMAIL_SEND_FAILED`.
1988
2035
  */
1989
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>;
1990
2050
  /**
1991
2051
  * Hands the payload to the transport, converting a transport failure into a plain
1992
2052
  * `Error` whose message has the SMTP password scrubbed out. The email body is
@@ -2112,15 +2172,16 @@ declare class SmtpEmailProvider implements IEmailProvider {
2112
2172
  * Returns the cached transport, lazily importing `nodemailer` on first use.
2113
2173
  * Concurrent first calls share one in-flight initialization promise so the dynamic
2114
2174
  * import and creation run exactly once; a failed init is dropped from the cache so
2115
- * 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.
2116
2178
  *
2117
2179
  * @returns The initialized transport.
2118
2180
  * @throws Error When the configuration is incomplete or `nodemailer` is missing.
2119
2181
  */
2120
2182
  private getTransport;
2121
2183
  /**
2122
- * Builds a fresh transport, resetting the cached promise on any failure so the
2123
- * provider is not permanently bricked by a transient init error.
2184
+ * Builds a fresh transport.
2124
2185
  *
2125
2186
  * @returns The initialized transport.
2126
2187
  * @throws Error When the configuration is incomplete or `nodemailer` is missing.
@@ -2195,7 +2256,7 @@ declare class SmtpEmailProvider implements IEmailProvider {
2195
2256
  * @fileoverview In-memory `IOtpStorage` for development and unit tests.
2196
2257
  * @layer infrastructure
2197
2258
  *
2198
- * Backed by two native `Map`s. It is atomic by construction: `consumeAttempt`
2259
+ * Backed by native `Map`s. It is atomic by construction: `consumeAttempt`
2199
2260
  * performs its read → checks → increment → write with NO `await` in between, so
2200
2261
  * Node's single-threaded event loop cannot interleave two calls and overshoot
2201
2262
  * `maxAttempts`.
@@ -2204,10 +2265,11 @@ declare class SmtpEmailProvider implements IEmailProvider {
2204
2265
  * and are not shared across instances; use `RedisOtpStorage` there.
2205
2266
  */
2206
2267
 
2207
- /** Aggregate sizes of the two internal maps — exposed by the {@link InMemoryOtpStorage.size} helper. */
2268
+ /** Aggregate sizes of the three internal maps — exposed by the {@link InMemoryOtpStorage.size} helper. */
2208
2269
  interface InMemoryStorageSize {
2209
2270
  otps: number;
2210
2271
  cooldowns: number;
2272
+ failures: number;
2211
2273
  }
2212
2274
  /** Process-local `IOtpStorage` for dev/test. */
2213
2275
  declare class InMemoryOtpStorage implements IOtpStorage {
@@ -2336,13 +2398,14 @@ declare class InMemoryOtpStorage implements IOtpStorage {
2336
2398
  */
2337
2399
  clearCooldown(tenantId: string, recipient: string, purpose: string): Promise<void>;
2338
2400
  /**
2339
- * Test helper — wipes all entries and cooldowns. Not part of `IOtpStorage`.
2401
+ * Test helper — wipes all entries, cooldowns and failure counters. Not part of `IOtpStorage`.
2340
2402
  */
2341
2403
  clear(): void;
2342
2404
  /**
2343
- * Test helper — current map sizes. Not part of `IOtpStorage`.
2405
+ * Test helper — current map sizes. Not part of `IOtpStorage`. Like the cooldowns, a failure
2406
+ * counter that has lapsed stays counted until it is read or cleared.
2344
2407
  *
2345
- * @returns The number of stored OTP entries and active cooldowns.
2408
+ * @returns The number of stored OTP entries, cooldowns and failure counters.
2346
2409
  */
2347
2410
  size(): InMemoryStorageSize;
2348
2411
  /** The unexpired failure count for a key, dropping a lapsed counter. Synchronous. */
@@ -2730,8 +2793,10 @@ declare const NOTIFICATION_ERROR_CODES: {
2730
2793
  readonly AUDIT_LOG_FAILED: "notification.audit_log_failed";
2731
2794
  readonly CHANNEL_DISABLED: "notification.channel_disabled";
2732
2795
  /**
2733
- * A `tenantId` or `recipient` that identifies nobody reached a scoping
2734
- * boundary — empty, whitespace-only, or not a string at all. Distinct from
2796
+ * A `tenantId`, `recipient` or `purpose` that cannot scope an OTP reached a
2797
+ * scoping boundary: empty, whitespace-only, not a string at all, carrying a
2798
+ * control character, or, for a purpose, longer than 64 characters or made of
2799
+ * anything but `A-Z a-z 0-9 : _ -`. Distinct from
2735
2800
  * {@link EMAIL_INVALID_RECIPIENT}, which is about a malformed address rather
2736
2801
  * than a value that cannot scope anything.
2737
2802
  */
@@ -2897,7 +2962,7 @@ declare const NOTIFICATION_ERROR_DEFINITIONS: {
2897
2962
  readonly INVALID_SCOPE_IDENTIFIER: {
2898
2963
  readonly code: "notification.invalid_scope_identifier";
2899
2964
  readonly status: HttpStatus.BAD_REQUEST;
2900
- readonly message: "Tenant or recipient identifier does not identify anybody";
2965
+ readonly message: "A tenant, recipient or purpose identifier is not valid";
2901
2966
  };
2902
2967
  };
2903
2968
  /** The symbolic key of any entry in {@link NOTIFICATION_ERROR_DEFINITIONS}. */
@@ -3032,4 +3097,4 @@ declare const DEFAULT_TTLS: {
3032
3097
  };
3033
3098
 
3034
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 };
3035
- 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 {
@@ -1227,7 +1240,7 @@ declare class OtpService implements OnModuleInit {
1227
1240
  * consumer-supplied {@link IOtpStorage} is not required to, and a blank scope would
1228
1241
  * then be shared by every caller that sent one.
1229
1242
  *
1230
- * @throws NotificationException `INVALID_SCOPE_IDENTIFIER` when either is blank.
1243
+ * @throws NotificationException `INVALID_SCOPE_IDENTIFIER` when either is blank or the purpose is not a plain name.
1231
1244
  */
1232
1245
  private assertScope;
1233
1246
  /**
@@ -1463,7 +1476,12 @@ declare class NotificationAuditInterceptor implements NestInterceptor {
1463
1476
  private buildEntry;
1464
1477
  /** Extracts the (unmasked) recipient from the dispatch payload. */
1465
1478
  private extractRecipient;
1466
- /** Extracts the audit `purpose`: the OTP purpose, or the email template name. */
1479
+ /**
1480
+ * Extracts the audit `purpose`: the OTP purpose, or the email template name. The interceptor sees
1481
+ * the payload before the service refuses it and audits a refused call too, so an OTP purpose that
1482
+ * is not a plain name is left out of the entry: a control character in it would forge a log
1483
+ * record and its length is unbounded.
1484
+ */
1467
1485
  private extractPurpose;
1468
1486
  }
1469
1487
 
@@ -1688,13 +1706,18 @@ declare class DefaultTemplateRenderer implements IEmailTemplateRenderer {
1688
1706
  /** Replaces every `{{path}}` placeholder, escaping only when `escape` is `true`. */
1689
1707
  private interpolate;
1690
1708
  /**
1691
- * Builds a variable resolver for one render call. Lookups go through a `Map`
1692
- * built from own enumerable entries (never bracket indexing) so neither flat
1693
- * nor nested resolution can reach inherited/prototype keys.
1709
+ * Builds a variable resolver for one render call. A key resolves only when the object holds it as
1710
+ * an own enumerable property, so neither flat nor nested resolution can reach inherited or
1711
+ * prototype keys, and only the property that is named is read.
1694
1712
  */
1695
1713
  private buildResolver;
1696
1714
  /** Walks a dotted path through own enumerable keys, stopping at any non-object. */
1697
1715
  private resolveNested;
1716
+ /**
1717
+ * The value of `key` when `object` holds it as an own enumerable property, otherwise `undefined`.
1718
+ * Called through `Object.prototype` so an object without a prototype works too.
1719
+ */
1720
+ private ownValue;
1698
1721
  /**
1699
1722
  * Validates a registered template shape, throwing on the offending key. The
1700
1723
  * optional `text` body, when present, must be a string — a non-string `text`
@@ -1825,26 +1848,11 @@ declare class ResendEmailProvider implements IEmailProvider {
1825
1848
  }
1826
1849
 
1827
1850
  /**
1828
- * @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.
1829
1854
  * @layer infrastructure
1830
- *
1831
- * SMTP is the protocol every relay, Postfix, corporate gateway, SES-via-SMTP and
1832
- * mail-capture server (Mailpit, MailHog) understands, so this adapter serves both
1833
- * production delivery and the end-to-end tests a consumer needs to exercise its
1834
- * email flows.
1835
- *
1836
- * `nodemailer` is an OPTIONAL peer dependency: it is loaded lazily via a dynamic
1837
- * `import()` the first time `send()` runs, so a consumer who picks a different
1838
- * transport never has to install it. The adapter forward-declares the slim shape it
1839
- * needs instead of importing `nodemailer` at compile time, keeping the library free
1840
- * of a hard dependency on its types.
1841
- *
1842
- * Security: the email body (`html` / `text`) may carry OTP codes or PII — it is
1843
- * NEVER logged. The SMTP password is held in an ECMAScript private field so it
1844
- * cannot be walked by a serializer, and is scrubbed from any transport error before
1845
- * that error is logged or re-thrown.
1846
1855
  */
1847
-
1848
1856
  /** TLS knobs forwarded to the transport, for relays using a private CA. */
1849
1857
  interface SmtpTlsOptions {
1850
1858
  /**
@@ -1924,7 +1932,46 @@ interface SmtpEmailProviderOptions {
1924
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.
1925
1933
  */
1926
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;
1927
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;
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
+
1928
1975
  /**
1929
1976
  * Reference {@link IEmailProvider} speaking SMTP.
1930
1977
  *
@@ -1951,7 +1998,7 @@ interface SmtpEmailProviderOptions {
1951
1998
  * @remarks `EmailSendOptions.tags` are not forwarded: SMTP has no tag facility.
1952
1999
  * They still reach the audit log through `EmailService`.
1953
2000
  */
1954
- declare class SmtpEmailProvider implements IEmailProvider {
2001
+ declare class SmtpEmailProvider implements IEmailProvider, OnModuleDestroy {
1955
2002
  #private;
1956
2003
  readonly name = "smtp";
1957
2004
  private readonly logger;
@@ -1987,6 +2034,19 @@ declare class SmtpEmailProvider implements IEmailProvider {
1987
2034
  * comes back. `EmailService` maps any thrown `Error` to `EMAIL_SEND_FAILED`.
1988
2035
  */
1989
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>;
1990
2050
  /**
1991
2051
  * Hands the payload to the transport, converting a transport failure into a plain
1992
2052
  * `Error` whose message has the SMTP password scrubbed out. The email body is
@@ -2112,15 +2172,16 @@ declare class SmtpEmailProvider implements IEmailProvider {
2112
2172
  * Returns the cached transport, lazily importing `nodemailer` on first use.
2113
2173
  * Concurrent first calls share one in-flight initialization promise so the dynamic
2114
2174
  * import and creation run exactly once; a failed init is dropped from the cache so
2115
- * 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.
2116
2178
  *
2117
2179
  * @returns The initialized transport.
2118
2180
  * @throws Error When the configuration is incomplete or `nodemailer` is missing.
2119
2181
  */
2120
2182
  private getTransport;
2121
2183
  /**
2122
- * Builds a fresh transport, resetting the cached promise on any failure so the
2123
- * provider is not permanently bricked by a transient init error.
2184
+ * Builds a fresh transport.
2124
2185
  *
2125
2186
  * @returns The initialized transport.
2126
2187
  * @throws Error When the configuration is incomplete or `nodemailer` is missing.
@@ -2195,7 +2256,7 @@ declare class SmtpEmailProvider implements IEmailProvider {
2195
2256
  * @fileoverview In-memory `IOtpStorage` for development and unit tests.
2196
2257
  * @layer infrastructure
2197
2258
  *
2198
- * Backed by two native `Map`s. It is atomic by construction: `consumeAttempt`
2259
+ * Backed by native `Map`s. It is atomic by construction: `consumeAttempt`
2199
2260
  * performs its read → checks → increment → write with NO `await` in between, so
2200
2261
  * Node's single-threaded event loop cannot interleave two calls and overshoot
2201
2262
  * `maxAttempts`.
@@ -2204,10 +2265,11 @@ declare class SmtpEmailProvider implements IEmailProvider {
2204
2265
  * and are not shared across instances; use `RedisOtpStorage` there.
2205
2266
  */
2206
2267
 
2207
- /** Aggregate sizes of the two internal maps — exposed by the {@link InMemoryOtpStorage.size} helper. */
2268
+ /** Aggregate sizes of the three internal maps — exposed by the {@link InMemoryOtpStorage.size} helper. */
2208
2269
  interface InMemoryStorageSize {
2209
2270
  otps: number;
2210
2271
  cooldowns: number;
2272
+ failures: number;
2211
2273
  }
2212
2274
  /** Process-local `IOtpStorage` for dev/test. */
2213
2275
  declare class InMemoryOtpStorage implements IOtpStorage {
@@ -2336,13 +2398,14 @@ declare class InMemoryOtpStorage implements IOtpStorage {
2336
2398
  */
2337
2399
  clearCooldown(tenantId: string, recipient: string, purpose: string): Promise<void>;
2338
2400
  /**
2339
- * Test helper — wipes all entries and cooldowns. Not part of `IOtpStorage`.
2401
+ * Test helper — wipes all entries, cooldowns and failure counters. Not part of `IOtpStorage`.
2340
2402
  */
2341
2403
  clear(): void;
2342
2404
  /**
2343
- * Test helper — current map sizes. Not part of `IOtpStorage`.
2405
+ * Test helper — current map sizes. Not part of `IOtpStorage`. Like the cooldowns, a failure
2406
+ * counter that has lapsed stays counted until it is read or cleared.
2344
2407
  *
2345
- * @returns The number of stored OTP entries and active cooldowns.
2408
+ * @returns The number of stored OTP entries, cooldowns and failure counters.
2346
2409
  */
2347
2410
  size(): InMemoryStorageSize;
2348
2411
  /** The unexpired failure count for a key, dropping a lapsed counter. Synchronous. */
@@ -2730,8 +2793,10 @@ declare const NOTIFICATION_ERROR_CODES: {
2730
2793
  readonly AUDIT_LOG_FAILED: "notification.audit_log_failed";
2731
2794
  readonly CHANNEL_DISABLED: "notification.channel_disabled";
2732
2795
  /**
2733
- * A `tenantId` or `recipient` that identifies nobody reached a scoping
2734
- * boundary — empty, whitespace-only, or not a string at all. Distinct from
2796
+ * A `tenantId`, `recipient` or `purpose` that cannot scope an OTP reached a
2797
+ * scoping boundary: empty, whitespace-only, not a string at all, carrying a
2798
+ * control character, or, for a purpose, longer than 64 characters or made of
2799
+ * anything but `A-Z a-z 0-9 : _ -`. Distinct from
2735
2800
  * {@link EMAIL_INVALID_RECIPIENT}, which is about a malformed address rather
2736
2801
  * than a value that cannot scope anything.
2737
2802
  */
@@ -2897,7 +2962,7 @@ declare const NOTIFICATION_ERROR_DEFINITIONS: {
2897
2962
  readonly INVALID_SCOPE_IDENTIFIER: {
2898
2963
  readonly code: "notification.invalid_scope_identifier";
2899
2964
  readonly status: HttpStatus.BAD_REQUEST;
2900
- readonly message: "Tenant or recipient identifier does not identify anybody";
2965
+ readonly message: "A tenant, recipient or purpose identifier is not valid";
2901
2966
  };
2902
2967
  };
2903
2968
  /** The symbolic key of any entry in {@link NOTIFICATION_ERROR_DEFINITIONS}. */
@@ -3032,4 +3097,4 @@ declare const DEFAULT_TTLS: {
3032
3097
  };
3033
3098
 
3034
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 };
3035
- 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 };