@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.
@@ -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";
@@ -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";
@@ -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";
@@ -31,20 +228,9 @@ function makeScope() {
31
228
  };
32
229
  }
33
230
  var DEFAULT_EXPIRY_WAIT_MS = 1500;
34
- var RACERS = 25;
35
231
  function makeEntry(ttlMs, maxAttempts = 3, code = ANY_CODE) {
36
232
  return { code, expiresAt: Date.now() + ttlMs, attempts: 0, maxAttempts };
37
233
  }
38
- function check(condition, message) {
39
- if (!condition) {
40
- throw new Error(`IOtpStorage contract violated: ${message}`);
41
- }
42
- }
43
- function wait(ms) {
44
- return new Promise((resolve) => {
45
- setTimeout(resolve, ms);
46
- });
47
- }
48
234
  async function cleanUp(storage, scope) {
49
235
  const keys = [
50
236
  [scope.tenantA, scope.purpose],
@@ -56,10 +242,13 @@ async function cleanUp(storage, scope) {
56
242
  await storage.clearCooldown(tenant, scope.recipient, purpose);
57
243
  await storage.delete(tenant, scope.absentRecipient, purpose);
58
244
  await storage.clearCooldown(tenant, scope.absentRecipient, purpose);
245
+ await storage.clearFailures?.(tenant, scope.recipient, purpose);
246
+ await storage.clearFailures?.(tenant, scope.absentRecipient, purpose);
59
247
  }
60
248
  for (const [tenant, recipient] of scope.boundaryShifts.flatMap((s) => [s.left, s.right])) {
61
249
  await storage.delete(tenant, recipient, scope.purpose);
62
250
  await storage.clearCooldown(tenant, recipient, scope.purpose);
251
+ await storage.clearFailures?.(tenant, recipient, scope.purpose);
63
252
  }
64
253
  }
65
254
  function roundTripCase({ scope, withStorage }) {
@@ -436,7 +625,13 @@ var CASE_BUILDERS = [
436
625
  cooldownPurposeScopeCase,
437
626
  cooldownAtomicCase,
438
627
  keyBoundaryCase,
439
- cooldownKeyBoundaryCase
628
+ cooldownKeyBoundaryCase,
629
+ failureCountCase,
630
+ failureScopeCase,
631
+ failureBoundaryCase,
632
+ failureClearCase,
633
+ failureTtlCase,
634
+ failureAtomicCase
440
635
  ];
441
636
  function otpStorageContract(factory, options = {}) {
442
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. */
@@ -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. */
@@ -1,5 +1,202 @@
1
1
  import { randomUUID } from 'crypto';
2
2
 
3
+ // src/testing/otp-storage-contract.ts
4
+
5
+ // src/testing/otp-storage-contract.shared.ts
6
+ var RACERS = 25;
7
+ function check(condition, message) {
8
+ if (!condition) {
9
+ throw new Error(`IOtpStorage contract violated: ${message}`);
10
+ }
11
+ }
12
+ function wait(ms) {
13
+ return new Promise((resolve) => {
14
+ setTimeout(resolve, ms);
15
+ });
16
+ }
17
+
18
+ // src/testing/otp-storage-contract.failures.ts
19
+ function hasFailureMethods(storage) {
20
+ return storage.getFailures !== void 0 && storage.recordFailure !== void 0 && storage.clearFailures !== void 0;
21
+ }
22
+ var FAILURE_TTL_SECONDS = 60;
23
+ function failureCountCase({ scope, withStorage }) {
24
+ return {
25
+ name: "counts failures per scope (optional: getFailures, recordFailure, clearFailures)",
26
+ run: () => withStorage(async (storage) => {
27
+ if (!hasFailureMethods(storage)) {
28
+ return;
29
+ }
30
+ const counts = [
31
+ await storage.recordFailure(
32
+ scope.tenantA,
33
+ scope.recipient,
34
+ scope.purpose,
35
+ FAILURE_TTL_SECONDS
36
+ ),
37
+ await storage.recordFailure(
38
+ scope.tenantA,
39
+ scope.recipient,
40
+ scope.purpose,
41
+ FAILURE_TTL_SECONDS
42
+ ),
43
+ await storage.recordFailure(
44
+ scope.tenantA,
45
+ scope.recipient,
46
+ scope.purpose,
47
+ FAILURE_TTL_SECONDS
48
+ )
49
+ ];
50
+ const read = await storage.getFailures(scope.tenantA, scope.recipient, scope.purpose);
51
+ const none = await storage.getFailures(scope.tenantA, scope.absentRecipient, scope.purpose);
52
+ check(
53
+ counts.join() === "1,2,3",
54
+ `recordFailure returned ${counts.join()} for three failures instead of 1,2,3`
55
+ );
56
+ check(read === 3, `getFailures returned ${String(read)} after three failures`);
57
+ check(none === 0, "getFailures returned a count for a scope that never failed");
58
+ })
59
+ };
60
+ }
61
+ function failureScopeCase({ scope, withStorage }) {
62
+ return {
63
+ name: "scopes the failure counter by tenant, recipient and purpose",
64
+ run: () => withStorage(async (storage) => {
65
+ if (!hasFailureMethods(storage)) {
66
+ return;
67
+ }
68
+ await storage.recordFailure(
69
+ scope.tenantA,
70
+ scope.recipient,
71
+ scope.purpose,
72
+ FAILURE_TTL_SECONDS
73
+ );
74
+ const otherTenant = await storage.getFailures(scope.tenantB, scope.recipient, scope.purpose);
75
+ const otherRecipient = await storage.getFailures(
76
+ scope.tenantA,
77
+ scope.absentRecipient,
78
+ scope.purpose
79
+ );
80
+ const otherPurpose = await storage.getFailures(
81
+ scope.tenantA,
82
+ scope.recipient,
83
+ scope.otherPurpose
84
+ );
85
+ check(otherTenant === 0, "a failure recorded for one tenant counted against another");
86
+ check(otherRecipient === 0, "a failure recorded for one recipient counted against another");
87
+ check(otherPurpose === 0, "a failure recorded for one purpose counted against another");
88
+ })
89
+ };
90
+ }
91
+ function failureBoundaryCase({
92
+ scope,
93
+ withStorage
94
+ }) {
95
+ return {
96
+ name: "keeps the tenant and recipient boundary when composing a failure-counter key",
97
+ run: () => withStorage(async (storage) => {
98
+ if (!hasFailureMethods(storage)) {
99
+ return;
100
+ }
101
+ for (const { left, right } of scope.boundaryShifts) {
102
+ await storage.recordFailure(left[0], left[1], scope.purpose, FAILURE_TTL_SECONDS);
103
+ const bled = await storage.getFailures(right[0], right[1], scope.purpose);
104
+ check(
105
+ bled === 0,
106
+ "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"
107
+ );
108
+ }
109
+ })
110
+ };
111
+ }
112
+ function failureClearCase({ scope, withStorage }) {
113
+ return {
114
+ name: "clearFailures removes only its own counter and is idempotent",
115
+ run: () => withStorage(async (storage) => {
116
+ if (!hasFailureMethods(storage)) {
117
+ return;
118
+ }
119
+ await storage.recordFailure(
120
+ scope.tenantA,
121
+ scope.recipient,
122
+ scope.purpose,
123
+ FAILURE_TTL_SECONDS
124
+ );
125
+ await storage.recordFailure(
126
+ scope.tenantA,
127
+ scope.absentRecipient,
128
+ scope.purpose,
129
+ FAILURE_TTL_SECONDS
130
+ );
131
+ await storage.clearFailures(scope.tenantA, scope.recipient, scope.purpose);
132
+ await storage.clearFailures(scope.tenantA, scope.recipient, scope.purpose);
133
+ check(
134
+ await storage.getFailures(scope.tenantA, scope.recipient, scope.purpose) === 0,
135
+ "getFailures still counted failures after clearFailures"
136
+ );
137
+ check(
138
+ await storage.getFailures(scope.tenantA, scope.absentRecipient, scope.purpose) === 1,
139
+ "clearFailures removed the counter of another recipient"
140
+ );
141
+ })
142
+ };
143
+ }
144
+ function failureTtlCase({
145
+ scope,
146
+ withStorage,
147
+ expiryWaitMs
148
+ }) {
149
+ return {
150
+ name: "a failure counter lapses after its lifetime",
151
+ run: () => withStorage(async (storage) => {
152
+ if (!hasFailureMethods(storage)) {
153
+ return;
154
+ }
155
+ await storage.recordFailure(scope.tenantA, scope.recipient, scope.purpose, 1e-3);
156
+ await wait(expiryWaitMs);
157
+ check(
158
+ await storage.getFailures(scope.tenantA, scope.recipient, scope.purpose) === 0,
159
+ "getFailures counted a failure whose lifetime had passed \u2014 a counter that never lapses locks a recipient out for good"
160
+ );
161
+ check(
162
+ await storage.recordFailure(
163
+ scope.tenantA,
164
+ scope.recipient,
165
+ scope.purpose,
166
+ FAILURE_TTL_SECONDS
167
+ ) === 1,
168
+ "a lapsed counter did not start again from one"
169
+ );
170
+ })
171
+ };
172
+ }
173
+ function failureAtomicCase({ scope, withStorage }) {
174
+ return {
175
+ name: "recordFailure is ATOMIC under concurrency",
176
+ run: () => withStorage(async (storage) => {
177
+ if (!hasFailureMethods(storage)) {
178
+ return;
179
+ }
180
+ const counts = await Promise.all(
181
+ Array.from(
182
+ { length: RACERS },
183
+ () => storage.recordFailure(
184
+ scope.tenantA,
185
+ scope.recipient,
186
+ scope.purpose,
187
+ FAILURE_TTL_SECONDS
188
+ )
189
+ )
190
+ );
191
+ const distinct = new Set(counts).size;
192
+ check(
193
+ distinct === RACERS,
194
+ `${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`
195
+ );
196
+ })
197
+ };
198
+ }
199
+
3
200
  // src/testing/otp-storage-contract.ts
4
201
  var KEY_PREFIX = "nest_notification_contract";
5
202
  var TENANT_A = "tenant_a";
@@ -29,20 +226,9 @@ function makeScope() {
29
226
  };
30
227
  }
31
228
  var DEFAULT_EXPIRY_WAIT_MS = 1500;
32
- var RACERS = 25;
33
229
  function makeEntry(ttlMs, maxAttempts = 3, code = ANY_CODE) {
34
230
  return { code, expiresAt: Date.now() + ttlMs, attempts: 0, maxAttempts };
35
231
  }
36
- function check(condition, message) {
37
- if (!condition) {
38
- throw new Error(`IOtpStorage contract violated: ${message}`);
39
- }
40
- }
41
- function wait(ms) {
42
- return new Promise((resolve) => {
43
- setTimeout(resolve, ms);
44
- });
45
- }
46
232
  async function cleanUp(storage, scope) {
47
233
  const keys = [
48
234
  [scope.tenantA, scope.purpose],
@@ -54,10 +240,13 @@ async function cleanUp(storage, scope) {
54
240
  await storage.clearCooldown(tenant, scope.recipient, purpose);
55
241
  await storage.delete(tenant, scope.absentRecipient, purpose);
56
242
  await storage.clearCooldown(tenant, scope.absentRecipient, purpose);
243
+ await storage.clearFailures?.(tenant, scope.recipient, purpose);
244
+ await storage.clearFailures?.(tenant, scope.absentRecipient, purpose);
57
245
  }
58
246
  for (const [tenant, recipient] of scope.boundaryShifts.flatMap((s) => [s.left, s.right])) {
59
247
  await storage.delete(tenant, recipient, scope.purpose);
60
248
  await storage.clearCooldown(tenant, recipient, scope.purpose);
249
+ await storage.clearFailures?.(tenant, recipient, scope.purpose);
61
250
  }
62
251
  }
63
252
  function roundTripCase({ scope, withStorage }) {
@@ -434,7 +623,13 @@ var CASE_BUILDERS = [
434
623
  cooldownPurposeScopeCase,
435
624
  cooldownAtomicCase,
436
625
  keyBoundaryCase,
437
- cooldownKeyBoundaryCase
626
+ cooldownKeyBoundaryCase,
627
+ failureCountCase,
628
+ failureScopeCase,
629
+ failureBoundaryCase,
630
+ failureClearCase,
631
+ failureTtlCase,
632
+ failureAtomicCase
438
633
  ];
439
634
  function otpStorageContract(factory, options = {}) {
440
635
  const scope = makeScope();