@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.
@@ -12,6 +12,7 @@ var NOTIFICATION_ERROR_CODES = {
12
12
  TEMPLATE_RENDER_FAILED: "notification.template_render_failed",
13
13
  OTP_STORAGE_NOT_CONFIGURED: "notification.otp_storage_not_configured",
14
14
  OTP_EMAIL_DELIVERY_NOT_CONFIGURED: "notification.otp_email_delivery_not_configured",
15
+ OTP_MANUAL_DELIVERY_UNAVAILABLE: "notification.otp_manual_delivery_unavailable",
15
16
  OTP_COOLDOWN_ACTIVE: "notification.otp_cooldown_active",
16
17
  OTP_NOT_FOUND: "notification.otp_not_found",
17
18
  OTP_EXPIRED: "notification.otp_expired",
@@ -74,7 +74,7 @@ interface NotificationErrorResponse {
74
74
  * Stable error-code identifiers, keyed by their symbolic name.
75
75
  *
76
76
  * Values are namespaced under `notification.*` and never change once published —
77
- * consumers branch on them to localize messages. The 23 entries cover the email,
77
+ * consumers branch on them to localize messages. The 24 entries cover the email,
78
78
  * template, OTP, SMS, push, audit, channel-config and scoping failure surfaces.
79
79
  */
80
80
  declare const NOTIFICATION_ERROR_CODES: {
@@ -88,6 +88,7 @@ declare const NOTIFICATION_ERROR_CODES: {
88
88
  readonly TEMPLATE_RENDER_FAILED: "notification.template_render_failed";
89
89
  readonly OTP_STORAGE_NOT_CONFIGURED: "notification.otp_storage_not_configured";
90
90
  readonly OTP_EMAIL_DELIVERY_NOT_CONFIGURED: "notification.otp_email_delivery_not_configured";
91
+ readonly OTP_MANUAL_DELIVERY_UNAVAILABLE: "notification.otp_manual_delivery_unavailable";
91
92
  readonly OTP_COOLDOWN_ACTIVE: "notification.otp_cooldown_active";
92
93
  readonly OTP_NOT_FOUND: "notification.otp_not_found";
93
94
  readonly OTP_EXPIRED: "notification.otp_expired";
@@ -142,4 +143,5 @@ declare const DEFAULT_TTLS: {
142
143
  readonly OTP_GENERIC_SECONDS: 600;
143
144
  };
144
145
 
145
- export { DEFAULT_TTLS, NOTIFICATION_ERROR_CODES, type NotificationChannel, type NotificationErrorCode, type NotificationErrorResponse, type OtpPurpose };
146
+ export { DEFAULT_TTLS, NOTIFICATION_ERROR_CODES };
147
+ export type { NotificationChannel, NotificationErrorCode, NotificationErrorResponse, OtpPurpose };
@@ -74,7 +74,7 @@ interface NotificationErrorResponse {
74
74
  * Stable error-code identifiers, keyed by their symbolic name.
75
75
  *
76
76
  * Values are namespaced under `notification.*` and never change once published —
77
- * consumers branch on them to localize messages. The 23 entries cover the email,
77
+ * consumers branch on them to localize messages. The 24 entries cover the email,
78
78
  * template, OTP, SMS, push, audit, channel-config and scoping failure surfaces.
79
79
  */
80
80
  declare const NOTIFICATION_ERROR_CODES: {
@@ -88,6 +88,7 @@ declare const NOTIFICATION_ERROR_CODES: {
88
88
  readonly TEMPLATE_RENDER_FAILED: "notification.template_render_failed";
89
89
  readonly OTP_STORAGE_NOT_CONFIGURED: "notification.otp_storage_not_configured";
90
90
  readonly OTP_EMAIL_DELIVERY_NOT_CONFIGURED: "notification.otp_email_delivery_not_configured";
91
+ readonly OTP_MANUAL_DELIVERY_UNAVAILABLE: "notification.otp_manual_delivery_unavailable";
91
92
  readonly OTP_COOLDOWN_ACTIVE: "notification.otp_cooldown_active";
92
93
  readonly OTP_NOT_FOUND: "notification.otp_not_found";
93
94
  readonly OTP_EXPIRED: "notification.otp_expired";
@@ -142,4 +143,5 @@ declare const DEFAULT_TTLS: {
142
143
  readonly OTP_GENERIC_SECONDS: 600;
143
144
  };
144
145
 
145
- export { DEFAULT_TTLS, NOTIFICATION_ERROR_CODES, type NotificationChannel, type NotificationErrorCode, type NotificationErrorResponse, type OtpPurpose };
146
+ export { DEFAULT_TTLS, NOTIFICATION_ERROR_CODES };
147
+ export type { NotificationChannel, NotificationErrorCode, NotificationErrorResponse, OtpPurpose };
@@ -10,6 +10,7 @@ var NOTIFICATION_ERROR_CODES = {
10
10
  TEMPLATE_RENDER_FAILED: "notification.template_render_failed",
11
11
  OTP_STORAGE_NOT_CONFIGURED: "notification.otp_storage_not_configured",
12
12
  OTP_EMAIL_DELIVERY_NOT_CONFIGURED: "notification.otp_email_delivery_not_configured",
13
+ OTP_MANUAL_DELIVERY_UNAVAILABLE: "notification.otp_manual_delivery_unavailable",
13
14
  OTP_COOLDOWN_ACTIVE: "notification.otp_cooldown_active",
14
15
  OTP_NOT_FOUND: "notification.otp_not_found",
15
16
  OTP_EXPIRED: "notification.otp_expired",
@@ -2,6 +2,203 @@
2
2
 
3
3
  var crypto = require('crypto');
4
4
 
5
+ // src/testing/otp-storage-contract.ts
6
+
7
+ // src/testing/otp-storage-contract.shared.ts
8
+ var RACERS = 25;
9
+ function check(condition, message) {
10
+ if (!condition) {
11
+ throw new Error(`IOtpStorage contract violated: ${message}`);
12
+ }
13
+ }
14
+ function wait(ms) {
15
+ return new Promise((resolve) => {
16
+ setTimeout(resolve, ms);
17
+ });
18
+ }
19
+
20
+ // src/testing/otp-storage-contract.failures.ts
21
+ function hasFailureMethods(storage) {
22
+ return storage.getFailures !== void 0 && storage.recordFailure !== void 0 && storage.clearFailures !== void 0;
23
+ }
24
+ var FAILURE_TTL_SECONDS = 60;
25
+ function failureCountCase({ scope, withStorage }) {
26
+ return {
27
+ name: "counts failures per scope (optional: getFailures, recordFailure, clearFailures)",
28
+ run: () => withStorage(async (storage) => {
29
+ if (!hasFailureMethods(storage)) {
30
+ return;
31
+ }
32
+ const counts = [
33
+ await storage.recordFailure(
34
+ scope.tenantA,
35
+ scope.recipient,
36
+ scope.purpose,
37
+ FAILURE_TTL_SECONDS
38
+ ),
39
+ await storage.recordFailure(
40
+ scope.tenantA,
41
+ scope.recipient,
42
+ scope.purpose,
43
+ FAILURE_TTL_SECONDS
44
+ ),
45
+ await storage.recordFailure(
46
+ scope.tenantA,
47
+ scope.recipient,
48
+ scope.purpose,
49
+ FAILURE_TTL_SECONDS
50
+ )
51
+ ];
52
+ const read = await storage.getFailures(scope.tenantA, scope.recipient, scope.purpose);
53
+ const none = await storage.getFailures(scope.tenantA, scope.absentRecipient, scope.purpose);
54
+ check(
55
+ counts.join() === "1,2,3",
56
+ `recordFailure returned ${counts.join()} for three failures instead of 1,2,3`
57
+ );
58
+ check(read === 3, `getFailures returned ${String(read)} after three failures`);
59
+ check(none === 0, "getFailures returned a count for a scope that never failed");
60
+ })
61
+ };
62
+ }
63
+ function failureScopeCase({ scope, withStorage }) {
64
+ return {
65
+ name: "scopes the failure counter by tenant, recipient and purpose",
66
+ run: () => withStorage(async (storage) => {
67
+ if (!hasFailureMethods(storage)) {
68
+ return;
69
+ }
70
+ await storage.recordFailure(
71
+ scope.tenantA,
72
+ scope.recipient,
73
+ scope.purpose,
74
+ FAILURE_TTL_SECONDS
75
+ );
76
+ const otherTenant = await storage.getFailures(scope.tenantB, scope.recipient, scope.purpose);
77
+ const otherRecipient = await storage.getFailures(
78
+ scope.tenantA,
79
+ scope.absentRecipient,
80
+ scope.purpose
81
+ );
82
+ const otherPurpose = await storage.getFailures(
83
+ scope.tenantA,
84
+ scope.recipient,
85
+ scope.otherPurpose
86
+ );
87
+ check(otherTenant === 0, "a failure recorded for one tenant counted against another");
88
+ check(otherRecipient === 0, "a failure recorded for one recipient counted against another");
89
+ check(otherPurpose === 0, "a failure recorded for one purpose counted against another");
90
+ })
91
+ };
92
+ }
93
+ function failureBoundaryCase({
94
+ scope,
95
+ withStorage
96
+ }) {
97
+ return {
98
+ name: "keeps the tenant and recipient boundary when composing a failure-counter key",
99
+ run: () => withStorage(async (storage) => {
100
+ if (!hasFailureMethods(storage)) {
101
+ return;
102
+ }
103
+ for (const { left, right } of scope.boundaryShifts) {
104
+ await storage.recordFailure(left[0], left[1], scope.purpose, FAILURE_TTL_SECONDS);
105
+ const bled = await storage.getFailures(right[0], right[1], scope.purpose);
106
+ check(
107
+ bled === 0,
108
+ "a failure recorded for one tenant counted against another whose id and recipient differ only in where the boundary falls \u2014 the counter key concatenates the two fields without encoding the split, so one tenant can lock another out. The entry key, the cooldown key and the counter key are composed separately and all need this"
109
+ );
110
+ }
111
+ })
112
+ };
113
+ }
114
+ function failureClearCase({ scope, withStorage }) {
115
+ return {
116
+ name: "clearFailures removes only its own counter and is idempotent",
117
+ run: () => withStorage(async (storage) => {
118
+ if (!hasFailureMethods(storage)) {
119
+ return;
120
+ }
121
+ await storage.recordFailure(
122
+ scope.tenantA,
123
+ scope.recipient,
124
+ scope.purpose,
125
+ FAILURE_TTL_SECONDS
126
+ );
127
+ await storage.recordFailure(
128
+ scope.tenantA,
129
+ scope.absentRecipient,
130
+ scope.purpose,
131
+ FAILURE_TTL_SECONDS
132
+ );
133
+ await storage.clearFailures(scope.tenantA, scope.recipient, scope.purpose);
134
+ await storage.clearFailures(scope.tenantA, scope.recipient, scope.purpose);
135
+ check(
136
+ await storage.getFailures(scope.tenantA, scope.recipient, scope.purpose) === 0,
137
+ "getFailures still counted failures after clearFailures"
138
+ );
139
+ check(
140
+ await storage.getFailures(scope.tenantA, scope.absentRecipient, scope.purpose) === 1,
141
+ "clearFailures removed the counter of another recipient"
142
+ );
143
+ })
144
+ };
145
+ }
146
+ function failureTtlCase({
147
+ scope,
148
+ withStorage,
149
+ expiryWaitMs
150
+ }) {
151
+ return {
152
+ name: "a failure counter lapses after its lifetime",
153
+ run: () => withStorage(async (storage) => {
154
+ if (!hasFailureMethods(storage)) {
155
+ return;
156
+ }
157
+ await storage.recordFailure(scope.tenantA, scope.recipient, scope.purpose, 1e-3);
158
+ await wait(expiryWaitMs);
159
+ check(
160
+ await storage.getFailures(scope.tenantA, scope.recipient, scope.purpose) === 0,
161
+ "getFailures counted a failure whose lifetime had passed \u2014 a counter that never lapses locks a recipient out for good"
162
+ );
163
+ check(
164
+ await storage.recordFailure(
165
+ scope.tenantA,
166
+ scope.recipient,
167
+ scope.purpose,
168
+ FAILURE_TTL_SECONDS
169
+ ) === 1,
170
+ "a lapsed counter did not start again from one"
171
+ );
172
+ })
173
+ };
174
+ }
175
+ function failureAtomicCase({ scope, withStorage }) {
176
+ return {
177
+ name: "recordFailure is ATOMIC under concurrency",
178
+ run: () => withStorage(async (storage) => {
179
+ if (!hasFailureMethods(storage)) {
180
+ return;
181
+ }
182
+ const counts = await Promise.all(
183
+ Array.from(
184
+ { length: RACERS },
185
+ () => storage.recordFailure(
186
+ scope.tenantA,
187
+ scope.recipient,
188
+ scope.purpose,
189
+ FAILURE_TTL_SECONDS
190
+ )
191
+ )
192
+ );
193
+ const distinct = new Set(counts).size;
194
+ check(
195
+ distinct === RACERS,
196
+ `${String(RACERS)} concurrent failures produced only ${String(distinct)} distinct counts \u2014 the read and the write are not one step, so concurrent wrong guesses are lost and the attempt ceiling can be exceeded`
197
+ );
198
+ })
199
+ };
200
+ }
201
+
5
202
  // src/testing/otp-storage-contract.ts
6
203
  var KEY_PREFIX = "nest_notification_contract";
7
204
  var TENANT_A = "tenant_a";
@@ -22,26 +219,18 @@ function makeScope() {
22
219
  purpose: `${KEY_PREFIX}_${run}_${PURPOSE_MAIN}`,
23
220
  otherPurpose: `${KEY_PREFIX}_${run}_${PURPOSE_OTHER}`,
24
221
  // Same characters, two different (tenant, recipient) splits. A key built by
25
- // joining the raw values around `:` maps both onto one string.
26
- shiftedLeft: [`${KEY_PREFIX}_${run}_x:y`, "z"],
27
- shiftedRight: [`${KEY_PREFIX}_${run}_x`, "y:z"]
222
+ // joining the raw values around `:` maps both onto one string, and so does one
223
+ // built around `::`, which the single-colon pair alone does not expose.
224
+ boundaryShifts: [
225
+ { left: [`${KEY_PREFIX}_${run}_x:y`, "z"], right: [`${KEY_PREFIX}_${run}_x`, "y:z"] },
226
+ { left: [`${KEY_PREFIX}_${run}_x::y`, "z"], right: [`${KEY_PREFIX}_${run}_x`, "y::z"] }
227
+ ]
28
228
  };
29
229
  }
30
230
  var DEFAULT_EXPIRY_WAIT_MS = 1500;
31
- var RACERS = 25;
32
231
  function makeEntry(ttlMs, maxAttempts = 3, code = ANY_CODE) {
33
232
  return { code, expiresAt: Date.now() + ttlMs, attempts: 0, maxAttempts };
34
233
  }
35
- function check(condition, message) {
36
- if (!condition) {
37
- throw new Error(`IOtpStorage contract violated: ${message}`);
38
- }
39
- }
40
- function wait(ms) {
41
- return new Promise((resolve) => {
42
- setTimeout(resolve, ms);
43
- });
44
- }
45
234
  async function cleanUp(storage, scope) {
46
235
  const keys = [
47
236
  [scope.tenantA, scope.purpose],
@@ -53,10 +242,13 @@ async function cleanUp(storage, scope) {
53
242
  await storage.clearCooldown(tenant, scope.recipient, purpose);
54
243
  await storage.delete(tenant, scope.absentRecipient, purpose);
55
244
  await storage.clearCooldown(tenant, scope.absentRecipient, purpose);
245
+ await storage.clearFailures?.(tenant, scope.recipient, purpose);
246
+ await storage.clearFailures?.(tenant, scope.absentRecipient, purpose);
56
247
  }
57
- for (const [tenant, recipient] of [scope.shiftedLeft, scope.shiftedRight]) {
248
+ for (const [tenant, recipient] of scope.boundaryShifts.flatMap((s) => [s.left, s.right])) {
58
249
  await storage.delete(tenant, recipient, scope.purpose);
59
250
  await storage.clearCooldown(tenant, recipient, scope.purpose);
251
+ await storage.clearFailures?.(tenant, recipient, scope.purpose);
60
252
  }
61
253
  }
62
254
  function roundTripCase({ scope, withStorage }) {
@@ -382,14 +574,14 @@ function keyBoundaryCase({ scope, withStorage }) {
382
574
  return {
383
575
  name: "keeps the tenant and recipient boundary when composing a key",
384
576
  run: () => withStorage(async (storage) => {
385
- const [leftTenant, leftRecipient] = scope.shiftedLeft;
386
- const [rightTenant, rightRecipient] = scope.shiftedRight;
387
- await storage.set(leftTenant, leftRecipient, scope.purpose, makeEntry(6e4));
388
- const bled = await storage.get(rightTenant, rightRecipient, scope.purpose);
389
- check(
390
- bled === null,
391
- "an entry written for one tenant was readable by another whose id and recipient differ only in where the boundary falls \u2014 the key concatenates the two fields without encoding the split, so one tenant can read and consume another OTP. Hash or length-prefix each field before joining; no digest strength repairs it"
392
- );
577
+ for (const { left, right } of scope.boundaryShifts) {
578
+ await storage.set(left[0], left[1], scope.purpose, makeEntry(6e4));
579
+ const bled = await storage.get(right[0], right[1], scope.purpose);
580
+ check(
581
+ bled === null,
582
+ "an entry written for one tenant was readable by another whose id and recipient differ only in where the boundary falls \u2014 the key concatenates the two fields without encoding the split, so one tenant can read and consume another OTP. Hash or length-prefix each field before joining; no digest strength repairs it"
583
+ );
584
+ }
393
585
  })
394
586
  };
395
587
  }
@@ -397,23 +589,18 @@ function cooldownKeyBoundaryCase({ scope, withStorage }) {
397
589
  return {
398
590
  name: "keeps the tenant and recipient boundary when composing a cooldown key",
399
591
  run: () => withStorage(async (storage) => {
400
- const [leftTenant, leftRecipient] = scope.shiftedLeft;
401
- const [rightTenant, rightRecipient] = scope.shiftedRight;
402
- const held = await storage.tryAcquireCooldown(leftTenant, leftRecipient, scope.purpose, 60);
403
- check(
404
- held,
405
- "the first cooldown could not be acquired, so this case proves nothing about boundary encoding \u2014 a case that cannot fail is decoration"
406
- );
407
- const other = await storage.tryAcquireCooldown(
408
- rightTenant,
409
- rightRecipient,
410
- scope.purpose,
411
- 60
412
- );
413
- check(
414
- other,
415
- "a cooldown held for one tenant blocked another whose id and recipient differ only in where the boundary falls \u2014 the cooldown key concatenates the two fields without encoding the split, so one tenant can suppress another resends. The entry key and the cooldown key are composed separately and both need this"
416
- );
592
+ for (const { left, right } of scope.boundaryShifts) {
593
+ const held = await storage.tryAcquireCooldown(left[0], left[1], scope.purpose, 60);
594
+ check(
595
+ held,
596
+ "the first cooldown could not be acquired, so this case proves nothing about boundary encoding \u2014 a case that cannot fail is decoration"
597
+ );
598
+ const other = await storage.tryAcquireCooldown(right[0], right[1], scope.purpose, 60);
599
+ check(
600
+ other,
601
+ "a cooldown held for one tenant blocked another whose id and recipient differ only in where the boundary falls \u2014 the cooldown key concatenates the two fields without encoding the split, so one tenant can suppress another resends. The entry key and the cooldown key are composed separately and both need this"
602
+ );
603
+ }
417
604
  })
418
605
  };
419
606
  }
@@ -438,7 +625,13 @@ var CASE_BUILDERS = [
438
625
  cooldownPurposeScopeCase,
439
626
  cooldownAtomicCase,
440
627
  keyBoundaryCase,
441
- cooldownKeyBoundaryCase
628
+ cooldownKeyBoundaryCase,
629
+ failureCountCase,
630
+ failureScopeCase,
631
+ failureBoundaryCase,
632
+ failureClearCase,
633
+ failureTtlCase,
634
+ failureAtomicCase
442
635
  ];
443
636
  function otpStorageContract(factory, options = {}) {
444
637
  const scope = makeScope();
@@ -106,12 +106,48 @@ interface IOtpStorage {
106
106
  * cancelled flow can restart immediately).
107
107
  */
108
108
  clearCooldown(tenantId: string, recipient: string, purpose: string): Promise<void>;
109
+ /**
110
+ * Optional. Verification attempts counted for `(tenant, recipient, purpose)`, or `0`.
111
+ *
112
+ * Together with {@link IOtpStorage.recordFailure} and {@link IOtpStorage.clearFailures} this
113
+ * makes the failed-attempt count outlive a code: NIST SP 800-63B-4 §3.1.3.2 says generating a
114
+ * new authentication secret "SHALL NOT reset the failed authentication count". `OtpService`
115
+ * counts each verification attempt against a live code with `recordFailure` before comparing it and refuses
116
+ * once the number it returns passes the attempt ceiling; this method is the read side of the
117
+ * same counter. A storage that omits the three keeps a fresh budget per code, and a warning at
118
+ * startup names the deviation.
119
+ */
120
+ getFailures?(tenantId: string, recipient: string, purpose: string): Promise<number>;
121
+ /**
122
+ * Optional. Atomically adds one verification attempt and (re)sets the counter's lifetime to
123
+ * `ttlSeconds`, returning the new count. A counter that is not touched for `ttlSeconds`
124
+ * lapses, which starts the count again from zero.
125
+ *
126
+ * MUST be atomic (Redis: `INCR` and `EXPIRE` in one script).
127
+ */
128
+ recordFailure?(tenantId: string, recipient: string, purpose: string, ttlSeconds: number): Promise<number>;
129
+ /** Optional. Removes the failure counter. Idempotent. Called on success and on `consume()`. */
130
+ clearFailures?(tenantId: string, recipient: string, purpose: string): Promise<void>;
109
131
  /** Whether the storage is configured and ready. Used during module initialization. */
110
132
  isConfigured(): boolean;
111
133
  /** Storage name (e.g. `'redis'`, `'memory'`, `'dynamodb'`). */
112
134
  readonly name: string;
113
135
  }
114
136
 
137
+ /**
138
+ * @fileoverview Types and helpers shared by the `IOtpStorage` contract and its optional
139
+ * failure-counter cases.
140
+ * @layer testing
141
+ */
142
+
143
+ /** One executable obligation. `run` throws when the storage violates it. */
144
+ interface OtpStorageContractCase {
145
+ /** What the case checks, suitable as a test title. */
146
+ name: string;
147
+ /** Runs the case against a fresh storage; throws on violation. */
148
+ run: () => Promise<void>;
149
+ }
150
+
115
151
  /**
116
152
  * @fileoverview Executable contract for third-party `IOtpStorage` implementations.
117
153
  * @layer testing
@@ -139,13 +175,6 @@ interface IOtpStorage {
139
175
  * ```
140
176
  */
141
177
 
142
- /** One executable obligation. `run` throws when the storage violates it. */
143
- interface OtpStorageContractCase {
144
- /** What the case checks, suitable as a test title. */
145
- name: string;
146
- /** Runs the case against a fresh storage; throws on violation. */
147
- run: () => Promise<void>;
148
- }
149
178
  /** How the contract obtains a storage to exercise. */
150
179
  type OtpStorageFactory = () => IOtpStorage | Promise<IOtpStorage>;
151
180
  /** Tuning for the cases that must observe real time pass. */
@@ -171,4 +200,5 @@ interface OtpStorageContractOptions {
171
200
  */
172
201
  declare function otpStorageContract(factory: OtpStorageFactory, options?: OtpStorageContractOptions): OtpStorageContractCase[];
173
202
 
174
- export { type OtpStorageContractCase, type OtpStorageContractOptions, type OtpStorageFactory, otpStorageContract };
203
+ export { otpStorageContract };
204
+ export type { OtpStorageContractCase, OtpStorageContractOptions, OtpStorageFactory };
@@ -106,12 +106,48 @@ interface IOtpStorage {
106
106
  * cancelled flow can restart immediately).
107
107
  */
108
108
  clearCooldown(tenantId: string, recipient: string, purpose: string): Promise<void>;
109
+ /**
110
+ * Optional. Verification attempts counted for `(tenant, recipient, purpose)`, or `0`.
111
+ *
112
+ * Together with {@link IOtpStorage.recordFailure} and {@link IOtpStorage.clearFailures} this
113
+ * makes the failed-attempt count outlive a code: NIST SP 800-63B-4 §3.1.3.2 says generating a
114
+ * new authentication secret "SHALL NOT reset the failed authentication count". `OtpService`
115
+ * counts each verification attempt against a live code with `recordFailure` before comparing it and refuses
116
+ * once the number it returns passes the attempt ceiling; this method is the read side of the
117
+ * same counter. A storage that omits the three keeps a fresh budget per code, and a warning at
118
+ * startup names the deviation.
119
+ */
120
+ getFailures?(tenantId: string, recipient: string, purpose: string): Promise<number>;
121
+ /**
122
+ * Optional. Atomically adds one verification attempt and (re)sets the counter's lifetime to
123
+ * `ttlSeconds`, returning the new count. A counter that is not touched for `ttlSeconds`
124
+ * lapses, which starts the count again from zero.
125
+ *
126
+ * MUST be atomic (Redis: `INCR` and `EXPIRE` in one script).
127
+ */
128
+ recordFailure?(tenantId: string, recipient: string, purpose: string, ttlSeconds: number): Promise<number>;
129
+ /** Optional. Removes the failure counter. Idempotent. Called on success and on `consume()`. */
130
+ clearFailures?(tenantId: string, recipient: string, purpose: string): Promise<void>;
109
131
  /** Whether the storage is configured and ready. Used during module initialization. */
110
132
  isConfigured(): boolean;
111
133
  /** Storage name (e.g. `'redis'`, `'memory'`, `'dynamodb'`). */
112
134
  readonly name: string;
113
135
  }
114
136
 
137
+ /**
138
+ * @fileoverview Types and helpers shared by the `IOtpStorage` contract and its optional
139
+ * failure-counter cases.
140
+ * @layer testing
141
+ */
142
+
143
+ /** One executable obligation. `run` throws when the storage violates it. */
144
+ interface OtpStorageContractCase {
145
+ /** What the case checks, suitable as a test title. */
146
+ name: string;
147
+ /** Runs the case against a fresh storage; throws on violation. */
148
+ run: () => Promise<void>;
149
+ }
150
+
115
151
  /**
116
152
  * @fileoverview Executable contract for third-party `IOtpStorage` implementations.
117
153
  * @layer testing
@@ -139,13 +175,6 @@ interface IOtpStorage {
139
175
  * ```
140
176
  */
141
177
 
142
- /** One executable obligation. `run` throws when the storage violates it. */
143
- interface OtpStorageContractCase {
144
- /** What the case checks, suitable as a test title. */
145
- name: string;
146
- /** Runs the case against a fresh storage; throws on violation. */
147
- run: () => Promise<void>;
148
- }
149
178
  /** How the contract obtains a storage to exercise. */
150
179
  type OtpStorageFactory = () => IOtpStorage | Promise<IOtpStorage>;
151
180
  /** Tuning for the cases that must observe real time pass. */
@@ -171,4 +200,5 @@ interface OtpStorageContractOptions {
171
200
  */
172
201
  declare function otpStorageContract(factory: OtpStorageFactory, options?: OtpStorageContractOptions): OtpStorageContractCase[];
173
202
 
174
- export { type OtpStorageContractCase, type OtpStorageContractOptions, type OtpStorageFactory, otpStorageContract };
203
+ export { otpStorageContract };
204
+ export type { OtpStorageContractCase, OtpStorageContractOptions, OtpStorageFactory };