@bymax-one/nest-notification 1.4.0 → 1.4.2

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,5 @@
1
1
  import { HttpStatus, Injectable, Inject, Optional, Logger, Module, HttpException } from '@nestjs/common';
2
- import { randomInt, timingSafeEqual, randomUUID, createHash } from 'crypto';
2
+ import { randomInt, timingSafeEqual, createHmac, randomUUID, createHash } from 'crypto';
3
3
  import { catchError, from, concatMap, throwError, map } from 'rxjs';
4
4
 
5
5
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
@@ -48,6 +48,16 @@ var DEFAULT_EMAIL_OPTIONS = {
48
48
  var DEFAULT_AUDIT_OPTIONS = {
49
49
  swallowErrors: true
50
50
  };
51
+ var CODE_DIGEST_PREFIX = "hmac-sha256:v1:";
52
+ var MIN_CODE_SECRET_BYTES = 32;
53
+ var CONTEXT = "bymax-notification:otp-code:v1\0";
54
+ function createCodeDigester(secret) {
55
+ const key = Buffer.from(secret, "utf8");
56
+ return (code) => `${CODE_DIGEST_PREFIX}${createHmac("sha256", key).update(CONTEXT).update(code).digest("hex")}`;
57
+ }
58
+ function isCodeDigest(stored) {
59
+ return stored.startsWith(CODE_DIGEST_PREFIX);
60
+ }
51
61
 
52
62
  // src/server/config/resolved-options.ts
53
63
  function resolveOptions(options) {
@@ -95,6 +105,7 @@ function resolveOtp(otp) {
95
105
  defaultMaxAttempts: base.maxAttempts,
96
106
  resendCooldownSeconds: base.resendCooldownSeconds,
97
107
  consumeOnVerify: otp.consumeOnVerify ?? DEFAULT_OTP_OPTIONS.consumeOnVerify,
108
+ ...otp.codeSecret !== void 0 ? { digestCode: createCodeDigester(otp.codeSecret) } : {},
98
109
  perPurpose,
99
110
  resolveForPurpose: (purpose) => perPurposeMap.get(purpose) ?? base
100
111
  };
@@ -132,6 +143,7 @@ var NOTIFICATION_ERROR_CODES = {
132
143
  TEMPLATE_RENDER_FAILED: "notification.template_render_failed",
133
144
  OTP_STORAGE_NOT_CONFIGURED: "notification.otp_storage_not_configured",
134
145
  OTP_EMAIL_DELIVERY_NOT_CONFIGURED: "notification.otp_email_delivery_not_configured",
146
+ OTP_MANUAL_DELIVERY_UNAVAILABLE: "notification.otp_manual_delivery_unavailable",
135
147
  OTP_COOLDOWN_ACTIVE: "notification.otp_cooldown_active",
136
148
  OTP_NOT_FOUND: "notification.otp_not_found",
137
149
  OTP_EXPIRED: "notification.otp_expired",
@@ -171,6 +183,7 @@ var NOTIFICATION_ERROR_DEFINITIONS = {
171
183
  status: HttpStatus.PAYLOAD_TOO_LARGE,
172
184
  message: "Email attachments exceed size limit"
173
185
  },
186
+ /** Reserved: `to` is not validated, so the library never throws this code. */
174
187
  EMAIL_INVALID_RECIPIENT: {
175
188
  code: NOTIFICATION_ERROR_CODES.EMAIL_INVALID_RECIPIENT,
176
189
  status: HttpStatus.BAD_REQUEST,
@@ -201,26 +214,35 @@ var NOTIFICATION_ERROR_DEFINITIONS = {
201
214
  status: HttpStatus.INTERNAL_SERVER_ERROR,
202
215
  message: "OTP email delivery requested but email channel not configured"
203
216
  },
217
+ OTP_MANUAL_DELIVERY_UNAVAILABLE: {
218
+ code: NOTIFICATION_ERROR_CODES.OTP_MANUAL_DELIVERY_UNAVAILABLE,
219
+ status: HttpStatus.BAD_REQUEST,
220
+ message: "OTP manual delivery is unavailable while otp.codeSecret is set"
221
+ },
204
222
  OTP_COOLDOWN_ACTIVE: {
205
223
  code: NOTIFICATION_ERROR_CODES.OTP_COOLDOWN_ACTIVE,
206
224
  status: HttpStatus.TOO_MANY_REQUESTS,
207
225
  message: "Resend cooldown is active"
208
226
  },
227
+ /** Reserved: `verify()` returns `{ valid: false, reason: 'not_found' }` instead of throwing. */
209
228
  OTP_NOT_FOUND: {
210
229
  code: NOTIFICATION_ERROR_CODES.OTP_NOT_FOUND,
211
230
  status: HttpStatus.NOT_FOUND,
212
231
  message: "OTP not found or expired"
213
232
  },
233
+ /** Reserved: an expired code is reported as `not_found`. */
214
234
  OTP_EXPIRED: {
215
235
  code: NOTIFICATION_ERROR_CODES.OTP_EXPIRED,
216
236
  status: HttpStatus.GONE,
217
237
  message: "OTP code expired"
218
238
  },
239
+ /** Reserved: `verify()` returns `{ valid: false, reason: 'max_attempts' }` instead of throwing. */
219
240
  OTP_MAX_ATTEMPTS_EXCEEDED: {
220
241
  code: NOTIFICATION_ERROR_CODES.OTP_MAX_ATTEMPTS_EXCEEDED,
221
242
  status: HttpStatus.TOO_MANY_REQUESTS,
222
243
  message: "Maximum OTP attempts exceeded"
223
244
  },
245
+ /** Reserved: `verify()` returns `{ valid: false, reason: 'invalid_code' }` instead of throwing. */
224
246
  OTP_INVALID_CODE: {
225
247
  code: NOTIFICATION_ERROR_CODES.OTP_INVALID_CODE,
226
248
  status: HttpStatus.UNAUTHORIZED,
@@ -231,26 +253,31 @@ var NOTIFICATION_ERROR_DEFINITIONS = {
231
253
  status: HttpStatus.BAD_REQUEST,
232
254
  message: "Invalid OTP length config"
233
255
  },
256
+ /** Reserved: the SMS channel is not implemented. */
234
257
  SMS_PROVIDER_NOT_CONFIGURED: {
235
258
  code: NOTIFICATION_ERROR_CODES.SMS_PROVIDER_NOT_CONFIGURED,
236
259
  status: HttpStatus.INTERNAL_SERVER_ERROR,
237
260
  message: "SMS provider not configured"
238
261
  },
262
+ /** Reserved: the SMS channel is not implemented. */
239
263
  SMS_SEND_FAILED: {
240
264
  code: NOTIFICATION_ERROR_CODES.SMS_SEND_FAILED,
241
265
  status: HttpStatus.BAD_GATEWAY,
242
266
  message: "Failed to send SMS"
243
267
  },
268
+ /** Reserved: the SMS channel is not implemented. */
244
269
  SMS_INVALID_RECIPIENT: {
245
270
  code: NOTIFICATION_ERROR_CODES.SMS_INVALID_RECIPIENT,
246
271
  status: HttpStatus.BAD_REQUEST,
247
272
  message: "Invalid phone number"
248
273
  },
274
+ /** Reserved: the push channel is not implemented. */
249
275
  PUSH_PROVIDER_NOT_CONFIGURED: {
250
276
  code: NOTIFICATION_ERROR_CODES.PUSH_PROVIDER_NOT_CONFIGURED,
251
277
  status: HttpStatus.INTERNAL_SERVER_ERROR,
252
278
  message: "Push provider not configured"
253
279
  },
280
+ /** Reserved: the push channel is not implemented. */
254
281
  PUSH_SEND_FAILED: {
255
282
  code: NOTIFICATION_ERROR_CODES.PUSH_SEND_FAILED,
256
283
  status: HttpStatus.BAD_GATEWAY,
@@ -380,6 +407,13 @@ function validateEmailOptions(email) {
380
407
  );
381
408
  }
382
409
  }
410
+ function validateCodeSecret(secret) {
411
+ if (typeof secret !== "string" || Buffer.byteLength(secret, "utf8") < MIN_CODE_SECRET_BYTES) {
412
+ throw new Error(
413
+ `[BymaxNotificationModule] options.otp.codeSecret must be a string of at least ${String(MIN_CODE_SECRET_BYTES)} bytes`
414
+ );
415
+ }
416
+ }
383
417
  function validateOtpOptions(otp) {
384
418
  if (!otp.storage) {
385
419
  throw new Error(
@@ -395,6 +429,9 @@ function validateOtpOptions(otp) {
395
429
  });
396
430
  }
397
431
  }
432
+ if (otp.codeSecret !== void 0) {
433
+ validateCodeSecret(otp.codeSecret);
434
+ }
398
435
  if (otp.defaultCodeType !== void 0 && !VALID_CODE_TYPES.includes(otp.defaultCodeType)) {
399
436
  throw new Error(
400
437
  `[BymaxNotificationModule] options.otp.defaultCodeType must be one of: ${VALID_CODE_TYPES.join(", ")}`
@@ -841,6 +878,27 @@ function buildRedactedCopy(name, message, stack) {
841
878
  return copy;
842
879
  }
843
880
 
881
+ // src/server/utils/tenant-scope.ts
882
+ var CONTROL_CHARACTER = new RegExp("\\p{Cc}", "u");
883
+ function refuse(owner, label, reason) {
884
+ return new NotificationException(
885
+ "INVALID_SCOPE_IDENTIFIER",
886
+ { boundary: owner, parameter: label, reason },
887
+ { message: `[${owner}] ${label} ${reason}` }
888
+ );
889
+ }
890
+ function assertIdentifies(owner, label, value) {
891
+ if (typeof value !== "string") {
892
+ throw refuse(owner, label, `expected a string, received ${typeof value}`);
893
+ }
894
+ if (value.trim() === "") {
895
+ throw refuse(owner, label, "empty or whitespace-only");
896
+ }
897
+ if (CONTROL_CHARACTER.test(value)) {
898
+ throw refuse(owner, label, "contains a control character");
899
+ }
900
+ }
901
+
844
902
  // src/server/services/email.service.ts
845
903
  var FALLBACK_LOCALE = "en";
846
904
  var WITHHELD_PROVIDER_TEXT = "[provider text withheld]";
@@ -888,11 +946,13 @@ var EmailService = class {
888
946
  *
889
947
  * @param input - The message envelope and rendered body.
890
948
  * @returns The provider's message id.
891
- * @throws NotificationException `EMAIL_PROVIDER_NOT_CONFIGURED`, `EMAIL_ATTACHMENTS_TOO_LARGE`,
949
+ * @throws NotificationException `EMAIL_PROVIDER_NOT_CONFIGURED`, `INVALID_SCOPE_IDENTIFIER`
950
+ * (a blank tenant or one with a control character), `EMAIL_ATTACHMENTS_TOO_LARGE`,
892
951
  * `EMAIL_SEND_FAILED`, or `AUDIT_LOG_FAILED` (only when `audit.swallowErrors` is `false`).
893
952
  */
894
953
  async send(input) {
895
954
  const email = this.requireEmailOptions();
955
+ assertIdentifies("EmailService", "tenantId", input.tenantId);
896
956
  this.guardAttachmentSize(input.attachments, email.maxAttachmentBytes);
897
957
  const sendOptions = this.buildSendOptions(input, email);
898
958
  const recipient = this.maskRecipients(input.to);
@@ -951,6 +1011,7 @@ var EmailService = class {
951
1011
  * `TEMPLATE_RENDER_FAILED` (the renderer threw), plus anything {@link EmailService.send} throws.
952
1012
  */
953
1013
  async sendTemplate(input) {
1014
+ assertIdentifies("EmailService", "tenantId", input.tenantId);
954
1015
  const requestedLocale = input.locale ?? this.options.global.defaultLocale;
955
1016
  const locale = await this.resolveTemplateLocale(input.template, requestedLocale);
956
1017
  const rendered = await this.renderTemplate(
@@ -1196,6 +1257,12 @@ function formatCooldown(remainingSeconds) {
1196
1257
  }
1197
1258
  return parts.join(" ");
1198
1259
  }
1260
+
1261
+ // src/server/utils/recipient.ts
1262
+ function normalizeRecipient(recipient) {
1263
+ const trimmed = recipient.trim();
1264
+ return trimmed.includes("@") ? trimmed.toLowerCase() : trimmed;
1265
+ }
1199
1266
  function safeCompare(expected, actual) {
1200
1267
  const expectedBytes = Buffer.from(expected, "utf8");
1201
1268
  const actualBytes = Buffer.from(actual, "utf8");
@@ -1209,6 +1276,9 @@ function safeCompare(expected, actual) {
1209
1276
  var MS_PER_SECOND2 = 1e3;
1210
1277
  var SECONDS_PER_MINUTE2 = 60;
1211
1278
  var DEFAULT_OTP_TEMPLATE = "otp_code";
1279
+ function carriesFailures(storage) {
1280
+ return storage.getFailures !== void 0 && storage.recordFailure !== void 0 && storage.clearFailures !== void 0;
1281
+ }
1212
1282
  var OtpService = class {
1213
1283
  /**
1214
1284
  * @param options - The resolved, frozen module options.
@@ -1221,6 +1291,8 @@ var OtpService = class {
1221
1291
  this.storage = storage;
1222
1292
  this.auditLog = auditLog;
1223
1293
  this.emailService = emailService;
1294
+ this.logger = new Logger(OtpService.name);
1295
+ this.warnedFailuresNotCarried = false;
1224
1296
  }
1225
1297
  /**
1226
1298
  * Whether the OTP channel is configured and its storage is ready.
@@ -1241,12 +1313,23 @@ var OtpService = class {
1241
1313
  */
1242
1314
  async generate(input) {
1243
1315
  const otp = this.requireOtpOptions();
1316
+ this.assertScope(input);
1317
+ const scope = this.keyed(input);
1318
+ this.assertDeliverable(input, otp.digestCode);
1244
1319
  const cfg = otp.resolveForPurpose(input.purpose);
1245
- await this.acquireCooldownOrThrow(input, cfg.resendCooldownSeconds);
1320
+ await this.acquireCooldownOrThrow(scope, cfg.resendCooldownSeconds);
1246
1321
  const code = generateOtpCode(cfg.length, cfg.codeType);
1247
1322
  const expiresAt = Date.now() + cfg.ttlSeconds * MS_PER_SECOND2;
1248
- await this.persistAndDeliver(input, code, expiresAt, cfg);
1249
- await this.audit(this.otpAuditEntry("generated", input, void 0));
1323
+ const entry = {
1324
+ // What the store holds is the digest when a secret is configured; the delivery
1325
+ // carries the plaintext code the recipient has to type.
1326
+ code: otp.digestCode ? otp.digestCode(code) : code,
1327
+ expiresAt,
1328
+ attempts: 0,
1329
+ maxAttempts: cfg.maxAttempts
1330
+ };
1331
+ await this.persistAndDeliver(input, scope, code, entry, cfg);
1332
+ await this.audit(this.otpAuditEntry("generated", scope, void 0));
1250
1333
  return { expiresAt, cooldownSeconds: cfg.resendCooldownSeconds };
1251
1334
  }
1252
1335
  /**
@@ -1258,27 +1341,44 @@ var OtpService = class {
1258
1341
  */
1259
1342
  async verify(input) {
1260
1343
  const otp = this.requireOtpOptions();
1261
- const result = await this.storage.consumeAttempt(input.tenantId, input.recipient, input.purpose);
1344
+ this.assertScope(input);
1345
+ const scope = this.keyed(input);
1346
+ const cfg = otp.resolveForPurpose(scope.purpose);
1347
+ const attempt = await this.countAttempt(scope, cfg.ttlSeconds);
1348
+ if (attempt === null) {
1349
+ await this.audit(this.otpAuditEntry("failed", scope, { reason: "not_found" }));
1350
+ return { valid: false, reason: "not_found" };
1351
+ }
1352
+ if (attempt !== void 0 && attempt > cfg.maxAttempts) {
1353
+ await this.audit(
1354
+ this.otpAuditEntry("max_attempts_exceeded", scope, { reason: "max_attempts" })
1355
+ );
1356
+ return { valid: false, reason: "max_attempts" };
1357
+ }
1358
+ const result = await this.storage.consumeAttempt(scope.tenantId, scope.recipient, scope.purpose);
1262
1359
  if (result.status === "not_found") {
1263
- await this.audit(this.otpAuditEntry("failed", input, { reason: "not_found" }));
1360
+ await this.audit(this.otpAuditEntry("failed", scope, { reason: "not_found" }));
1264
1361
  return { valid: false, reason: "not_found" };
1265
1362
  }
1266
1363
  if (result.status === "max_attempts") {
1267
1364
  await this.audit(
1268
- this.otpAuditEntry("max_attempts_exceeded", input, { reason: "max_attempts" })
1365
+ this.otpAuditEntry("max_attempts_exceeded", scope, { reason: "max_attempts" })
1269
1366
  );
1270
1367
  return { valid: false, reason: "max_attempts" };
1271
1368
  }
1272
1369
  const { entry } = result;
1273
- if (!safeCompare(entry.code, input.code)) {
1274
- await this.audit(this.otpAuditEntry("failed", input, { reason: "invalid_code" }));
1370
+ if (!this.matchesStoredCode(entry.code, scope.code, otp.digestCode)) {
1371
+ await this.audit(this.otpAuditEntry("failed", scope, { reason: "invalid_code" }));
1372
+ const ofCode = entry.maxAttempts - entry.attempts;
1275
1373
  return {
1276
1374
  valid: false,
1277
1375
  reason: "invalid_code",
1278
- remainingAttempts: entry.maxAttempts - entry.attempts
1376
+ // The code's own budget and the recipient's failure budget both run out; the nearer wins.
1377
+ remainingAttempts: attempt === void 0 ? ofCode : Math.min(ofCode, cfg.maxAttempts - attempt)
1279
1378
  };
1280
1379
  }
1281
- await this.finalizeVerifySuccess(input, entry, otp.consumeOnVerify);
1380
+ await this.storage.clearFailures?.(scope.tenantId, scope.recipient, scope.purpose);
1381
+ await this.finalizeVerifySuccess(scope, entry, otp.consumeOnVerify);
1282
1382
  return { valid: true };
1283
1383
  }
1284
1384
  /**
@@ -1289,8 +1389,11 @@ var OtpService = class {
1289
1389
  */
1290
1390
  async consume(input) {
1291
1391
  this.requireOtpOptions();
1292
- await this.storage.delete(input.tenantId, input.recipient, input.purpose);
1293
- await this.storage.clearCooldown(input.tenantId, input.recipient, input.purpose);
1392
+ this.assertScope(input);
1393
+ const scope = this.keyed(input);
1394
+ await this.storage.delete(scope.tenantId, scope.recipient, scope.purpose);
1395
+ await this.storage.clearCooldown(scope.tenantId, scope.recipient, scope.purpose);
1396
+ await this.storage.clearFailures?.(scope.tenantId, scope.recipient, scope.purpose);
1294
1397
  }
1295
1398
  /**
1296
1399
  * Explicit resend — a functional alias of {@link OtpService.generate}.
@@ -1308,9 +1411,11 @@ var OtpService = class {
1308
1411
  * @returns Existence, expiry, attempt counters, validation flag, and cooldown.
1309
1412
  */
1310
1413
  async getStatus(input) {
1414
+ this.assertScope(input);
1415
+ const scope = this.keyed(input);
1311
1416
  const [entry, cooldownSeconds] = await Promise.all([
1312
- this.storage.get(input.tenantId, input.recipient, input.purpose),
1313
- this.storage.getCooldown(input.tenantId, input.recipient, input.purpose)
1417
+ this.storage.get(scope.tenantId, scope.recipient, scope.purpose),
1418
+ this.storage.getCooldown(scope.tenantId, scope.recipient, scope.purpose)
1314
1419
  ]);
1315
1420
  if (!entry) {
1316
1421
  return { exists: false, cooldownSeconds };
@@ -1354,38 +1459,100 @@ var OtpService = class {
1354
1459
  * plaintext code is never placed in the failure audit entry. The original typed
1355
1460
  * error is re-thrown after the lock is released.
1356
1461
  */
1357
- async persistAndDeliver(input, code, expiresAt, cfg) {
1462
+ async persistAndDeliver(input, scope, code, entry, cfg) {
1358
1463
  try {
1359
- await this.storage.set(input.tenantId, input.recipient, input.purpose, {
1360
- code,
1361
- expiresAt,
1362
- attempts: 0,
1363
- maxAttempts: cfg.maxAttempts
1364
- });
1464
+ await this.storage.set(scope.tenantId, scope.recipient, scope.purpose, entry);
1365
1465
  await this.deliverOtp(input, code, cfg);
1366
1466
  } catch (error) {
1367
- let failure = error;
1368
- try {
1369
- await this.releaseOtp(input);
1370
- } catch (cleanupError) {
1371
- attachCauseIfAbsent(cleanupError, error);
1372
- failure = cleanupError;
1373
- }
1374
- const outgoing = isSafeError(failure) ? scrubValuesFromErrorChain(failure, [code]) : coerceRedacted(failure, [code]);
1375
- await this.audit(
1376
- this.otpAuditEntry("failed", input, {
1377
- // `outgoing` is already fully redacted by the scrub above; this read
1378
- // only needs the fail-closed guard, not a second redaction pass.
1379
- errorMessage: readRedactedMessage(outgoing)
1380
- })
1381
- );
1382
- throw outgoing;
1467
+ throw await this.failedOutgoing(scope, error, code);
1468
+ }
1469
+ }
1470
+ /**
1471
+ * Releases the cooldown and the orphan entry after a failed persist or delivery, audits the
1472
+ * failure, and returns what the caller must throw.
1473
+ *
1474
+ * A failed cleanup supersedes the delivery error — the cooldown/OTP may now be orphaned,
1475
+ * which the caller must see — and it must NOT bypass the scrub below. The delivery error is
1476
+ * preserved as its cause when the cleanup error can verifiably carry one; a hostile trap
1477
+ * inside the attachment is contained by the helper.
1478
+ *
1479
+ * The scrub runs BEFORE the audit write and the rethrow, so neither the entry's
1480
+ * `errorMessage` nor the outgoing chain can carry the plaintext code. An Error chain is
1481
+ * scrubbed (in place, or via redacted copies when a node resists mutation); ANY other
1482
+ * rejection (string, object from a custom storage, number) is flattened to a redacted
1483
+ * string, because a raw object could carry the code in its properties and a primitive
1484
+ * cannot be mutated.
1485
+ */
1486
+ async failedOutgoing(scope, error, code) {
1487
+ let failure = error;
1488
+ try {
1489
+ await this.releaseOtp(scope);
1490
+ } catch (cleanupError) {
1491
+ attachCauseIfAbsent(cleanupError, error);
1492
+ failure = cleanupError;
1493
+ }
1494
+ const outgoing = isSafeError(failure) ? scrubValuesFromErrorChain(failure, [code]) : coerceRedacted(failure, [code]);
1495
+ await this.audit(
1496
+ this.otpAuditEntry("failed", scope, {
1497
+ // `outgoing` is already fully redacted by the scrub above; this read
1498
+ // only needs the fail-closed guard, not a second redaction pass.
1499
+ errorMessage: readRedactedMessage(outgoing)
1500
+ })
1501
+ );
1502
+ return outgoing;
1503
+ }
1504
+ /**
1505
+ * Warns once when the storage cannot carry failed attempts across a re-issue, naming the
1506
+ * deviation from NIST SP 800-63B-4 §3.1.3.2 and the methods that remove it.
1507
+ */
1508
+ onModuleInit() {
1509
+ const storage = this.storage;
1510
+ if (carriesFailures(storage) || this.warnedFailuresNotCarried) {
1511
+ return;
1512
+ }
1513
+ this.warnedFailuresNotCarried = true;
1514
+ this.logger.warn(
1515
+ `[BYMAX_NOTIFICATION_OTP_FAILURES_NOT_CARRIED] The ${storage.name} OTP storage does not implement getFailures, recordFailure and clearFailures, so issuing a new code gives it a fresh attempt budget; NIST SP 800-63B-4 \xA73.1.3.2 says generating a new secret SHALL NOT reset the failed authentication count. Implement the three optional methods to carry the count across re-issues.`
1516
+ );
1517
+ }
1518
+ /**
1519
+ * Counts one verification attempt against the recipient. Returns `undefined` when the storage
1520
+ * does not carry failures, and `null` when no code is live: a verification with no code guesses
1521
+ * at nothing, so it spends no budget, and the caller must answer `not_found` instead of going on
1522
+ * to consume an attempt from a code issued in the meantime, which would then go uncounted.
1523
+ */
1524
+ async countAttempt(scope, ttlSeconds) {
1525
+ const storage = this.storage;
1526
+ if (!carriesFailures(storage)) {
1527
+ return void 0;
1528
+ }
1529
+ const live = await storage.get(scope.tenantId, scope.recipient, scope.purpose);
1530
+ if (live === null) {
1531
+ return null;
1532
+ }
1533
+ return storage.recordFailure(scope.tenantId, scope.recipient, scope.purpose, ttlSeconds);
1534
+ }
1535
+ /** How a generated code reaches the recipient: by email when asked or when an email channel exists. */
1536
+ deliveryOf(input) {
1537
+ return input.deliverVia ?? (this.emailService ? "email" : "manual");
1538
+ }
1539
+ /**
1540
+ * Refuses a manual delivery while codes are stored as digests, before the cooldown is taken
1541
+ * or anything is stored. `generate` never returns the code and a digest cannot be handed to
1542
+ * a person, so the call would otherwise succeed with nothing deliverable.
1543
+ *
1544
+ * @throws NotificationException `OTP_MANUAL_DELIVERY_UNAVAILABLE`.
1545
+ */
1546
+ assertDeliverable(input, digestCode) {
1547
+ if (digestCode && this.deliveryOf(input) !== "email") {
1548
+ throw new NotificationException("OTP_MANUAL_DELIVERY_UNAVAILABLE", {
1549
+ remedy: "unset otp.codeSecret to read the code from the store, or configure an email channel and deliver by email"
1550
+ });
1383
1551
  }
1384
1552
  }
1385
1553
  /** Delivers the code by email when requested; throws on failure (release is handled by the caller). */
1386
1554
  async deliverOtp(input, code, cfg) {
1387
- const deliverVia = input.deliverVia ?? (this.emailService ? "email" : "manual");
1388
- if (deliverVia !== "email") {
1555
+ if (this.deliveryOf(input) !== "email") {
1389
1556
  return;
1390
1557
  }
1391
1558
  if (!this.emailService) {
@@ -1429,6 +1596,43 @@ var OtpService = class {
1429
1596
  }
1430
1597
  await this.audit(this.otpAuditEntry("verified", input, void 0));
1431
1598
  }
1599
+ /**
1600
+ * Refuses a tenant id or recipient that identifies nobody, before any storage call.
1601
+ *
1602
+ * The reference storage already refuses these through `hashTenantRecipient`, but a
1603
+ * consumer-supplied {@link IOtpStorage} is not required to, and a blank scope would
1604
+ * then be shared by every caller that sent one.
1605
+ *
1606
+ * @throws NotificationException `INVALID_SCOPE_IDENTIFIER` when either is blank.
1607
+ */
1608
+ assertScope(ref) {
1609
+ assertIdentifies("OtpService", "tenantId", ref.tenantId);
1610
+ assertIdentifies("OtpService", "recipient", ref.recipient);
1611
+ }
1612
+ /**
1613
+ * Returns the input with its recipient replaced by the value the OTP state is keyed on.
1614
+ *
1615
+ * Every storage call and audit entry takes the result, so two spellings of one mailbox
1616
+ * share a cooldown and an attempt counter. Delivery takes the original input: the
1617
+ * message is addressed exactly as the caller wrote it.
1618
+ */
1619
+ keyed(input) {
1620
+ return { ...input, recipient: normalizeRecipient(input.recipient) };
1621
+ }
1622
+ /**
1623
+ * Compares a guessed code with the stored value in constant time.
1624
+ *
1625
+ * A stored digest is recomputed from the guess. A digest that cannot be recomputed (no
1626
+ * secret configured, or a different one) never matches, and the digest string itself is
1627
+ * not accepted as a code. A stored value that is not a digest is a plaintext code written
1628
+ * while no secret was set; it is compared directly and ages out with its TTL.
1629
+ */
1630
+ matchesStoredCode(stored, guess, digestCode) {
1631
+ if (!isCodeDigest(stored)) {
1632
+ return safeCompare(stored, guess);
1633
+ }
1634
+ return digestCode !== void 0 && safeCompare(stored, digestCode(guess));
1635
+ }
1432
1636
  /** Returns the resolved OTP options or throws `OTP_STORAGE_NOT_CONFIGURED`. */
1433
1637
  requireOtpOptions() {
1434
1638
  if (!this.options.otp) {
@@ -1479,6 +1683,7 @@ var NotificationService = class {
1479
1683
  constructor(emailService, otpService) {
1480
1684
  this.emailService = emailService;
1481
1685
  this.otpService = otpService;
1686
+ this.logger = new Logger(NotificationService.name);
1482
1687
  }
1483
1688
  /**
1484
1689
  * Dispatches a notification to the channel named in `input`.
@@ -1522,6 +1727,12 @@ var NotificationService = class {
1522
1727
  if (!this.emailService) {
1523
1728
  throw new NotificationException("CHANNEL_DISABLED", { channel: "email" });
1524
1729
  }
1730
+ if (!this.emailService.isConfigured()) {
1731
+ throw new NotificationException("CHANNEL_DISABLED", {
1732
+ channel: "email",
1733
+ reason: "provider_not_configured"
1734
+ });
1735
+ }
1525
1736
  return this.emailService;
1526
1737
  }
1527
1738
  /**
@@ -1534,8 +1745,34 @@ var NotificationService = class {
1534
1745
  if (!this.otpService) {
1535
1746
  throw new NotificationException("CHANNEL_DISABLED", { channel: "otp" });
1536
1747
  }
1748
+ if (!this.otpService.isConfigured()) {
1749
+ throw new NotificationException("CHANNEL_DISABLED", {
1750
+ channel: "otp",
1751
+ reason: "storage_not_configured"
1752
+ });
1753
+ }
1537
1754
  return this.otpService;
1538
1755
  }
1756
+ /**
1757
+ * Warns once per channel that is configured but cannot be used, because its provider or
1758
+ * storage reports `isConfigured() === false`. Such a channel is absent from
1759
+ * {@link NotificationService.getEnabledChannels} and refused by the accessors; without this
1760
+ * line the first sign of it would be a failed send.
1761
+ */
1762
+ onModuleInit() {
1763
+ if (this.emailService && !this.emailService.isConfigured()) {
1764
+ this.warnNotUsable("email", "provider");
1765
+ }
1766
+ if (this.otpService && !this.otpService.isConfigured()) {
1767
+ this.warnNotUsable("otp", "storage");
1768
+ }
1769
+ }
1770
+ /** Logs the not-usable warning for one channel. */
1771
+ warnNotUsable(channel, part) {
1772
+ this.logger.warn(
1773
+ `[BYMAX_NOTIFICATION_CHANNEL_NOT_USABLE] The ${channel} channel is configured but its ${part} reports isConfigured() = false, so it is not enabled: check the ${part}'s credentials or environment.`
1774
+ );
1775
+ }
1539
1776
  /** Routes an email dispatch to `sendTemplate` (template) or `send` (raw body). */
1540
1777
  async dispatchEmail(tenantId, payload) {
1541
1778
  const email = this.getEmail();
@@ -1623,6 +1860,17 @@ NotificationService = __decorateClass([
1623
1860
  // src/server/bymax-notification.module.ts
1624
1861
  var RAW_NOTIFICATION_OPTIONS = /* @__PURE__ */ Symbol("RAW_NOTIFICATION_OPTIONS");
1625
1862
  var BymaxNotificationModule = class {
1863
+ /**
1864
+ * Logs one warning when the OTP channel stores codes in plaintext, i.e. `otp.codeSecret`
1865
+ * is not configured. A reader of the store would see every live code.
1866
+ */
1867
+ static warnPlaintextCodes(resolved) {
1868
+ if (resolved.otp && !resolved.otp.digestCode) {
1869
+ BymaxNotificationModule.logger.warn(
1870
+ "[BYMAX_NOTIFICATION_PLAINTEXT_OTP_CODES] otp.codeSecret is not set: OTP codes are stored in plaintext. Set otp.codeSecret (at least 32 bytes) to store an HMAC-SHA-256 digest instead."
1871
+ );
1872
+ }
1873
+ }
1626
1874
  /**
1627
1875
  * Registers the module synchronously from static options.
1628
1876
  *
@@ -1633,6 +1881,7 @@ var BymaxNotificationModule = class {
1633
1881
  static forRoot(options) {
1634
1882
  validateOptions(options);
1635
1883
  const resolved = resolveOptions(options);
1884
+ this.warnPlaintextCodes(resolved);
1636
1885
  const tokenProviders = this.buildProviders(options, resolved);
1637
1886
  const serviceProviders = this.buildServiceProviders(resolved);
1638
1887
  this.logger.log(
@@ -1733,7 +1982,11 @@ var BymaxNotificationModule = class {
1733
1982
  return [
1734
1983
  {
1735
1984
  provide: BYMAX_NOTIFICATION_OPTIONS,
1736
- useFactory: (raw) => resolveOptions(raw),
1985
+ useFactory: (raw) => {
1986
+ const resolved = resolveOptions(raw);
1987
+ BymaxNotificationModule.warnPlaintextCodes(resolved);
1988
+ return resolved;
1989
+ },
1737
1990
  inject: [RAW_NOTIFICATION_OPTIONS]
1738
1991
  },
1739
1992
  {
@@ -1845,25 +2098,6 @@ function instantiate(valueOrClass) {
1845
2098
  }
1846
2099
  return new ctor();
1847
2100
  }
1848
-
1849
- // src/server/utils/tenant-scope.ts
1850
- function refuse(owner, label, reason) {
1851
- return new NotificationException(
1852
- "INVALID_SCOPE_IDENTIFIER",
1853
- { boundary: owner, parameter: label, reason },
1854
- { message: `[${owner}] ${label} ${reason}` }
1855
- );
1856
- }
1857
- function assertIdentifies(owner, label, value) {
1858
- if (typeof value !== "string") {
1859
- throw refuse(owner, label, `expected a string, received ${typeof value}`);
1860
- }
1861
- if (value.trim() === "") {
1862
- throw refuse(owner, label, "empty or whitespace-only");
1863
- }
1864
- }
1865
-
1866
- // src/server/interceptors/notification-audit.interceptor.ts
1867
2101
  var INTERCEPTOR_NAME = "NotificationAuditInterceptor";
1868
2102
  var INTERCEPTOR_PROVIDER_NAME = "__interceptor__";
1869
2103
  function toErrorMessage(error) {
@@ -2725,6 +2959,45 @@ var InMemoryOtpStorage = class {
2725
2959
  this.store = /* @__PURE__ */ new Map();
2726
2960
  /** Cooldown expiries (epoch ms) keyed by the same composite key. */
2727
2961
  this.cooldowns = /* @__PURE__ */ new Map();
2962
+ /** Failed-verification counters and their expiry (epoch ms), keyed the same way. */
2963
+ this.failures = /* @__PURE__ */ new Map();
2964
+ }
2965
+ /**
2966
+ * Failed verifications recorded for the scope, or `0` once the counter has lapsed.
2967
+ *
2968
+ * @param tenantId - Tenant isolation scope.
2969
+ * @param recipient - Pre-normalized recipient identifier.
2970
+ * @param purpose - OTP purpose.
2971
+ * @returns The count.
2972
+ */
2973
+ async getFailures(tenantId, recipient, purpose) {
2974
+ return this.liveFailures(this.key(tenantId, recipient, purpose));
2975
+ }
2976
+ /**
2977
+ * Adds one failed verification and restarts the counter's lifetime. Synchronous
2978
+ * read-modify-write, so concurrent calls each see a distinct count.
2979
+ *
2980
+ * @param tenantId - Tenant isolation scope.
2981
+ * @param recipient - Pre-normalized recipient identifier.
2982
+ * @param purpose - OTP purpose.
2983
+ * @param ttlSeconds - How long the counter lives without another failure.
2984
+ * @returns The new count.
2985
+ */
2986
+ async recordFailure(tenantId, recipient, purpose, ttlSeconds) {
2987
+ const key = this.key(tenantId, recipient, purpose);
2988
+ const count = this.liveFailures(key) + 1;
2989
+ this.failures.set(key, { count, expiresAt: Date.now() + ttlSeconds * MS_PER_SECOND3 });
2990
+ return count;
2991
+ }
2992
+ /**
2993
+ * Removes the failure counter. Idempotent.
2994
+ *
2995
+ * @param tenantId - Tenant isolation scope.
2996
+ * @param recipient - Pre-normalized recipient identifier.
2997
+ * @param purpose - OTP purpose.
2998
+ */
2999
+ async clearFailures(tenantId, recipient, purpose) {
3000
+ this.failures.delete(this.key(tenantId, recipient, purpose));
2728
3001
  }
2729
3002
  /** Always ready — there is nothing to configure.
2730
3003
  *
@@ -2871,6 +3144,7 @@ var InMemoryOtpStorage = class {
2871
3144
  clear() {
2872
3145
  this.store.clear();
2873
3146
  this.cooldowns.clear();
3147
+ this.failures.clear();
2874
3148
  }
2875
3149
  /**
2876
3150
  * Test helper — current map sizes. Not part of `IOtpStorage`.
@@ -2880,6 +3154,18 @@ var InMemoryOtpStorage = class {
2880
3154
  size() {
2881
3155
  return { otps: this.store.size, cooldowns: this.cooldowns.size };
2882
3156
  }
3157
+ /** The unexpired failure count for a key, dropping a lapsed counter. Synchronous. */
3158
+ liveFailures(key) {
3159
+ const found = this.failures.get(key);
3160
+ if (!found) {
3161
+ return 0;
3162
+ }
3163
+ if (found.expiresAt <= Date.now()) {
3164
+ this.failures.delete(key);
3165
+ return 0;
3166
+ }
3167
+ return found.count;
3168
+ }
2883
3169
  /**
2884
3170
  * Collapses the `(tenantId, recipient, purpose)` tuple into one map key.
2885
3171
  *
@@ -3049,10 +3335,54 @@ var RedisOtpStorage = class {
3049
3335
  async clearCooldown(tenantId, recipient, purpose) {
3050
3336
  await __privateGet(this, _redis).del(this.cooldownKey(tenantId, recipient, purpose));
3051
3337
  }
3338
+ /**
3339
+ * Failed verifications recorded for the scope.
3340
+ *
3341
+ * @param tenantId - Tenant isolation scope.
3342
+ * @param recipient - Pre-normalized recipient identifier.
3343
+ * @param purpose - OTP purpose.
3344
+ * @returns The count, or `0` when there is no counter.
3345
+ */
3346
+ async getFailures(tenantId, recipient, purpose) {
3347
+ const raw = await __privateGet(this, _redis).get(this.failureKey(tenantId, recipient, purpose));
3348
+ return raw === null ? 0 : Number.parseInt(raw, 10);
3349
+ }
3350
+ /**
3351
+ * Adds one failed verification and restarts the counter's lifetime, atomically.
3352
+ *
3353
+ * @param tenantId - Tenant isolation scope.
3354
+ * @param recipient - Pre-normalized recipient identifier.
3355
+ * @param purpose - OTP purpose.
3356
+ * @param ttlSeconds - How long the counter lives without another failure.
3357
+ * @returns The new count.
3358
+ */
3359
+ async recordFailure(tenantId, recipient, purpose, ttlSeconds) {
3360
+ const result = await __privateGet(this, _redis).eval(
3361
+ RedisOtpStorage.RECORD_FAILURE_LUA,
3362
+ 1,
3363
+ this.failureKey(tenantId, recipient, purpose),
3364
+ Math.max(1, Math.ceil(ttlSeconds))
3365
+ );
3366
+ return Number(result);
3367
+ }
3368
+ /**
3369
+ * Removes the failure counter. Idempotent.
3370
+ *
3371
+ * @param tenantId - Tenant isolation scope.
3372
+ * @param recipient - Pre-normalized recipient identifier.
3373
+ * @param purpose - OTP purpose.
3374
+ */
3375
+ async clearFailures(tenantId, recipient, purpose) {
3376
+ await __privateGet(this, _redis).del(this.failureKey(tenantId, recipient, purpose));
3377
+ }
3052
3378
  /** Builds the OTP entry key: `{namespace}:otp:{purpose}:{hashTenantRecipient(...)}`. */
3053
3379
  otpKey(tenantId, recipient, purpose) {
3054
3380
  return `${this.namespace}:otp:${purpose}:${hashTenantRecipient(tenantId, recipient)}`;
3055
3381
  }
3382
+ /** Builds the failure-counter key: `{namespace}:otp_fail:{purpose}:{hashTenantRecipient(...)}`. */
3383
+ failureKey(tenantId, recipient, purpose) {
3384
+ return `${this.namespace}:otp_fail:${purpose}:${hashTenantRecipient(tenantId, recipient)}`;
3385
+ }
3056
3386
  /** Builds the cooldown key: `{namespace}:otp_cd:{purpose}:{hashTenantRecipient(...)}`. */
3057
3387
  cooldownKey(tenantId, recipient, purpose) {
3058
3388
  return `${this.namespace}:otp_cd:${purpose}:${hashTenantRecipient(tenantId, recipient)}`;
@@ -3086,6 +3416,17 @@ RedisOtpStorage.CONSUME_ATTEMPT_LUA = `
3086
3416
  end
3087
3417
  return cjson.encode({ status = 'ok', entry = entry })
3088
3418
  `;
3419
+ /**
3420
+ * Atomic failure-counter primitive: one `INCR` and the lifetime refresh in a single script, so
3421
+ * concurrent failures each receive a distinct count and the counter never outlives its window
3422
+ * by a gap between the two commands.
3423
+ */
3424
+ // Stryker disable next-line StringLiteral: the Lua body executes only on a real Redis server; unit tests drive a JS fake whose `eval` recognises the script by its command, so an emptied-string mutant is unkillable without a live Redis integration run.
3425
+ RedisOtpStorage.RECORD_FAILURE_LUA = `
3426
+ local count = redis.call('INCR', KEYS[1])
3427
+ redis.call('EXPIRE', KEYS[1], tonumber(ARGV[1]))
3428
+ return count
3429
+ `;
3089
3430
  RedisOtpStorage = __decorateClass([
3090
3431
  Injectable()
3091
3432
  ], RedisOtpStorage);