@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.
@@ -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(
@@ -1197,21 +1258,10 @@ function formatCooldown(remainingSeconds) {
1197
1258
  return parts.join(" ");
1198
1259
  }
1199
1260
 
1200
- // src/server/utils/tenant-scope.ts
1201
- function refuse(owner, label, reason) {
1202
- return new NotificationException(
1203
- "INVALID_SCOPE_IDENTIFIER",
1204
- { boundary: owner, parameter: label, reason },
1205
- { message: `[${owner}] ${label} ${reason}` }
1206
- );
1207
- }
1208
- function assertIdentifies(owner, label, value) {
1209
- if (typeof value !== "string") {
1210
- throw refuse(owner, label, `expected a string, received ${typeof value}`);
1211
- }
1212
- if (value.trim() === "") {
1213
- throw refuse(owner, label, "empty or whitespace-only");
1214
- }
1261
+ // src/server/utils/recipient.ts
1262
+ function normalizeRecipient(recipient) {
1263
+ const trimmed = recipient.trim();
1264
+ return trimmed.includes("@") ? trimmed.toLowerCase() : trimmed;
1215
1265
  }
1216
1266
  function safeCompare(expected, actual) {
1217
1267
  const expectedBytes = Buffer.from(expected, "utf8");
@@ -1226,6 +1276,9 @@ function safeCompare(expected, actual) {
1226
1276
  var MS_PER_SECOND2 = 1e3;
1227
1277
  var SECONDS_PER_MINUTE2 = 60;
1228
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
+ }
1229
1282
  var OtpService = class {
1230
1283
  /**
1231
1284
  * @param options - The resolved, frozen module options.
@@ -1238,6 +1291,8 @@ var OtpService = class {
1238
1291
  this.storage = storage;
1239
1292
  this.auditLog = auditLog;
1240
1293
  this.emailService = emailService;
1294
+ this.logger = new Logger(OtpService.name);
1295
+ this.warnedFailuresNotCarried = false;
1241
1296
  }
1242
1297
  /**
1243
1298
  * Whether the OTP channel is configured and its storage is ready.
@@ -1259,12 +1314,22 @@ var OtpService = class {
1259
1314
  async generate(input) {
1260
1315
  const otp = this.requireOtpOptions();
1261
1316
  this.assertScope(input);
1317
+ const scope = this.keyed(input);
1318
+ this.assertDeliverable(input, otp.digestCode);
1262
1319
  const cfg = otp.resolveForPurpose(input.purpose);
1263
- await this.acquireCooldownOrThrow(input, cfg.resendCooldownSeconds);
1320
+ await this.acquireCooldownOrThrow(scope, cfg.resendCooldownSeconds);
1264
1321
  const code = generateOtpCode(cfg.length, cfg.codeType);
1265
1322
  const expiresAt = Date.now() + cfg.ttlSeconds * MS_PER_SECOND2;
1266
- await this.persistAndDeliver(input, code, expiresAt, cfg);
1267
- 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));
1268
1333
  return { expiresAt, cooldownSeconds: cfg.resendCooldownSeconds };
1269
1334
  }
1270
1335
  /**
@@ -1277,27 +1342,43 @@ var OtpService = class {
1277
1342
  async verify(input) {
1278
1343
  const otp = this.requireOtpOptions();
1279
1344
  this.assertScope(input);
1280
- const result = await this.storage.consumeAttempt(input.tenantId, input.recipient, input.purpose);
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);
1281
1359
  if (result.status === "not_found") {
1282
- await this.audit(this.otpAuditEntry("failed", input, { reason: "not_found" }));
1360
+ await this.audit(this.otpAuditEntry("failed", scope, { reason: "not_found" }));
1283
1361
  return { valid: false, reason: "not_found" };
1284
1362
  }
1285
1363
  if (result.status === "max_attempts") {
1286
1364
  await this.audit(
1287
- this.otpAuditEntry("max_attempts_exceeded", input, { reason: "max_attempts" })
1365
+ this.otpAuditEntry("max_attempts_exceeded", scope, { reason: "max_attempts" })
1288
1366
  );
1289
1367
  return { valid: false, reason: "max_attempts" };
1290
1368
  }
1291
1369
  const { entry } = result;
1292
- if (!safeCompare(entry.code, input.code)) {
1293
- 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;
1294
1373
  return {
1295
1374
  valid: false,
1296
1375
  reason: "invalid_code",
1297
- 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)
1298
1378
  };
1299
1379
  }
1300
- 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);
1301
1382
  return { valid: true };
1302
1383
  }
1303
1384
  /**
@@ -1309,8 +1390,10 @@ var OtpService = class {
1309
1390
  async consume(input) {
1310
1391
  this.requireOtpOptions();
1311
1392
  this.assertScope(input);
1312
- await this.storage.delete(input.tenantId, input.recipient, input.purpose);
1313
- await this.storage.clearCooldown(input.tenantId, input.recipient, input.purpose);
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);
1314
1397
  }
1315
1398
  /**
1316
1399
  * Explicit resend — a functional alias of {@link OtpService.generate}.
@@ -1329,9 +1412,10 @@ var OtpService = class {
1329
1412
  */
1330
1413
  async getStatus(input) {
1331
1414
  this.assertScope(input);
1415
+ const scope = this.keyed(input);
1332
1416
  const [entry, cooldownSeconds] = await Promise.all([
1333
- this.storage.get(input.tenantId, input.recipient, input.purpose),
1334
- 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)
1335
1419
  ]);
1336
1420
  if (!entry) {
1337
1421
  return { exists: false, cooldownSeconds };
@@ -1375,38 +1459,100 @@ var OtpService = class {
1375
1459
  * plaintext code is never placed in the failure audit entry. The original typed
1376
1460
  * error is re-thrown after the lock is released.
1377
1461
  */
1378
- async persistAndDeliver(input, code, expiresAt, cfg) {
1462
+ async persistAndDeliver(input, scope, code, entry, cfg) {
1379
1463
  try {
1380
- await this.storage.set(input.tenantId, input.recipient, input.purpose, {
1381
- code,
1382
- expiresAt,
1383
- attempts: 0,
1384
- maxAttempts: cfg.maxAttempts
1385
- });
1464
+ await this.storage.set(scope.tenantId, scope.recipient, scope.purpose, entry);
1386
1465
  await this.deliverOtp(input, code, cfg);
1387
1466
  } catch (error) {
1388
- let failure = error;
1389
- try {
1390
- await this.releaseOtp(input);
1391
- } catch (cleanupError) {
1392
- attachCauseIfAbsent(cleanupError, error);
1393
- failure = cleanupError;
1394
- }
1395
- const outgoing = isSafeError(failure) ? scrubValuesFromErrorChain(failure, [code]) : coerceRedacted(failure, [code]);
1396
- await this.audit(
1397
- this.otpAuditEntry("failed", input, {
1398
- // `outgoing` is already fully redacted by the scrub above; this read
1399
- // only needs the fail-closed guard, not a second redaction pass.
1400
- errorMessage: readRedactedMessage(outgoing)
1401
- })
1402
- );
1403
- 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
+ });
1404
1551
  }
1405
1552
  }
1406
1553
  /** Delivers the code by email when requested; throws on failure (release is handled by the caller). */
1407
1554
  async deliverOtp(input, code, cfg) {
1408
- const deliverVia = input.deliverVia ?? (this.emailService ? "email" : "manual");
1409
- if (deliverVia !== "email") {
1555
+ if (this.deliveryOf(input) !== "email") {
1410
1556
  return;
1411
1557
  }
1412
1558
  if (!this.emailService) {
@@ -1463,6 +1609,30 @@ var OtpService = class {
1463
1609
  assertIdentifies("OtpService", "tenantId", ref.tenantId);
1464
1610
  assertIdentifies("OtpService", "recipient", ref.recipient);
1465
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
+ }
1466
1636
  /** Returns the resolved OTP options or throws `OTP_STORAGE_NOT_CONFIGURED`. */
1467
1637
  requireOtpOptions() {
1468
1638
  if (!this.options.otp) {
@@ -1513,6 +1683,7 @@ var NotificationService = class {
1513
1683
  constructor(emailService, otpService) {
1514
1684
  this.emailService = emailService;
1515
1685
  this.otpService = otpService;
1686
+ this.logger = new Logger(NotificationService.name);
1516
1687
  }
1517
1688
  /**
1518
1689
  * Dispatches a notification to the channel named in `input`.
@@ -1556,6 +1727,12 @@ var NotificationService = class {
1556
1727
  if (!this.emailService) {
1557
1728
  throw new NotificationException("CHANNEL_DISABLED", { channel: "email" });
1558
1729
  }
1730
+ if (!this.emailService.isConfigured()) {
1731
+ throw new NotificationException("CHANNEL_DISABLED", {
1732
+ channel: "email",
1733
+ reason: "provider_not_configured"
1734
+ });
1735
+ }
1559
1736
  return this.emailService;
1560
1737
  }
1561
1738
  /**
@@ -1568,8 +1745,34 @@ var NotificationService = class {
1568
1745
  if (!this.otpService) {
1569
1746
  throw new NotificationException("CHANNEL_DISABLED", { channel: "otp" });
1570
1747
  }
1748
+ if (!this.otpService.isConfigured()) {
1749
+ throw new NotificationException("CHANNEL_DISABLED", {
1750
+ channel: "otp",
1751
+ reason: "storage_not_configured"
1752
+ });
1753
+ }
1571
1754
  return this.otpService;
1572
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
+ }
1573
1776
  /** Routes an email dispatch to `sendTemplate` (template) or `send` (raw body). */
1574
1777
  async dispatchEmail(tenantId, payload) {
1575
1778
  const email = this.getEmail();
@@ -1657,6 +1860,17 @@ NotificationService = __decorateClass([
1657
1860
  // src/server/bymax-notification.module.ts
1658
1861
  var RAW_NOTIFICATION_OPTIONS = /* @__PURE__ */ Symbol("RAW_NOTIFICATION_OPTIONS");
1659
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
+ }
1660
1874
  /**
1661
1875
  * Registers the module synchronously from static options.
1662
1876
  *
@@ -1667,6 +1881,7 @@ var BymaxNotificationModule = class {
1667
1881
  static forRoot(options) {
1668
1882
  validateOptions(options);
1669
1883
  const resolved = resolveOptions(options);
1884
+ this.warnPlaintextCodes(resolved);
1670
1885
  const tokenProviders = this.buildProviders(options, resolved);
1671
1886
  const serviceProviders = this.buildServiceProviders(resolved);
1672
1887
  this.logger.log(
@@ -1767,7 +1982,11 @@ var BymaxNotificationModule = class {
1767
1982
  return [
1768
1983
  {
1769
1984
  provide: BYMAX_NOTIFICATION_OPTIONS,
1770
- useFactory: (raw) => resolveOptions(raw),
1985
+ useFactory: (raw) => {
1986
+ const resolved = resolveOptions(raw);
1987
+ BymaxNotificationModule.warnPlaintextCodes(resolved);
1988
+ return resolved;
1989
+ },
1771
1990
  inject: [RAW_NOTIFICATION_OPTIONS]
1772
1991
  },
1773
1992
  {
@@ -2740,6 +2959,45 @@ var InMemoryOtpStorage = class {
2740
2959
  this.store = /* @__PURE__ */ new Map();
2741
2960
  /** Cooldown expiries (epoch ms) keyed by the same composite key. */
2742
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));
2743
3001
  }
2744
3002
  /** Always ready — there is nothing to configure.
2745
3003
  *
@@ -2886,6 +3144,7 @@ var InMemoryOtpStorage = class {
2886
3144
  clear() {
2887
3145
  this.store.clear();
2888
3146
  this.cooldowns.clear();
3147
+ this.failures.clear();
2889
3148
  }
2890
3149
  /**
2891
3150
  * Test helper — current map sizes. Not part of `IOtpStorage`.
@@ -2895,6 +3154,18 @@ var InMemoryOtpStorage = class {
2895
3154
  size() {
2896
3155
  return { otps: this.store.size, cooldowns: this.cooldowns.size };
2897
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
+ }
2898
3169
  /**
2899
3170
  * Collapses the `(tenantId, recipient, purpose)` tuple into one map key.
2900
3171
  *
@@ -3064,10 +3335,54 @@ var RedisOtpStorage = class {
3064
3335
  async clearCooldown(tenantId, recipient, purpose) {
3065
3336
  await __privateGet(this, _redis).del(this.cooldownKey(tenantId, recipient, purpose));
3066
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
+ }
3067
3378
  /** Builds the OTP entry key: `{namespace}:otp:{purpose}:{hashTenantRecipient(...)}`. */
3068
3379
  otpKey(tenantId, recipient, purpose) {
3069
3380
  return `${this.namespace}:otp:${purpose}:${hashTenantRecipient(tenantId, recipient)}`;
3070
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
+ }
3071
3386
  /** Builds the cooldown key: `{namespace}:otp_cd:{purpose}:{hashTenantRecipient(...)}`. */
3072
3387
  cooldownKey(tenantId, recipient, purpose) {
3073
3388
  return `${this.namespace}:otp_cd:${purpose}:${hashTenantRecipient(tenantId, recipient)}`;
@@ -3101,6 +3416,17 @@ RedisOtpStorage.CONSUME_ATTEMPT_LUA = `
3101
3416
  end
3102
3417
  return cjson.encode({ status = 'ok', entry = entry })
3103
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
+ `;
3104
3430
  RedisOtpStorage = __decorateClass([
3105
3431
  Injectable()
3106
3432
  ], RedisOtpStorage);