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