nextjs-secure 0.7.0 → 0.8.0

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/dist/api.js ADDED
@@ -0,0 +1,1650 @@
1
+ // src/middleware/api/types.ts
2
+ var API_PROTECTION_PRESETS = {
3
+ /** Basic: Only timestamp and versioning */
4
+ basic: {
5
+ signing: false,
6
+ replay: false,
7
+ timestamp: {
8
+ maxAge: 600,
9
+ // 10 minutes
10
+ required: false
11
+ },
12
+ versioning: false,
13
+ idempotency: false
14
+ },
15
+ /** Standard: Timestamp, replay prevention, versioning */
16
+ standard: {
17
+ signing: false,
18
+ replay: {
19
+ ttl: 3e5,
20
+ // 5 minutes
21
+ required: true
22
+ },
23
+ timestamp: {
24
+ maxAge: 300,
25
+ // 5 minutes
26
+ required: true
27
+ },
28
+ versioning: false,
29
+ idempotency: {
30
+ required: false
31
+ }
32
+ },
33
+ /** Strict: All protections enabled */
34
+ strict: {
35
+ signing: {
36
+ secret: "",
37
+ // Must be provided
38
+ algorithm: "sha256",
39
+ timestampTolerance: 300
40
+ },
41
+ replay: {
42
+ ttl: 3e5,
43
+ required: true,
44
+ minLength: 32
45
+ },
46
+ timestamp: {
47
+ maxAge: 300,
48
+ required: true,
49
+ allowFuture: false
50
+ },
51
+ versioning: false,
52
+ idempotency: {
53
+ required: true,
54
+ methods: ["POST", "PUT", "PATCH", "DELETE"]
55
+ }
56
+ },
57
+ /** Financial: Maximum security for financial APIs */
58
+ financial: {
59
+ signing: {
60
+ secret: "",
61
+ // Must be provided
62
+ algorithm: "sha512",
63
+ timestampTolerance: 60,
64
+ // 1 minute
65
+ components: {
66
+ method: true,
67
+ path: true,
68
+ query: true,
69
+ body: true,
70
+ timestamp: true,
71
+ nonce: true
72
+ }
73
+ },
74
+ replay: {
75
+ ttl: 864e5,
76
+ // 24 hours
77
+ required: true,
78
+ minLength: 64
79
+ },
80
+ timestamp: {
81
+ maxAge: 60,
82
+ // 1 minute
83
+ required: true,
84
+ allowFuture: false,
85
+ maxFuture: 10
86
+ },
87
+ versioning: false,
88
+ idempotency: {
89
+ required: true,
90
+ ttl: 6048e5,
91
+ // 7 days
92
+ methods: ["POST", "PUT", "PATCH", "DELETE"],
93
+ hashRequestBody: true
94
+ }
95
+ }
96
+ };
97
+
98
+ // src/middleware/api/signing.ts
99
+ var DEFAULT_SIGNING_OPTIONS = {
100
+ algorithm: "sha256",
101
+ encoding: "hex",
102
+ signatureHeader: "x-signature",
103
+ timestampHeader: "x-timestamp",
104
+ nonceHeader: "x-nonce",
105
+ components: {
106
+ method: true,
107
+ path: true,
108
+ query: true,
109
+ body: true,
110
+ headers: [],
111
+ timestamp: true,
112
+ nonce: false
113
+ },
114
+ timestampTolerance: 300
115
+ // 5 minutes
116
+ };
117
+ async function createHMAC(data, secret, algorithm = "sha256", encoding = "hex") {
118
+ const encoder = new TextEncoder();
119
+ const keyData = encoder.encode(secret);
120
+ const messageData = encoder.encode(data);
121
+ const hashName = {
122
+ sha1: "SHA-1",
123
+ sha256: "SHA-256",
124
+ sha384: "SHA-384",
125
+ sha512: "SHA-512"
126
+ }[algorithm];
127
+ const key = await crypto.subtle.importKey(
128
+ "raw",
129
+ keyData,
130
+ { name: "HMAC", hash: hashName },
131
+ false,
132
+ ["sign"]
133
+ );
134
+ const signature = await crypto.subtle.sign("HMAC", key, messageData);
135
+ return encodeSignature(new Uint8Array(signature), encoding);
136
+ }
137
+ function encodeSignature(bytes, encoding) {
138
+ switch (encoding) {
139
+ case "hex":
140
+ return Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("");
141
+ case "base64":
142
+ return btoa(String.fromCharCode(...bytes));
143
+ case "base64url":
144
+ return btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
145
+ default:
146
+ return Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("");
147
+ }
148
+ }
149
+ function timingSafeEqual(a, b) {
150
+ if (a.length !== b.length) {
151
+ return false;
152
+ }
153
+ let result = 0;
154
+ for (let i = 0; i < a.length; i++) {
155
+ result |= a.charCodeAt(i) ^ b.charCodeAt(i);
156
+ }
157
+ return result === 0;
158
+ }
159
+ async function buildCanonicalString(req, components, options = {}) {
160
+ const parts = [];
161
+ if (components.method) {
162
+ parts.push(req.method.toUpperCase());
163
+ }
164
+ if (components.path) {
165
+ const url = new URL(req.url);
166
+ parts.push(url.pathname);
167
+ }
168
+ if (components.query) {
169
+ const url = new URL(req.url);
170
+ const params = new URLSearchParams(url.search);
171
+ const sortedParams = Array.from(params.entries()).sort((a, b) => a[0].localeCompare(b[0])).map(([k, v]) => `${k}=${v}`).join("&");
172
+ parts.push(sortedParams);
173
+ }
174
+ if (components.body) {
175
+ try {
176
+ const cloned = req.clone();
177
+ const body = await cloned.text();
178
+ if (body) {
179
+ parts.push(body);
180
+ }
181
+ } catch {
182
+ }
183
+ }
184
+ if (components.headers && components.headers.length > 0) {
185
+ const headerParts = components.headers.map((h) => h.toLowerCase()).sort().map((h) => `${h}:${req.headers.get(h) || ""}`);
186
+ parts.push(headerParts.join("\n"));
187
+ }
188
+ if (components.timestamp) {
189
+ const timestampHeader = options.timestampHeader || "x-timestamp";
190
+ const timestamp = req.headers.get(timestampHeader) || "";
191
+ parts.push(timestamp);
192
+ }
193
+ if (components.nonce) {
194
+ const nonceHeader = options.nonceHeader || "x-nonce";
195
+ const nonce = req.headers.get(nonceHeader) || "";
196
+ parts.push(nonce);
197
+ }
198
+ return parts.join("\n");
199
+ }
200
+ async function generateSignature(req, options) {
201
+ const {
202
+ secret,
203
+ algorithm = DEFAULT_SIGNING_OPTIONS.algorithm,
204
+ encoding = DEFAULT_SIGNING_OPTIONS.encoding,
205
+ components = DEFAULT_SIGNING_OPTIONS.components,
206
+ timestampHeader = DEFAULT_SIGNING_OPTIONS.timestampHeader,
207
+ nonceHeader = DEFAULT_SIGNING_OPTIONS.nonceHeader,
208
+ canonicalBuilder
209
+ } = options;
210
+ const canonical = canonicalBuilder ? await canonicalBuilder(req, components) : await buildCanonicalString(req, components, { timestampHeader, nonceHeader });
211
+ return createHMAC(canonical, secret, algorithm, encoding);
212
+ }
213
+ async function generateSignatureHeaders(method, url, body, options) {
214
+ const {
215
+ secret,
216
+ algorithm = DEFAULT_SIGNING_OPTIONS.algorithm,
217
+ encoding = DEFAULT_SIGNING_OPTIONS.encoding,
218
+ components = DEFAULT_SIGNING_OPTIONS.components,
219
+ signatureHeader = DEFAULT_SIGNING_OPTIONS.signatureHeader,
220
+ timestampHeader = DEFAULT_SIGNING_OPTIONS.timestampHeader,
221
+ nonceHeader = DEFAULT_SIGNING_OPTIONS.nonceHeader,
222
+ includeTimestamp = true,
223
+ includeNonce = false
224
+ } = options;
225
+ const headers = {};
226
+ const parts = [];
227
+ if (components.method) {
228
+ parts.push(method.toUpperCase());
229
+ }
230
+ if (components.path) {
231
+ const parsedUrl = new URL(url);
232
+ parts.push(parsedUrl.pathname);
233
+ }
234
+ if (components.query) {
235
+ const parsedUrl = new URL(url);
236
+ const params = new URLSearchParams(parsedUrl.search);
237
+ const sortedParams = Array.from(params.entries()).sort((a, b) => a[0].localeCompare(b[0])).map(([k, v]) => `${k}=${v}`).join("&");
238
+ parts.push(sortedParams);
239
+ }
240
+ if (components.body && body) {
241
+ parts.push(body);
242
+ }
243
+ if (components.timestamp && includeTimestamp) {
244
+ const timestamp = Math.floor(Date.now() / 1e3).toString();
245
+ headers[timestampHeader] = timestamp;
246
+ parts.push(timestamp);
247
+ }
248
+ if (components.nonce && includeNonce) {
249
+ const nonce = generateNonce();
250
+ headers[nonceHeader] = nonce;
251
+ parts.push(nonce);
252
+ }
253
+ const canonical = parts.join("\n");
254
+ const signature = await createHMAC(canonical, secret, algorithm, encoding);
255
+ headers[signatureHeader] = signature;
256
+ return headers;
257
+ }
258
+ function generateNonce(length = 32) {
259
+ const bytes = new Uint8Array(length);
260
+ crypto.getRandomValues(bytes);
261
+ return Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("");
262
+ }
263
+ async function verifySignature(req, options) {
264
+ const {
265
+ secret,
266
+ algorithm = DEFAULT_SIGNING_OPTIONS.algorithm,
267
+ encoding = DEFAULT_SIGNING_OPTIONS.encoding,
268
+ signatureHeader = DEFAULT_SIGNING_OPTIONS.signatureHeader,
269
+ timestampHeader = DEFAULT_SIGNING_OPTIONS.timestampHeader,
270
+ nonceHeader = DEFAULT_SIGNING_OPTIONS.nonceHeader,
271
+ components = DEFAULT_SIGNING_OPTIONS.components,
272
+ timestampTolerance = DEFAULT_SIGNING_OPTIONS.timestampTolerance,
273
+ canonicalBuilder
274
+ } = options;
275
+ const providedSignature = req.headers.get(signatureHeader);
276
+ if (!providedSignature) {
277
+ return {
278
+ valid: false,
279
+ reason: "Missing signature header"
280
+ };
281
+ }
282
+ if (components.timestamp) {
283
+ const timestamp = req.headers.get(timestampHeader);
284
+ if (!timestamp) {
285
+ return {
286
+ valid: false,
287
+ reason: "Missing timestamp header"
288
+ };
289
+ }
290
+ const timestampNum = parseInt(timestamp, 10);
291
+ if (isNaN(timestampNum)) {
292
+ return {
293
+ valid: false,
294
+ reason: "Invalid timestamp format"
295
+ };
296
+ }
297
+ const now = Math.floor(Date.now() / 1e3);
298
+ const age = Math.abs(now - timestampNum);
299
+ if (age > timestampTolerance) {
300
+ return {
301
+ valid: false,
302
+ reason: `Timestamp too old or too far in future (age: ${age}s, max: ${timestampTolerance}s)`
303
+ };
304
+ }
305
+ }
306
+ const canonical = canonicalBuilder ? await canonicalBuilder(req, components) : await buildCanonicalString(req, components, { timestampHeader, nonceHeader });
307
+ const computedSignature = await createHMAC(canonical, secret, algorithm, encoding);
308
+ const valid = timingSafeEqual(providedSignature, computedSignature);
309
+ return {
310
+ valid,
311
+ reason: valid ? void 0 : "Signature mismatch",
312
+ computed: computedSignature,
313
+ provided: providedSignature,
314
+ canonical
315
+ };
316
+ }
317
+ function defaultInvalidResponse(reason) {
318
+ return new Response(
319
+ JSON.stringify({
320
+ error: "Unauthorized",
321
+ message: reason,
322
+ code: "INVALID_SIGNATURE"
323
+ }),
324
+ {
325
+ status: 401,
326
+ headers: { "Content-Type": "application/json" }
327
+ }
328
+ );
329
+ }
330
+ function withRequestSigning(handler, options) {
331
+ return async (req, ctx) => {
332
+ if (options.skip && await options.skip(req)) {
333
+ return handler(req, ctx);
334
+ }
335
+ const result = await verifySignature(req, options);
336
+ if (!result.valid) {
337
+ const onInvalid = options.onInvalid || defaultInvalidResponse;
338
+ return onInvalid(result.reason || "Invalid signature");
339
+ }
340
+ return handler(req, ctx);
341
+ };
342
+ }
343
+
344
+ // src/middleware/api/replay.ts
345
+ var DEFAULT_REPLAY_OPTIONS = {
346
+ nonceHeader: "x-nonce",
347
+ nonceQuery: "",
348
+ ttl: 3e5,
349
+ // 5 minutes
350
+ required: true,
351
+ minLength: 16,
352
+ maxLength: 128
353
+ };
354
+ var MemoryNonceStore = class {
355
+ nonces = /* @__PURE__ */ new Map();
356
+ maxSize;
357
+ cleanupInterval = null;
358
+ constructor(options = {}) {
359
+ const { maxSize = 1e5, autoCleanup = true, cleanupIntervalMs = 6e4 } = options;
360
+ this.maxSize = maxSize;
361
+ if (autoCleanup) {
362
+ this.cleanupInterval = setInterval(() => {
363
+ this.cleanup();
364
+ }, cleanupIntervalMs);
365
+ if (this.cleanupInterval.unref) {
366
+ this.cleanupInterval.unref();
367
+ }
368
+ }
369
+ }
370
+ async exists(nonce) {
371
+ const entry = this.nonces.get(nonce);
372
+ if (!entry) {
373
+ return false;
374
+ }
375
+ if (Date.now() > entry.expiresAt) {
376
+ this.nonces.delete(nonce);
377
+ return false;
378
+ }
379
+ return true;
380
+ }
381
+ async set(nonce, ttl) {
382
+ if (this.nonces.size >= this.maxSize) {
383
+ this.evictOldest();
384
+ }
385
+ const now = Date.now();
386
+ this.nonces.set(nonce, {
387
+ timestamp: now,
388
+ expiresAt: now + ttl
389
+ });
390
+ }
391
+ async cleanup() {
392
+ const now = Date.now();
393
+ for (const [nonce, entry] of this.nonces.entries()) {
394
+ if (now > entry.expiresAt) {
395
+ this.nonces.delete(nonce);
396
+ }
397
+ }
398
+ }
399
+ getStats() {
400
+ let oldestTimestamp;
401
+ for (const entry of this.nonces.values()) {
402
+ if (!oldestTimestamp || entry.timestamp < oldestTimestamp) {
403
+ oldestTimestamp = entry.timestamp;
404
+ }
405
+ }
406
+ return {
407
+ size: this.nonces.size,
408
+ oldestTimestamp
409
+ };
410
+ }
411
+ evictOldest() {
412
+ const toRemove = Math.ceil(this.maxSize * 0.1);
413
+ const entries = Array.from(this.nonces.entries()).sort((a, b) => a[1].timestamp - b[1].timestamp).slice(0, toRemove);
414
+ for (const [nonce] of entries) {
415
+ this.nonces.delete(nonce);
416
+ }
417
+ }
418
+ /**
419
+ * Clear all nonces
420
+ */
421
+ clear() {
422
+ this.nonces.clear();
423
+ }
424
+ /**
425
+ * Stop auto cleanup
426
+ */
427
+ destroy() {
428
+ if (this.cleanupInterval) {
429
+ clearInterval(this.cleanupInterval);
430
+ this.cleanupInterval = null;
431
+ }
432
+ }
433
+ };
434
+ var globalNonceStore = null;
435
+ function getGlobalNonceStore() {
436
+ if (!globalNonceStore) {
437
+ globalNonceStore = new MemoryNonceStore();
438
+ }
439
+ return globalNonceStore;
440
+ }
441
+ function generateNonce2(length = 32) {
442
+ const bytes = new Uint8Array(length);
443
+ crypto.getRandomValues(bytes);
444
+ return Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("");
445
+ }
446
+ function isValidNonceFormat(nonce, minLength = 16, maxLength = 128) {
447
+ if (!nonce || typeof nonce !== "string") {
448
+ return false;
449
+ }
450
+ if (nonce.length < minLength || nonce.length > maxLength) {
451
+ return false;
452
+ }
453
+ return /^[a-zA-Z0-9_-]+$/.test(nonce);
454
+ }
455
+ function extractNonce(req, options = {}) {
456
+ const {
457
+ nonceHeader = DEFAULT_REPLAY_OPTIONS.nonceHeader,
458
+ nonceQuery = DEFAULT_REPLAY_OPTIONS.nonceQuery
459
+ } = options;
460
+ const headerNonce = req.headers.get(nonceHeader);
461
+ if (headerNonce) {
462
+ return headerNonce;
463
+ }
464
+ if (nonceQuery) {
465
+ const url = new URL(req.url);
466
+ const queryNonce = url.searchParams.get(nonceQuery);
467
+ if (queryNonce) {
468
+ return queryNonce;
469
+ }
470
+ }
471
+ return null;
472
+ }
473
+ async function checkReplay(req, options = {}) {
474
+ const {
475
+ store = getGlobalNonceStore(),
476
+ nonceHeader = DEFAULT_REPLAY_OPTIONS.nonceHeader,
477
+ nonceQuery = DEFAULT_REPLAY_OPTIONS.nonceQuery,
478
+ ttl = DEFAULT_REPLAY_OPTIONS.ttl,
479
+ required = DEFAULT_REPLAY_OPTIONS.required,
480
+ minLength = DEFAULT_REPLAY_OPTIONS.minLength,
481
+ maxLength = DEFAULT_REPLAY_OPTIONS.maxLength,
482
+ validate
483
+ } = options;
484
+ const nonce = extractNonce(req, { nonceHeader, nonceQuery });
485
+ if (!nonce) {
486
+ if (required) {
487
+ return {
488
+ isReplay: false,
489
+ // Not a replay, but missing
490
+ nonce: null,
491
+ reason: "Missing nonce"
492
+ };
493
+ }
494
+ return {
495
+ isReplay: false
496
+ };
497
+ }
498
+ if (!isValidNonceFormat(nonce, minLength, maxLength)) {
499
+ return {
500
+ isReplay: false,
501
+ nonce,
502
+ reason: `Invalid nonce format (length must be ${minLength}-${maxLength}, alphanumeric)`
503
+ };
504
+ }
505
+ if (validate) {
506
+ const isValid = await validate(nonce);
507
+ if (!isValid) {
508
+ return {
509
+ isReplay: false,
510
+ nonce,
511
+ reason: "Nonce failed custom validation"
512
+ };
513
+ }
514
+ }
515
+ const exists = await store.exists(nonce);
516
+ if (exists) {
517
+ return {
518
+ isReplay: true,
519
+ nonce,
520
+ reason: "Nonce has already been used"
521
+ };
522
+ }
523
+ await store.set(nonce, ttl);
524
+ return {
525
+ isReplay: false,
526
+ nonce
527
+ };
528
+ }
529
+ function defaultReplayResponse(nonce) {
530
+ return new Response(
531
+ JSON.stringify({
532
+ error: "Forbidden",
533
+ message: "Request replay detected",
534
+ code: "REPLAY_DETECTED",
535
+ nonce
536
+ }),
537
+ {
538
+ status: 403,
539
+ headers: { "Content-Type": "application/json" }
540
+ }
541
+ );
542
+ }
543
+ function defaultMissingNonceResponse(reason) {
544
+ return new Response(
545
+ JSON.stringify({
546
+ error: "Bad Request",
547
+ message: reason,
548
+ code: "INVALID_NONCE"
549
+ }),
550
+ {
551
+ status: 400,
552
+ headers: { "Content-Type": "application/json" }
553
+ }
554
+ );
555
+ }
556
+ function withReplayPrevention(handler, options = {}) {
557
+ return async (req, ctx) => {
558
+ if (options.skip && await options.skip(req)) {
559
+ return handler(req, ctx);
560
+ }
561
+ const result = await checkReplay(req, options);
562
+ if (result.isReplay) {
563
+ const onReplay = options.onReplay || defaultReplayResponse;
564
+ return onReplay(result.nonce);
565
+ }
566
+ if (result.reason && options.required !== false) {
567
+ return defaultMissingNonceResponse(result.reason);
568
+ }
569
+ return handler(req, ctx);
570
+ };
571
+ }
572
+ function addNonceHeader(headers = {}, options = {}) {
573
+ const { headerName = "x-nonce", length = 32 } = options;
574
+ return {
575
+ ...headers,
576
+ [headerName]: generateNonce2(length)
577
+ };
578
+ }
579
+
580
+ // src/middleware/api/timestamp.ts
581
+ var DEFAULT_TIMESTAMP_OPTIONS = {
582
+ timestampHeader: "x-timestamp",
583
+ format: "unix",
584
+ maxAge: 300,
585
+ // 5 minutes
586
+ allowFuture: false,
587
+ maxFuture: 60,
588
+ // 1 minute
589
+ required: true
590
+ };
591
+ function parseTimestamp(value, format = "unix") {
592
+ if (!value || typeof value !== "string") {
593
+ return null;
594
+ }
595
+ try {
596
+ switch (format) {
597
+ case "unix": {
598
+ const num = parseInt(value, 10);
599
+ if (isNaN(num) || num <= 0) {
600
+ return null;
601
+ }
602
+ return num;
603
+ }
604
+ case "unix-ms": {
605
+ const num = parseInt(value, 10);
606
+ if (isNaN(num) || num <= 0) {
607
+ return null;
608
+ }
609
+ return Math.floor(num / 1e3);
610
+ }
611
+ case "iso8601": {
612
+ const date = new Date(value);
613
+ if (isNaN(date.getTime())) {
614
+ return null;
615
+ }
616
+ return Math.floor(date.getTime() / 1e3);
617
+ }
618
+ default:
619
+ return null;
620
+ }
621
+ } catch {
622
+ return null;
623
+ }
624
+ }
625
+ function formatTimestamp(format = "unix") {
626
+ const now = Date.now();
627
+ switch (format) {
628
+ case "unix":
629
+ return Math.floor(now / 1e3).toString();
630
+ case "unix-ms":
631
+ return now.toString();
632
+ case "iso8601":
633
+ return new Date(now).toISOString();
634
+ default:
635
+ return Math.floor(now / 1e3).toString();
636
+ }
637
+ }
638
+ function extractTimestamp(req, options = {}) {
639
+ const {
640
+ timestampHeader = DEFAULT_TIMESTAMP_OPTIONS.timestampHeader,
641
+ timestampQuery
642
+ } = options;
643
+ const headerTimestamp = req.headers.get(timestampHeader);
644
+ if (headerTimestamp) {
645
+ return headerTimestamp;
646
+ }
647
+ if (timestampQuery) {
648
+ const url = new URL(req.url);
649
+ const queryTimestamp = url.searchParams.get(timestampQuery);
650
+ if (queryTimestamp) {
651
+ return queryTimestamp;
652
+ }
653
+ }
654
+ return null;
655
+ }
656
+ function validateTimestamp(req, options = {}) {
657
+ const {
658
+ timestampHeader = DEFAULT_TIMESTAMP_OPTIONS.timestampHeader,
659
+ timestampQuery,
660
+ format = DEFAULT_TIMESTAMP_OPTIONS.format,
661
+ maxAge = DEFAULT_TIMESTAMP_OPTIONS.maxAge,
662
+ allowFuture = DEFAULT_TIMESTAMP_OPTIONS.allowFuture,
663
+ maxFuture = DEFAULT_TIMESTAMP_OPTIONS.maxFuture,
664
+ required = DEFAULT_TIMESTAMP_OPTIONS.required
665
+ } = options;
666
+ const timestampStr = extractTimestamp(req, { timestampHeader, timestampQuery });
667
+ if (!timestampStr) {
668
+ if (required) {
669
+ return {
670
+ valid: false,
671
+ reason: "Missing timestamp"
672
+ };
673
+ }
674
+ return {
675
+ valid: true
676
+ };
677
+ }
678
+ const timestamp = parseTimestamp(timestampStr, format);
679
+ if (timestamp === null) {
680
+ return {
681
+ valid: false,
682
+ reason: `Invalid timestamp format (expected: ${format})`
683
+ };
684
+ }
685
+ const now = Math.floor(Date.now() / 1e3);
686
+ const age = now - timestamp;
687
+ if (age > maxAge) {
688
+ return {
689
+ valid: false,
690
+ timestamp,
691
+ age,
692
+ reason: `Timestamp too old (age: ${age}s, max: ${maxAge}s)`
693
+ };
694
+ }
695
+ if (age < 0) {
696
+ if (!allowFuture) {
697
+ return {
698
+ valid: false,
699
+ timestamp,
700
+ age,
701
+ reason: "Timestamp is in the future"
702
+ };
703
+ }
704
+ const futureAge = Math.abs(age);
705
+ if (futureAge > maxFuture) {
706
+ return {
707
+ valid: false,
708
+ timestamp,
709
+ age,
710
+ reason: `Timestamp too far in future (${futureAge}s, max: ${maxFuture}s)`
711
+ };
712
+ }
713
+ }
714
+ return {
715
+ valid: true,
716
+ timestamp,
717
+ age
718
+ };
719
+ }
720
+ function isTimestampValid(timestampStr, options = {}) {
721
+ const {
722
+ format = "unix",
723
+ maxAge = 300,
724
+ allowFuture = false,
725
+ maxFuture = 60
726
+ } = options;
727
+ const timestamp = parseTimestamp(timestampStr, format);
728
+ if (timestamp === null) {
729
+ return false;
730
+ }
731
+ const now = Math.floor(Date.now() / 1e3);
732
+ const age = now - timestamp;
733
+ if (age > maxAge) {
734
+ return false;
735
+ }
736
+ if (age < 0) {
737
+ if (!allowFuture) {
738
+ return false;
739
+ }
740
+ if (Math.abs(age) > maxFuture) {
741
+ return false;
742
+ }
743
+ }
744
+ return true;
745
+ }
746
+ function defaultInvalidResponse2(reason) {
747
+ return new Response(
748
+ JSON.stringify({
749
+ error: "Bad Request",
750
+ message: reason,
751
+ code: "INVALID_TIMESTAMP"
752
+ }),
753
+ {
754
+ status: 400,
755
+ headers: { "Content-Type": "application/json" }
756
+ }
757
+ );
758
+ }
759
+ function withTimestamp(handler, options = {}) {
760
+ return async (req, ctx) => {
761
+ if (options.skip && await options.skip(req)) {
762
+ return handler(req, ctx);
763
+ }
764
+ const result = validateTimestamp(req, options);
765
+ if (!result.valid) {
766
+ const onInvalid = options.onInvalid || defaultInvalidResponse2;
767
+ return onInvalid(result.reason || "Invalid timestamp");
768
+ }
769
+ return handler(req, ctx);
770
+ };
771
+ }
772
+ function addTimestampHeader(headers = {}, options = {}) {
773
+ const { headerName = "x-timestamp", format = "unix" } = options;
774
+ return {
775
+ ...headers,
776
+ [headerName]: formatTimestamp(format)
777
+ };
778
+ }
779
+ function getRequestAge(req, options = {}) {
780
+ const timestampStr = extractTimestamp(req, options);
781
+ if (!timestampStr) {
782
+ return null;
783
+ }
784
+ const timestamp = parseTimestamp(timestampStr, options.format);
785
+ if (timestamp === null) {
786
+ return null;
787
+ }
788
+ const now = Math.floor(Date.now() / 1e3);
789
+ return now - timestamp;
790
+ }
791
+
792
+ // src/middleware/api/versioning.ts
793
+ var DEFAULT_VERSIONING_OPTIONS = {
794
+ source: "header",
795
+ versionHeader: "x-api-version",
796
+ versionQuery: "version",
797
+ addDeprecationHeaders: true
798
+ };
799
+ function extractFromHeader(req, headerName) {
800
+ return req.headers.get(headerName);
801
+ }
802
+ function extractFromQuery(req, queryParam) {
803
+ const url = new URL(req.url);
804
+ return url.searchParams.get(queryParam);
805
+ }
806
+ function extractFromPath(req, pattern) {
807
+ if (!pattern) {
808
+ pattern = /\/v(\d+(?:\.\d+)?)\//;
809
+ }
810
+ const url = new URL(req.url);
811
+ const match = url.pathname.match(pattern);
812
+ if (match && match[1]) {
813
+ return match[1];
814
+ }
815
+ return null;
816
+ }
817
+ function extractFromAccept(req, pattern) {
818
+ const accept = req.headers.get("accept");
819
+ if (!accept) {
820
+ return null;
821
+ }
822
+ if (!pattern) {
823
+ pattern = /version=(\d+(?:\.\d+)?)/;
824
+ }
825
+ const match = accept.match(pattern);
826
+ if (match && match[1]) {
827
+ return match[1];
828
+ }
829
+ return null;
830
+ }
831
+ function extractVersion(req, options) {
832
+ const {
833
+ source = DEFAULT_VERSIONING_OPTIONS.source,
834
+ versionHeader = DEFAULT_VERSIONING_OPTIONS.versionHeader,
835
+ versionQuery = DEFAULT_VERSIONING_OPTIONS.versionQuery,
836
+ pathPattern,
837
+ acceptPattern,
838
+ parseVersion
839
+ } = options;
840
+ let version = null;
841
+ let extractedSource = null;
842
+ switch (source) {
843
+ case "header":
844
+ version = extractFromHeader(req, versionHeader);
845
+ extractedSource = version ? "header" : null;
846
+ break;
847
+ case "query":
848
+ version = extractFromQuery(req, versionQuery);
849
+ extractedSource = version ? "query" : null;
850
+ break;
851
+ case "path":
852
+ version = extractFromPath(req, pathPattern);
853
+ extractedSource = version ? "path" : null;
854
+ break;
855
+ case "accept":
856
+ version = extractFromAccept(req, acceptPattern);
857
+ extractedSource = version ? "accept" : null;
858
+ break;
859
+ }
860
+ if (version && parseVersion) {
861
+ version = parseVersion(version);
862
+ }
863
+ return { version, source: extractedSource };
864
+ }
865
+ function extractVersionMultiSource(req, options, sources = ["header", "query", "path", "accept"]) {
866
+ for (const source of sources) {
867
+ const result = extractVersion(req, { ...options, source });
868
+ if (result.version) {
869
+ return result;
870
+ }
871
+ }
872
+ return { version: null, source: null };
873
+ }
874
+ function getVersionStatus(version, options) {
875
+ const { current, supported, deprecated = [], sunset = [] } = options;
876
+ if (version === current) {
877
+ return "current";
878
+ }
879
+ if (sunset.includes(version)) {
880
+ return "sunset";
881
+ }
882
+ if (deprecated.includes(version)) {
883
+ return "deprecated";
884
+ }
885
+ if (supported.includes(version)) {
886
+ return "supported";
887
+ }
888
+ return null;
889
+ }
890
+ function isVersionSupported(version, options) {
891
+ const status = getVersionStatus(version, options);
892
+ return status === "current" || status === "supported" || status === "deprecated";
893
+ }
894
+ function validateVersion(req, options) {
895
+ const { current, supported, deprecated = [], sunset = [], sunsetDates = {} } = options;
896
+ const { version, source } = extractVersion(req, options);
897
+ if (!version) {
898
+ return {
899
+ version: current,
900
+ source: null,
901
+ status: "current",
902
+ valid: true
903
+ };
904
+ }
905
+ if (sunset.includes(version)) {
906
+ const sunsetDate = sunsetDates[version];
907
+ return {
908
+ version,
909
+ source,
910
+ status: "sunset",
911
+ valid: false,
912
+ reason: `API version ${version} has been sunset${sunsetDate ? ` on ${sunsetDate.toISOString()}` : ""}`,
913
+ sunsetDate
914
+ };
915
+ }
916
+ if (deprecated.includes(version)) {
917
+ const sunsetDate = sunsetDates[version];
918
+ return {
919
+ version,
920
+ source,
921
+ status: "deprecated",
922
+ valid: true,
923
+ sunsetDate
924
+ };
925
+ }
926
+ if (version === current) {
927
+ return {
928
+ version,
929
+ source,
930
+ status: "current",
931
+ valid: true
932
+ };
933
+ }
934
+ if (supported.includes(version)) {
935
+ return {
936
+ version,
937
+ source,
938
+ status: "supported",
939
+ valid: true
940
+ };
941
+ }
942
+ return {
943
+ version,
944
+ source,
945
+ status: null,
946
+ valid: false,
947
+ reason: `Unsupported API version: ${version}. Supported versions: ${[current, ...supported].join(", ")}`
948
+ };
949
+ }
950
+ function addDeprecationHeaders(response, version, sunsetDate) {
951
+ const headers = new Headers(response.headers);
952
+ headers.set("Deprecation", "true");
953
+ if (sunsetDate) {
954
+ headers.set("Sunset", sunsetDate.toUTCString());
955
+ }
956
+ headers.set(
957
+ "Warning",
958
+ `299 - "API version ${version} is deprecated${sunsetDate ? ` and will be removed on ${sunsetDate.toISOString().split("T")[0]}` : ""}"`
959
+ );
960
+ return new Response(response.body, {
961
+ status: response.status,
962
+ statusText: response.statusText,
963
+ headers
964
+ });
965
+ }
966
+ function defaultUnsupportedResponse(version, supportedVersions) {
967
+ return new Response(
968
+ JSON.stringify({
969
+ error: "Bad Request",
970
+ message: `Unsupported API version: ${version}`,
971
+ code: "UNSUPPORTED_VERSION",
972
+ supportedVersions
973
+ }),
974
+ {
975
+ status: 400,
976
+ headers: { "Content-Type": "application/json" }
977
+ }
978
+ );
979
+ }
980
+ function defaultSunsetResponse(version, sunsetDate) {
981
+ return new Response(
982
+ JSON.stringify({
983
+ error: "Gone",
984
+ message: `API version ${version} is no longer available${sunsetDate ? `. It was sunset on ${sunsetDate.toISOString().split("T")[0]}` : ""}`,
985
+ code: "VERSION_SUNSET"
986
+ }),
987
+ {
988
+ status: 410,
989
+ headers: { "Content-Type": "application/json" }
990
+ }
991
+ );
992
+ }
993
+ function withAPIVersion(handler, options) {
994
+ return async (req, ctx) => {
995
+ if (options.skip && await options.skip(req)) {
996
+ return handler(req, ctx);
997
+ }
998
+ const result = validateVersion(req, options);
999
+ if (result.status === "sunset") {
1000
+ return defaultSunsetResponse(result.version, result.sunsetDate);
1001
+ }
1002
+ if (!result.valid) {
1003
+ const onUnsupported = options.onUnsupported || ((v) => defaultUnsupportedResponse(v, [options.current, ...options.supported]));
1004
+ return onUnsupported(result.version);
1005
+ }
1006
+ let response = await handler(req, ctx);
1007
+ if (result.status === "deprecated") {
1008
+ if (options.onDeprecated) {
1009
+ options.onDeprecated(result.version, result.sunsetDate);
1010
+ }
1011
+ if (options.addDeprecationHeaders !== false) {
1012
+ response = addDeprecationHeaders(response, result.version, result.sunsetDate);
1013
+ }
1014
+ }
1015
+ return response;
1016
+ };
1017
+ }
1018
+ function createVersionRouter(handlers, options) {
1019
+ const versions = Object.keys(handlers);
1020
+ const defaultVersion = options.default || versions[versions.length - 1];
1021
+ return async (req, ctx) => {
1022
+ const { version } = extractVersion(req, {
1023
+ ...options});
1024
+ const targetVersion = version || defaultVersion;
1025
+ const handler = handlers[targetVersion];
1026
+ if (!handler) {
1027
+ return defaultUnsupportedResponse(targetVersion, versions);
1028
+ }
1029
+ return handler(req, ctx);
1030
+ };
1031
+ }
1032
+ function compareVersions(a, b) {
1033
+ const partsA = a.split(".").map(Number);
1034
+ const partsB = b.split(".").map(Number);
1035
+ const maxLength = Math.max(partsA.length, partsB.length);
1036
+ for (let i = 0; i < maxLength; i++) {
1037
+ const numA = partsA[i] || 0;
1038
+ const numB = partsB[i] || 0;
1039
+ if (numA > numB) return 1;
1040
+ if (numA < numB) return -1;
1041
+ }
1042
+ return 0;
1043
+ }
1044
+ function isVersionAtLeast(version, minimum) {
1045
+ return compareVersions(version, minimum) >= 0;
1046
+ }
1047
+ function normalizeVersion(version) {
1048
+ version = version.replace(/^v/i, "");
1049
+ const parts = version.split(".");
1050
+ while (parts.length < 2) {
1051
+ parts.push("0");
1052
+ }
1053
+ return parts.join(".");
1054
+ }
1055
+
1056
+ // src/middleware/api/idempotency.ts
1057
+ var DEFAULT_IDEMPOTENCY_OPTIONS = {
1058
+ keyHeader: "idempotency-key",
1059
+ ttl: 864e5,
1060
+ // 24 hours
1061
+ required: false,
1062
+ methods: ["POST", "PUT", "PATCH"],
1063
+ minKeyLength: 16,
1064
+ maxKeyLength: 256,
1065
+ hashRequestBody: true,
1066
+ lockTimeout: 3e4,
1067
+ // 30 seconds
1068
+ waitForLock: true,
1069
+ maxWaitTime: 1e4
1070
+ // 10 seconds
1071
+ };
1072
+ var MemoryIdempotencyStore = class {
1073
+ cache = /* @__PURE__ */ new Map();
1074
+ processing = /* @__PURE__ */ new Map();
1075
+ maxSize;
1076
+ cleanupInterval = null;
1077
+ constructor(options = {}) {
1078
+ const { maxSize = 1e4, autoCleanup = true, cleanupIntervalMs = 6e4 } = options;
1079
+ this.maxSize = maxSize;
1080
+ if (autoCleanup) {
1081
+ this.cleanupInterval = setInterval(() => {
1082
+ this.cleanup();
1083
+ }, cleanupIntervalMs);
1084
+ if (this.cleanupInterval.unref) {
1085
+ this.cleanupInterval.unref();
1086
+ }
1087
+ }
1088
+ }
1089
+ async get(key) {
1090
+ const entry = this.cache.get(key);
1091
+ if (!entry) {
1092
+ return null;
1093
+ }
1094
+ if (Date.now() > entry.expiresAt) {
1095
+ this.cache.delete(key);
1096
+ return null;
1097
+ }
1098
+ return entry.response;
1099
+ }
1100
+ async set(key, response, ttl) {
1101
+ if (this.cache.size >= this.maxSize) {
1102
+ this.evictOldest();
1103
+ }
1104
+ this.cache.set(key, {
1105
+ response,
1106
+ expiresAt: Date.now() + ttl
1107
+ });
1108
+ }
1109
+ async isProcessing(key) {
1110
+ const entry = this.processing.get(key);
1111
+ if (!entry) {
1112
+ return false;
1113
+ }
1114
+ if (Date.now() > entry.expiresAt) {
1115
+ this.processing.delete(key);
1116
+ return false;
1117
+ }
1118
+ return true;
1119
+ }
1120
+ async startProcessing(key, timeout) {
1121
+ if (await this.isProcessing(key)) {
1122
+ return false;
1123
+ }
1124
+ const now = Date.now();
1125
+ this.processing.set(key, {
1126
+ startedAt: now,
1127
+ expiresAt: now + timeout
1128
+ });
1129
+ return true;
1130
+ }
1131
+ async endProcessing(key) {
1132
+ this.processing.delete(key);
1133
+ }
1134
+ async delete(key) {
1135
+ this.cache.delete(key);
1136
+ this.processing.delete(key);
1137
+ }
1138
+ async cleanup() {
1139
+ const now = Date.now();
1140
+ for (const [key, entry] of this.cache.entries()) {
1141
+ if (now > entry.expiresAt) {
1142
+ this.cache.delete(key);
1143
+ }
1144
+ }
1145
+ for (const [key, entry] of this.processing.entries()) {
1146
+ if (now > entry.expiresAt) {
1147
+ this.processing.delete(key);
1148
+ }
1149
+ }
1150
+ }
1151
+ getStats() {
1152
+ return {
1153
+ cacheSize: this.cache.size,
1154
+ processingSize: this.processing.size
1155
+ };
1156
+ }
1157
+ evictOldest() {
1158
+ const toRemove = Math.ceil(this.maxSize * 0.1);
1159
+ const entries = Array.from(this.cache.entries()).sort((a, b) => a[1].response.cachedAt - b[1].response.cachedAt).slice(0, toRemove);
1160
+ for (const [key] of entries) {
1161
+ this.cache.delete(key);
1162
+ }
1163
+ }
1164
+ /**
1165
+ * Clear all entries
1166
+ */
1167
+ clear() {
1168
+ this.cache.clear();
1169
+ this.processing.clear();
1170
+ }
1171
+ /**
1172
+ * Stop auto cleanup
1173
+ */
1174
+ destroy() {
1175
+ if (this.cleanupInterval) {
1176
+ clearInterval(this.cleanupInterval);
1177
+ this.cleanupInterval = null;
1178
+ }
1179
+ }
1180
+ };
1181
+ var globalIdempotencyStore = null;
1182
+ function getGlobalIdempotencyStore() {
1183
+ if (!globalIdempotencyStore) {
1184
+ globalIdempotencyStore = new MemoryIdempotencyStore();
1185
+ }
1186
+ return globalIdempotencyStore;
1187
+ }
1188
+ function generateIdempotencyKey(length = 32) {
1189
+ const bytes = new Uint8Array(length);
1190
+ crypto.getRandomValues(bytes);
1191
+ return Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("");
1192
+ }
1193
+ async function hashRequestBody(body) {
1194
+ const encoder = new TextEncoder();
1195
+ const data = encoder.encode(body);
1196
+ const hashBuffer = await crypto.subtle.digest("SHA-256", data);
1197
+ const hashArray = new Uint8Array(hashBuffer);
1198
+ return Array.from(hashArray).map((b) => b.toString(16).padStart(2, "0")).join("");
1199
+ }
1200
+ function isValidIdempotencyKey(key, minLength = 16, maxLength = 256) {
1201
+ if (!key || typeof key !== "string") {
1202
+ return false;
1203
+ }
1204
+ if (key.length < minLength || key.length > maxLength) {
1205
+ return false;
1206
+ }
1207
+ return /^[a-zA-Z0-9_-]+$/.test(key);
1208
+ }
1209
+ async function createCacheKey(idempotencyKey, req, hashBody = true) {
1210
+ const parts = [idempotencyKey, req.method, new URL(req.url).pathname];
1211
+ if (hashBody) {
1212
+ try {
1213
+ const cloned = req.clone();
1214
+ const body = await cloned.text();
1215
+ if (body) {
1216
+ const bodyHash = await hashRequestBody(body);
1217
+ parts.push(bodyHash);
1218
+ }
1219
+ } catch {
1220
+ }
1221
+ }
1222
+ return parts.join(":");
1223
+ }
1224
+ function extractIdempotencyKey(req, options = {}) {
1225
+ const { keyHeader = DEFAULT_IDEMPOTENCY_OPTIONS.keyHeader } = options;
1226
+ return req.headers.get(keyHeader);
1227
+ }
1228
+ async function checkIdempotency(req, options = {}) {
1229
+ const {
1230
+ store = getGlobalIdempotencyStore(),
1231
+ keyHeader = DEFAULT_IDEMPOTENCY_OPTIONS.keyHeader,
1232
+ required = DEFAULT_IDEMPOTENCY_OPTIONS.required,
1233
+ methods = DEFAULT_IDEMPOTENCY_OPTIONS.methods,
1234
+ minKeyLength = DEFAULT_IDEMPOTENCY_OPTIONS.minKeyLength,
1235
+ maxKeyLength = DEFAULT_IDEMPOTENCY_OPTIONS.maxKeyLength,
1236
+ hashRequestBody: hashBody = DEFAULT_IDEMPOTENCY_OPTIONS.hashRequestBody,
1237
+ validateKey
1238
+ } = options;
1239
+ const method = req.method.toUpperCase();
1240
+ if (!methods.includes(method)) {
1241
+ return {
1242
+ key: null,
1243
+ fromCache: false,
1244
+ isProcessing: false
1245
+ };
1246
+ }
1247
+ const key = req.headers.get(keyHeader);
1248
+ if (!key) {
1249
+ if (required) {
1250
+ return {
1251
+ key: null,
1252
+ fromCache: false,
1253
+ isProcessing: false,
1254
+ reason: "Missing idempotency key"
1255
+ };
1256
+ }
1257
+ return {
1258
+ key: null,
1259
+ fromCache: false,
1260
+ isProcessing: false
1261
+ };
1262
+ }
1263
+ if (!isValidIdempotencyKey(key, minKeyLength, maxKeyLength)) {
1264
+ return {
1265
+ key,
1266
+ fromCache: false,
1267
+ isProcessing: false,
1268
+ reason: `Invalid idempotency key format (length must be ${minKeyLength}-${maxKeyLength}, alphanumeric)`
1269
+ };
1270
+ }
1271
+ if (validateKey) {
1272
+ const isValid = await validateKey(key);
1273
+ if (!isValid) {
1274
+ return {
1275
+ key,
1276
+ fromCache: false,
1277
+ isProcessing: false,
1278
+ reason: "Idempotency key failed custom validation"
1279
+ };
1280
+ }
1281
+ }
1282
+ const cacheKey = await createCacheKey(key, req, hashBody);
1283
+ const cached = await store.get(cacheKey);
1284
+ if (cached) {
1285
+ return {
1286
+ key,
1287
+ fromCache: true,
1288
+ cachedResponse: cached,
1289
+ isProcessing: false
1290
+ };
1291
+ }
1292
+ const isProcessing = await store.isProcessing(cacheKey);
1293
+ return {
1294
+ key,
1295
+ fromCache: false,
1296
+ isProcessing,
1297
+ reason: isProcessing ? "Request is currently being processed" : void 0
1298
+ };
1299
+ }
1300
+ async function cacheResponse(key, req, response, options = {}) {
1301
+ const {
1302
+ store = getGlobalIdempotencyStore(),
1303
+ ttl = DEFAULT_IDEMPOTENCY_OPTIONS.ttl,
1304
+ hashRequestBody: hashBody = DEFAULT_IDEMPOTENCY_OPTIONS.hashRequestBody
1305
+ } = options;
1306
+ const cacheKey = await createCacheKey(key, req, hashBody);
1307
+ const cloned = response.clone();
1308
+ const body = await cloned.text();
1309
+ const headers = {};
1310
+ response.headers.forEach((value, name) => {
1311
+ headers[name] = value;
1312
+ });
1313
+ const cachedResponse = {
1314
+ status: response.status,
1315
+ headers,
1316
+ body,
1317
+ cachedAt: Date.now()
1318
+ };
1319
+ await store.set(cacheKey, cachedResponse, ttl);
1320
+ await store.endProcessing(cacheKey);
1321
+ }
1322
+ function createResponseFromCache(cached) {
1323
+ const headers = new Headers(cached.headers);
1324
+ headers.set("x-idempotency-replayed", "true");
1325
+ headers.set("x-idempotency-cached-at", new Date(cached.cachedAt).toISOString());
1326
+ return new Response(cached.body, {
1327
+ status: cached.status,
1328
+ headers
1329
+ });
1330
+ }
1331
+ function defaultErrorResponse(reason) {
1332
+ return new Response(
1333
+ JSON.stringify({
1334
+ error: "Bad Request",
1335
+ message: reason,
1336
+ code: "IDEMPOTENCY_ERROR"
1337
+ }),
1338
+ {
1339
+ status: 400,
1340
+ headers: { "Content-Type": "application/json" }
1341
+ }
1342
+ );
1343
+ }
1344
+ async function waitForLock(store, cacheKey, maxWaitTime, pollInterval = 100) {
1345
+ const startTime = Date.now();
1346
+ while (Date.now() - startTime < maxWaitTime) {
1347
+ const cached = await store.get(cacheKey);
1348
+ if (cached) {
1349
+ return cached;
1350
+ }
1351
+ const isProcessing = await store.isProcessing(cacheKey);
1352
+ if (!isProcessing) {
1353
+ return null;
1354
+ }
1355
+ await new Promise((resolve) => setTimeout(resolve, pollInterval));
1356
+ }
1357
+ return null;
1358
+ }
1359
+ function withIdempotency(handler, options = {}) {
1360
+ return async (req, ctx) => {
1361
+ if (options.skip && await options.skip(req)) {
1362
+ return handler(req, ctx);
1363
+ }
1364
+ const {
1365
+ store = getGlobalIdempotencyStore(),
1366
+ methods = DEFAULT_IDEMPOTENCY_OPTIONS.methods,
1367
+ hashRequestBody: hashBody = DEFAULT_IDEMPOTENCY_OPTIONS.hashRequestBody,
1368
+ lockTimeout = DEFAULT_IDEMPOTENCY_OPTIONS.lockTimeout,
1369
+ waitForLock: shouldWait = DEFAULT_IDEMPOTENCY_OPTIONS.waitForLock,
1370
+ maxWaitTime = DEFAULT_IDEMPOTENCY_OPTIONS.maxWaitTime,
1371
+ onError,
1372
+ onCacheHit
1373
+ } = options;
1374
+ const method = req.method.toUpperCase();
1375
+ if (!methods.includes(method)) {
1376
+ return handler(req, ctx);
1377
+ }
1378
+ const result = await checkIdempotency(req, options);
1379
+ if (result.reason && !result.isProcessing) {
1380
+ const errorHandler = onError || defaultErrorResponse;
1381
+ return errorHandler(result.reason);
1382
+ }
1383
+ if (result.fromCache && result.cachedResponse) {
1384
+ if (onCacheHit) {
1385
+ onCacheHit(result.key, result.cachedResponse);
1386
+ }
1387
+ return createResponseFromCache(result.cachedResponse);
1388
+ }
1389
+ if (!result.key) {
1390
+ return handler(req, ctx);
1391
+ }
1392
+ const cacheKey = await createCacheKey(result.key, req, hashBody);
1393
+ if (result.isProcessing) {
1394
+ if (shouldWait) {
1395
+ const cached = await waitForLock(store, cacheKey, maxWaitTime);
1396
+ if (cached) {
1397
+ if (onCacheHit) {
1398
+ onCacheHit(result.key, cached);
1399
+ }
1400
+ return createResponseFromCache(cached);
1401
+ }
1402
+ }
1403
+ return new Response(
1404
+ JSON.stringify({
1405
+ error: "Conflict",
1406
+ message: "Request with this idempotency key is currently being processed",
1407
+ code: "IDEMPOTENCY_CONFLICT"
1408
+ }),
1409
+ {
1410
+ status: 409,
1411
+ headers: { "Content-Type": "application/json" }
1412
+ }
1413
+ );
1414
+ }
1415
+ const acquired = await store.startProcessing(cacheKey, lockTimeout);
1416
+ if (!acquired) {
1417
+ if (shouldWait) {
1418
+ const cached = await waitForLock(store, cacheKey, maxWaitTime);
1419
+ if (cached) {
1420
+ if (onCacheHit) {
1421
+ onCacheHit(result.key, cached);
1422
+ }
1423
+ return createResponseFromCache(cached);
1424
+ }
1425
+ }
1426
+ return new Response(
1427
+ JSON.stringify({
1428
+ error: "Conflict",
1429
+ message: "Request with this idempotency key is currently being processed",
1430
+ code: "IDEMPOTENCY_CONFLICT"
1431
+ }),
1432
+ {
1433
+ status: 409,
1434
+ headers: { "Content-Type": "application/json" }
1435
+ }
1436
+ );
1437
+ }
1438
+ try {
1439
+ const response = await handler(req, ctx);
1440
+ if (response.status >= 200 && response.status < 300) {
1441
+ await cacheResponse(result.key, req, response, options);
1442
+ } else {
1443
+ await store.endProcessing(cacheKey);
1444
+ }
1445
+ return response;
1446
+ } catch (error) {
1447
+ await store.endProcessing(cacheKey);
1448
+ throw error;
1449
+ }
1450
+ };
1451
+ }
1452
+ function addIdempotencyHeader(headers = {}, options = {}) {
1453
+ const { headerName = "idempotency-key", key = generateIdempotencyKey() } = options;
1454
+ return {
1455
+ ...headers,
1456
+ [headerName]: key
1457
+ };
1458
+ }
1459
+
1460
+ // src/middleware/api/middleware.ts
1461
+ async function checkAPIProtection(req, options) {
1462
+ const result = {
1463
+ passed: true
1464
+ };
1465
+ if (options.timestamp !== false) {
1466
+ const timestampResult = validateTimestamp(req, options.timestamp);
1467
+ result.timestamp = timestampResult;
1468
+ if (!timestampResult.valid) {
1469
+ result.passed = false;
1470
+ result.error = {
1471
+ type: "timestamp",
1472
+ message: timestampResult.reason || "Invalid timestamp"
1473
+ };
1474
+ return result;
1475
+ }
1476
+ }
1477
+ if (options.replay !== false) {
1478
+ const replayOpts = options.replay;
1479
+ const replayResult = await checkReplay(req, {
1480
+ ...replayOpts,
1481
+ store: replayOpts.store || getGlobalNonceStore()
1482
+ });
1483
+ result.replay = replayResult;
1484
+ if (replayResult.isReplay) {
1485
+ result.passed = false;
1486
+ result.error = {
1487
+ type: "replay",
1488
+ message: "Request replay detected",
1489
+ details: { nonce: replayResult.nonce }
1490
+ };
1491
+ return result;
1492
+ }
1493
+ if (replayResult.reason && replayOpts.required !== false) {
1494
+ result.passed = false;
1495
+ result.error = {
1496
+ type: "replay",
1497
+ message: replayResult.reason
1498
+ };
1499
+ return result;
1500
+ }
1501
+ }
1502
+ if (options.signing !== false) {
1503
+ const signingOpts = options.signing;
1504
+ const signingResult = await verifySignature(req, signingOpts);
1505
+ result.signing = signingResult;
1506
+ if (!signingResult.valid) {
1507
+ result.passed = false;
1508
+ result.error = {
1509
+ type: "signing",
1510
+ message: signingResult.reason || "Invalid signature"
1511
+ };
1512
+ return result;
1513
+ }
1514
+ }
1515
+ if (options.versioning !== false) {
1516
+ const versioningOpts = options.versioning;
1517
+ const versionResult = validateVersion(req, versioningOpts);
1518
+ result.version = versionResult;
1519
+ if (!versionResult.valid) {
1520
+ result.passed = false;
1521
+ result.error = {
1522
+ type: "versioning",
1523
+ message: versionResult.reason || "Unsupported version",
1524
+ details: { version: versionResult.version }
1525
+ };
1526
+ return result;
1527
+ }
1528
+ }
1529
+ if (options.idempotency !== false) {
1530
+ const idempotencyOpts = options.idempotency;
1531
+ const idempotencyResult = await checkIdempotency(req, {
1532
+ ...idempotencyOpts,
1533
+ store: idempotencyOpts.store || getGlobalIdempotencyStore()
1534
+ });
1535
+ result.idempotency = idempotencyResult;
1536
+ if (idempotencyResult.reason && !idempotencyResult.isProcessing && !idempotencyResult.fromCache) {
1537
+ if (idempotencyOpts.required) {
1538
+ result.passed = false;
1539
+ result.error = {
1540
+ type: "idempotency",
1541
+ message: idempotencyResult.reason,
1542
+ details: { key: idempotencyResult.key }
1543
+ };
1544
+ return result;
1545
+ }
1546
+ }
1547
+ }
1548
+ return result;
1549
+ }
1550
+ function defaultErrorResponse2(error) {
1551
+ const statusMap = {
1552
+ signing: 401,
1553
+ replay: 403,
1554
+ timestamp: 400,
1555
+ versioning: 400,
1556
+ idempotency: 400
1557
+ };
1558
+ const codeMap = {
1559
+ signing: "INVALID_SIGNATURE",
1560
+ replay: "REPLAY_DETECTED",
1561
+ timestamp: "INVALID_TIMESTAMP",
1562
+ versioning: "UNSUPPORTED_VERSION",
1563
+ idempotency: "IDEMPOTENCY_ERROR"
1564
+ };
1565
+ return new Response(
1566
+ JSON.stringify({
1567
+ error: error.type === "signing" ? "Unauthorized" : error.type === "replay" ? "Forbidden" : "Bad Request",
1568
+ message: error.message,
1569
+ code: codeMap[error.type],
1570
+ ...error.details || {}
1571
+ }),
1572
+ {
1573
+ status: statusMap[error.type],
1574
+ headers: { "Content-Type": "application/json" }
1575
+ }
1576
+ );
1577
+ }
1578
+ function withAPIProtection(handler, options) {
1579
+ return async (req, ctx) => {
1580
+ if (options.skip && await options.skip(req)) {
1581
+ return handler(req, ctx);
1582
+ }
1583
+ const result = await checkAPIProtection(req, options);
1584
+ if (!result.passed && result.error) {
1585
+ const onError = options.onError || defaultErrorResponse2;
1586
+ return onError(result.error);
1587
+ }
1588
+ if (result.idempotency?.fromCache && result.idempotency.cachedResponse) {
1589
+ const idempotencyOpts = options.idempotency;
1590
+ if (idempotencyOpts.onCacheHit) {
1591
+ idempotencyOpts.onCacheHit(result.idempotency.key, result.idempotency.cachedResponse);
1592
+ }
1593
+ return createResponseFromCache(result.idempotency.cachedResponse);
1594
+ }
1595
+ if (result.idempotency?.isProcessing) {
1596
+ return new Response(
1597
+ JSON.stringify({
1598
+ error: "Conflict",
1599
+ message: "Request with this idempotency key is currently being processed",
1600
+ code: "IDEMPOTENCY_CONFLICT"
1601
+ }),
1602
+ {
1603
+ status: 409,
1604
+ headers: { "Content-Type": "application/json" }
1605
+ }
1606
+ );
1607
+ }
1608
+ let response = await handler(req, ctx);
1609
+ if (result.version?.status === "deprecated") {
1610
+ const versioningOpts = options.versioning;
1611
+ if (versioningOpts.addDeprecationHeaders !== false) {
1612
+ response = addDeprecationHeaders(response, result.version.version, result.version.sunsetDate);
1613
+ }
1614
+ if (versioningOpts.onDeprecated) {
1615
+ versioningOpts.onDeprecated(result.version.version, result.version.sunsetDate);
1616
+ }
1617
+ }
1618
+ if (result.idempotency?.key && options.idempotency !== false) {
1619
+ const idempotencyOpts = options.idempotency;
1620
+ if (response.status >= 200 && response.status < 300) {
1621
+ await cacheResponse(result.idempotency.key, req, response, idempotencyOpts);
1622
+ }
1623
+ }
1624
+ return response;
1625
+ };
1626
+ }
1627
+ function withAPIProtectionPreset(handler, preset, overrides = {}) {
1628
+ const presetConfig = API_PROTECTION_PRESETS[preset];
1629
+ const mergedOptions = {
1630
+ ...presetConfig,
1631
+ ...overrides
1632
+ };
1633
+ if (presetConfig.signing && typeof presetConfig.signing === "object" && overrides.signing && typeof overrides.signing === "object") {
1634
+ mergedOptions.signing = { ...presetConfig.signing, ...overrides.signing };
1635
+ }
1636
+ if (presetConfig.replay && typeof presetConfig.replay === "object" && overrides.replay && typeof overrides.replay === "object") {
1637
+ mergedOptions.replay = { ...presetConfig.replay, ...overrides.replay };
1638
+ }
1639
+ if (presetConfig.timestamp && typeof presetConfig.timestamp === "object" && overrides.timestamp && typeof overrides.timestamp === "object") {
1640
+ mergedOptions.timestamp = { ...presetConfig.timestamp, ...overrides.timestamp };
1641
+ }
1642
+ if (presetConfig.idempotency && typeof presetConfig.idempotency === "object" && overrides.idempotency && typeof overrides.idempotency === "object") {
1643
+ mergedOptions.idempotency = { ...presetConfig.idempotency, ...overrides.idempotency };
1644
+ }
1645
+ return withAPIProtection(handler, mergedOptions);
1646
+ }
1647
+
1648
+ export { API_PROTECTION_PRESETS, DEFAULT_IDEMPOTENCY_OPTIONS, DEFAULT_REPLAY_OPTIONS, DEFAULT_SIGNING_OPTIONS, DEFAULT_TIMESTAMP_OPTIONS, DEFAULT_VERSIONING_OPTIONS, MemoryIdempotencyStore, MemoryNonceStore, addDeprecationHeaders, addIdempotencyHeader, addNonceHeader, addTimestampHeader, buildCanonicalString, cacheResponse, checkAPIProtection, checkIdempotency, checkReplay, compareVersions, createCacheKey, createHMAC, generateNonce as createNonce, createResponseFromCache, createVersionRouter, extractIdempotencyKey, extractNonce, extractTimestamp, extractVersion, extractVersionMultiSource, formatTimestamp, generateIdempotencyKey, generateNonce2 as generateNonce, generateSignature, generateSignatureHeaders, getGlobalIdempotencyStore, getGlobalNonceStore, getRequestAge, getVersionStatus, hashRequestBody, isTimestampValid, isValidIdempotencyKey, isValidNonceFormat, isVersionAtLeast, isVersionSupported, normalizeVersion, parseTimestamp, timingSafeEqual, validateTimestamp, validateVersion, verifySignature, withAPIProtection, withAPIProtectionPreset, withAPIVersion, withIdempotency, withReplayPrevention, withRequestSigning, withTimestamp };
1649
+ //# sourceMappingURL=api.js.map
1650
+ //# sourceMappingURL=api.js.map