@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,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;
@@ -49,6 +51,15 @@ var DEFAULT_EMAIL_OPTIONS = {
49
51
  var DEFAULT_AUDIT_OPTIONS = {
50
52
  swallowErrors: true
51
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
+ };
52
63
  var CODE_DIGEST_PREFIX = "hmac-sha256:v1:";
53
64
  var MIN_CODE_SECRET_BYTES = 32;
54
65
  var CONTEXT = "bymax-notification:otp-code:v1\0";
@@ -100,6 +111,10 @@ function resolveOtp(otp) {
100
111
  );
101
112
  const perPurpose = Object.fromEntries(entries);
102
113
  const perPurposeMap = new Map(entries);
114
+ const registered = /* @__PURE__ */ new Set([
115
+ ...Object.values(NOTIFICATION_PURPOSES),
116
+ ...perPurposeMap.keys()
117
+ ]);
103
118
  return {
104
119
  defaultLength: base.length,
105
120
  defaultCodeType: base.codeType,
@@ -109,7 +124,9 @@ function resolveOtp(otp) {
109
124
  consumeOnVerify: otp.consumeOnVerify ?? DEFAULT_OTP_OPTIONS.consumeOnVerify,
110
125
  ...otp.codeSecret !== void 0 ? { digestCode: createCodeDigester(otp.codeSecret) } : {},
111
126
  perPurpose,
112
- resolveForPurpose: (purpose) => perPurposeMap.get(purpose) ?? base
127
+ resolveForPurpose: (purpose) => perPurposeMap.get(purpose) ?? base,
128
+ strictPurposes: otp.strictPurposes ?? false,
129
+ isRegisteredPurpose: (purpose) => registered.has(purpose)
113
130
  };
114
131
  }
115
132
  function resolveAudit(options) {
@@ -167,8 +184,10 @@ var NOTIFICATION_ERROR_CODES = {
167
184
  AUDIT_LOG_FAILED: "notification.audit_log_failed",
168
185
  CHANNEL_DISABLED: "notification.channel_disabled",
169
186
  /**
170
- * A `tenantId` or `recipient` that identifies nobody reached a scoping
171
- * boundary — empty, whitespace-only, or not a string at all. Distinct from
187
+ * A `tenantId`, `recipient` or `purpose` that cannot scope an OTP reached a
188
+ * scoping boundary: empty, whitespace-only, not a string at all, carrying a
189
+ * control character, or, for a purpose, longer than 64 characters or made of
190
+ * anything but `A-Z a-z 0-9 : _ -`. Distinct from
172
191
  * {@link EMAIL_INVALID_RECIPIENT}, which is about a malformed address rather
173
192
  * than a value that cannot scope anything.
174
193
  */
@@ -311,7 +330,7 @@ var NOTIFICATION_ERROR_DEFINITIONS = {
311
330
  INVALID_SCOPE_IDENTIFIER: {
312
331
  code: NOTIFICATION_ERROR_CODES.INVALID_SCOPE_IDENTIFIER,
313
332
  status: HttpStatus.BAD_REQUEST,
314
- message: "Tenant or recipient identifier does not identify anybody"
333
+ message: "A tenant, recipient or purpose identifier is not valid"
315
334
  }
316
335
  };
317
336
  var NOTIFICATION_ERROR_DEFINITION_MAP = new Map(
@@ -376,6 +395,52 @@ var NotificationException = class extends HttpException {
376
395
  }
377
396
  };
378
397
 
398
+ // src/server/utils/tenant-scope.ts
399
+ var CONTROL_CHARACTER = new RegExp("\\p{Cc}", "u");
400
+ function refuse(owner, label, reason) {
401
+ return new NotificationException(
402
+ "INVALID_SCOPE_IDENTIFIER",
403
+ { boundary: owner, parameter: label, reason },
404
+ { message: `[${owner}] ${label} ${reason}` }
405
+ );
406
+ }
407
+ function assertIdentifies(owner, label, value) {
408
+ if (typeof value !== "string") {
409
+ throw refuse(owner, label, `expected a string, received ${typeof value}`);
410
+ }
411
+ if (value.trim() === "") {
412
+ throw refuse(owner, label, "empty or whitespace-only");
413
+ }
414
+ if (CONTROL_CHARACTER.test(value)) {
415
+ throw refuse(owner, label, "contains a control character");
416
+ }
417
+ }
418
+ var MAX_PURPOSE_LENGTH = 64;
419
+ var PURPOSE_CHARACTERS = /^[A-Za-z0-9:_-]+$/;
420
+ function purposeProblem(value) {
421
+ if (typeof value !== "string") {
422
+ return `expected a string, received ${typeof value}`;
423
+ }
424
+ if (value === "") {
425
+ return "empty";
426
+ }
427
+ if (value.length > MAX_PURPOSE_LENGTH) {
428
+ return `longer than ${String(MAX_PURPOSE_LENGTH)} characters`;
429
+ }
430
+ return PURPOSE_CHARACTERS.test(value) ? void 0 : "contains a character outside A-Z a-z 0-9 : _ -";
431
+ }
432
+ function assertRegisteredPurpose(owner, value, isRegistered) {
433
+ if (!isRegistered(value)) {
434
+ throw refuse(owner, "purpose", "not a registered purpose");
435
+ }
436
+ }
437
+ function assertPurpose(owner, value) {
438
+ const problem = purposeProblem(value);
439
+ if (problem !== void 0) {
440
+ throw refuse(owner, "purpose", problem);
441
+ }
442
+ }
443
+
379
444
  // src/server/config/default-options.ts
380
445
  var VALID_CODE_TYPES = ["numeric", "alpha", "alphanumeric"];
381
446
  var OTP_MIN_LENGTH = 1;
@@ -470,6 +535,17 @@ function validateOtpOptions(otp) {
470
535
  if (otp.defaultMaxAttempts !== void 0 && otp.defaultMaxAttempts < 1) {
471
536
  throw new Error("[BymaxNotificationModule] options.otp.defaultMaxAttempts must be at least 1");
472
537
  }
538
+ for (const key of Object.keys(otp.perPurpose ?? {})) {
539
+ const problem = purposeProblem(key);
540
+ if (problem !== void 0) {
541
+ throw new Error(
542
+ `[BymaxNotificationModule] options.otp.perPurpose has the key ${JSON.stringify(key)}, which is not a valid purpose: ${problem}`
543
+ );
544
+ }
545
+ }
546
+ if (otp.strictPurposes !== void 0 && typeof otp.strictPurposes !== "boolean") {
547
+ throw new Error("[BymaxNotificationModule] options.otp.strictPurposes must be a boolean");
548
+ }
473
549
  if (otp.resendCooldownSeconds !== void 0 && otp.resendCooldownSeconds < 0) {
474
550
  throw new Error(
475
551
  "[BymaxNotificationModule] options.otp.resendCooldownSeconds must be 0 or greater"
@@ -552,14 +628,13 @@ var DefaultTemplateRenderer = class {
552
628
  });
553
629
  }
554
630
  /**
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.
631
+ * Builds a variable resolver for one render call. A key resolves only when the object holds it as
632
+ * an own enumerable property, so neither flat nor nested resolution can reach inherited or
633
+ * prototype keys, and only the property that is named is read.
558
634
  */
559
635
  buildResolver(data) {
560
636
  if (!this.enableNestedPaths) {
561
- const values = new Map(Object.entries(data));
562
- return (path) => values.get(path);
637
+ return (path) => this.ownValue(data, path);
563
638
  }
564
639
  return (path) => this.resolveNested(data, path);
565
640
  }
@@ -570,10 +645,17 @@ var DefaultTemplateRenderer = class {
570
645
  if (current === null || current === void 0 || typeof current !== "object") {
571
646
  return void 0;
572
647
  }
573
- current = new Map(Object.entries(current)).get(key);
648
+ current = this.ownValue(current, key);
574
649
  }
575
650
  return current;
576
651
  }
652
+ /**
653
+ * The value of `key` when `object` holds it as an own enumerable property, otherwise `undefined`.
654
+ * Called through `Object.prototype` so an object without a prototype works too.
655
+ */
656
+ ownValue(object, key) {
657
+ return Object.prototype.propertyIsEnumerable.call(object, key) ? Reflect.get(object, key) : void 0;
658
+ }
577
659
  /**
578
660
  * Validates a registered template shape, throwing on the offending key. The
579
661
  * optional `text` body, when present, must be a string — a non-string `text`
@@ -598,6 +680,87 @@ var DefaultTemplateRenderer = class {
598
680
  DefaultTemplateRenderer = __decorateClass([
599
681
  Injectable()
600
682
  ], DefaultTemplateRenderer);
683
+
684
+ // src/server/utils/audit-escape.ts
685
+ var MAX_METADATA_DEPTH = 4;
686
+ var DEPTH_LIMIT_MARKER = "[depth limit]";
687
+ var CIRCULAR_MARKER = "[circular]";
688
+ var NON_PLAIN_MARKER = "[non-plain value]";
689
+ var ESCAPED = /[\p{Cc}\p{Zl}\p{Zp}\u061C\u200E\u200F\u202A-\u202E\u2066-\u2069]/gu;
690
+ var NAMED = /* @__PURE__ */ new Map([
691
+ ["\n", "\\n"],
692
+ ["\r", "\\r"],
693
+ [" ", "\\t"]
694
+ ]);
695
+ function sequenceOf(character) {
696
+ return NAMED.get(character) ?? `\\u${character.charCodeAt(0).toString(16).padStart(4, "0")}`;
697
+ }
698
+ function escapeAuditString(value) {
699
+ return value.replace(ESCAPED, sequenceOf);
700
+ }
701
+ function isPlainObject(value) {
702
+ const prototype = Object.getPrototypeOf(value);
703
+ return prototype === Object.prototype || prototype === null;
704
+ }
705
+ function escapeRecord(record, level, ancestors) {
706
+ const escaped = /* @__PURE__ */ new Map();
707
+ for (const [key, value] of Object.entries(record)) {
708
+ const base = escapeAuditString(key);
709
+ let name = base;
710
+ for (let attempt = 2; escaped.has(name); attempt++) {
711
+ name = `${base}#${attempt}`;
712
+ }
713
+ escaped.set(name, escapeValue(value, level + 1, ancestors));
714
+ }
715
+ return Object.fromEntries(escaped);
716
+ }
717
+ function escapeValue(value, level, ancestors) {
718
+ if (typeof value === "string") {
719
+ return escapeAuditString(value);
720
+ }
721
+ if (typeof value === "function" || typeof value === "symbol") {
722
+ return NON_PLAIN_MARKER;
723
+ }
724
+ if (typeof value !== "object" || value === null) {
725
+ return value;
726
+ }
727
+ if (level > MAX_METADATA_DEPTH) {
728
+ return DEPTH_LIMIT_MARKER;
729
+ }
730
+ if (ancestors.has(value)) {
731
+ return CIRCULAR_MARKER;
732
+ }
733
+ const isArray = Array.isArray(value);
734
+ if (!isArray && !isPlainObject(value)) {
735
+ return NON_PLAIN_MARKER;
736
+ }
737
+ ancestors.add(value);
738
+ try {
739
+ return isArray ? value.map((item) => escapeValue(item, level + 1, ancestors)) : escapeRecord(value, level, ancestors);
740
+ } finally {
741
+ ancestors.delete(value);
742
+ }
743
+ }
744
+ function escapeAuditEntry(entry) {
745
+ return escapeRecord(
746
+ entry,
747
+ 0,
748
+ /* @__PURE__ */ new WeakSet()
749
+ );
750
+ }
751
+
752
+ // src/server/providers/escaping-log-repository.ts
753
+ var EscapingLogRepository = class {
754
+ /** @param inner - The host's repository that receives the escaped entries. */
755
+ constructor(inner) {
756
+ this.inner = inner;
757
+ this.name = inner.name;
758
+ }
759
+ /** Writes `entry` to the wrapped repository with its strings escaped. */
760
+ async create(entry) {
761
+ await this.inner.create(escapeAuditEntry(entry));
762
+ }
763
+ };
601
764
  var NoOpNotificationLogRepository = class {
602
765
  constructor() {
603
766
  this.name = "noop";
@@ -1188,27 +1351,6 @@ function buildRedactedCopy(name, message, stack) {
1188
1351
  return copy;
1189
1352
  }
1190
1353
 
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
1354
  // src/server/services/email.service.ts
1213
1355
  var FALLBACK_LOCALE = "en";
1214
1356
  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 +1702,7 @@ EmailService = __decorateClass([
1560
1702
  __decorateParam(0, Inject(BYMAX_NOTIFICATION_OPTIONS)),
1561
1703
  __decorateParam(1, Inject(BYMAX_NOTIFICATION_EMAIL_PROVIDER)),
1562
1704
  __decorateParam(2, Inject(BYMAX_NOTIFICATION_TEMPLATE_RENDERER)),
1563
- __decorateParam(3, Inject(BYMAX_NOTIFICATION_LOG_REPOSITORY))
1705
+ __decorateParam(3, Inject(BYMAX_NOTIFICATION_AUDIT_SINK))
1564
1706
  ], EmailService);
1565
1707
  var NUMERIC = "0123456789";
1566
1708
  var ALPHA = "ABCDEFGHJKLMNPQRSTUVWXYZ";
@@ -1624,11 +1766,31 @@ function formatCooldown(remainingSeconds) {
1624
1766
  }
1625
1767
  return parts.join(" ");
1626
1768
  }
1627
-
1628
- // src/server/utils/recipient.ts
1769
+ var PLAIN_DOMAIN = /^[\p{L}\p{N}\p{M}_.-]+$/u;
1770
+ var ASCII_LABEL = new RegExp("^\\p{ASCII}*$", "u");
1771
+ function isLabelWiseMapping(folded, mapped) {
1772
+ const expected = folded.split(".").map((label) => ASCII_LABEL.test(label) ? label.toLowerCase() : null);
1773
+ const output = mapped.split(".");
1774
+ return expected.length === output.length && output.every((label, index) => {
1775
+ const want = expected.at(index);
1776
+ return want === null ? label.startsWith("xn--") : label === want;
1777
+ });
1778
+ }
1779
+ function normalizeDomain(domain) {
1780
+ const folded = domain.normalize("NFKC");
1781
+ if (!PLAIN_DOMAIN.test(folded)) {
1782
+ return domain.toLowerCase();
1783
+ }
1784
+ const mapped = domainToASCII(domain);
1785
+ return isLabelWiseMapping(folded, mapped) ? mapped : domain.toLowerCase();
1786
+ }
1629
1787
  function normalizeRecipient(recipient) {
1630
1788
  const trimmed = recipient.trim();
1631
- return trimmed.includes("@") ? trimmed.toLowerCase() : trimmed;
1789
+ const at = trimmed.lastIndexOf("@");
1790
+ if (at === -1) {
1791
+ return trimmed;
1792
+ }
1793
+ return `${trimmed.slice(0, at).toLowerCase()}@${normalizeDomain(trimmed.slice(at + 1))}`;
1632
1794
  }
1633
1795
 
1634
1796
  // src/server/utils/storage-failures.ts
@@ -1969,7 +2131,7 @@ var OtpService = class {
1969
2131
  );
1970
2132
  } catch (error) {
1971
2133
  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.`
2134
+ `[${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
2135
  );
1974
2136
  }
1975
2137
  }
@@ -2104,11 +2266,16 @@ var OtpService = class {
2104
2266
  * consumer-supplied {@link IOtpStorage} is not required to, and a blank scope would
2105
2267
  * then be shared by every caller that sent one.
2106
2268
  *
2107
- * @throws NotificationException `INVALID_SCOPE_IDENTIFIER` when either is blank.
2269
+ * @throws NotificationException `INVALID_SCOPE_IDENTIFIER` when either is blank or the purpose is not a plain name.
2108
2270
  */
2109
2271
  assertScope(ref) {
2110
2272
  assertIdentifies("OtpService", "tenantId", ref.tenantId);
2111
2273
  assertIdentifies("OtpService", "recipient", ref.recipient);
2274
+ assertPurpose("OtpService", ref.purpose);
2275
+ const otp = this.options.otp;
2276
+ if (otp?.strictPurposes === true) {
2277
+ assertRegisteredPurpose("OtpService", ref.purpose, otp.isRegisteredPurpose);
2278
+ }
2112
2279
  }
2113
2280
  /**
2114
2281
  * Returns the input with its recipient replaced by the value the OTP state is keyed on.
@@ -2171,7 +2338,7 @@ OtpService = __decorateClass([
2171
2338
  Injectable(),
2172
2339
  __decorateParam(0, Inject(BYMAX_NOTIFICATION_OPTIONS)),
2173
2340
  __decorateParam(1, Inject(BYMAX_NOTIFICATION_OTP_STORAGE)),
2174
- __decorateParam(2, Inject(BYMAX_NOTIFICATION_LOG_REPOSITORY)),
2341
+ __decorateParam(2, Inject(BYMAX_NOTIFICATION_AUDIT_SINK)),
2175
2342
  __decorateParam(3, Optional()),
2176
2343
  __decorateParam(3, Inject(EmailService))
2177
2344
  ], OtpService);
@@ -2430,6 +2597,7 @@ var BymaxNotificationModule = class {
2430
2597
  exports: [
2431
2598
  BYMAX_NOTIFICATION_OPTIONS,
2432
2599
  BYMAX_NOTIFICATION_LOG_REPOSITORY,
2600
+ BYMAX_NOTIFICATION_AUDIT_SINK,
2433
2601
  BYMAX_NOTIFICATION_EMAIL_PROVIDER,
2434
2602
  BYMAX_NOTIFICATION_TEMPLATE_RENDERER,
2435
2603
  BYMAX_NOTIFICATION_OTP_STORAGE,
@@ -2456,7 +2624,7 @@ var BymaxNotificationModule = class {
2456
2624
  BYMAX_NOTIFICATION_OPTIONS,
2457
2625
  BYMAX_NOTIFICATION_EMAIL_PROVIDER,
2458
2626
  BYMAX_NOTIFICATION_TEMPLATE_RENDERER,
2459
- BYMAX_NOTIFICATION_LOG_REPOSITORY
2627
+ BYMAX_NOTIFICATION_AUDIT_SINK
2460
2628
  ]
2461
2629
  },
2462
2630
  {
@@ -2465,7 +2633,7 @@ var BymaxNotificationModule = class {
2465
2633
  inject: [
2466
2634
  BYMAX_NOTIFICATION_OPTIONS,
2467
2635
  BYMAX_NOTIFICATION_OTP_STORAGE,
2468
- BYMAX_NOTIFICATION_LOG_REPOSITORY,
2636
+ BYMAX_NOTIFICATION_AUDIT_SINK,
2469
2637
  // 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
2638
  { token: EmailService, optional: true }
2471
2639
  ]
@@ -2496,6 +2664,7 @@ var BymaxNotificationModule = class {
2496
2664
  useFactory: (raw) => raw.audit ? instantiate(raw.audit.repository) : new NoOpNotificationLogRepository(),
2497
2665
  inject: [RAW_NOTIFICATION_OPTIONS]
2498
2666
  },
2667
+ auditSinkProvider(),
2499
2668
  {
2500
2669
  provide: BYMAX_NOTIFICATION_EMAIL_PROVIDER,
2501
2670
  useFactory: (raw) => raw.email ? instantiate(raw.email.provider) : null,
@@ -2517,7 +2686,8 @@ var BymaxNotificationModule = class {
2517
2686
  static buildProviders(options, resolved) {
2518
2687
  const providers = [
2519
2688
  { 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 }
2689
+ options.audit?.repository ? resolveAsProvider(BYMAX_NOTIFICATION_LOG_REPOSITORY, options.audit.repository) : { provide: BYMAX_NOTIFICATION_LOG_REPOSITORY, useClass: NoOpNotificationLogRepository },
2690
+ auditSinkProvider()
2521
2691
  ];
2522
2692
  if (resolved.email && options.email) {
2523
2693
  providers.push(resolveAsProvider(BYMAX_NOTIFICATION_EMAIL_PROVIDER, options.email.provider));
@@ -2559,6 +2729,13 @@ function activeChannels(resolved) {
2559
2729
  }
2560
2730
  return channels;
2561
2731
  }
2732
+ function auditSinkProvider() {
2733
+ return {
2734
+ provide: BYMAX_NOTIFICATION_AUDIT_SINK,
2735
+ useFactory: (repository) => new EscapingLogRepository(repository),
2736
+ inject: [BYMAX_NOTIFICATION_LOG_REPOSITORY]
2737
+ };
2738
+ }
2562
2739
  function resolveRenderer(renderer) {
2563
2740
  if (renderer === void 0) {
2564
2741
  return {
@@ -2743,25 +2920,24 @@ var NotificationAuditInterceptor = class {
2743
2920
  }
2744
2921
  return input.payload.recipient;
2745
2922
  }
2746
- /** Extracts the audit `purpose`: the OTP purpose, or the email template name. */
2923
+ /**
2924
+ * Extracts the audit `purpose`: the OTP purpose, or the email template name. The interceptor sees
2925
+ * the payload before the service refuses it and audits a refused call too, so an OTP purpose that
2926
+ * is not a plain name is left out of the entry: a control character in it would forge a log
2927
+ * record and its length is unbounded.
2928
+ */
2747
2929
  extractPurpose(input) {
2748
- return input.channel === "otp" ? input.payload.purpose : input.payload.template;
2930
+ if (input.channel !== "otp") {
2931
+ return input.payload.template;
2932
+ }
2933
+ return purposeProblem(input.payload.purpose) === void 0 ? input.payload.purpose : void 0;
2749
2934
  }
2750
2935
  };
2751
2936
  NotificationAuditInterceptor = __decorateClass([
2752
2937
  Injectable(),
2753
2938
  __decorateParam(0, Inject(BYMAX_NOTIFICATION_OPTIONS)),
2754
- __decorateParam(1, Inject(BYMAX_NOTIFICATION_LOG_REPOSITORY))
2939
+ __decorateParam(1, Inject(BYMAX_NOTIFICATION_AUDIT_SINK))
2755
2940
  ], NotificationAuditInterceptor);
2756
-
2757
- // src/server/constants/notification-purposes.ts
2758
- var NOTIFICATION_PURPOSES = {
2759
- EMAIL_VERIFICATION: "email_verification",
2760
- PASSWORD_RESET: "password_reset",
2761
- MFA_OOB: "mfa_oob",
2762
- PHONE_VERIFICATION: "phone_verification",
2763
- MAGIC_LINK: "magic_link"
2764
- };
2765
2941
  function maskEmail(address) {
2766
2942
  const at = address.lastIndexOf("@");
2767
2943
  if (at <= 0) {
@@ -2962,7 +3138,7 @@ var ResendEmailProvider = class {
2962
3138
  return withCode(new Error("Resend send failed"), code);
2963
3139
  }
2964
3140
  const reason = this.scrubSendError(rawMessage, options);
2965
- this.logger.warn(`[RESEND_SEND_FAILED] ${reason}`);
3141
+ this.logger.warn(`[RESEND_SEND_FAILED] ${escapeAuditString(reason)}`);
2966
3142
  return withCode(new Error(`Resend send failed: ${reason}`), code);
2967
3143
  }
2968
3144
  /**
@@ -3073,6 +3249,32 @@ function settleOrTimeout(call, timeoutMs) {
3073
3249
  });
3074
3250
  }
3075
3251
  var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "::1", "[::1]"]);
3252
+ function assertPool(pool) {
3253
+ if (pool === void 0) {
3254
+ return;
3255
+ }
3256
+ if (typeof pool !== "object" || pool === null) {
3257
+ throw new Error("SmtpEmailProvider: pool must be an object");
3258
+ }
3259
+ for (const [name, value] of [
3260
+ ["maxConnections", pool.maxConnections],
3261
+ ["maxMessages", pool.maxMessages]
3262
+ ]) {
3263
+ if (value !== void 0 && !(Number.isInteger(value) && value >= 1)) {
3264
+ throw new Error(`SmtpEmailProvider: pool.${name} must be a positive integer`);
3265
+ }
3266
+ }
3267
+ }
3268
+ function poolConfig(pool) {
3269
+ if (pool === void 0) {
3270
+ return {};
3271
+ }
3272
+ return {
3273
+ pool: true,
3274
+ ...pool.maxConnections === void 0 ? {} : { maxConnections: pool.maxConnections },
3275
+ ...pool.maxMessages === void 0 ? {} : { maxMessages: pool.maxMessages }
3276
+ };
3277
+ }
3076
3278
  function areCredentialsComplete(credentials) {
3077
3279
  return Boolean(credentials.user) && Boolean(credentials.pass);
3078
3280
  }
@@ -3111,6 +3313,7 @@ var SmtpEmailProvider = class {
3111
3313
  `SmtpEmailProvider: sendTimeoutMs must be a positive integer of at most ${String(MAX_SEND_TIMEOUT_MS)}`
3112
3314
  );
3113
3315
  }
3316
+ assertPool(options.pool);
3114
3317
  __privateSet(this, _options2, options);
3115
3318
  }
3116
3319
  /**
@@ -3173,6 +3376,38 @@ var SmtpEmailProvider = class {
3173
3376
  }
3174
3377
  return { messageId: info.messageId };
3175
3378
  }
3379
+ /**
3380
+ * Closes the transport this provider built, so a pooled connection does not keep the process
3381
+ * alive. A send already in flight on a pooled transport finishes; one still waiting for a
3382
+ * connection fails with `Connection pool was closed`. Idempotent, and it never builds a transport
3383
+ * to close it. A `send()` after it builds a new transport, which the host has to close again if it
3384
+ * keeps the provider alive.
3385
+ *
3386
+ * A close that throws is logged as a fixed line and not rethrown, so one failure cannot stop the
3387
+ * other shutdown hooks of the application.
3388
+ */
3389
+ async close() {
3390
+ const pending = __privateGet(this, _transportPromise);
3391
+ __privateSet(this, _transportPromise, null);
3392
+ if (pending === null) {
3393
+ return;
3394
+ }
3395
+ let transport;
3396
+ try {
3397
+ transport = await pending;
3398
+ } catch {
3399
+ return;
3400
+ }
3401
+ try {
3402
+ transport.close?.();
3403
+ } catch {
3404
+ this.logger.warn("[SMTP_CLOSE_FAILED] The transport could not be closed.");
3405
+ }
3406
+ }
3407
+ /** Nest calls this when the application closes; it closes the transport. */
3408
+ async onModuleDestroy() {
3409
+ await this.close();
3410
+ }
3176
3411
  /**
3177
3412
  * Hands the payload to the transport, converting a transport failure into a plain
3178
3413
  * `Error` whose message has the SMTP password scrubbed out. The email body is
@@ -3201,7 +3436,7 @@ var SmtpEmailProvider = class {
3201
3436
  return this.withheldFailure(raw, code, redactValuesList);
3202
3437
  }
3203
3438
  const reason = this.scrubTransportError(raw, payload, redactValuesList);
3204
- this.logger.warn(`[SMTP_SEND_FAILED] ${reason}`);
3439
+ this.logger.warn(`[SMTP_SEND_FAILED] ${escapeAuditString(reason)}`);
3205
3440
  return Object.assign(
3206
3441
  new Error(`SMTP send failed: ${reason}`),
3207
3442
  code === void 0 ? {} : { code }
@@ -3377,31 +3612,37 @@ var SmtpEmailProvider = class {
3377
3612
  * Returns the cached transport, lazily importing `nodemailer` on first use.
3378
3613
  * Concurrent first calls share one in-flight initialization promise so the dynamic
3379
3614
  * import and creation run exactly once; a failed init is dropped from the cache so
3380
- * a later call can retry instead of being permanently bricked.
3615
+ * a later call can retry instead of being permanently bricked. It is dropped only while
3616
+ * it is still the cached build: `close()` may have taken it, and a newer send may have
3617
+ * started a build of its own, which a late failure here must not clear.
3381
3618
  *
3382
3619
  * @returns The initialized transport.
3383
3620
  * @throws Error When the configuration is incomplete or `nodemailer` is missing.
3384
3621
  */
3385
3622
  getTransport() {
3386
- __privateGet(this, _transportPromise) ?? __privateSet(this, _transportPromise, this.createTransport());
3387
- return __privateGet(this, _transportPromise);
3623
+ const cached = __privateGet(this, _transportPromise);
3624
+ if (cached !== null) {
3625
+ return cached;
3626
+ }
3627
+ const build = this.createTransport();
3628
+ __privateSet(this, _transportPromise, build);
3629
+ build.catch(() => {
3630
+ if (__privateGet(this, _transportPromise) === build) {
3631
+ __privateSet(this, _transportPromise, null);
3632
+ }
3633
+ });
3634
+ return build;
3388
3635
  }
3389
3636
  /**
3390
- * Builds a fresh transport, resetting the cached promise on any failure so the
3391
- * provider is not permanently bricked by a transient init error.
3637
+ * Builds a fresh transport.
3392
3638
  *
3393
3639
  * @returns The initialized transport.
3394
3640
  * @throws Error When the configuration is incomplete or `nodemailer` is missing.
3395
3641
  */
3396
3642
  async createTransport() {
3397
- try {
3398
- const config = this.buildTransportConfig();
3399
- const nodemailer = await this.loadNodemailer();
3400
- return this.instantiate(nodemailer, config);
3401
- } catch (error) {
3402
- __privateSet(this, _transportPromise, null);
3403
- throw error;
3404
- }
3643
+ const config = this.buildTransportConfig();
3644
+ const nodemailer = await this.loadNodemailer();
3645
+ return this.instantiate(nodemailer, config);
3405
3646
  }
3406
3647
  /**
3407
3648
  * Calls into Nodemailer to build the transport, scrubbing the password out of a
@@ -3473,7 +3714,8 @@ var SmtpEmailProvider = class {
3473
3714
  tls: options.tls,
3474
3715
  connectionTimeout: options.connectionTimeout ?? DEFAULT_CONNECTION_TIMEOUT_MS,
3475
3716
  greetingTimeout: options.greetingTimeout ?? DEFAULT_GREETING_TIMEOUT_MS,
3476
- socketTimeout: options.socketTimeout ?? DEFAULT_SOCKET_TIMEOUT_MS
3717
+ socketTimeout: options.socketTimeout ?? DEFAULT_SOCKET_TIMEOUT_MS,
3718
+ ...poolConfig(options.pool)
3477
3719
  };
3478
3720
  }
3479
3721
  /**
@@ -3736,7 +3978,7 @@ var InMemoryOtpStorage = class {
3736
3978
  this.cooldowns.delete(this.key(tenantId, recipient, purpose));
3737
3979
  }
3738
3980
  /**
3739
- * Test helper — wipes all entries and cooldowns. Not part of `IOtpStorage`.
3981
+ * Test helper — wipes all entries, cooldowns and failure counters. Not part of `IOtpStorage`.
3740
3982
  */
3741
3983
  clear() {
3742
3984
  this.store.clear();
@@ -3744,12 +3986,17 @@ var InMemoryOtpStorage = class {
3744
3986
  this.failures.clear();
3745
3987
  }
3746
3988
  /**
3747
- * Test helper — current map sizes. Not part of `IOtpStorage`.
3989
+ * Test helper — current map sizes. Not part of `IOtpStorage`. Like the cooldowns, a failure
3990
+ * counter that has lapsed stays counted until it is read or cleared.
3748
3991
  *
3749
- * @returns The number of stored OTP entries and active cooldowns.
3992
+ * @returns The number of stored OTP entries, cooldowns and failure counters.
3750
3993
  */
3751
3994
  size() {
3752
- return { otps: this.store.size, cooldowns: this.cooldowns.size };
3995
+ return {
3996
+ otps: this.store.size,
3997
+ cooldowns: this.cooldowns.size,
3998
+ failures: this.failures.size
3999
+ };
3753
4000
  }
3754
4001
  /** The unexpired failure count for a key, dropping a lapsed counter. Synchronous. */
3755
4002
  liveFailures(key) {
@@ -3773,6 +4020,7 @@ var InMemoryOtpStorage = class {
3773
4020
  * stays unambiguous too.
3774
4021
  */
3775
4022
  key(tenantId, recipient, purpose) {
4023
+ assertPurpose("InMemoryOtpStorage", purpose);
3776
4024
  return `${hashTenantRecipient(tenantId, recipient)}::${purpose}`;
3777
4025
  }
3778
4026
  };
@@ -3992,14 +4240,17 @@ var RedisOtpStorage = class {
3992
4240
  }
3993
4241
  /** Builds the OTP entry key: `{namespace}:otp:{purpose}:{hashTenantRecipient(...)}`. */
3994
4242
  otpKey(tenantId, recipient, purpose) {
4243
+ assertPurpose("RedisOtpStorage", purpose);
3995
4244
  return `${this.namespace}:otp:${purpose}:${hashTenantRecipient(tenantId, recipient)}`;
3996
4245
  }
3997
4246
  /** Builds the failure-counter key: `{namespace}:otp_fail:{purpose}:{hashTenantRecipient(...)}`. */
3998
4247
  failureKey(tenantId, recipient, purpose) {
4248
+ assertPurpose("RedisOtpStorage", purpose);
3999
4249
  return `${this.namespace}:otp_fail:${purpose}:${hashTenantRecipient(tenantId, recipient)}`;
4000
4250
  }
4001
4251
  /** Builds the cooldown key: `{namespace}:otp_cd:{purpose}:{hashTenantRecipient(...)}`. */
4002
4252
  cooldownKey(tenantId, recipient, purpose) {
4253
+ assertPurpose("RedisOtpStorage", purpose);
4003
4254
  return `${this.namespace}:otp_cd:${purpose}:${hashTenantRecipient(tenantId, recipient)}`;
4004
4255
  }
4005
4256
  };