@bymax-one/nest-notification 1.4.8 → 1.4.10

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.
@@ -319,6 +319,27 @@ interface IOtpStorage {
319
319
  update(tenantId: string, recipient: string, purpose: string, entry: OtpEntry): Promise<void>;
320
320
  /** Removes the OTP entry. Idempotent. */
321
321
  delete(tenantId: string, recipient: string, purpose: string): Promise<void>;
322
+ /**
323
+ * Atomic compare-and-delete: removes the entry only when the value it still stores equals
324
+ * `expectedStored`, and reports whether this call removed it. Of N concurrent calls for one
325
+ * stored value, exactly one returns `true`.
326
+ *
327
+ * `expectedStored` is the exact STORED `code` the service read from the entry (the keyed
328
+ * digest when `otp.codeSecret` is set), never the guess a user typed: no plaintext guess
329
+ * reaches the storage. The service has already compared the guess in constant time; this
330
+ * only makes the one-time property hold when several verifications of the right code run
331
+ * at once. A code regenerated in between stores a different value, so it is left alone and
332
+ * the call returns `false`.
333
+ *
334
+ * Required when `otp.consumeOnVerify` is `true`: the service refuses to start without it,
335
+ * so a storage that cannot do this atomically never silently keeps the race.
336
+ *
337
+ * MUST be atomic.
338
+ *
339
+ * @param expectedStored - The stored code value the caller read.
340
+ * @returns `true` when this call deleted the entry, `false` when it was absent or changed.
341
+ */
342
+ deleteIfCode?(tenantId: string, recipient: string, purpose: string, expectedStored: string): Promise<boolean>;
322
343
  /**
323
344
  * Atomic cooldown acquire for `(tenant, recipient, purpose)`. Sets the cooldown
324
345
  * key only if it does not already exist (Redis: `SET NX EX`). Returns `true`
@@ -543,6 +564,12 @@ interface EmailChannelOptions {
543
564
  * Default: `10_485_760` (10 MiB).
544
565
  */
545
566
  maxAttachmentBytes?: number;
567
+ /**
568
+ * Maximum recipients of one message: `to`, `cc` and `bcc` together, counted after splitting
569
+ * each string on `,` and `;` the way the transport does. `EmailService` refuses a larger
570
+ * message with `EMAIL_INVALID_RECIPIENT` before the provider is called. Default: `50`.
571
+ */
572
+ maxRecipients?: number;
546
573
  }
547
574
  /** OTP channel configuration. Omitted when the OTP channel is not used. */
548
575
  interface OtpChannelOptions {
@@ -758,6 +785,7 @@ interface ResolvedEmailOptions {
758
785
  value: string;
759
786
  }>;
760
787
  maxAttachmentBytes: number;
788
+ maxRecipients: number;
761
789
  }
762
790
  /** Resolved OTP section — present only when the OTP channel is configured. */
763
791
  interface ResolvedOtpOptions {
@@ -902,6 +930,7 @@ declare class EmailService {
902
930
  * @returns The provider's message id.
903
931
  * @throws NotificationException `EMAIL_PROVIDER_NOT_CONFIGURED`, `INVALID_SCOPE_IDENTIFIER`
904
932
  * (a blank tenant or one with a control character), `EMAIL_ATTACHMENTS_TOO_LARGE`,
933
+ * `EMAIL_INVALID_RECIPIENT` (more recipients than `maxRecipients`),
905
934
  * `EMAIL_SEND_FAILED`, or `AUDIT_LOG_FAILED` (only when `audit.swallowErrors` is `false`).
906
935
  */
907
936
  send(input: EmailSendInput): Promise<{
@@ -939,6 +968,11 @@ declare class EmailService {
939
968
  }>;
940
969
  /** Returns the resolved email options or throws when the channel is not configured. */
941
970
  private requireEmailOptions;
971
+ /**
972
+ * Throws `EMAIL_INVALID_RECIPIENT` when to, cc and bcc together address more mailboxes than
973
+ * the channel allows. The refusal names the limit and never an address.
974
+ */
975
+ private guardRecipientCount;
942
976
  /** Throws `EMAIL_ATTACHMENTS_TOO_LARGE` when the attachments exceed the byte budget. */
943
977
  private guardAttachmentSize;
944
978
  /** Applies channel defaults and concatenates default + caller tags. */
@@ -1048,18 +1082,19 @@ interface OtpStatusResult {
1048
1082
  /** OTP generation, verification, consumption, and status. */
1049
1083
  declare class OtpService implements OnModuleInit {
1050
1084
  private readonly options;
1051
- private readonly storage;
1052
1085
  private readonly auditLog;
1053
1086
  private readonly emailService?;
1054
1087
  private readonly logger;
1055
1088
  private warnedFailuresNotCarried;
1089
+ /** The store every operation goes through: an outage of it answers 503. */
1090
+ private readonly storage;
1056
1091
  /**
1057
1092
  * @param options - The resolved, frozen module options.
1058
1093
  * @param storage - The configured OTP storage.
1059
1094
  * @param auditLog - The audit-log repository (no-op when none configured).
1060
1095
  * @param emailService - The email service; present only when the email channel is configured.
1061
1096
  */
1062
- constructor(options: ResolvedNotificationOptions, storage: IOtpStorage, auditLog: INotificationLogRepository, emailService?: EmailService | undefined);
1097
+ constructor(options: ResolvedNotificationOptions, store: IOtpStorage, auditLog: INotificationLogRepository, emailService?: EmailService | undefined);
1063
1098
  /**
1064
1099
  * Whether the OTP channel is configured and its storage is ready.
1065
1100
  *
@@ -1155,12 +1190,34 @@ declare class OtpService implements OnModuleInit {
1155
1190
  * @throws NotificationException `OTP_MANUAL_DELIVERY_UNAVAILABLE`.
1156
1191
  */
1157
1192
  private assertDeliverable;
1193
+ /**
1194
+ * Refuses, before any state exists, an email delivery to a string that is not exactly one
1195
+ * mailbox: the code goes to every address the string names. A manual delivery is the
1196
+ * caller's own, so a phone number or a device id stays a valid recipient.
1197
+ *
1198
+ * @throws NotificationException `EMAIL_INVALID_RECIPIENT`.
1199
+ */
1200
+ private assertMailbox;
1158
1201
  /** Delivers the code by email when requested; throws on failure (release is handled by the caller). */
1159
1202
  private deliverOtp;
1160
1203
  /** Clears the cooldown and deletes the OTP — used to undo a failed delivery. */
1161
1204
  private releaseOtp;
1162
1205
  /** Builds the OTP email payload with the auto-injected `{ code, expiresInMinutes, purpose }`. */
1163
1206
  private buildOtpEmail;
1207
+ /** Audits and returns the `not_found` verdict: no live code, or it was consumed by another call. */
1208
+ private rejectNotFound;
1209
+ /** Audits and returns the `max_attempts` verdict. */
1210
+ private rejectMaxAttempts;
1211
+ /**
1212
+ * With `consumeOnVerify`, removes the entry atomically while it still stores the value this
1213
+ * verification read, and reports whether another verification got there first. The one-time
1214
+ * property is decided here, not by a delete that follows: of N concurrent verifications of the
1215
+ * right code exactly one removes the entry. `storedCode` is the STORED value (the digest when
1216
+ * keyed), never the guess.
1217
+ *
1218
+ * @returns `true` when a concurrent verification consumed the code or it was regenerated.
1219
+ */
1220
+ private lostConsume;
1164
1221
  /** Finalizes a correct verification: consume-and-clear, or mark `validated`. */
1165
1222
  private finalizeVerifySuccess;
1166
1223
  /**
@@ -1170,7 +1227,7 @@ declare class OtpService implements OnModuleInit {
1170
1227
  * consumer-supplied {@link IOtpStorage} is not required to, and a blank scope would
1171
1228
  * then be shared by every caller that sent one.
1172
1229
  *
1173
- * @throws NotificationException `INVALID_SCOPE_IDENTIFIER` when either is blank.
1230
+ * @throws NotificationException `INVALID_SCOPE_IDENTIFIER` when either is blank or the purpose is not a plain name.
1174
1231
  */
1175
1232
  private assertScope;
1176
1233
  /**
@@ -1406,7 +1463,12 @@ declare class NotificationAuditInterceptor implements NestInterceptor {
1406
1463
  private buildEntry;
1407
1464
  /** Extracts the (unmasked) recipient from the dispatch payload. */
1408
1465
  private extractRecipient;
1409
- /** Extracts the audit `purpose`: the OTP purpose, or the email template name. */
1466
+ /**
1467
+ * Extracts the audit `purpose`: the OTP purpose, or the email template name. The interceptor sees
1468
+ * the payload before the service refuses it and audits a refused call too, so an OTP purpose that
1469
+ * is not a plain name is left out of the entry: a control character in it would forge a log
1470
+ * record and its length is unbounded.
1471
+ */
1410
1472
  private extractPurpose;
1411
1473
  }
1412
1474
 
@@ -1631,13 +1693,18 @@ declare class DefaultTemplateRenderer implements IEmailTemplateRenderer {
1631
1693
  /** Replaces every `{{path}}` placeholder, escaping only when `escape` is `true`. */
1632
1694
  private interpolate;
1633
1695
  /**
1634
- * Builds a variable resolver for one render call. Lookups go through a `Map`
1635
- * built from own enumerable entries (never bracket indexing) so neither flat
1636
- * nor nested resolution can reach inherited/prototype keys.
1696
+ * Builds a variable resolver for one render call. A key resolves only when the object holds it as
1697
+ * an own enumerable property, so neither flat nor nested resolution can reach inherited or
1698
+ * prototype keys, and only the property that is named is read.
1637
1699
  */
1638
1700
  private buildResolver;
1639
1701
  /** Walks a dotted path through own enumerable keys, stopping at any non-object. */
1640
1702
  private resolveNested;
1703
+ /**
1704
+ * The value of `key` when `object` holds it as an own enumerable property, otherwise `undefined`.
1705
+ * Called through `Object.prototype` so an object without a prototype works too.
1706
+ */
1707
+ private ownValue;
1641
1708
  /**
1642
1709
  * Validates a registered template shape, throwing on the offending key. The
1643
1710
  * optional `text` body, when present, must be a string — a non-string `text`
@@ -1670,6 +1737,13 @@ declare class DefaultTemplateRenderer implements IEmailTemplateRenderer {
1670
1737
  interface ResendEmailProviderOptions {
1671
1738
  /** Resend API key. When absent the provider is not configured and `send()` throws. */
1672
1739
  apiKey?: string;
1740
+ /**
1741
+ * Longest one `send()` may take, in milliseconds, from the request to the end of the response
1742
+ * body. An integer from `1` to `2147483647`; default `15000`. A send that exceeds it fails with
1743
+ * `EMAIL_SEND_FAILED`. The message may still have been accepted by Resend: only the answer is
1744
+ * missing, so the failure does not say the message was not sent.
1745
+ */
1746
+ timeoutMs?: number;
1673
1747
  }
1674
1748
  /**
1675
1749
  * Reference {@link IEmailProvider} on top of Resend.
@@ -1851,6 +1925,15 @@ interface SmtpEmailProviderOptions {
1851
1925
  greetingTimeout?: number;
1852
1926
  /** Idle-socket timeout in milliseconds. Defaults to `20000`. */
1853
1927
  socketTimeout?: number;
1928
+ /**
1929
+ * Longest one `send()` may take, in milliseconds, from the call to the transport's answer. An
1930
+ * integer from `1` to `2147483647`; default `60000`. The three timeouts above bound a phase or an
1931
+ * idle socket, so a relay that keeps trickling bytes could hold a send past all of them; this
1932
+ * bounds the whole call. A send that exceeds it fails with `EMAIL_SEND_FAILED` (HTTP 503). The
1933
+ * relay may still accept the message: only the answer is missing, so the failure does not say the
1934
+ * 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
+ */
1936
+ sendTimeoutMs?: number;
1854
1937
  }
1855
1938
  /**
1856
1939
  * Reference {@link IEmailProvider} speaking SMTP.
@@ -1885,6 +1968,7 @@ declare class SmtpEmailProvider implements IEmailProvider {
1885
1968
  /**
1886
1969
  * @param options - Adapter options; `host` is required to actually send, and
1887
1970
  * `credentials` must be complete whenever supplied at all.
1971
+ * @throws Error When `sendTimeoutMs` is not an integer from `1` to `2147483647`.
1888
1972
  */
1889
1973
  constructor(options?: SmtpEmailProviderOptions);
1890
1974
  /**
@@ -1924,6 +2008,19 @@ declare class SmtpEmailProvider implements IEmailProvider {
1924
2008
  * @throws Error When the transport rejects the message.
1925
2009
  */
1926
2010
  private dispatch;
2011
+ /** Builds the error this adapter throws for a transport failure, logging the scrubbed reason. */
2012
+ private failure;
2013
+ /**
2014
+ * The failure of a send whose body carries a credential: none of the relay's own words may reach a
2015
+ * log line or a thrown message — redaction removes the shapes it predicts and a re-encoded echo
2016
+ * defeats it. Only the reply codes a fixed grammar can express are published, and they are the
2017
+ * same whatever the body held.
2018
+ *
2019
+ * Filtered HERE, not only in EmailService: this adapter is public, and its own warn line would
2020
+ * otherwise write a code that contains the caller's declared secret — an OTP of `55` sits inside a
2021
+ * `550` reply.
2022
+ */
2023
+ private withheldFailure;
1927
2024
  /**
1928
2025
  * Removes the credentials, the caller's declared secrets and any echoed body
1929
2026
  * excerpt from a transport error's text — the credential scrub alone cannot
@@ -1941,7 +2038,15 @@ declare class SmtpEmailProvider implements IEmailProvider {
1941
2038
  * @returns The message with every known-secret value replaced.
1942
2039
  */
1943
2040
  private scrubTransportError;
1944
- /** The configured credentials that qualify as secret material, if any. */
2041
+ /**
2042
+ * The configured credentials that qualify as secret material, if any, and the base64 forms the
2043
+ * AUTH exchange carries them in: the user and the password as AUTH LOGIN sends them, and the
2044
+ * AUTH PLAIN token, which has an empty authorization identity. A relay that quotes the exchange
2045
+ * shows those, and a literal match cannot see them. The token is its own value: base64 groups
2046
+ * three bytes, so the token's bytes usually sit at another alignment than the user's or the
2047
+ * password's, and then neither of their encodings appears inside it. It cannot be derived from
2048
+ * them.
2049
+ */
1945
2050
  private credentialValues;
1946
2051
  /**
1947
2052
  * Replaces every occurrence of either configured credential with a placeholder.
@@ -2100,7 +2205,7 @@ declare class SmtpEmailProvider implements IEmailProvider {
2100
2205
  * @fileoverview In-memory `IOtpStorage` for development and unit tests.
2101
2206
  * @layer infrastructure
2102
2207
  *
2103
- * Backed by two native `Map`s. It is atomic by construction: `consumeAttempt`
2208
+ * Backed by native `Map`s. It is atomic by construction: `consumeAttempt`
2104
2209
  * performs its read → checks → increment → write with NO `await` in between, so
2105
2210
  * Node's single-threaded event loop cannot interleave two calls and overshoot
2106
2211
  * `maxAttempts`.
@@ -2109,10 +2214,11 @@ declare class SmtpEmailProvider implements IEmailProvider {
2109
2214
  * and are not shared across instances; use `RedisOtpStorage` there.
2110
2215
  */
2111
2216
 
2112
- /** Aggregate sizes of the two internal maps — exposed by the {@link InMemoryOtpStorage.size} helper. */
2217
+ /** Aggregate sizes of the three internal maps — exposed by the {@link InMemoryOtpStorage.size} helper. */
2113
2218
  interface InMemoryStorageSize {
2114
2219
  otps: number;
2115
2220
  cooldowns: number;
2221
+ failures: number;
2116
2222
  }
2117
2223
  /** Process-local `IOtpStorage` for dev/test. */
2118
2224
  declare class InMemoryOtpStorage implements IOtpStorage {
@@ -2202,6 +2308,17 @@ declare class InMemoryOtpStorage implements IOtpStorage {
2202
2308
  * @param purpose - OTP purpose.
2203
2309
  */
2204
2310
  delete(tenantId: string, recipient: string, purpose: string): Promise<void>;
2311
+ /**
2312
+ * Deletes the entry only when it still stores `expectedStored`. Synchronous inside the
2313
+ * method, so of N concurrent callers exactly one sees the value and removes it.
2314
+ *
2315
+ * @param tenantId - Tenant isolation scope.
2316
+ * @param recipient - Pre-normalized recipient identifier.
2317
+ * @param purpose - OTP purpose.
2318
+ * @param expectedStored - The stored code value the caller read.
2319
+ * @returns `true` when this call removed the entry.
2320
+ */
2321
+ deleteIfCode(tenantId: string, recipient: string, purpose: string, expectedStored: string): Promise<boolean>;
2205
2322
  /**
2206
2323
  * Acquires the cooldown lock only when one is not already active.
2207
2324
  *
@@ -2230,13 +2347,14 @@ declare class InMemoryOtpStorage implements IOtpStorage {
2230
2347
  */
2231
2348
  clearCooldown(tenantId: string, recipient: string, purpose: string): Promise<void>;
2232
2349
  /**
2233
- * Test helper — wipes all entries and cooldowns. Not part of `IOtpStorage`.
2350
+ * Test helper — wipes all entries, cooldowns and failure counters. Not part of `IOtpStorage`.
2234
2351
  */
2235
2352
  clear(): void;
2236
2353
  /**
2237
- * Test helper — current map sizes. Not part of `IOtpStorage`.
2354
+ * Test helper — current map sizes. Not part of `IOtpStorage`. Like the cooldowns, a failure
2355
+ * counter that has lapsed stays counted until it is read or cleared.
2238
2356
  *
2239
- * @returns The number of stored OTP entries and active cooldowns.
2357
+ * @returns The number of stored OTP entries, cooldowns and failure counters.
2240
2358
  */
2241
2359
  size(): InMemoryStorageSize;
2242
2360
  /** The unexpired failure count for a key, dropping a lapsed counter. Synchronous. */
@@ -2312,6 +2430,11 @@ declare class RedisOtpStorage implements IOtpStorage {
2312
2430
  * `PTTL` is read inside the script to preserve the original expiry on rewrite.
2313
2431
  */
2314
2432
  private static readonly CONSUME_ATTEMPT_LUA;
2433
+ /**
2434
+ * Atomic compare-and-delete: reads the entry, and deletes it only when its stored `code` equals
2435
+ * the value the caller read, so of N concurrent verifications exactly one removes it.
2436
+ */
2437
+ private static readonly DELETE_IF_CODE_LUA;
2315
2438
  /**
2316
2439
  * Atomic failure-counter primitive: one `INCR` and the lifetime refresh in a single script, so
2317
2440
  * concurrent failures each receive a distinct count and the counter never outlives its window
@@ -2368,6 +2491,16 @@ declare class RedisOtpStorage implements IOtpStorage {
2368
2491
  * @param purpose - OTP purpose.
2369
2492
  */
2370
2493
  delete(tenantId: string, recipient: string, purpose: string): Promise<void>;
2494
+ /**
2495
+ * Deletes the entry only when it still stores `expectedStored`, in one script.
2496
+ *
2497
+ * @param tenantId - Tenant isolation scope.
2498
+ * @param recipient - Pre-normalized recipient identifier.
2499
+ * @param purpose - OTP purpose.
2500
+ * @param expectedStored - The stored code value the caller read (the digest, when keyed).
2501
+ * @returns `true` when this call removed the entry.
2502
+ */
2503
+ deleteIfCode(tenantId: string, recipient: string, purpose: string, expectedStored: string): Promise<boolean>;
2371
2504
  /**
2372
2505
  * Atomic cooldown acquire with `SET … NX EX` — only the first concurrent caller wins.
2373
2506
  *
@@ -2599,6 +2732,7 @@ declare const NOTIFICATION_ERROR_CODES: {
2599
2732
  readonly OTP_EXPIRED: "notification.otp_expired";
2600
2733
  readonly OTP_MAX_ATTEMPTS_EXCEEDED: "notification.otp_max_attempts_exceeded";
2601
2734
  readonly OTP_INVALID_CODE: "notification.otp_invalid_code";
2735
+ readonly OTP_STORAGE_UNAVAILABLE: "notification.otp_storage_unavailable";
2602
2736
  readonly OTP_INVALID_LENGTH: "notification.otp_invalid_length";
2603
2737
  readonly SMS_PROVIDER_NOT_CONFIGURED: "notification.sms_provider_not_configured";
2604
2738
  readonly SMS_SEND_FAILED: "notification.sms_send_failed";
@@ -2608,8 +2742,10 @@ declare const NOTIFICATION_ERROR_CODES: {
2608
2742
  readonly AUDIT_LOG_FAILED: "notification.audit_log_failed";
2609
2743
  readonly CHANNEL_DISABLED: "notification.channel_disabled";
2610
2744
  /**
2611
- * A `tenantId` or `recipient` that identifies nobody reached a scoping
2612
- * boundary — empty, whitespace-only, or not a string at all. Distinct from
2745
+ * A `tenantId`, `recipient` or `purpose` that cannot scope an OTP reached a
2746
+ * scoping boundary: empty, whitespace-only, not a string at all, carrying a
2747
+ * control character, or, for a purpose, longer than 64 characters or made of
2748
+ * anything but `A-Z a-z 0-9 : _ -`. Distinct from
2613
2749
  * {@link EMAIL_INVALID_RECIPIENT}, which is about a malformed address rather
2614
2750
  * than a value that cannot scope anything.
2615
2751
  */
@@ -2656,7 +2792,7 @@ declare const NOTIFICATION_ERROR_DEFINITIONS: {
2656
2792
  readonly status: HttpStatus.PAYLOAD_TOO_LARGE;
2657
2793
  readonly message: "Email attachments exceed size limit";
2658
2794
  };
2659
- /** Reserved: `to` is not validated, so the library never throws this code. */
2795
+ /** Raised for an OTP recipient that is not one mailbox, and for a message over `maxRecipients`. */
2660
2796
  readonly EMAIL_INVALID_RECIPIENT: {
2661
2797
  readonly code: "notification.email_invalid_recipient";
2662
2798
  readonly status: HttpStatus.BAD_REQUEST;
@@ -2715,6 +2851,12 @@ declare const NOTIFICATION_ERROR_DEFINITIONS: {
2715
2851
  readonly status: HttpStatus.TOO_MANY_REQUESTS;
2716
2852
  readonly message: "Maximum OTP attempts exceeded";
2717
2853
  };
2854
+ /** Raised when the OTP store cannot be reached, is closed, or timed out: the caller may retry. */
2855
+ readonly OTP_STORAGE_UNAVAILABLE: {
2856
+ readonly code: "notification.otp_storage_unavailable";
2857
+ readonly status: HttpStatus.SERVICE_UNAVAILABLE;
2858
+ readonly message: "OTP storage unavailable";
2859
+ };
2718
2860
  /** Reserved: `verify()` returns `{ valid: false, reason: 'invalid_code' }` instead of throwing. */
2719
2861
  readonly OTP_INVALID_CODE: {
2720
2862
  readonly code: "notification.otp_invalid_code";
@@ -2769,7 +2911,7 @@ declare const NOTIFICATION_ERROR_DEFINITIONS: {
2769
2911
  readonly INVALID_SCOPE_IDENTIFIER: {
2770
2912
  readonly code: "notification.invalid_scope_identifier";
2771
2913
  readonly status: HttpStatus.BAD_REQUEST;
2772
- readonly message: "Tenant or recipient identifier does not identify anybody";
2914
+ readonly message: "A tenant, recipient or purpose identifier is not valid";
2773
2915
  };
2774
2916
  };
2775
2917
  /** The symbolic key of any entry in {@link NOTIFICATION_ERROR_DEFINITIONS}. */