@bymax-one/nest-notification 1.4.1 → 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(
@@ -1199,21 +1260,10 @@ function formatCooldown(remainingSeconds) {
1199
1260
  return parts.join(" ");
1200
1261
  }
1201
1262
 
1202
- // src/server/utils/tenant-scope.ts
1203
- function refuse(owner, label, reason) {
1204
- return new NotificationException(
1205
- "INVALID_SCOPE_IDENTIFIER",
1206
- { boundary: owner, parameter: label, reason },
1207
- { message: `[${owner}] ${label} ${reason}` }
1208
- );
1209
- }
1210
- function assertIdentifies(owner, label, value) {
1211
- if (typeof value !== "string") {
1212
- throw refuse(owner, label, `expected a string, received ${typeof value}`);
1213
- }
1214
- if (value.trim() === "") {
1215
- throw refuse(owner, label, "empty or whitespace-only");
1216
- }
1263
+ // src/server/utils/recipient.ts
1264
+ function normalizeRecipient(recipient) {
1265
+ const trimmed = recipient.trim();
1266
+ return trimmed.includes("@") ? trimmed.toLowerCase() : trimmed;
1217
1267
  }
1218
1268
  function safeCompare(expected, actual) {
1219
1269
  const expectedBytes = Buffer.from(expected, "utf8");
@@ -1228,6 +1278,9 @@ function safeCompare(expected, actual) {
1228
1278
  var MS_PER_SECOND2 = 1e3;
1229
1279
  var SECONDS_PER_MINUTE2 = 60;
1230
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
+ }
1231
1284
  exports.OtpService = class OtpService {
1232
1285
  /**
1233
1286
  * @param options - The resolved, frozen module options.
@@ -1240,6 +1293,8 @@ exports.OtpService = class OtpService {
1240
1293
  this.storage = storage;
1241
1294
  this.auditLog = auditLog;
1242
1295
  this.emailService = emailService;
1296
+ this.logger = new common.Logger(exports.OtpService.name);
1297
+ this.warnedFailuresNotCarried = false;
1243
1298
  }
1244
1299
  /**
1245
1300
  * Whether the OTP channel is configured and its storage is ready.
@@ -1261,12 +1316,22 @@ exports.OtpService = class OtpService {
1261
1316
  async generate(input) {
1262
1317
  const otp = this.requireOtpOptions();
1263
1318
  this.assertScope(input);
1319
+ const scope = this.keyed(input);
1320
+ this.assertDeliverable(input, otp.digestCode);
1264
1321
  const cfg = otp.resolveForPurpose(input.purpose);
1265
- await this.acquireCooldownOrThrow(input, cfg.resendCooldownSeconds);
1322
+ await this.acquireCooldownOrThrow(scope, cfg.resendCooldownSeconds);
1266
1323
  const code = generateOtpCode(cfg.length, cfg.codeType);
1267
1324
  const expiresAt = Date.now() + cfg.ttlSeconds * MS_PER_SECOND2;
1268
- await this.persistAndDeliver(input, code, expiresAt, cfg);
1269
- 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));
1270
1335
  return { expiresAt, cooldownSeconds: cfg.resendCooldownSeconds };
1271
1336
  }
1272
1337
  /**
@@ -1279,27 +1344,43 @@ exports.OtpService = class OtpService {
1279
1344
  async verify(input) {
1280
1345
  const otp = this.requireOtpOptions();
1281
1346
  this.assertScope(input);
1282
- const result = await this.storage.consumeAttempt(input.tenantId, input.recipient, input.purpose);
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);
1283
1361
  if (result.status === "not_found") {
1284
- await this.audit(this.otpAuditEntry("failed", input, { reason: "not_found" }));
1362
+ await this.audit(this.otpAuditEntry("failed", scope, { reason: "not_found" }));
1285
1363
  return { valid: false, reason: "not_found" };
1286
1364
  }
1287
1365
  if (result.status === "max_attempts") {
1288
1366
  await this.audit(
1289
- this.otpAuditEntry("max_attempts_exceeded", input, { reason: "max_attempts" })
1367
+ this.otpAuditEntry("max_attempts_exceeded", scope, { reason: "max_attempts" })
1290
1368
  );
1291
1369
  return { valid: false, reason: "max_attempts" };
1292
1370
  }
1293
1371
  const { entry } = result;
1294
- if (!safeCompare(entry.code, input.code)) {
1295
- 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;
1296
1375
  return {
1297
1376
  valid: false,
1298
1377
  reason: "invalid_code",
1299
- 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)
1300
1380
  };
1301
1381
  }
1302
- 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);
1303
1384
  return { valid: true };
1304
1385
  }
1305
1386
  /**
@@ -1311,8 +1392,10 @@ exports.OtpService = class OtpService {
1311
1392
  async consume(input) {
1312
1393
  this.requireOtpOptions();
1313
1394
  this.assertScope(input);
1314
- await this.storage.delete(input.tenantId, input.recipient, input.purpose);
1315
- await this.storage.clearCooldown(input.tenantId, input.recipient, input.purpose);
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);
1316
1399
  }
1317
1400
  /**
1318
1401
  * Explicit resend — a functional alias of {@link OtpService.generate}.
@@ -1331,9 +1414,10 @@ exports.OtpService = class OtpService {
1331
1414
  */
1332
1415
  async getStatus(input) {
1333
1416
  this.assertScope(input);
1417
+ const scope = this.keyed(input);
1334
1418
  const [entry, cooldownSeconds] = await Promise.all([
1335
- this.storage.get(input.tenantId, input.recipient, input.purpose),
1336
- 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)
1337
1421
  ]);
1338
1422
  if (!entry) {
1339
1423
  return { exists: false, cooldownSeconds };
@@ -1377,38 +1461,100 @@ exports.OtpService = class OtpService {
1377
1461
  * plaintext code is never placed in the failure audit entry. The original typed
1378
1462
  * error is re-thrown after the lock is released.
1379
1463
  */
1380
- async persistAndDeliver(input, code, expiresAt, cfg) {
1464
+ async persistAndDeliver(input, scope, code, entry, cfg) {
1381
1465
  try {
1382
- await this.storage.set(input.tenantId, input.recipient, input.purpose, {
1383
- code,
1384
- expiresAt,
1385
- attempts: 0,
1386
- maxAttempts: cfg.maxAttempts
1387
- });
1466
+ await this.storage.set(scope.tenantId, scope.recipient, scope.purpose, entry);
1388
1467
  await this.deliverOtp(input, code, cfg);
1389
1468
  } catch (error) {
1390
- let failure = error;
1391
- try {
1392
- await this.releaseOtp(input);
1393
- } catch (cleanupError) {
1394
- attachCauseIfAbsent(cleanupError, error);
1395
- failure = cleanupError;
1396
- }
1397
- const outgoing = isSafeError(failure) ? scrubValuesFromErrorChain(failure, [code]) : coerceRedacted(failure, [code]);
1398
- await this.audit(
1399
- this.otpAuditEntry("failed", input, {
1400
- // `outgoing` is already fully redacted by the scrub above; this read
1401
- // only needs the fail-closed guard, not a second redaction pass.
1402
- errorMessage: readRedactedMessage(outgoing)
1403
- })
1404
- );
1405
- 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
+ });
1406
1553
  }
1407
1554
  }
1408
1555
  /** Delivers the code by email when requested; throws on failure (release is handled by the caller). */
1409
1556
  async deliverOtp(input, code, cfg) {
1410
- const deliverVia = input.deliverVia ?? (this.emailService ? "email" : "manual");
1411
- if (deliverVia !== "email") {
1557
+ if (this.deliveryOf(input) !== "email") {
1412
1558
  return;
1413
1559
  }
1414
1560
  if (!this.emailService) {
@@ -1465,6 +1611,30 @@ exports.OtpService = class OtpService {
1465
1611
  assertIdentifies("OtpService", "tenantId", ref.tenantId);
1466
1612
  assertIdentifies("OtpService", "recipient", ref.recipient);
1467
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
+ }
1468
1638
  /** Returns the resolved OTP options or throws `OTP_STORAGE_NOT_CONFIGURED`. */
1469
1639
  requireOtpOptions() {
1470
1640
  if (!this.options.otp) {
@@ -1515,6 +1685,7 @@ exports.NotificationService = class NotificationService {
1515
1685
  constructor(emailService, otpService) {
1516
1686
  this.emailService = emailService;
1517
1687
  this.otpService = otpService;
1688
+ this.logger = new common.Logger(exports.NotificationService.name);
1518
1689
  }
1519
1690
  /**
1520
1691
  * Dispatches a notification to the channel named in `input`.
@@ -1558,6 +1729,12 @@ exports.NotificationService = class NotificationService {
1558
1729
  if (!this.emailService) {
1559
1730
  throw new NotificationException("CHANNEL_DISABLED", { channel: "email" });
1560
1731
  }
1732
+ if (!this.emailService.isConfigured()) {
1733
+ throw new NotificationException("CHANNEL_DISABLED", {
1734
+ channel: "email",
1735
+ reason: "provider_not_configured"
1736
+ });
1737
+ }
1561
1738
  return this.emailService;
1562
1739
  }
1563
1740
  /**
@@ -1570,8 +1747,34 @@ exports.NotificationService = class NotificationService {
1570
1747
  if (!this.otpService) {
1571
1748
  throw new NotificationException("CHANNEL_DISABLED", { channel: "otp" });
1572
1749
  }
1750
+ if (!this.otpService.isConfigured()) {
1751
+ throw new NotificationException("CHANNEL_DISABLED", {
1752
+ channel: "otp",
1753
+ reason: "storage_not_configured"
1754
+ });
1755
+ }
1573
1756
  return this.otpService;
1574
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
+ }
1575
1778
  /** Routes an email dispatch to `sendTemplate` (template) or `send` (raw body). */
1576
1779
  async dispatchEmail(tenantId, payload) {
1577
1780
  const email = this.getEmail();
@@ -1659,6 +1862,17 @@ exports.NotificationService = __decorateClass([
1659
1862
  // src/server/bymax-notification.module.ts
1660
1863
  var RAW_NOTIFICATION_OPTIONS = /* @__PURE__ */ Symbol("RAW_NOTIFICATION_OPTIONS");
1661
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
+ }
1662
1876
  /**
1663
1877
  * Registers the module synchronously from static options.
1664
1878
  *
@@ -1669,6 +1883,7 @@ exports.BymaxNotificationModule = class BymaxNotificationModule {
1669
1883
  static forRoot(options) {
1670
1884
  validateOptions(options);
1671
1885
  const resolved = resolveOptions(options);
1886
+ this.warnPlaintextCodes(resolved);
1672
1887
  const tokenProviders = this.buildProviders(options, resolved);
1673
1888
  const serviceProviders = this.buildServiceProviders(resolved);
1674
1889
  this.logger.log(
@@ -1769,7 +1984,11 @@ exports.BymaxNotificationModule = class BymaxNotificationModule {
1769
1984
  return [
1770
1985
  {
1771
1986
  provide: BYMAX_NOTIFICATION_OPTIONS,
1772
- useFactory: (raw) => resolveOptions(raw),
1987
+ useFactory: (raw) => {
1988
+ const resolved = resolveOptions(raw);
1989
+ exports.BymaxNotificationModule.warnPlaintextCodes(resolved);
1990
+ return resolved;
1991
+ },
1773
1992
  inject: [RAW_NOTIFICATION_OPTIONS]
1774
1993
  },
1775
1994
  {
@@ -2742,6 +2961,45 @@ exports.InMemoryOtpStorage = class InMemoryOtpStorage {
2742
2961
  this.store = /* @__PURE__ */ new Map();
2743
2962
  /** Cooldown expiries (epoch ms) keyed by the same composite key. */
2744
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));
2745
3003
  }
2746
3004
  /** Always ready — there is nothing to configure.
2747
3005
  *
@@ -2888,6 +3146,7 @@ exports.InMemoryOtpStorage = class InMemoryOtpStorage {
2888
3146
  clear() {
2889
3147
  this.store.clear();
2890
3148
  this.cooldowns.clear();
3149
+ this.failures.clear();
2891
3150
  }
2892
3151
  /**
2893
3152
  * Test helper — current map sizes. Not part of `IOtpStorage`.
@@ -2897,6 +3156,18 @@ exports.InMemoryOtpStorage = class InMemoryOtpStorage {
2897
3156
  size() {
2898
3157
  return { otps: this.store.size, cooldowns: this.cooldowns.size };
2899
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
+ }
2900
3171
  /**
2901
3172
  * Collapses the `(tenantId, recipient, purpose)` tuple into one map key.
2902
3173
  *
@@ -3066,10 +3337,54 @@ exports.RedisOtpStorage = class RedisOtpStorage {
3066
3337
  async clearCooldown(tenantId, recipient, purpose) {
3067
3338
  await __privateGet(this, _redis).del(this.cooldownKey(tenantId, recipient, purpose));
3068
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
+ }
3069
3380
  /** Builds the OTP entry key: `{namespace}:otp:{purpose}:{hashTenantRecipient(...)}`. */
3070
3381
  otpKey(tenantId, recipient, purpose) {
3071
3382
  return `${this.namespace}:otp:${purpose}:${hashTenantRecipient(tenantId, recipient)}`;
3072
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
+ }
3073
3388
  /** Builds the cooldown key: `{namespace}:otp_cd:{purpose}:{hashTenantRecipient(...)}`. */
3074
3389
  cooldownKey(tenantId, recipient, purpose) {
3075
3390
  return `${this.namespace}:otp_cd:${purpose}:${hashTenantRecipient(tenantId, recipient)}`;
@@ -3103,6 +3418,17 @@ exports.RedisOtpStorage.CONSUME_ATTEMPT_LUA = `
3103
3418
  end
3104
3419
  return cjson.encode({ status = 'ok', entry = entry })
3105
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
+ `;
3106
3432
  exports.RedisOtpStorage = __decorateClass([
3107
3433
  common.Injectable()
3108
3434
  ], exports.RedisOtpStorage);