@bymax-one/nest-notification 1.2.2 → 1.3.1
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.
- package/CHANGELOG.md +94 -1
- package/README.md +33 -9
- package/dist/server/index.cjs +165 -22
- package/dist/server/index.d.cts +80 -0
- package/dist/server/index.d.ts +80 -0
- package/dist/server/index.mjs +165 -22
- package/dist/testing/index.cjs +411 -0
- package/dist/testing/index.d.cts +174 -0
- package/dist/testing/index.d.ts +174 -0
- package/dist/testing/index.mjs +409 -0
- package/package.json +14 -1
|
@@ -0,0 +1,411 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var crypto = require('crypto');
|
|
4
|
+
|
|
5
|
+
// src/testing/otp-storage-contract.ts
|
|
6
|
+
var KEY_PREFIX = "nest_notification_contract";
|
|
7
|
+
var TENANT_A = "tenant_a";
|
|
8
|
+
var TENANT_B = "tenant_b";
|
|
9
|
+
var RECIPIENT_LOCAL = "contract@example.com";
|
|
10
|
+
var ABSENT_LOCAL = "absent@example.com";
|
|
11
|
+
var PURPOSE_MAIN = "purpose_main";
|
|
12
|
+
var PURPOSE_OTHER = "purpose_other";
|
|
13
|
+
var ANY_CODE = "111111";
|
|
14
|
+
var OTHER_CODE = "222222";
|
|
15
|
+
function makeScope() {
|
|
16
|
+
const run = crypto.randomUUID();
|
|
17
|
+
return {
|
|
18
|
+
tenantA: `${KEY_PREFIX}_${run}_${TENANT_A}`,
|
|
19
|
+
tenantB: `${KEY_PREFIX}_${run}_${TENANT_B}`,
|
|
20
|
+
recipient: `${run}_${RECIPIENT_LOCAL}`,
|
|
21
|
+
absentRecipient: `${run}_${ABSENT_LOCAL}`,
|
|
22
|
+
purpose: `${KEY_PREFIX}_${run}_${PURPOSE_MAIN}`,
|
|
23
|
+
otherPurpose: `${KEY_PREFIX}_${run}_${PURPOSE_OTHER}`
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
var DEFAULT_EXPIRY_WAIT_MS = 1500;
|
|
27
|
+
var RACERS = 25;
|
|
28
|
+
function makeEntry(ttlMs, maxAttempts = 3, code = ANY_CODE) {
|
|
29
|
+
return { code, expiresAt: Date.now() + ttlMs, attempts: 0, maxAttempts };
|
|
30
|
+
}
|
|
31
|
+
function check(condition, message) {
|
|
32
|
+
if (!condition) {
|
|
33
|
+
throw new Error(`IOtpStorage contract violated: ${message}`);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
function wait(ms) {
|
|
37
|
+
return new Promise((resolve) => {
|
|
38
|
+
setTimeout(resolve, ms);
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
async function cleanUp(storage, scope) {
|
|
42
|
+
const keys = [
|
|
43
|
+
[scope.tenantA, scope.purpose],
|
|
44
|
+
[scope.tenantA, scope.otherPurpose],
|
|
45
|
+
[scope.tenantB, scope.purpose]
|
|
46
|
+
];
|
|
47
|
+
for (const [tenant, purpose] of keys) {
|
|
48
|
+
await storage.delete(tenant, scope.recipient, purpose);
|
|
49
|
+
await storage.clearCooldown(tenant, scope.recipient, purpose);
|
|
50
|
+
await storage.delete(tenant, scope.absentRecipient, purpose);
|
|
51
|
+
await storage.clearCooldown(tenant, scope.absentRecipient, purpose);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
function roundTripCase({ scope, withStorage }) {
|
|
55
|
+
return {
|
|
56
|
+
name: "stores an entry and reads it back",
|
|
57
|
+
run: () => withStorage(async (storage) => {
|
|
58
|
+
await storage.set(scope.tenantA, scope.recipient, scope.purpose, makeEntry(6e4));
|
|
59
|
+
const found = await storage.get(scope.tenantA, scope.recipient, scope.purpose);
|
|
60
|
+
check(found?.code === ANY_CODE, "get did not return the entry that was set");
|
|
61
|
+
})
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
function absentCase({ scope, withStorage }) {
|
|
65
|
+
return {
|
|
66
|
+
name: "returns null for an entry that was never set",
|
|
67
|
+
run: () => withStorage(async (storage) => {
|
|
68
|
+
const missing = await storage.get(scope.tenantA, scope.absentRecipient, scope.purpose);
|
|
69
|
+
check(missing === null, "get must return null for an absent entry, not undefined");
|
|
70
|
+
})
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
function tenantScopeCase({ scope, withStorage }) {
|
|
74
|
+
return {
|
|
75
|
+
name: "scopes keys by tenant so two tenants never collide",
|
|
76
|
+
run: () => withStorage(async (storage) => {
|
|
77
|
+
await storage.set(scope.tenantA, scope.recipient, scope.purpose, makeEntry(6e4));
|
|
78
|
+
await storage.set(
|
|
79
|
+
scope.tenantB,
|
|
80
|
+
scope.recipient,
|
|
81
|
+
scope.purpose,
|
|
82
|
+
makeEntry(6e4, 3, OTHER_CODE)
|
|
83
|
+
);
|
|
84
|
+
const first = await storage.get(scope.tenantA, scope.recipient, scope.purpose);
|
|
85
|
+
const second = await storage.get(scope.tenantB, scope.recipient, scope.purpose);
|
|
86
|
+
check(
|
|
87
|
+
first?.code === ANY_CODE && second?.code === OTHER_CODE,
|
|
88
|
+
"the same recipient under two tenants shares one key \u2014 one tenant can read or overwrite another tenant's code"
|
|
89
|
+
);
|
|
90
|
+
})
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
function recipientScopeCase({ scope, withStorage }) {
|
|
94
|
+
return {
|
|
95
|
+
name: "scopes keys by recipient",
|
|
96
|
+
run: () => withStorage(async (storage) => {
|
|
97
|
+
await storage.set(scope.tenantA, scope.recipient, scope.purpose, makeEntry(6e4));
|
|
98
|
+
await storage.set(
|
|
99
|
+
scope.tenantA,
|
|
100
|
+
scope.absentRecipient,
|
|
101
|
+
scope.purpose,
|
|
102
|
+
makeEntry(6e4, 3, OTHER_CODE)
|
|
103
|
+
);
|
|
104
|
+
const first = await storage.get(scope.tenantA, scope.recipient, scope.purpose);
|
|
105
|
+
const second = await storage.get(scope.tenantA, scope.absentRecipient, scope.purpose);
|
|
106
|
+
await storage.delete(scope.tenantA, scope.absentRecipient, scope.purpose);
|
|
107
|
+
check(
|
|
108
|
+
first?.code === ANY_CODE && second?.code === OTHER_CODE,
|
|
109
|
+
"two recipients under one tenant share a key \u2014 one user can overwrite or verify another user's code"
|
|
110
|
+
);
|
|
111
|
+
})
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
function purposeScopeCase({ scope, withStorage }) {
|
|
115
|
+
return {
|
|
116
|
+
name: "scopes keys by purpose",
|
|
117
|
+
run: () => withStorage(async (storage) => {
|
|
118
|
+
await storage.set(scope.tenantA, scope.recipient, scope.purpose, makeEntry(6e4));
|
|
119
|
+
await storage.set(
|
|
120
|
+
scope.tenantA,
|
|
121
|
+
scope.recipient,
|
|
122
|
+
scope.otherPurpose,
|
|
123
|
+
makeEntry(6e4, 3, OTHER_CODE)
|
|
124
|
+
);
|
|
125
|
+
const found = await storage.get(scope.tenantA, scope.recipient, scope.purpose);
|
|
126
|
+
check(found?.code === ANY_CODE, "two purposes for one recipient share a key");
|
|
127
|
+
})
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
function deleteCase({ scope, withStorage }) {
|
|
131
|
+
return {
|
|
132
|
+
name: "deletes an entry",
|
|
133
|
+
run: () => withStorage(async (storage) => {
|
|
134
|
+
await storage.set(scope.tenantA, scope.recipient, scope.purpose, makeEntry(6e4));
|
|
135
|
+
await storage.delete(scope.tenantA, scope.recipient, scope.purpose);
|
|
136
|
+
const found = await storage.get(scope.tenantA, scope.recipient, scope.purpose);
|
|
137
|
+
check(found === null, "delete left the entry");
|
|
138
|
+
})
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
function ttlCase({ scope, withStorage, expiryWaitMs }) {
|
|
142
|
+
return {
|
|
143
|
+
name: "applies the TTL: an expired entry is gone",
|
|
144
|
+
run: () => withStorage(async (storage) => {
|
|
145
|
+
await storage.set(scope.tenantA, scope.recipient, scope.purpose, makeEntry(1));
|
|
146
|
+
await wait(expiryWaitMs);
|
|
147
|
+
const found = await storage.get(scope.tenantA, scope.recipient, scope.purpose);
|
|
148
|
+
const consumed = await storage.consumeAttempt(scope.tenantA, scope.recipient, scope.purpose);
|
|
149
|
+
check(found === null, "get returned an entry whose expiresAt has passed");
|
|
150
|
+
check(
|
|
151
|
+
consumed.status === "not_found",
|
|
152
|
+
"consumeAttempt served an expired entry instead of reporting not_found"
|
|
153
|
+
);
|
|
154
|
+
})
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
function updateKeepsTtlCase({
|
|
158
|
+
scope,
|
|
159
|
+
withStorage,
|
|
160
|
+
expiryWaitMs
|
|
161
|
+
}) {
|
|
162
|
+
return {
|
|
163
|
+
name: "update preserves the remaining TTL",
|
|
164
|
+
run: () => withStorage(async (storage) => {
|
|
165
|
+
const entry = makeEntry(1);
|
|
166
|
+
await storage.set(scope.tenantA, scope.recipient, scope.purpose, entry);
|
|
167
|
+
await storage.update(scope.tenantA, scope.recipient, scope.purpose, entry);
|
|
168
|
+
await wait(expiryWaitMs);
|
|
169
|
+
const found = await storage.get(scope.tenantA, scope.recipient, scope.purpose);
|
|
170
|
+
check(found === null, "update reset the expiry, extending the code beyond its TTL");
|
|
171
|
+
})
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
function updateAfterExpiryCase({
|
|
175
|
+
scope,
|
|
176
|
+
withStorage,
|
|
177
|
+
expiryWaitMs
|
|
178
|
+
}) {
|
|
179
|
+
return {
|
|
180
|
+
name: "update does not resurrect an expired entry",
|
|
181
|
+
run: () => withStorage(async (storage) => {
|
|
182
|
+
const entry = makeEntry(1);
|
|
183
|
+
await storage.set(scope.tenantA, scope.recipient, scope.purpose, entry);
|
|
184
|
+
await wait(expiryWaitMs);
|
|
185
|
+
await storage.update(scope.tenantA, scope.recipient, scope.purpose, entry);
|
|
186
|
+
const found = await storage.get(scope.tenantA, scope.recipient, scope.purpose);
|
|
187
|
+
check(found === null, "update recreated an entry that had already expired");
|
|
188
|
+
})
|
|
189
|
+
};
|
|
190
|
+
}
|
|
191
|
+
function consumeNotFoundCase({ scope, withStorage }) {
|
|
192
|
+
return {
|
|
193
|
+
name: "consumeAttempt reports not_found when there is no entry",
|
|
194
|
+
run: () => withStorage(async (storage) => {
|
|
195
|
+
const result = await storage.consumeAttempt(scope.tenantA, scope.recipient, scope.purpose);
|
|
196
|
+
check(result.status === "not_found", "consumeAttempt must report not_found");
|
|
197
|
+
})
|
|
198
|
+
};
|
|
199
|
+
}
|
|
200
|
+
function consumeSpendsCase({ scope, withStorage }) {
|
|
201
|
+
return {
|
|
202
|
+
name: "consumeAttempt spends one attempt per call and returns the stored entry",
|
|
203
|
+
run: () => withStorage(async (storage) => {
|
|
204
|
+
await storage.set(scope.tenantA, scope.recipient, scope.purpose, makeEntry(6e4, 3));
|
|
205
|
+
const first = await storage.consumeAttempt(scope.tenantA, scope.recipient, scope.purpose);
|
|
206
|
+
check(first.status === "ok", "the first attempt must succeed");
|
|
207
|
+
check(
|
|
208
|
+
first.status === "ok" && first.entry.code === ANY_CODE,
|
|
209
|
+
"consumeAttempt must return the STORED code so the caller can compare it"
|
|
210
|
+
);
|
|
211
|
+
check(
|
|
212
|
+
first.status === "ok" && first.entry.attempts === 1,
|
|
213
|
+
"consumeAttempt must return the entry with the attempt already counted"
|
|
214
|
+
);
|
|
215
|
+
})
|
|
216
|
+
};
|
|
217
|
+
}
|
|
218
|
+
function consumeCeilingCase({ scope, withStorage }) {
|
|
219
|
+
return {
|
|
220
|
+
name: "consumeAttempt reports max_attempts once the ceiling is reached",
|
|
221
|
+
run: () => withStorage(async (storage) => {
|
|
222
|
+
await storage.set(scope.tenantA, scope.recipient, scope.purpose, makeEntry(6e4, 2));
|
|
223
|
+
await storage.consumeAttempt(scope.tenantA, scope.recipient, scope.purpose);
|
|
224
|
+
await storage.consumeAttempt(scope.tenantA, scope.recipient, scope.purpose);
|
|
225
|
+
const third = await storage.consumeAttempt(scope.tenantA, scope.recipient, scope.purpose);
|
|
226
|
+
const found = await storage.get(scope.tenantA, scope.recipient, scope.purpose);
|
|
227
|
+
check(third.status === "max_attempts", "the ceiling was not enforced");
|
|
228
|
+
check(found === null, "the entry must be deleted once the ceiling is reached");
|
|
229
|
+
})
|
|
230
|
+
};
|
|
231
|
+
}
|
|
232
|
+
function consumeAtomicCase({ scope, withStorage }) {
|
|
233
|
+
return {
|
|
234
|
+
name: "consumeAttempt is ATOMIC under concurrency",
|
|
235
|
+
run: () => withStorage(async (storage) => {
|
|
236
|
+
const maxAttempts = 5;
|
|
237
|
+
await storage.set(
|
|
238
|
+
scope.tenantA,
|
|
239
|
+
scope.recipient,
|
|
240
|
+
scope.purpose,
|
|
241
|
+
makeEntry(6e4, maxAttempts)
|
|
242
|
+
);
|
|
243
|
+
const results = await Promise.all(
|
|
244
|
+
Array.from(
|
|
245
|
+
{ length: RACERS },
|
|
246
|
+
() => storage.consumeAttempt(scope.tenantA, scope.recipient, scope.purpose)
|
|
247
|
+
)
|
|
248
|
+
);
|
|
249
|
+
const succeeded = results.filter((result) => result.status === "ok").length;
|
|
250
|
+
check(
|
|
251
|
+
succeeded <= maxAttempts,
|
|
252
|
+
`${succeeded} of ${RACERS} concurrent calls consumed an attempt against a ceiling of ${maxAttempts} \u2014 the lookup and the increment are not one indivisible operation, so the brute-force limit can be bypassed by sending requests in parallel`
|
|
253
|
+
);
|
|
254
|
+
})
|
|
255
|
+
};
|
|
256
|
+
}
|
|
257
|
+
function cooldownHoldsCase({ scope, withStorage }) {
|
|
258
|
+
return {
|
|
259
|
+
name: "tryAcquireCooldown holds until cleared",
|
|
260
|
+
run: () => withStorage(async (storage) => {
|
|
261
|
+
const acquired = await storage.tryAcquireCooldown(
|
|
262
|
+
scope.tenantA,
|
|
263
|
+
scope.recipient,
|
|
264
|
+
scope.purpose,
|
|
265
|
+
60
|
|
266
|
+
);
|
|
267
|
+
const second = await storage.tryAcquireCooldown(
|
|
268
|
+
scope.tenantA,
|
|
269
|
+
scope.recipient,
|
|
270
|
+
scope.purpose,
|
|
271
|
+
60
|
|
272
|
+
);
|
|
273
|
+
const remaining = await storage.getCooldown(scope.tenantA, scope.recipient, scope.purpose);
|
|
274
|
+
await storage.clearCooldown(scope.tenantA, scope.recipient, scope.purpose);
|
|
275
|
+
const reacquired = await storage.tryAcquireCooldown(
|
|
276
|
+
scope.tenantA,
|
|
277
|
+
scope.recipient,
|
|
278
|
+
scope.purpose,
|
|
279
|
+
60
|
|
280
|
+
);
|
|
281
|
+
check(acquired, "the first acquire must succeed");
|
|
282
|
+
check(!second, "a second acquire must fail while the cooldown is held");
|
|
283
|
+
check(remaining > 0, "getCooldown must report the seconds still to run");
|
|
284
|
+
check(reacquired, "clearCooldown must release the cooldown");
|
|
285
|
+
})
|
|
286
|
+
};
|
|
287
|
+
}
|
|
288
|
+
function cooldownZeroCase({ scope, withStorage }) {
|
|
289
|
+
return {
|
|
290
|
+
name: "getCooldown reports zero when no cooldown is held",
|
|
291
|
+
run: () => withStorage(async (storage) => {
|
|
292
|
+
const remaining = await storage.getCooldown(scope.tenantA, scope.recipient, scope.purpose);
|
|
293
|
+
check(remaining === 0, "getCooldown must report 0 when nothing is held");
|
|
294
|
+
})
|
|
295
|
+
};
|
|
296
|
+
}
|
|
297
|
+
function cooldownTenantScopeCase({ scope, withStorage }) {
|
|
298
|
+
return {
|
|
299
|
+
name: "scopes the cooldown by tenant",
|
|
300
|
+
run: () => withStorage(async (storage) => {
|
|
301
|
+
await storage.tryAcquireCooldown(scope.tenantA, scope.recipient, scope.purpose, 60);
|
|
302
|
+
const other = await storage.tryAcquireCooldown(
|
|
303
|
+
scope.tenantB,
|
|
304
|
+
scope.recipient,
|
|
305
|
+
scope.purpose,
|
|
306
|
+
60
|
|
307
|
+
);
|
|
308
|
+
check(
|
|
309
|
+
other,
|
|
310
|
+
"a cooldown held for one tenant blocked another \u2014 cooldown keys are not scoped by tenant, so one tenant can suppress another tenant resends"
|
|
311
|
+
);
|
|
312
|
+
})
|
|
313
|
+
};
|
|
314
|
+
}
|
|
315
|
+
function cooldownRecipientScopeCase({
|
|
316
|
+
scope,
|
|
317
|
+
withStorage
|
|
318
|
+
}) {
|
|
319
|
+
return {
|
|
320
|
+
name: "scopes the cooldown by recipient",
|
|
321
|
+
run: () => withStorage(async (storage) => {
|
|
322
|
+
await storage.tryAcquireCooldown(scope.tenantA, scope.recipient, scope.purpose, 60);
|
|
323
|
+
const other = await storage.tryAcquireCooldown(
|
|
324
|
+
scope.tenantA,
|
|
325
|
+
scope.absentRecipient,
|
|
326
|
+
scope.purpose,
|
|
327
|
+
60
|
|
328
|
+
);
|
|
329
|
+
await storage.clearCooldown(scope.tenantA, scope.absentRecipient, scope.purpose);
|
|
330
|
+
check(
|
|
331
|
+
other,
|
|
332
|
+
"a cooldown held for one recipient blocked another \u2014 one user can suppress another user's resends"
|
|
333
|
+
);
|
|
334
|
+
})
|
|
335
|
+
};
|
|
336
|
+
}
|
|
337
|
+
function cooldownPurposeScopeCase({ scope, withStorage }) {
|
|
338
|
+
return {
|
|
339
|
+
name: "scopes the cooldown by purpose",
|
|
340
|
+
run: () => withStorage(async (storage) => {
|
|
341
|
+
await storage.tryAcquireCooldown(scope.tenantA, scope.recipient, scope.purpose, 60);
|
|
342
|
+
const other = await storage.tryAcquireCooldown(
|
|
343
|
+
scope.tenantA,
|
|
344
|
+
scope.recipient,
|
|
345
|
+
scope.otherPurpose,
|
|
346
|
+
60
|
|
347
|
+
);
|
|
348
|
+
check(
|
|
349
|
+
other,
|
|
350
|
+
"a cooldown held for one purpose blocked another \u2014 a password reset and an email verification would share one anti-resend window"
|
|
351
|
+
);
|
|
352
|
+
})
|
|
353
|
+
};
|
|
354
|
+
}
|
|
355
|
+
function cooldownAtomicCase({ scope, withStorage }) {
|
|
356
|
+
return {
|
|
357
|
+
name: "tryAcquireCooldown is ATOMIC under concurrency",
|
|
358
|
+
run: () => withStorage(async (storage) => {
|
|
359
|
+
const results = await Promise.all(
|
|
360
|
+
Array.from(
|
|
361
|
+
{ length: RACERS },
|
|
362
|
+
() => storage.tryAcquireCooldown(scope.tenantA, scope.recipient, scope.purpose, 60)
|
|
363
|
+
)
|
|
364
|
+
);
|
|
365
|
+
const winners = results.filter(Boolean).length;
|
|
366
|
+
check(
|
|
367
|
+
winners === 1,
|
|
368
|
+
`${winners} of ${RACERS} concurrent acquires won \u2014 the check and the set are not one step, so two resends can both pass and the anti-resend window stops holding`
|
|
369
|
+
);
|
|
370
|
+
})
|
|
371
|
+
};
|
|
372
|
+
}
|
|
373
|
+
var CASE_BUILDERS = [
|
|
374
|
+
roundTripCase,
|
|
375
|
+
absentCase,
|
|
376
|
+
tenantScopeCase,
|
|
377
|
+
recipientScopeCase,
|
|
378
|
+
purposeScopeCase,
|
|
379
|
+
deleteCase,
|
|
380
|
+
ttlCase,
|
|
381
|
+
updateKeepsTtlCase,
|
|
382
|
+
updateAfterExpiryCase,
|
|
383
|
+
consumeNotFoundCase,
|
|
384
|
+
consumeSpendsCase,
|
|
385
|
+
consumeCeilingCase,
|
|
386
|
+
consumeAtomicCase,
|
|
387
|
+
cooldownHoldsCase,
|
|
388
|
+
cooldownZeroCase,
|
|
389
|
+
cooldownTenantScopeCase,
|
|
390
|
+
cooldownRecipientScopeCase,
|
|
391
|
+
cooldownPurposeScopeCase,
|
|
392
|
+
cooldownAtomicCase
|
|
393
|
+
];
|
|
394
|
+
function otpStorageContract(factory, options = {}) {
|
|
395
|
+
const scope = makeScope();
|
|
396
|
+
const context = {
|
|
397
|
+
scope,
|
|
398
|
+
expiryWaitMs: options.expiryWaitMs ?? DEFAULT_EXPIRY_WAIT_MS,
|
|
399
|
+
withStorage: async (body) => {
|
|
400
|
+
const storage = await factory();
|
|
401
|
+
try {
|
|
402
|
+
await body(storage);
|
|
403
|
+
} finally {
|
|
404
|
+
await cleanUp(storage, scope);
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
};
|
|
408
|
+
return CASE_BUILDERS.map((build) => build(context));
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
exports.otpStorageContract = otpStorageContract;
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview OTP storage contract (`IOtpStorage`) — the core security surface.
|
|
3
|
+
* @layer domain
|
|
4
|
+
*
|
|
5
|
+
* Single persistence interface for all OTP state. This interface DISSOLVES the
|
|
6
|
+
* Prisma coupling that a typical consumer's hand-rolled OTP store would otherwise
|
|
7
|
+
* impose: the library never imports the Prisma client (nor any ORM) — every
|
|
8
|
+
* consumer plugs in their own storage (Redis, in-memory, …).
|
|
9
|
+
*/
|
|
10
|
+
/** A stored OTP entry. */
|
|
11
|
+
interface OtpEntry {
|
|
12
|
+
/** Plaintext OTP code. Never logged. */
|
|
13
|
+
code: string;
|
|
14
|
+
/** Expiration as a Unix timestamp in milliseconds. */
|
|
15
|
+
expiresAt: number;
|
|
16
|
+
/** Number of verification attempts made so far. */
|
|
17
|
+
attempts: number;
|
|
18
|
+
/** Maximum attempts before the entry is invalidated. */
|
|
19
|
+
maxAttempts: number;
|
|
20
|
+
/** Whether the OTP has already been successfully verified (not yet deleted). */
|
|
21
|
+
validated?: boolean;
|
|
22
|
+
/** Optional caller metadata — ignored by the library. */
|
|
23
|
+
metadata?: Record<string, unknown>;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Result of the atomic {@link IOtpStorage.consumeAttempt} primitive.
|
|
27
|
+
*
|
|
28
|
+
* - `not_found` — no entry, or it expired (the two are indistinguishable once the TTL lapses).
|
|
29
|
+
* - `max_attempts` — the attempt ceiling was already reached; the entry is deleted.
|
|
30
|
+
* - `ok` — an attempt was consumed; `entry` carries the updated entry (incl. the stored `code`).
|
|
31
|
+
*/
|
|
32
|
+
type ConsumeAttemptResult = {
|
|
33
|
+
status: 'not_found';
|
|
34
|
+
} | {
|
|
35
|
+
status: 'max_attempts';
|
|
36
|
+
} | {
|
|
37
|
+
status: 'ok';
|
|
38
|
+
entry: OtpEntry;
|
|
39
|
+
};
|
|
40
|
+
/**
|
|
41
|
+
* OTP storage.
|
|
42
|
+
*
|
|
43
|
+
* Implementations MUST:
|
|
44
|
+
* - make `consumeAttempt` **atomic** — the lookup + attempt increment is a single
|
|
45
|
+
* indivisible operation (Redis: a Lua script; in-memory: one synchronous
|
|
46
|
+
* read-modify-write). A plain `get`+`update` races and lets the `maxAttempts`
|
|
47
|
+
* brute-force limit be bypassed under concurrency;
|
|
48
|
+
* - make `tryAcquireCooldown` **atomic** — a check-and-set in one step (Redis:
|
|
49
|
+
* `SET NX EX`), so two concurrent generate/resend calls cannot both pass;
|
|
50
|
+
* - apply TTL — expired entries must not be returned by `get` / `consumeAttempt`;
|
|
51
|
+
* - scope keys by `(tenantId, recipient, purpose)` without cross-tenant collision;
|
|
52
|
+
* - never expose OTP codes in plaintext logs.
|
|
53
|
+
*
|
|
54
|
+
* The library does NOT normalize `recipient`: callers must pass a canonical value
|
|
55
|
+
* (e.g. `email.trim().toLowerCase()`); `'A@x.com'` and `'a@x.com'` map to distinct keys.
|
|
56
|
+
*/
|
|
57
|
+
interface IOtpStorage {
|
|
58
|
+
/**
|
|
59
|
+
* Creates or replaces an OTP entry (with its own TTL).
|
|
60
|
+
*
|
|
61
|
+
* @param tenantId - Tenant isolation scope.
|
|
62
|
+
* @param recipient - Pre-normalized recipient identifier (email, phone, userId — caller decides).
|
|
63
|
+
* @param purpose - OTP purpose (e.g. `'email_verification'`).
|
|
64
|
+
* @param entry - The entry to persist.
|
|
65
|
+
*/
|
|
66
|
+
set(tenantId: string, recipient: string, purpose: string, entry: OtpEntry): Promise<void>;
|
|
67
|
+
/**
|
|
68
|
+
* Reads an OTP entry. Returns `null` if it does not exist or has expired.
|
|
69
|
+
* Read-only — used by `getStatus()`. Verification MUST go through `consumeAttempt`.
|
|
70
|
+
*/
|
|
71
|
+
get(tenantId: string, recipient: string, purpose: string): Promise<OtpEntry | null>;
|
|
72
|
+
/**
|
|
73
|
+
* Atomic verification primitive — in one indivisible step: returns `not_found`
|
|
74
|
+
* when absent/expired; deletes the entry and returns `max_attempts` when the
|
|
75
|
+
* ceiling is reached; otherwise increments `attempts` (preserving TTL) and
|
|
76
|
+
* returns `ok` with the updated entry. The caller then constant-time-compares
|
|
77
|
+
* the guessed code against `entry.code`.
|
|
78
|
+
*
|
|
79
|
+
* MUST be atomic.
|
|
80
|
+
*/
|
|
81
|
+
consumeAttempt(tenantId: string, recipient: string, purpose: string): Promise<ConsumeAttemptResult>;
|
|
82
|
+
/**
|
|
83
|
+
* Updates an existing entry, preserving its remaining TTL. A no-op if the entry
|
|
84
|
+
* is gone (TTL expired). Used to mark `validated` / write `metadata` after a
|
|
85
|
+
* successful verify — never for the attempt counter (that is `consumeAttempt`).
|
|
86
|
+
*/
|
|
87
|
+
update(tenantId: string, recipient: string, purpose: string, entry: OtpEntry): Promise<void>;
|
|
88
|
+
/** Removes the OTP entry. Idempotent. */
|
|
89
|
+
delete(tenantId: string, recipient: string, purpose: string): Promise<void>;
|
|
90
|
+
/**
|
|
91
|
+
* Atomic cooldown acquire for `(tenant, recipient, purpose)`. Sets the cooldown
|
|
92
|
+
* key only if it does not already exist (Redis: `SET NX EX`). Returns `true`
|
|
93
|
+
* when acquired, `false` when a cooldown is already active. Acts as a
|
|
94
|
+
* short-lived lock around generate/resend.
|
|
95
|
+
*
|
|
96
|
+
* MUST be atomic.
|
|
97
|
+
*
|
|
98
|
+
* @param ttlSeconds - Cooldown duration in seconds.
|
|
99
|
+
*/
|
|
100
|
+
tryAcquireCooldown(tenantId: string, recipient: string, purpose: string, ttlSeconds: number): Promise<boolean>;
|
|
101
|
+
/** Remaining cooldown in seconds, or `0` when there is no active cooldown. */
|
|
102
|
+
getCooldown(tenantId: string, recipient: string, purpose: string): Promise<number>;
|
|
103
|
+
/**
|
|
104
|
+
* Clears the cooldown for `(tenant, recipient, purpose)`. Idempotent. Called when
|
|
105
|
+
* a delivery fails (so the user is not locked out) and on `consume()` (so a
|
|
106
|
+
* cancelled flow can restart immediately).
|
|
107
|
+
*/
|
|
108
|
+
clearCooldown(tenantId: string, recipient: string, purpose: string): Promise<void>;
|
|
109
|
+
/** Whether the storage is configured and ready. Used during module initialization. */
|
|
110
|
+
isConfigured(): boolean;
|
|
111
|
+
/** Storage name (e.g. `'redis'`, `'memory'`, `'dynamodb'`). */
|
|
112
|
+
readonly name: string;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* @fileoverview Executable contract for third-party `IOtpStorage` implementations.
|
|
117
|
+
* @layer testing
|
|
118
|
+
*
|
|
119
|
+
* `IOtpStorage` is the extension point where a consumer supplies their own
|
|
120
|
+
* persistence, and four of its obligations cannot be checked by a type: the
|
|
121
|
+
* attempt counter and the cooldown must be mutated ATOMICALLY, the TTL must be
|
|
122
|
+
* applied, and keys must be scoped by `(tenantId, recipient, purpose)` so two
|
|
123
|
+
* tenants never collide. A wrong implementation type-checks, passes a casual
|
|
124
|
+
* smoke test, and silently lets the max-attempts ceiling be bypassed under
|
|
125
|
+
* concurrency — which is exactly how a brute-force limit stops limiting.
|
|
126
|
+
*
|
|
127
|
+
* The cases below are plain async functions that throw on violation, so they
|
|
128
|
+
* plug into any runner (`jest`, `vitest`, `node:test`) without this package
|
|
129
|
+
* depending on one:
|
|
130
|
+
*
|
|
131
|
+
* ```ts
|
|
132
|
+
* import { otpStorageContract } from '@bymax-one/nest-notification/testing'
|
|
133
|
+
*
|
|
134
|
+
* describe('MyOtpStorage', () => {
|
|
135
|
+
* for (const { name, run } of otpStorageContract(() => new MyOtpStorage(client))) {
|
|
136
|
+
* it(name, run)
|
|
137
|
+
* }
|
|
138
|
+
* })
|
|
139
|
+
* ```
|
|
140
|
+
*/
|
|
141
|
+
|
|
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
|
+
/** How the contract obtains a storage to exercise. */
|
|
150
|
+
type OtpStorageFactory = () => IOtpStorage | Promise<IOtpStorage>;
|
|
151
|
+
/** Tuning for the cases that must observe real time pass. */
|
|
152
|
+
interface OtpStorageContractOptions {
|
|
153
|
+
/**
|
|
154
|
+
* Milliseconds the TTL cases wait for an entry to lapse. Must exceed the
|
|
155
|
+
* storage's own expiry granularity — Redis expires in whole seconds, so the
|
|
156
|
+
* default allows for that. Raise it for a backend with coarser granularity.
|
|
157
|
+
*/
|
|
158
|
+
expiryWaitMs?: number;
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* Builds the contract cases for an `IOtpStorage` implementation.
|
|
162
|
+
*
|
|
163
|
+
* Each case obtains its own storage from `factory` and cleans up the keys it
|
|
164
|
+
* wrote, so the cases are order-independent. Every call gets a random key scope,
|
|
165
|
+
* so two suites running in parallel against one backend cannot see each other's
|
|
166
|
+
* state as a violation.
|
|
167
|
+
*
|
|
168
|
+
* @param factory - Produces the storage under test; called once per case.
|
|
169
|
+
* @param options - Timing tuning for the cases that wait for a TTL to lapse.
|
|
170
|
+
* @returns The cases to run, each throwing on violation.
|
|
171
|
+
*/
|
|
172
|
+
declare function otpStorageContract(factory: OtpStorageFactory, options?: OtpStorageContractOptions): OtpStorageContractCase[];
|
|
173
|
+
|
|
174
|
+
export { type OtpStorageContractCase, type OtpStorageContractOptions, type OtpStorageFactory, otpStorageContract };
|