@bymax-one/nest-notification 1.4.9 → 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.
@@ -1,5 +1,6 @@
1
1
  import { HttpStatus, Injectable, Inject, Optional, Logger, Module, HttpException } from '@nestjs/common';
2
2
  import { randomInt, timingSafeEqual, createHmac, randomUUID, createHash } from 'crypto';
3
+ import { domainToASCII } from 'url';
3
4
  import { catchError, from, concatMap, throwError, map } from 'rxjs';
4
5
 
5
6
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
@@ -27,6 +28,7 @@ var BYMAX_NOTIFICATION_SMS_PROVIDER = /* @__PURE__ */ Symbol("BYMAX_NOTIFICATION
27
28
  var BYMAX_NOTIFICATION_PUSH_PROVIDER = /* @__PURE__ */ Symbol("BYMAX_NOTIFICATION_PUSH_PROVIDER");
28
29
  var BYMAX_NOTIFICATION_TEMPLATE_RENDERER = /* @__PURE__ */ Symbol("BYMAX_NOTIFICATION_TEMPLATE_RENDERER");
29
30
  var BYMAX_NOTIFICATION_LOG_REPOSITORY = /* @__PURE__ */ Symbol("BYMAX_NOTIFICATION_LOG_REPOSITORY");
31
+ var BYMAX_NOTIFICATION_AUDIT_SINK = /* @__PURE__ */ Symbol("BYMAX_NOTIFICATION_AUDIT_SINK");
30
32
 
31
33
  // src/server/constants/default-options.constants.ts
32
34
  var DEFAULT_MAX_ATTACHMENT_BYTES = 10485760;
@@ -167,8 +169,10 @@ var NOTIFICATION_ERROR_CODES = {
167
169
  AUDIT_LOG_FAILED: "notification.audit_log_failed",
168
170
  CHANNEL_DISABLED: "notification.channel_disabled",
169
171
  /**
170
- * A `tenantId` or `recipient` that identifies nobody reached a scoping
171
- * boundary — empty, whitespace-only, or not a string at all. Distinct from
172
+ * A `tenantId`, `recipient` or `purpose` that cannot scope an OTP reached a
173
+ * scoping boundary: empty, whitespace-only, not a string at all, carrying a
174
+ * control character, or, for a purpose, longer than 64 characters or made of
175
+ * anything but `A-Z a-z 0-9 : _ -`. Distinct from
172
176
  * {@link EMAIL_INVALID_RECIPIENT}, which is about a malformed address rather
173
177
  * than a value that cannot scope anything.
174
178
  */
@@ -311,7 +315,7 @@ var NOTIFICATION_ERROR_DEFINITIONS = {
311
315
  INVALID_SCOPE_IDENTIFIER: {
312
316
  code: NOTIFICATION_ERROR_CODES.INVALID_SCOPE_IDENTIFIER,
313
317
  status: HttpStatus.BAD_REQUEST,
314
- message: "Tenant or recipient identifier does not identify anybody"
318
+ message: "A tenant, recipient or purpose identifier is not valid"
315
319
  }
316
320
  };
317
321
  var NOTIFICATION_ERROR_DEFINITION_MAP = new Map(
@@ -376,6 +380,47 @@ var NotificationException = class extends HttpException {
376
380
  }
377
381
  };
378
382
 
383
+ // src/server/utils/tenant-scope.ts
384
+ var CONTROL_CHARACTER = new RegExp("\\p{Cc}", "u");
385
+ function refuse(owner, label, reason) {
386
+ return new NotificationException(
387
+ "INVALID_SCOPE_IDENTIFIER",
388
+ { boundary: owner, parameter: label, reason },
389
+ { message: `[${owner}] ${label} ${reason}` }
390
+ );
391
+ }
392
+ function assertIdentifies(owner, label, value) {
393
+ if (typeof value !== "string") {
394
+ throw refuse(owner, label, `expected a string, received ${typeof value}`);
395
+ }
396
+ if (value.trim() === "") {
397
+ throw refuse(owner, label, "empty or whitespace-only");
398
+ }
399
+ if (CONTROL_CHARACTER.test(value)) {
400
+ throw refuse(owner, label, "contains a control character");
401
+ }
402
+ }
403
+ var MAX_PURPOSE_LENGTH = 64;
404
+ var PURPOSE_CHARACTERS = /^[A-Za-z0-9:_-]+$/;
405
+ function purposeProblem(value) {
406
+ if (typeof value !== "string") {
407
+ return `expected a string, received ${typeof value}`;
408
+ }
409
+ if (value === "") {
410
+ return "empty";
411
+ }
412
+ if (value.length > MAX_PURPOSE_LENGTH) {
413
+ return `longer than ${String(MAX_PURPOSE_LENGTH)} characters`;
414
+ }
415
+ return PURPOSE_CHARACTERS.test(value) ? void 0 : "contains a character outside A-Z a-z 0-9 : _ -";
416
+ }
417
+ function assertPurpose(owner, value) {
418
+ const problem = purposeProblem(value);
419
+ if (problem !== void 0) {
420
+ throw refuse(owner, "purpose", problem);
421
+ }
422
+ }
423
+
379
424
  // src/server/config/default-options.ts
380
425
  var VALID_CODE_TYPES = ["numeric", "alpha", "alphanumeric"];
381
426
  var OTP_MIN_LENGTH = 1;
@@ -470,6 +515,14 @@ function validateOtpOptions(otp) {
470
515
  if (otp.defaultMaxAttempts !== void 0 && otp.defaultMaxAttempts < 1) {
471
516
  throw new Error("[BymaxNotificationModule] options.otp.defaultMaxAttempts must be at least 1");
472
517
  }
518
+ for (const key of Object.keys(otp.perPurpose ?? {})) {
519
+ const problem = purposeProblem(key);
520
+ if (problem !== void 0) {
521
+ throw new Error(
522
+ `[BymaxNotificationModule] options.otp.perPurpose has the key ${JSON.stringify(key)}, which is not a valid purpose: ${problem}`
523
+ );
524
+ }
525
+ }
473
526
  if (otp.resendCooldownSeconds !== void 0 && otp.resendCooldownSeconds < 0) {
474
527
  throw new Error(
475
528
  "[BymaxNotificationModule] options.otp.resendCooldownSeconds must be 0 or greater"
@@ -552,14 +605,13 @@ var DefaultTemplateRenderer = class {
552
605
  });
553
606
  }
554
607
  /**
555
- * Builds a variable resolver for one render call. Lookups go through a `Map`
556
- * built from own enumerable entries (never bracket indexing) so neither flat
557
- * nor nested resolution can reach inherited/prototype keys.
608
+ * Builds a variable resolver for one render call. A key resolves only when the object holds it as
609
+ * an own enumerable property, so neither flat nor nested resolution can reach inherited or
610
+ * prototype keys, and only the property that is named is read.
558
611
  */
559
612
  buildResolver(data) {
560
613
  if (!this.enableNestedPaths) {
561
- const values = new Map(Object.entries(data));
562
- return (path) => values.get(path);
614
+ return (path) => this.ownValue(data, path);
563
615
  }
564
616
  return (path) => this.resolveNested(data, path);
565
617
  }
@@ -570,10 +622,17 @@ var DefaultTemplateRenderer = class {
570
622
  if (current === null || current === void 0 || typeof current !== "object") {
571
623
  return void 0;
572
624
  }
573
- current = new Map(Object.entries(current)).get(key);
625
+ current = this.ownValue(current, key);
574
626
  }
575
627
  return current;
576
628
  }
629
+ /**
630
+ * The value of `key` when `object` holds it as an own enumerable property, otherwise `undefined`.
631
+ * Called through `Object.prototype` so an object without a prototype works too.
632
+ */
633
+ ownValue(object, key) {
634
+ return Object.prototype.propertyIsEnumerable.call(object, key) ? Reflect.get(object, key) : void 0;
635
+ }
577
636
  /**
578
637
  * Validates a registered template shape, throwing on the offending key. The
579
638
  * optional `text` body, when present, must be a string — a non-string `text`
@@ -598,6 +657,87 @@ var DefaultTemplateRenderer = class {
598
657
  DefaultTemplateRenderer = __decorateClass([
599
658
  Injectable()
600
659
  ], DefaultTemplateRenderer);
660
+
661
+ // src/server/utils/audit-escape.ts
662
+ var MAX_METADATA_DEPTH = 4;
663
+ var DEPTH_LIMIT_MARKER = "[depth limit]";
664
+ var CIRCULAR_MARKER = "[circular]";
665
+ var NON_PLAIN_MARKER = "[non-plain value]";
666
+ var ESCAPED = /[\p{Cc}\p{Zl}\p{Zp}\u061C\u200E\u200F\u202A-\u202E\u2066-\u2069]/gu;
667
+ var NAMED = /* @__PURE__ */ new Map([
668
+ ["\n", "\\n"],
669
+ ["\r", "\\r"],
670
+ [" ", "\\t"]
671
+ ]);
672
+ function sequenceOf(character) {
673
+ return NAMED.get(character) ?? `\\u${character.charCodeAt(0).toString(16).padStart(4, "0")}`;
674
+ }
675
+ function escapeAuditString(value) {
676
+ return value.replace(ESCAPED, sequenceOf);
677
+ }
678
+ function isPlainObject(value) {
679
+ const prototype = Object.getPrototypeOf(value);
680
+ return prototype === Object.prototype || prototype === null;
681
+ }
682
+ function escapeRecord(record, level, ancestors) {
683
+ const escaped = /* @__PURE__ */ new Map();
684
+ for (const [key, value] of Object.entries(record)) {
685
+ const base = escapeAuditString(key);
686
+ let name = base;
687
+ for (let attempt = 2; escaped.has(name); attempt++) {
688
+ name = `${base}#${attempt}`;
689
+ }
690
+ escaped.set(name, escapeValue(value, level + 1, ancestors));
691
+ }
692
+ return Object.fromEntries(escaped);
693
+ }
694
+ function escapeValue(value, level, ancestors) {
695
+ if (typeof value === "string") {
696
+ return escapeAuditString(value);
697
+ }
698
+ if (typeof value === "function" || typeof value === "symbol") {
699
+ return NON_PLAIN_MARKER;
700
+ }
701
+ if (typeof value !== "object" || value === null) {
702
+ return value;
703
+ }
704
+ if (level > MAX_METADATA_DEPTH) {
705
+ return DEPTH_LIMIT_MARKER;
706
+ }
707
+ if (ancestors.has(value)) {
708
+ return CIRCULAR_MARKER;
709
+ }
710
+ const isArray = Array.isArray(value);
711
+ if (!isArray && !isPlainObject(value)) {
712
+ return NON_PLAIN_MARKER;
713
+ }
714
+ ancestors.add(value);
715
+ try {
716
+ return isArray ? value.map((item) => escapeValue(item, level + 1, ancestors)) : escapeRecord(value, level, ancestors);
717
+ } finally {
718
+ ancestors.delete(value);
719
+ }
720
+ }
721
+ function escapeAuditEntry(entry) {
722
+ return escapeRecord(
723
+ entry,
724
+ 0,
725
+ /* @__PURE__ */ new WeakSet()
726
+ );
727
+ }
728
+
729
+ // src/server/providers/escaping-log-repository.ts
730
+ var EscapingLogRepository = class {
731
+ /** @param inner - The host's repository that receives the escaped entries. */
732
+ constructor(inner) {
733
+ this.inner = inner;
734
+ this.name = inner.name;
735
+ }
736
+ /** Writes `entry` to the wrapped repository with its strings escaped. */
737
+ async create(entry) {
738
+ await this.inner.create(escapeAuditEntry(entry));
739
+ }
740
+ };
601
741
  var NoOpNotificationLogRepository = class {
602
742
  constructor() {
603
743
  this.name = "noop";
@@ -1188,27 +1328,6 @@ function buildRedactedCopy(name, message, stack) {
1188
1328
  return copy;
1189
1329
  }
1190
1330
 
1191
- // src/server/utils/tenant-scope.ts
1192
- var CONTROL_CHARACTER = new RegExp("\\p{Cc}", "u");
1193
- function refuse(owner, label, reason) {
1194
- return new NotificationException(
1195
- "INVALID_SCOPE_IDENTIFIER",
1196
- { boundary: owner, parameter: label, reason },
1197
- { message: `[${owner}] ${label} ${reason}` }
1198
- );
1199
- }
1200
- function assertIdentifies(owner, label, value) {
1201
- if (typeof value !== "string") {
1202
- throw refuse(owner, label, `expected a string, received ${typeof value}`);
1203
- }
1204
- if (value.trim() === "") {
1205
- throw refuse(owner, label, "empty or whitespace-only");
1206
- }
1207
- if (CONTROL_CHARACTER.test(value)) {
1208
- throw refuse(owner, label, "contains a control character");
1209
- }
1210
- }
1211
-
1212
1331
  // src/server/services/email.service.ts
1213
1332
  var FALLBACK_LOCALE = "en";
1214
1333
  var OTP_TEMPLATE_REMEDY = "register an 'otp_code' template (for example 'otp_code::en') in your template renderer, such as DefaultTemplateRenderer; the OTP email can use another template through the emailTemplate option of generate()";
@@ -1560,7 +1679,7 @@ EmailService = __decorateClass([
1560
1679
  __decorateParam(0, Inject(BYMAX_NOTIFICATION_OPTIONS)),
1561
1680
  __decorateParam(1, Inject(BYMAX_NOTIFICATION_EMAIL_PROVIDER)),
1562
1681
  __decorateParam(2, Inject(BYMAX_NOTIFICATION_TEMPLATE_RENDERER)),
1563
- __decorateParam(3, Inject(BYMAX_NOTIFICATION_LOG_REPOSITORY))
1682
+ __decorateParam(3, Inject(BYMAX_NOTIFICATION_AUDIT_SINK))
1564
1683
  ], EmailService);
1565
1684
  var NUMERIC = "0123456789";
1566
1685
  var ALPHA = "ABCDEFGHJKLMNPQRSTUVWXYZ";
@@ -1624,11 +1743,31 @@ function formatCooldown(remainingSeconds) {
1624
1743
  }
1625
1744
  return parts.join(" ");
1626
1745
  }
1627
-
1628
- // src/server/utils/recipient.ts
1746
+ var PLAIN_DOMAIN = /^[\p{L}\p{N}\p{M}_.-]+$/u;
1747
+ var ASCII_LABEL = new RegExp("^\\p{ASCII}*$", "u");
1748
+ function isLabelWiseMapping(folded, mapped) {
1749
+ const expected = folded.split(".").map((label) => ASCII_LABEL.test(label) ? label.toLowerCase() : null);
1750
+ const output = mapped.split(".");
1751
+ return expected.length === output.length && output.every((label, index) => {
1752
+ const want = expected.at(index);
1753
+ return want === null ? label.startsWith("xn--") : label === want;
1754
+ });
1755
+ }
1756
+ function normalizeDomain(domain) {
1757
+ const folded = domain.normalize("NFKC");
1758
+ if (!PLAIN_DOMAIN.test(folded)) {
1759
+ return domain.toLowerCase();
1760
+ }
1761
+ const mapped = domainToASCII(domain);
1762
+ return isLabelWiseMapping(folded, mapped) ? mapped : domain.toLowerCase();
1763
+ }
1629
1764
  function normalizeRecipient(recipient) {
1630
1765
  const trimmed = recipient.trim();
1631
- return trimmed.includes("@") ? trimmed.toLowerCase() : trimmed;
1766
+ const at = trimmed.lastIndexOf("@");
1767
+ if (at === -1) {
1768
+ return trimmed;
1769
+ }
1770
+ return `${trimmed.slice(0, at).toLowerCase()}@${normalizeDomain(trimmed.slice(at + 1))}`;
1632
1771
  }
1633
1772
 
1634
1773
  // src/server/utils/storage-failures.ts
@@ -1969,7 +2108,7 @@ var OtpService = class {
1969
2108
  );
1970
2109
  } catch (error) {
1971
2110
  this.logger.warn(
1972
- `[${TEMPLATE_WARNING_CODE}] Could not check whether the email template '${DEFAULT_OTP_TEMPLATE}' resolves (${describeError(error)}); if it does not, the first generate() that delivers by email fails with TEMPLATE_NOT_FOUND.`
2111
+ `[${TEMPLATE_WARNING_CODE}] Could not check whether the email template '${DEFAULT_OTP_TEMPLATE}' resolves (${escapeAuditString(describeError(error))}); if it does not, the first generate() that delivers by email fails with TEMPLATE_NOT_FOUND.`
1973
2112
  );
1974
2113
  }
1975
2114
  }
@@ -2104,11 +2243,12 @@ var OtpService = class {
2104
2243
  * consumer-supplied {@link IOtpStorage} is not required to, and a blank scope would
2105
2244
  * then be shared by every caller that sent one.
2106
2245
  *
2107
- * @throws NotificationException `INVALID_SCOPE_IDENTIFIER` when either is blank.
2246
+ * @throws NotificationException `INVALID_SCOPE_IDENTIFIER` when either is blank or the purpose is not a plain name.
2108
2247
  */
2109
2248
  assertScope(ref) {
2110
2249
  assertIdentifies("OtpService", "tenantId", ref.tenantId);
2111
2250
  assertIdentifies("OtpService", "recipient", ref.recipient);
2251
+ assertPurpose("OtpService", ref.purpose);
2112
2252
  }
2113
2253
  /**
2114
2254
  * Returns the input with its recipient replaced by the value the OTP state is keyed on.
@@ -2171,7 +2311,7 @@ OtpService = __decorateClass([
2171
2311
  Injectable(),
2172
2312
  __decorateParam(0, Inject(BYMAX_NOTIFICATION_OPTIONS)),
2173
2313
  __decorateParam(1, Inject(BYMAX_NOTIFICATION_OTP_STORAGE)),
2174
- __decorateParam(2, Inject(BYMAX_NOTIFICATION_LOG_REPOSITORY)),
2314
+ __decorateParam(2, Inject(BYMAX_NOTIFICATION_AUDIT_SINK)),
2175
2315
  __decorateParam(3, Optional()),
2176
2316
  __decorateParam(3, Inject(EmailService))
2177
2317
  ], OtpService);
@@ -2430,6 +2570,7 @@ var BymaxNotificationModule = class {
2430
2570
  exports: [
2431
2571
  BYMAX_NOTIFICATION_OPTIONS,
2432
2572
  BYMAX_NOTIFICATION_LOG_REPOSITORY,
2573
+ BYMAX_NOTIFICATION_AUDIT_SINK,
2433
2574
  BYMAX_NOTIFICATION_EMAIL_PROVIDER,
2434
2575
  BYMAX_NOTIFICATION_TEMPLATE_RENDERER,
2435
2576
  BYMAX_NOTIFICATION_OTP_STORAGE,
@@ -2456,7 +2597,7 @@ var BymaxNotificationModule = class {
2456
2597
  BYMAX_NOTIFICATION_OPTIONS,
2457
2598
  BYMAX_NOTIFICATION_EMAIL_PROVIDER,
2458
2599
  BYMAX_NOTIFICATION_TEMPLATE_RENDERER,
2459
- BYMAX_NOTIFICATION_LOG_REPOSITORY
2600
+ BYMAX_NOTIFICATION_AUDIT_SINK
2460
2601
  ]
2461
2602
  },
2462
2603
  {
@@ -2465,7 +2606,7 @@ var BymaxNotificationModule = class {
2465
2606
  inject: [
2466
2607
  BYMAX_NOTIFICATION_OPTIONS,
2467
2608
  BYMAX_NOTIFICATION_OTP_STORAGE,
2468
- BYMAX_NOTIFICATION_LOG_REPOSITORY,
2609
+ BYMAX_NOTIFICATION_AUDIT_SINK,
2469
2610
  // Stryker disable next-line BooleanLiteral: the EmailService token is ALWAYS registered in async mode (as a factory that resolves to `undefined` when email is absent), so Nest resolves it whether optional is true or false — `optional: false` would still inject `undefined`, never throw, making the flag observationally inert here.
2470
2611
  { token: EmailService, optional: true }
2471
2612
  ]
@@ -2496,6 +2637,7 @@ var BymaxNotificationModule = class {
2496
2637
  useFactory: (raw) => raw.audit ? instantiate(raw.audit.repository) : new NoOpNotificationLogRepository(),
2497
2638
  inject: [RAW_NOTIFICATION_OPTIONS]
2498
2639
  },
2640
+ auditSinkProvider(),
2499
2641
  {
2500
2642
  provide: BYMAX_NOTIFICATION_EMAIL_PROVIDER,
2501
2643
  useFactory: (raw) => raw.email ? instantiate(raw.email.provider) : null,
@@ -2517,7 +2659,8 @@ var BymaxNotificationModule = class {
2517
2659
  static buildProviders(options, resolved) {
2518
2660
  const providers = [
2519
2661
  { provide: BYMAX_NOTIFICATION_OPTIONS, useValue: resolved },
2520
- options.audit?.repository ? resolveAsProvider(BYMAX_NOTIFICATION_LOG_REPOSITORY, options.audit.repository) : { provide: BYMAX_NOTIFICATION_LOG_REPOSITORY, useClass: NoOpNotificationLogRepository }
2662
+ options.audit?.repository ? resolveAsProvider(BYMAX_NOTIFICATION_LOG_REPOSITORY, options.audit.repository) : { provide: BYMAX_NOTIFICATION_LOG_REPOSITORY, useClass: NoOpNotificationLogRepository },
2663
+ auditSinkProvider()
2521
2664
  ];
2522
2665
  if (resolved.email && options.email) {
2523
2666
  providers.push(resolveAsProvider(BYMAX_NOTIFICATION_EMAIL_PROVIDER, options.email.provider));
@@ -2559,6 +2702,13 @@ function activeChannels(resolved) {
2559
2702
  }
2560
2703
  return channels;
2561
2704
  }
2705
+ function auditSinkProvider() {
2706
+ return {
2707
+ provide: BYMAX_NOTIFICATION_AUDIT_SINK,
2708
+ useFactory: (repository) => new EscapingLogRepository(repository),
2709
+ inject: [BYMAX_NOTIFICATION_LOG_REPOSITORY]
2710
+ };
2711
+ }
2562
2712
  function resolveRenderer(renderer) {
2563
2713
  if (renderer === void 0) {
2564
2714
  return {
@@ -2743,15 +2893,23 @@ var NotificationAuditInterceptor = class {
2743
2893
  }
2744
2894
  return input.payload.recipient;
2745
2895
  }
2746
- /** Extracts the audit `purpose`: the OTP purpose, or the email template name. */
2896
+ /**
2897
+ * Extracts the audit `purpose`: the OTP purpose, or the email template name. The interceptor sees
2898
+ * the payload before the service refuses it and audits a refused call too, so an OTP purpose that
2899
+ * is not a plain name is left out of the entry: a control character in it would forge a log
2900
+ * record and its length is unbounded.
2901
+ */
2747
2902
  extractPurpose(input) {
2748
- return input.channel === "otp" ? input.payload.purpose : input.payload.template;
2903
+ if (input.channel !== "otp") {
2904
+ return input.payload.template;
2905
+ }
2906
+ return purposeProblem(input.payload.purpose) === void 0 ? input.payload.purpose : void 0;
2749
2907
  }
2750
2908
  };
2751
2909
  NotificationAuditInterceptor = __decorateClass([
2752
2910
  Injectable(),
2753
2911
  __decorateParam(0, Inject(BYMAX_NOTIFICATION_OPTIONS)),
2754
- __decorateParam(1, Inject(BYMAX_NOTIFICATION_LOG_REPOSITORY))
2912
+ __decorateParam(1, Inject(BYMAX_NOTIFICATION_AUDIT_SINK))
2755
2913
  ], NotificationAuditInterceptor);
2756
2914
 
2757
2915
  // src/server/constants/notification-purposes.ts
@@ -2962,7 +3120,7 @@ var ResendEmailProvider = class {
2962
3120
  return withCode(new Error("Resend send failed"), code);
2963
3121
  }
2964
3122
  const reason = this.scrubSendError(rawMessage, options);
2965
- this.logger.warn(`[RESEND_SEND_FAILED] ${reason}`);
3123
+ this.logger.warn(`[RESEND_SEND_FAILED] ${escapeAuditString(reason)}`);
2966
3124
  return withCode(new Error(`Resend send failed: ${reason}`), code);
2967
3125
  }
2968
3126
  /**
@@ -3201,7 +3359,7 @@ var SmtpEmailProvider = class {
3201
3359
  return this.withheldFailure(raw, code, redactValuesList);
3202
3360
  }
3203
3361
  const reason = this.scrubTransportError(raw, payload, redactValuesList);
3204
- this.logger.warn(`[SMTP_SEND_FAILED] ${reason}`);
3362
+ this.logger.warn(`[SMTP_SEND_FAILED] ${escapeAuditString(reason)}`);
3205
3363
  return Object.assign(
3206
3364
  new Error(`SMTP send failed: ${reason}`),
3207
3365
  code === void 0 ? {} : { code }
@@ -3736,7 +3894,7 @@ var InMemoryOtpStorage = class {
3736
3894
  this.cooldowns.delete(this.key(tenantId, recipient, purpose));
3737
3895
  }
3738
3896
  /**
3739
- * Test helper — wipes all entries and cooldowns. Not part of `IOtpStorage`.
3897
+ * Test helper — wipes all entries, cooldowns and failure counters. Not part of `IOtpStorage`.
3740
3898
  */
3741
3899
  clear() {
3742
3900
  this.store.clear();
@@ -3744,12 +3902,17 @@ var InMemoryOtpStorage = class {
3744
3902
  this.failures.clear();
3745
3903
  }
3746
3904
  /**
3747
- * Test helper — current map sizes. Not part of `IOtpStorage`.
3905
+ * Test helper — current map sizes. Not part of `IOtpStorage`. Like the cooldowns, a failure
3906
+ * counter that has lapsed stays counted until it is read or cleared.
3748
3907
  *
3749
- * @returns The number of stored OTP entries and active cooldowns.
3908
+ * @returns The number of stored OTP entries, cooldowns and failure counters.
3750
3909
  */
3751
3910
  size() {
3752
- return { otps: this.store.size, cooldowns: this.cooldowns.size };
3911
+ return {
3912
+ otps: this.store.size,
3913
+ cooldowns: this.cooldowns.size,
3914
+ failures: this.failures.size
3915
+ };
3753
3916
  }
3754
3917
  /** The unexpired failure count for a key, dropping a lapsed counter. Synchronous. */
3755
3918
  liveFailures(key) {
@@ -3773,6 +3936,7 @@ var InMemoryOtpStorage = class {
3773
3936
  * stays unambiguous too.
3774
3937
  */
3775
3938
  key(tenantId, recipient, purpose) {
3939
+ assertPurpose("InMemoryOtpStorage", purpose);
3776
3940
  return `${hashTenantRecipient(tenantId, recipient)}::${purpose}`;
3777
3941
  }
3778
3942
  };
@@ -3992,14 +4156,17 @@ var RedisOtpStorage = class {
3992
4156
  }
3993
4157
  /** Builds the OTP entry key: `{namespace}:otp:{purpose}:{hashTenantRecipient(...)}`. */
3994
4158
  otpKey(tenantId, recipient, purpose) {
4159
+ assertPurpose("RedisOtpStorage", purpose);
3995
4160
  return `${this.namespace}:otp:${purpose}:${hashTenantRecipient(tenantId, recipient)}`;
3996
4161
  }
3997
4162
  /** Builds the failure-counter key: `{namespace}:otp_fail:{purpose}:{hashTenantRecipient(...)}`. */
3998
4163
  failureKey(tenantId, recipient, purpose) {
4164
+ assertPurpose("RedisOtpStorage", purpose);
3999
4165
  return `${this.namespace}:otp_fail:${purpose}:${hashTenantRecipient(tenantId, recipient)}`;
4000
4166
  }
4001
4167
  /** Builds the cooldown key: `{namespace}:otp_cd:{purpose}:{hashTenantRecipient(...)}`. */
4002
4168
  cooldownKey(tenantId, recipient, purpose) {
4169
+ assertPurpose("RedisOtpStorage", purpose);
4003
4170
  return `${this.namespace}:otp_cd:${purpose}:${hashTenantRecipient(tenantId, recipient)}`;
4004
4171
  }
4005
4172
  };
@@ -28,8 +28,10 @@ var NOTIFICATION_ERROR_CODES = {
28
28
  AUDIT_LOG_FAILED: "notification.audit_log_failed",
29
29
  CHANNEL_DISABLED: "notification.channel_disabled",
30
30
  /**
31
- * A `tenantId` or `recipient` that identifies nobody reached a scoping
32
- * boundary — empty, whitespace-only, or not a string at all. Distinct from
31
+ * A `tenantId`, `recipient` or `purpose` that cannot scope an OTP reached a
32
+ * scoping boundary: empty, whitespace-only, not a string at all, carrying a
33
+ * control character, or, for a purpose, longer than 64 characters or made of
34
+ * anything but `A-Z a-z 0-9 : _ -`. Distinct from
33
35
  * {@link EMAIL_INVALID_RECIPIENT}, which is about a malformed address rather
34
36
  * than a value that cannot scope anything.
35
37
  */
@@ -104,8 +104,10 @@ declare const NOTIFICATION_ERROR_CODES: {
104
104
  readonly AUDIT_LOG_FAILED: "notification.audit_log_failed";
105
105
  readonly CHANNEL_DISABLED: "notification.channel_disabled";
106
106
  /**
107
- * A `tenantId` or `recipient` that identifies nobody reached a scoping
108
- * boundary — empty, whitespace-only, or not a string at all. Distinct from
107
+ * A `tenantId`, `recipient` or `purpose` that cannot scope an OTP reached a
108
+ * scoping boundary: empty, whitespace-only, not a string at all, carrying a
109
+ * control character, or, for a purpose, longer than 64 characters or made of
110
+ * anything but `A-Z a-z 0-9 : _ -`. Distinct from
109
111
  * {@link EMAIL_INVALID_RECIPIENT}, which is about a malformed address rather
110
112
  * than a value that cannot scope anything.
111
113
  */
@@ -104,8 +104,10 @@ declare const NOTIFICATION_ERROR_CODES: {
104
104
  readonly AUDIT_LOG_FAILED: "notification.audit_log_failed";
105
105
  readonly CHANNEL_DISABLED: "notification.channel_disabled";
106
106
  /**
107
- * A `tenantId` or `recipient` that identifies nobody reached a scoping
108
- * boundary — empty, whitespace-only, or not a string at all. Distinct from
107
+ * A `tenantId`, `recipient` or `purpose` that cannot scope an OTP reached a
108
+ * scoping boundary: empty, whitespace-only, not a string at all, carrying a
109
+ * control character, or, for a purpose, longer than 64 characters or made of
110
+ * anything but `A-Z a-z 0-9 : _ -`. Distinct from
109
111
  * {@link EMAIL_INVALID_RECIPIENT}, which is about a malformed address rather
110
112
  * than a value that cannot scope anything.
111
113
  */
@@ -26,8 +26,10 @@ var NOTIFICATION_ERROR_CODES = {
26
26
  AUDIT_LOG_FAILED: "notification.audit_log_failed",
27
27
  CHANNEL_DISABLED: "notification.channel_disabled",
28
28
  /**
29
- * A `tenantId` or `recipient` that identifies nobody reached a scoping
30
- * boundary — empty, whitespace-only, or not a string at all. Distinct from
29
+ * A `tenantId`, `recipient` or `purpose` that cannot scope an OTP reached a
30
+ * scoping boundary: empty, whitespace-only, not a string at all, carrying a
31
+ * control character, or, for a purpose, longer than 64 characters or made of
32
+ * anything but `A-Z a-z 0-9 : _ -`. Distinct from
31
33
  * {@link EMAIL_INVALID_RECIPIENT}, which is about a malformed address rather
32
34
  * than a value that cannot scope anything.
33
35
  */
@@ -284,13 +284,14 @@ var ANY_CODE = "111111";
284
284
  var OTHER_CODE = "222222";
285
285
  function makeScope() {
286
286
  const run = crypto.randomUUID();
287
+ const purposeRun = run.replaceAll("-", "").slice(0, 12);
287
288
  return {
288
289
  tenantA: `${KEY_PREFIX}_${run}_${TENANT_A}`,
289
290
  tenantB: `${KEY_PREFIX}_${run}_${TENANT_B}`,
290
291
  recipient: `${run}_${RECIPIENT_LOCAL}`,
291
292
  absentRecipient: `${run}_${ABSENT_LOCAL}`,
292
- purpose: `${KEY_PREFIX}_${run}_${PURPOSE_MAIN}`,
293
- otherPurpose: `${KEY_PREFIX}_${run}_${PURPOSE_OTHER}`,
293
+ purpose: `${KEY_PREFIX}_${purposeRun}_${PURPOSE_MAIN}`,
294
+ otherPurpose: `${KEY_PREFIX}_${purposeRun}_${PURPOSE_OTHER}`,
294
295
  // Same characters, two different (tenant, recipient) splits. A key built by
295
296
  // joining the raw values around `:` maps both onto one string, and so does one
296
297
  // built around `::`, which the single-colon pair alone does not expose.
@@ -282,13 +282,14 @@ var ANY_CODE = "111111";
282
282
  var OTHER_CODE = "222222";
283
283
  function makeScope() {
284
284
  const run = randomUUID();
285
+ const purposeRun = run.replaceAll("-", "").slice(0, 12);
285
286
  return {
286
287
  tenantA: `${KEY_PREFIX}_${run}_${TENANT_A}`,
287
288
  tenantB: `${KEY_PREFIX}_${run}_${TENANT_B}`,
288
289
  recipient: `${run}_${RECIPIENT_LOCAL}`,
289
290
  absentRecipient: `${run}_${ABSENT_LOCAL}`,
290
- purpose: `${KEY_PREFIX}_${run}_${PURPOSE_MAIN}`,
291
- otherPurpose: `${KEY_PREFIX}_${run}_${PURPOSE_OTHER}`,
291
+ purpose: `${KEY_PREFIX}_${purposeRun}_${PURPOSE_MAIN}`,
292
+ otherPurpose: `${KEY_PREFIX}_${purposeRun}_${PURPOSE_OTHER}`,
292
293
  // Same characters, two different (tenant, recipient) splits. A key built by
293
294
  // joining the raw values around `:` maps both onto one string, and so does one
294
295
  // built around `::`, which the single-colon pair alone does not expose.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bymax-one/nest-notification",
3
- "version": "1.4.9",
3
+ "version": "1.4.10",
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",