forked from Stellar-split/split-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebhookMiddleware.test.ts
More file actions
747 lines (623 loc) · 24.4 KB
/
Copy pathwebhookMiddleware.test.ts
File metadata and controls
747 lines (623 loc) · 24.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
/**
* Test suite for webhookMiddleware module.
*
* Tests cover:
* - HMAC-SHA256 signature verification
* - Timestamp validation and tolerance
* - Nonce-based replay attack prevention
* - LRU cache behavior
* - Error handling and edge cases
* - Express middleware integration
*/
import { describe, it, expect, beforeEach, vi } from "vitest";
import type { Request, Response, NextFunction } from "express";
import {
createWebhookMiddleware,
generateWebhookSignature,
verifyWebhookSignature,
parseWebhookPayload,
isValidEventType,
isWebhookRequest,
InvalidSignatureError,
TimestampOutOfBoundsError,
ReplayAttackError,
MissingHeaderError,
InvalidPayloadError,
type WebhookPayload,
type WebhookRequest,
type InvoiceEventType,
} from "../src/webhookMiddleware.js";
// ============================================================================
// Test Helpers
// ============================================================================
const TEST_SECRET = "test_secret_key_12345";
/**
* Create a valid webhook payload for testing.
*/
function createTestPayload(
event: InvoiceEventType = "invoice.paid",
data: unknown = { invoiceId: "123", amount: "1000" },
): WebhookPayload {
return {
event,
timestamp: Math.floor(Date.now() / 1000),
nonce: `nonce_${Date.now()}_${Math.random()}`,
data,
};
}
/**
* Create a mock Express request object.
*/
function createMockRequest(
body: Buffer | string | object,
headers: Record<string, string> = {},
): Partial<Request> {
return {
body,
headers: headers,
};
}
/**
* Create a mock Express response object.
*/
function createMockResponse(): Partial<Response> {
const res: Partial<Response> = {
status: vi.fn().mockReturnThis(),
json: vi.fn().mockReturnThis(),
};
return res;
}
/**
* Create a mock Express next function.
*/
function createMockNext(): NextFunction {
return vi.fn();
}
// ============================================================================
// Signature Generation & Verification Tests
// ============================================================================
describe("generateWebhookSignature", () => {
it("should generate a valid HMAC-SHA256 signature", async () => {
const payload = createTestPayload();
const signature = await generateWebhookSignature(payload, TEST_SECRET);
expect(signature).toBeDefined();
expect(typeof signature).toBe("string");
expect(signature.length).toBe(64); // SHA-256 produces 32 bytes = 64 hex chars
expect(signature).toMatch(/^[0-9a-f]{64}$/); // Valid hex string
});
it("should generate different signatures for different payloads", async () => {
const payload1 = createTestPayload("invoice.paid");
const payload2 = createTestPayload("invoice.released");
const sig1 = await generateWebhookSignature(payload1, TEST_SECRET);
const sig2 = await generateWebhookSignature(payload2, TEST_SECRET);
expect(sig1).not.toBe(sig2);
});
it("should generate different signatures for different secrets", async () => {
const payload = createTestPayload();
const sig1 = await generateWebhookSignature(payload, "secret1");
const sig2 = await generateWebhookSignature(payload, "secret2");
expect(sig1).not.toBe(sig2);
});
it("should generate consistent signatures for the same payload and secret", async () => {
const payload = createTestPayload();
const sig1 = await generateWebhookSignature(payload, TEST_SECRET);
const sig2 = await generateWebhookSignature(payload, TEST_SECRET);
expect(sig1).toBe(sig2);
});
});
describe("verifyWebhookSignature", () => {
it("should verify a valid signature", async () => {
const payload = createTestPayload();
const signature = await generateWebhookSignature(payload, TEST_SECRET);
const isValid = await verifyWebhookSignature(payload, signature, TEST_SECRET);
expect(isValid).toBe(true);
});
it("should verify a valid signature from string payload", async () => {
const payload = createTestPayload();
const payloadString = JSON.stringify(payload);
const signature = await generateWebhookSignature(payload, TEST_SECRET);
const isValid = await verifyWebhookSignature(
payloadString,
signature,
TEST_SECRET,
);
expect(isValid).toBe(true);
});
it("should reject an invalid signature", async () => {
const payload = createTestPayload();
const invalidSignature = "0".repeat(64);
const isValid = await verifyWebhookSignature(
payload,
invalidSignature,
TEST_SECRET,
);
expect(isValid).toBe(false);
});
it("should reject a signature with wrong secret", async () => {
const payload = createTestPayload();
const signature = await generateWebhookSignature(payload, "wrong_secret");
const isValid = await verifyWebhookSignature(payload, signature, TEST_SECRET);
expect(isValid).toBe(false);
});
it("should reject a tampered payload", async () => {
const payload = createTestPayload();
const signature = await generateWebhookSignature(payload, TEST_SECRET);
// Tamper with the payload
const tamperedPayload = { ...payload, data: { tampered: true } };
const isValid = await verifyWebhookSignature(
tamperedPayload,
signature,
TEST_SECRET,
);
expect(isValid).toBe(false);
});
it("should handle malformed hex signature gracefully", async () => {
const payload = createTestPayload();
const invalidHex = "not_a_hex_string";
const isValid = await verifyWebhookSignature(payload, invalidHex, TEST_SECRET);
expect(isValid).toBe(false);
});
it("should handle signature with odd length gracefully", async () => {
const payload = createTestPayload();
const oddLengthHex = "abc"; // Odd number of hex chars
const isValid = await verifyWebhookSignature(
payload,
oddLengthHex,
TEST_SECRET,
);
expect(isValid).toBe(false);
});
});
// ============================================================================
// Webhook Middleware Tests
// ============================================================================
describe("createWebhookMiddleware", () => {
it("should throw if secret is empty", () => {
expect(() => createWebhookMiddleware("")).toThrow("non-empty string");
});
it("should throw if secret is not a string", () => {
expect(() => createWebhookMiddleware(null as any)).toThrow("non-empty string");
expect(() => createWebhookMiddleware(123 as any)).toThrow("non-empty string");
});
it("should create middleware function", () => {
const middleware = createWebhookMiddleware(TEST_SECRET);
expect(typeof middleware).toBe("function");
expect(middleware.length).toBe(3); // Express middleware signature
});
it("should accept valid webhook request", async () => {
const payload = createTestPayload();
const signature = await generateWebhookSignature(payload, TEST_SECRET);
const rawBody = JSON.stringify(payload);
const req = createMockRequest(Buffer.from(rawBody), {
"x-stellarsplit-signature": signature,
"x-stellarsplit-timestamp": String(payload.timestamp),
"x-stellarsplit-nonce": payload.nonce,
});
const res = createMockResponse();
const next = createMockNext();
const middleware = createWebhookMiddleware(TEST_SECRET);
await middleware(req as Request, res as Response, next);
expect(next).toHaveBeenCalledOnce();
expect(res.status).not.toHaveBeenCalled();
expect(isWebhookRequest(req as Request)).toBe(true);
const webhookReq = req as WebhookRequest;
expect(webhookReq.webhookPayload).toEqual(payload);
expect(webhookReq.rawWebhookBody).toBe(rawBody);
});
it("should reject request with missing signature header", async () => {
const payload = createTestPayload();
const rawBody = JSON.stringify(payload);
const req = createMockRequest(Buffer.from(rawBody), {
"x-stellarsplit-timestamp": String(payload.timestamp),
"x-stellarsplit-nonce": payload.nonce,
});
const res = createMockResponse();
const next = createMockNext();
const middleware = createWebhookMiddleware(TEST_SECRET);
await middleware(req as Request, res as Response, next);
expect(next).not.toHaveBeenCalled();
expect(res.status).toHaveBeenCalledWith(400);
expect(res.json).toHaveBeenCalledWith(
expect.objectContaining({
error: "MissingHeaderError",
}),
);
});
it("should reject request with missing timestamp header", async () => {
const payload = createTestPayload();
const signature = await generateWebhookSignature(payload, TEST_SECRET);
const rawBody = JSON.stringify(payload);
const req = createMockRequest(Buffer.from(rawBody), {
"x-stellarsplit-signature": signature,
"x-stellarsplit-nonce": payload.nonce,
});
const res = createMockResponse();
const next = createMockNext();
const middleware = createWebhookMiddleware(TEST_SECRET);
await middleware(req as Request, res as Response, next);
expect(next).not.toHaveBeenCalled();
expect(res.status).toHaveBeenCalledWith(400);
expect(res.json).toHaveBeenCalledWith(
expect.objectContaining({
error: "MissingHeaderError",
}),
);
});
it("should reject request with missing nonce header", async () => {
const payload = createTestPayload();
const signature = await generateWebhookSignature(payload, TEST_SECRET);
const rawBody = JSON.stringify(payload);
const req = createMockRequest(Buffer.from(rawBody), {
"x-stellarsplit-signature": signature,
"x-stellarsplit-timestamp": String(payload.timestamp),
});
const res = createMockResponse();
const next = createMockNext();
const middleware = createWebhookMiddleware(TEST_SECRET);
await middleware(req as Request, res as Response, next);
expect(next).not.toHaveBeenCalled();
expect(res.status).toHaveBeenCalledWith(400);
expect(res.json).toHaveBeenCalledWith(
expect.objectContaining({
error: "MissingHeaderError",
}),
);
});
it("should reject request with invalid signature", async () => {
const payload = createTestPayload();
const rawBody = JSON.stringify(payload);
const invalidSignature = "0".repeat(64);
const req = createMockRequest(Buffer.from(rawBody), {
"x-stellarsplit-signature": invalidSignature,
"x-stellarsplit-timestamp": String(payload.timestamp),
"x-stellarsplit-nonce": payload.nonce,
});
const res = createMockResponse();
const next = createMockNext();
const middleware = createWebhookMiddleware(TEST_SECRET);
await middleware(req as Request, res as Response, next);
expect(next).not.toHaveBeenCalled();
expect(res.status).toHaveBeenCalledWith(400);
expect(res.json).toHaveBeenCalledWith(
expect.objectContaining({
error: "InvalidSignatureError",
}),
);
});
it("should reject request with timestamp outside tolerance", async () => {
const oldTimestamp = Math.floor(Date.now() / 1000) - 3600; // 1 hour ago
const payload: WebhookPayload = {
event: "invoice.paid",
timestamp: oldTimestamp,
nonce: `nonce_${Date.now()}`,
data: { test: true },
};
const signature = await generateWebhookSignature(payload, TEST_SECRET);
const rawBody = JSON.stringify(payload);
const req = createMockRequest(Buffer.from(rawBody), {
"x-stellarsplit-signature": signature,
"x-stellarsplit-timestamp": String(oldTimestamp),
"x-stellarsplit-nonce": payload.nonce,
});
const res = createMockResponse();
const next = createMockNext();
const middleware = createWebhookMiddleware(TEST_SECRET, {
toleranceSeconds: 300, // 5 minutes
});
await middleware(req as Request, res as Response, next);
expect(next).not.toHaveBeenCalled();
expect(res.status).toHaveBeenCalledWith(400);
expect(res.json).toHaveBeenCalledWith(
expect.objectContaining({
error: "TimestampOutOfBoundsError",
}),
);
});
it("should accept request with timestamp within tolerance", async () => {
const recentTimestamp = Math.floor(Date.now() / 1000) - 60; // 1 minute ago
const payload: WebhookPayload = {
event: "invoice.paid",
timestamp: recentTimestamp,
nonce: `nonce_${Date.now()}`,
data: { test: true },
};
const signature = await generateWebhookSignature(payload, TEST_SECRET);
const rawBody = JSON.stringify(payload);
const req = createMockRequest(Buffer.from(rawBody), {
"x-stellarsplit-signature": signature,
"x-stellarsplit-timestamp": String(recentTimestamp),
"x-stellarsplit-nonce": payload.nonce,
});
const res = createMockResponse();
const next = createMockNext();
const middleware = createWebhookMiddleware(TEST_SECRET, {
toleranceSeconds: 300,
});
await middleware(req as Request, res as Response, next);
expect(next).toHaveBeenCalledOnce();
expect(res.status).not.toHaveBeenCalled();
});
it("should reject replayed request (same nonce)", async () => {
const payload = createTestPayload();
const signature = await generateWebhookSignature(payload, TEST_SECRET);
const rawBody = JSON.stringify(payload);
const headers = {
"x-stellarsplit-signature": signature,
"x-stellarsplit-timestamp": String(payload.timestamp),
"x-stellarsplit-nonce": payload.nonce,
};
const middleware = createWebhookMiddleware(TEST_SECRET);
// First request should succeed
const req1 = createMockRequest(Buffer.from(rawBody), headers);
const res1 = createMockResponse();
const next1 = createMockNext();
await middleware(req1 as Request, res1 as Response, next1);
expect(next1).toHaveBeenCalledOnce();
// Second request with same nonce should be rejected
const req2 = createMockRequest(Buffer.from(rawBody), headers);
const res2 = createMockResponse();
const next2 = createMockNext();
await middleware(req2 as Request, res2 as Response, next2);
expect(next2).not.toHaveBeenCalled();
expect(res2.status).toHaveBeenCalledWith(400);
expect(res2.json).toHaveBeenCalledWith(
expect.objectContaining({
error: "ReplayAttackError",
}),
);
});
it("should accept multiple requests with different nonces", async () => {
const middleware = createWebhookMiddleware(TEST_SECRET);
for (let i = 0; i < 3; i++) {
const payload = createTestPayload();
const signature = await generateWebhookSignature(payload, TEST_SECRET);
const rawBody = JSON.stringify(payload);
const req = createMockRequest(Buffer.from(rawBody), {
"x-stellarsplit-signature": signature,
"x-stellarsplit-timestamp": String(payload.timestamp),
"x-stellarsplit-nonce": payload.nonce,
});
const res = createMockResponse();
const next = createMockNext();
await middleware(req as Request, res as Response, next);
expect(next).toHaveBeenCalledOnce();
expect(res.status).not.toHaveBeenCalled();
}
});
it("should handle malformed JSON payload", async () => {
const rawBody = "{ invalid json }";
const signature = await generateWebhookSignature(
{ event: "test" } as any,
TEST_SECRET,
);
const req = createMockRequest(Buffer.from(rawBody), {
"x-stellarsplit-signature": signature,
"x-stellarsplit-timestamp": String(Math.floor(Date.now() / 1000)),
"x-stellarsplit-nonce": "test-nonce",
});
const res = createMockResponse();
const next = createMockNext();
const middleware = createWebhookMiddleware(TEST_SECRET);
await middleware(req as Request, res as Response, next);
expect(next).not.toHaveBeenCalled();
expect(res.status).toHaveBeenCalledWith(400);
});
it("should handle body as string", async () => {
const payload = createTestPayload();
const signature = await generateWebhookSignature(payload, TEST_SECRET);
const rawBody = JSON.stringify(payload);
const req = createMockRequest(rawBody, {
"x-stellarsplit-signature": signature,
"x-stellarsplit-timestamp": String(payload.timestamp),
"x-stellarsplit-nonce": payload.nonce,
});
const res = createMockResponse();
const next = createMockNext();
const middleware = createWebhookMiddleware(TEST_SECRET);
await middleware(req as Request, res as Response, next);
expect(next).toHaveBeenCalledOnce();
});
it("should handle body as parsed object", async () => {
const payload = createTestPayload();
const signature = await generateWebhookSignature(payload, TEST_SECRET);
const req = createMockRequest(payload, {
"x-stellarsplit-signature": signature,
"x-stellarsplit-timestamp": String(payload.timestamp),
"x-stellarsplit-nonce": payload.nonce,
});
const res = createMockResponse();
const next = createMockNext();
const middleware = createWebhookMiddleware(TEST_SECRET);
await middleware(req as Request, res as Response, next);
expect(next).toHaveBeenCalledOnce();
});
it("should validate payload structure", async () => {
const invalidPayload = {
// Missing required fields
timestamp: Math.floor(Date.now() / 1000),
};
const signature = await generateWebhookSignature(invalidPayload as any, TEST_SECRET);
const rawBody = JSON.stringify(invalidPayload);
const req = createMockRequest(Buffer.from(rawBody), {
"x-stellarsplit-signature": signature,
"x-stellarsplit-timestamp": String(invalidPayload.timestamp),
"x-stellarsplit-nonce": "test-nonce",
});
const res = createMockResponse();
const next = createMockNext();
const middleware = createWebhookMiddleware(TEST_SECRET);
await middleware(req as Request, res as Response, next);
expect(next).not.toHaveBeenCalled();
expect(res.status).toHaveBeenCalledWith(400);
expect(res.json).toHaveBeenCalledWith(
expect.objectContaining({
error: "InvalidPayloadError",
}),
);
});
it("should verify nonce matches between header and payload", async () => {
const payload = createTestPayload();
const signature = await generateWebhookSignature(payload, TEST_SECRET);
const rawBody = JSON.stringify(payload);
const req = createMockRequest(Buffer.from(rawBody), {
"x-stellarsplit-signature": signature,
"x-stellarsplit-timestamp": String(payload.timestamp),
"x-stellarsplit-nonce": "different-nonce", // Mismatch
});
const res = createMockResponse();
const next = createMockNext();
const middleware = createWebhookMiddleware(TEST_SECRET);
await middleware(req as Request, res as Response, next);
expect(next).not.toHaveBeenCalled();
expect(res.status).toHaveBeenCalledWith(400);
});
it("should respect custom header names", async () => {
const payload = createTestPayload();
const signature = await generateWebhookSignature(payload, TEST_SECRET);
const rawBody = JSON.stringify(payload);
const req = createMockRequest(Buffer.from(rawBody), {
"x-custom-signature": signature,
"x-custom-timestamp": String(payload.timestamp),
"x-custom-nonce": payload.nonce,
});
const res = createMockResponse();
const next = createMockNext();
const middleware = createWebhookMiddleware(TEST_SECRET, {
signatureHeader: "x-custom-signature",
timestampHeader: "x-custom-timestamp",
nonceHeader: "x-custom-nonce",
});
await middleware(req as Request, res as Response, next);
expect(next).toHaveBeenCalledOnce();
});
});
// ============================================================================
// Utility Function Tests
// ============================================================================
describe("isValidEventType", () => {
it("should return true for valid event types", () => {
expect(isValidEventType("invoice.created")).toBe(true);
expect(isValidEventType("invoice.paid")).toBe(true);
expect(isValidEventType("invoice.failed")).toBe(true);
expect(isValidEventType("invoice.released")).toBe(true);
expect(isValidEventType("invoice.refunded")).toBe(true);
expect(isValidEventType("invoice.cancelled")).toBe(true);
expect(isValidEventType("invoice.expired")).toBe(true);
});
it("should return false for invalid event types", () => {
expect(isValidEventType("invoice.invalid")).toBe(false);
expect(isValidEventType("payment.received")).toBe(false);
expect(isValidEventType("")).toBe(false);
expect(isValidEventType("INVOICE.PAID")).toBe(false);
});
});
describe("parseWebhookPayload", () => {
it("should parse valid payload", () => {
const payload = createTestPayload();
const rawPayload = JSON.stringify(payload);
const parsed = parseWebhookPayload(rawPayload);
expect(parsed).toEqual(payload);
});
it("should throw on invalid JSON", () => {
expect(() => parseWebhookPayload("{ invalid }")).toThrow(InvalidPayloadError);
});
it("should throw on missing event field", () => {
const invalid = { timestamp: 123, nonce: "abc", data: {} };
expect(() => parseWebhookPayload(JSON.stringify(invalid))).toThrow(
InvalidPayloadError,
);
});
it("should throw on invalid event type", () => {
const invalid = {
event: "invalid.event",
timestamp: 123,
nonce: "abc",
data: {},
};
expect(() => parseWebhookPayload(JSON.stringify(invalid))).toThrow(
InvalidPayloadError,
);
});
it("should throw on missing timestamp", () => {
const invalid = { event: "invoice.paid", nonce: "abc", data: {} };
expect(() => parseWebhookPayload(JSON.stringify(invalid))).toThrow(
InvalidPayloadError,
);
});
it("should throw on missing nonce", () => {
const invalid = { event: "invoice.paid", timestamp: 123, data: {} };
expect(() => parseWebhookPayload(JSON.stringify(invalid))).toThrow(
InvalidPayloadError,
);
});
it("should throw on missing data", () => {
const invalid = { event: "invoice.paid", timestamp: 123, nonce: "abc" };
expect(() => parseWebhookPayload(JSON.stringify(invalid))).toThrow(
InvalidPayloadError,
);
});
});
describe("isWebhookRequest", () => {
it("should return true for webhook request", () => {
const req: Partial<WebhookRequest> = {
webhookPayload: createTestPayload(),
rawWebhookBody: "{}",
};
expect(isWebhookRequest(req as Request)).toBe(true);
});
it("should return false for regular request", () => {
const req: Partial<Request> = {
body: {},
};
expect(isWebhookRequest(req as Request)).toBe(false);
});
});
// ============================================================================
// LRU Cache Behavior Tests
// ============================================================================
describe("LRU Cache (via middleware)", () => {
it("should evict oldest nonce when cache is full", async () => {
const middleware = createWebhookMiddleware(TEST_SECRET, {
nonceWindowSize: 2, // Very small cache
});
// Send 3 requests with different nonces
const nonces = ["nonce1", "nonce2", "nonce3"];
for (const nonce of nonces) {
const payload: WebhookPayload = {
event: "invoice.paid",
timestamp: Math.floor(Date.now() / 1000),
nonce,
data: { test: true },
};
const signature = await generateWebhookSignature(payload, TEST_SECRET);
const rawBody = JSON.stringify(payload);
const req = createMockRequest(Buffer.from(rawBody), {
"x-stellarsplit-signature": signature,
"x-stellarsplit-timestamp": String(payload.timestamp),
"x-stellarsplit-nonce": nonce,
});
const res = createMockResponse();
const next = createMockNext();
await middleware(req as Request, res as Response, next);
expect(next).toHaveBeenCalled();
}
// Try to replay the first nonce (should succeed because it was evicted)
const firstPayload: WebhookPayload = {
event: "invoice.paid",
timestamp: Math.floor(Date.now() / 1000),
nonce: nonces[0]!,
data: { test: true },
};
const signature = await generateWebhookSignature(firstPayload, TEST_SECRET);
const rawBody = JSON.stringify(firstPayload);
const req = createMockRequest(Buffer.from(rawBody), {
"x-stellarsplit-signature": signature,
"x-stellarsplit-timestamp": String(firstPayload.timestamp),
"x-stellarsplit-nonce": nonces[0]!,
});
const res = createMockResponse();
const next = createMockNext();
await middleware(req as Request, res as Response, next);
expect(next).toHaveBeenCalled(); // Should succeed (was evicted)
});
});