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