@stacksjs/bun-router 0.0.17 → 0.0.19

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.
Files changed (153) hide show
  1. package/dist/chunk-2mx7fq49.js +4 -0
  2. package/dist/chunk-a8p83068.js +103 -0
  3. package/dist/{chunk-cgptvjdf.js → chunk-y3xq6wq6.js} +1 -1
  4. package/dist/cli.js +4 -3
  5. package/dist/container/index.js +1149 -211
  6. package/dist/container/service-provider.d.ts +3 -3
  7. package/dist/development/performance-profiler.d.ts +3 -3
  8. package/dist/development/route-debugger.d.ts +1 -1
  9. package/dist/development/route-inspector.d.ts +2 -2
  10. package/dist/index.js +369 -2209
  11. package/dist/observability/integration.d.ts +1 -1
  12. package/dist/response/macros.d.ts +1 -1
  13. package/dist/router/index.d.ts +7 -7
  14. package/dist/router/router.d.ts +0 -32
  15. package/dist/testing/performance-testing.d.ts +2 -2
  16. package/dist/testing/test-client.d.ts +1 -1
  17. package/dist/testing/websocket-testing.d.ts +1 -1
  18. package/package.json +7 -7
  19. package/dist/chunk-1ahs68ys.js +0 -18
  20. package/dist/chunk-g3ybefhg.js +0 -1923
  21. package/src/auth.ts +0 -489
  22. package/src/cache/lru-cache.ts +0 -457
  23. package/src/cache/middleware-memoization.ts +0 -531
  24. package/src/cache/route-cache-warmer.ts +0 -486
  25. package/src/cache/sqlite-cache.ts +0 -783
  26. package/src/cache/streaming-cache.ts +0 -572
  27. package/src/cli/colors.ts +0 -29
  28. package/src/cli/index.ts +0 -287
  29. package/src/cli/middleware.ts +0 -291
  30. package/src/cli/openapi.ts +0 -407
  31. package/src/cli/router.ts +0 -188
  32. package/src/cli/routes.ts +0 -265
  33. package/src/cli/utils.ts +0 -531
  34. package/src/cli.ts +0 -5
  35. package/src/config.ts +0 -322
  36. package/src/container/container.ts +0 -786
  37. package/src/container/contextual-binding.ts +0 -606
  38. package/src/container/decorators.ts +0 -368
  39. package/src/container/index.ts +0 -49
  40. package/src/container/service-provider.ts +0 -596
  41. package/src/development/hot-reload.ts +0 -673
  42. package/src/development/index.ts +0 -499
  43. package/src/development/performance-profiler.ts +0 -717
  44. package/src/development/route-debugger.ts +0 -527
  45. package/src/development/route-inspector.ts +0 -749
  46. package/src/development/typescript-utilities.ts +0 -682
  47. package/src/docs.ts +0 -397
  48. package/src/errors/circuit-breaker.ts +0 -733
  49. package/src/errors/error-handler.ts +0 -569
  50. package/src/errors/error-reporting.ts +0 -672
  51. package/src/errors/exceptions.ts +0 -536
  52. package/src/errors/graceful-degradation.ts +0 -623
  53. package/src/errors/index.ts +0 -21
  54. package/src/errors/router-errors.ts +0 -632
  55. package/src/file-serving/static-files.ts +0 -718
  56. package/src/index.ts +0 -66
  57. package/src/middleware/auth.ts +0 -220
  58. package/src/middleware/content_security_policy.ts +0 -215
  59. package/src/middleware/cors.ts +0 -142
  60. package/src/middleware/csrf.ts +0 -166
  61. package/src/middleware/ddos_protection.ts +0 -279
  62. package/src/middleware/file_security.ts +0 -191
  63. package/src/middleware/file_upload.ts +0 -275
  64. package/src/middleware/helmet.ts +0 -268
  65. package/src/middleware/index.ts +0 -117
  66. package/src/middleware/input_validation.ts +0 -453
  67. package/src/middleware/json_body.ts +0 -37
  68. package/src/middleware/performance_alerting.ts +0 -540
  69. package/src/middleware/performance_dashboard.ts +0 -661
  70. package/src/middleware/performance_monitor.ts +0 -945
  71. package/src/middleware/pipeline.ts +0 -489
  72. package/src/middleware/rate_limit.ts +0 -251
  73. package/src/middleware/request_id.ts +0 -36
  74. package/src/middleware/request_signing.ts +0 -638
  75. package/src/middleware/request_tracer.ts +0 -653
  76. package/src/middleware/response_cache.ts +0 -778
  77. package/src/middleware/security.ts +0 -482
  78. package/src/middleware/security_suite.ts +0 -257
  79. package/src/middleware/session.ts +0 -91
  80. package/src/model-binding/index.ts +0 -18
  81. package/src/model-binding/model-middleware.ts +0 -425
  82. package/src/model-binding/model-registry.ts +0 -550
  83. package/src/model-binding.ts +0 -370
  84. package/src/model-resolver-factory.ts +0 -106
  85. package/src/observability/correlation.ts +0 -691
  86. package/src/observability/health-checks.ts +0 -729
  87. package/src/observability/index.ts +0 -184
  88. package/src/observability/integration.ts +0 -548
  89. package/src/observability/metrics.ts +0 -753
  90. package/src/observability/tracing.ts +0 -638
  91. package/src/optimization/bun-utilities.ts +0 -778
  92. package/src/query-builder-integration.ts +0 -137
  93. package/src/request/context.ts +0 -109
  94. package/src/request/enhanced-request.ts +0 -876
  95. package/src/request/macros.ts +0 -822
  96. package/src/response/macros.ts +0 -665
  97. package/src/response/response-factory.ts +0 -596
  98. package/src/router/api-routes.ts +0 -243
  99. package/src/router/file-based-routing.ts +0 -697
  100. package/src/router/file-streaming.ts +0 -383
  101. package/src/router/fluent-routing.ts +0 -866
  102. package/src/router/group-organization.ts +0 -229
  103. package/src/router/handler-resolver.ts +0 -327
  104. package/src/router/http-methods.ts +0 -407
  105. package/src/router/index.ts +0 -193
  106. package/src/router/middleware-groups.ts +0 -222
  107. package/src/router/middleware-integration.ts +0 -399
  108. package/src/router/middleware.ts +0 -234
  109. package/src/router/model-binding.ts +0 -215
  110. package/src/router/optimized-route-matching.ts +0 -302
  111. package/src/router/route-building.ts +0 -221
  112. package/src/router/route-compiler.ts +0 -691
  113. package/src/router/route-matching.ts +0 -368
  114. package/src/router/route-trie.ts +0 -450
  115. package/src/router/router.ts +0 -1616
  116. package/src/router/server.ts +0 -684
  117. package/src/router/validation-integration.ts +0 -449
  118. package/src/router/view-rendering.ts +0 -233
  119. package/src/router/websocket.ts +0 -100
  120. package/src/routing/route-caching.ts +0 -402
  121. package/src/routing/route-throttling.ts +0 -469
  122. package/src/routing/subdomain-routing.ts +0 -492
  123. package/src/session/database-store.ts +0 -109
  124. package/src/session/file-store.ts +0 -148
  125. package/src/session/index.ts +0 -244
  126. package/src/session/memory-store.ts +0 -88
  127. package/src/session/redis-store.ts +0 -93
  128. package/src/streaming/index.ts +0 -17
  129. package/src/streaming/sse-handler.ts +0 -482
  130. package/src/streaming/stream-handler.ts +0 -552
  131. package/src/testing/auth-testing.ts +0 -448
  132. package/src/testing/file-upload-testing.ts +0 -543
  133. package/src/testing/index.ts +0 -10
  134. package/src/testing/middleware-testing.ts +0 -322
  135. package/src/testing/model-binding-testing.ts +0 -645
  136. package/src/testing/performance-testing.ts +0 -738
  137. package/src/testing/test-client.ts +0 -310
  138. package/src/testing/test-request.ts +0 -315
  139. package/src/testing/test-response.ts +0 -332
  140. package/src/testing/types.ts +0 -224
  141. package/src/testing/websocket-testing.ts +0 -590
  142. package/src/types/controller-types.ts +0 -385
  143. package/src/types/core.ts +0 -683
  144. package/src/types/middleware-types.ts +0 -422
  145. package/src/types/request-response-augmentation.ts +0 -489
  146. package/src/types/route-inference.ts +0 -372
  147. package/src/types.ts +0 -2123
  148. package/src/url.ts +0 -131
  149. package/src/utils/index.ts +0 -1
  150. package/src/utils/query-preservation.ts +0 -201
  151. package/src/utils.ts +0 -395
  152. package/src/validation/validator.ts +0 -688
  153. package/src/websocket/clustering.ts +0 -769
@@ -1,638 +0,0 @@
1
- /**
2
- * Request Signing Middleware
3
- *
4
- * Provides HMAC-based request signature verification for secure API authentication.
5
- * Supports multiple algorithms, timestamp validation, and replay attack prevention.
6
- */
7
-
8
- import type { EnhancedRequest, Middleware, NextFunction } from '../types'
9
-
10
- export type SignatureAlgorithm = 'sha256' | 'sha384' | 'sha512'
11
-
12
- export interface RequestSigningOptions {
13
- /**
14
- * Secret key(s) for HMAC verification.
15
- * Can be a single key or a function that returns the key based on key ID.
16
- */
17
- secret: string | ((_keyId: string) => string | Promise<string | null> | null)
18
-
19
- /**
20
- * HMAC algorithm to use
21
- * @default 'sha256'
22
- */
23
- algorithm?: SignatureAlgorithm
24
-
25
- /**
26
- * Header name containing the signature
27
- * @default 'X-Signature'
28
- */
29
- signatureHeader?: string
30
-
31
- /**
32
- * Header name containing the timestamp
33
- * @default 'X-Timestamp'
34
- */
35
- timestampHeader?: string
36
-
37
- /**
38
- * Header name containing the key ID (for multi-key setups)
39
- * @default 'X-Key-Id'
40
- */
41
- keyIdHeader?: string
42
-
43
- /**
44
- * Header name containing the nonce (for replay protection)
45
- * @default 'X-Nonce'
46
- */
47
- nonceHeader?: string
48
-
49
- /**
50
- * Maximum age of request in seconds (timestamp validation)
51
- * @default 300 (5 minutes)
52
- */
53
- maxAge?: number
54
-
55
- /**
56
- * Whether to require timestamp validation
57
- * @default true
58
- */
59
- requireTimestamp?: boolean
60
-
61
- /**
62
- * Whether to require nonce for replay protection
63
- * @default false
64
- */
65
- requireNonce?: boolean
66
-
67
- /**
68
- * Custom function to check if nonce has been used (for replay protection)
69
- */
70
- nonceStore?: NonceStore
71
-
72
- /**
73
- * Parts of the request to include in signature
74
- * @default ['method', 'path', 'timestamp', 'body']
75
- */
76
- signedParts?: SignedPart[]
77
-
78
- /**
79
- * Custom function to build the string to sign
80
- */
81
- stringToSign?: (req: EnhancedRequest, timestamp: string, nonce?: string) => Promise<string> | string
82
-
83
- /**
84
- * Custom error handler
85
- */
86
- onError?: (error: SignatureError, req: EnhancedRequest) => Response | Promise<Response>
87
-
88
- /**
89
- * Skip signature verification for certain paths
90
- */
91
- exclude?: string[] | ((_req: EnhancedRequest) => boolean)
92
-
93
- /**
94
- * Additional headers to include in signature
95
- */
96
- signedHeaders?: string[]
97
-
98
- /**
99
- * Signature encoding format
100
- * @default 'hex'
101
- */
102
- encoding?: 'hex' | 'base64'
103
- }
104
-
105
- export type SignedPart = 'method' | 'path' | 'query' | 'timestamp' | 'body' | 'nonce' | 'headers'
106
-
107
- export interface NonceStore {
108
- /**
109
- * Check if nonce exists (has been used)
110
- */
111
- has: (nonce: string) => Promise<boolean> | boolean
112
-
113
- /**
114
- * Store a nonce
115
- */
116
- set: (nonce: string, expiry?: number) => Promise<void> | void
117
- }
118
-
119
- export type SignatureErrorCode =
120
- | 'MISSING_SIGNATURE'
121
- | 'MISSING_TIMESTAMP'
122
- | 'MISSING_NONCE'
123
- | 'MISSING_KEY_ID'
124
- | 'INVALID_KEY'
125
- | 'INVALID_SIGNATURE'
126
- | 'EXPIRED_TIMESTAMP'
127
- | 'FUTURE_TIMESTAMP'
128
- | 'NONCE_REUSED'
129
- | 'SIGNATURE_MISMATCH'
130
-
131
- export class SignatureError extends Error {
132
- public readonly code: SignatureErrorCode
133
- public readonly statusCode: number
134
-
135
- constructor(code: SignatureErrorCode, message: string) {
136
- super(message)
137
- this.name = 'SignatureError'
138
- this.code = code
139
- this.statusCode = 401
140
- }
141
- }
142
-
143
- /**
144
- * In-memory nonce store with automatic expiry
145
- */
146
- export class InMemoryNonceStore implements NonceStore {
147
- private nonces = new Map<string, number>()
148
- private cleanupInterval: ReturnType<typeof setInterval> | null = null
149
-
150
- constructor(cleanupIntervalMs: number = 60000) {
151
- this.cleanupInterval = setInterval(() => this.cleanup(), cleanupIntervalMs)
152
- // Background housekeeping must not keep the process alive
153
- this.cleanupInterval.unref?.()
154
- }
155
-
156
- has(nonce: string): boolean {
157
- const expiry = this.nonces.get(nonce)
158
- if (expiry === undefined)
159
- return false
160
- if (Date.now() > expiry) {
161
- this.nonces.delete(nonce)
162
- return false
163
- }
164
- return true
165
- }
166
-
167
- set(nonce: string, expirySeconds: number = 300): void {
168
- this.nonces.set(nonce, Date.now() + expirySeconds * 1000)
169
- }
170
-
171
- private cleanup(): void {
172
- const now = Date.now()
173
- for (const [nonce, expiry] of this.nonces.entries()) {
174
- if (now > expiry) {
175
- this.nonces.delete(nonce)
176
- }
177
- }
178
- }
179
-
180
- destroy(): void {
181
- if (this.cleanupInterval) {
182
- clearInterval(this.cleanupInterval)
183
- this.cleanupInterval = null
184
- }
185
- this.nonces.clear()
186
- }
187
- }
188
-
189
- /**
190
- * Request Signing Middleware
191
- */
192
- export default class RequestSigning implements Middleware {
193
- private options: Required<Omit<RequestSigningOptions, 'onError' | 'exclude' | 'nonceStore' | 'stringToSign'>> & {
194
- onError?: RequestSigningOptions['onError']
195
- exclude?: RequestSigningOptions['exclude']
196
- nonceStore?: NonceStore
197
- stringToSign?: RequestSigningOptions['stringToSign']
198
- }
199
-
200
- constructor(options: RequestSigningOptions) {
201
- this.options = {
202
- secret: options.secret,
203
- algorithm: options.algorithm ?? 'sha256',
204
- signatureHeader: options.signatureHeader ?? 'X-Signature',
205
- timestampHeader: options.timestampHeader ?? 'X-Timestamp',
206
- keyIdHeader: options.keyIdHeader ?? 'X-Key-Id',
207
- nonceHeader: options.nonceHeader ?? 'X-Nonce',
208
- maxAge: options.maxAge ?? 300,
209
- requireTimestamp: options.requireTimestamp ?? true,
210
- requireNonce: options.requireNonce ?? false,
211
- signedParts: options.signedParts ?? ['method', 'path', 'timestamp', 'body'],
212
- signedHeaders: options.signedHeaders ?? [],
213
- encoding: options.encoding ?? 'hex',
214
- onError: options.onError,
215
- exclude: options.exclude,
216
- nonceStore: options.nonceStore,
217
- stringToSign: options.stringToSign,
218
- }
219
- }
220
-
221
- async handle(req: EnhancedRequest, next: NextFunction): Promise<Response | null> {
222
- // Check exclusions
223
- if (this.shouldSkip(req)) {
224
- return next()
225
- }
226
-
227
- try {
228
- await this.verifySignature(req)
229
- return next()
230
- }
231
- catch (error) {
232
- if (error instanceof SignatureError) {
233
- if (this.options.onError) {
234
- return this.options.onError(error, req)
235
- }
236
- return this.defaultErrorResponse(error)
237
- }
238
- throw error
239
- }
240
- }
241
-
242
- private shouldSkip(req: EnhancedRequest): boolean {
243
- if (!this.options.exclude)
244
- return false
245
-
246
- if (typeof this.options.exclude === 'function') {
247
- return this.options.exclude(req)
248
- }
249
-
250
- const url = new URL(req.url)
251
- return this.options.exclude.some(path =>
252
- url.pathname === path || url.pathname.startsWith(`${path}/`),
253
- )
254
- }
255
-
256
- private async verifySignature(req: EnhancedRequest): Promise<void> {
257
- // Get signature from header
258
- const signature = req.headers.get(this.options.signatureHeader)
259
- if (!signature) {
260
- throw new SignatureError('MISSING_SIGNATURE', `Missing ${this.options.signatureHeader} header`)
261
- }
262
-
263
- // Get and validate timestamp
264
- const timestamp = req.headers.get(this.options.timestampHeader)
265
- if (this.options.requireTimestamp) {
266
- if (!timestamp) {
267
- throw new SignatureError('MISSING_TIMESTAMP', `Missing ${this.options.timestampHeader} header`)
268
- }
269
- this.validateTimestamp(timestamp)
270
- }
271
-
272
- // Get and validate nonce
273
- const nonce = req.headers.get(this.options.nonceHeader)
274
- if (this.options.requireNonce) {
275
- if (!nonce) {
276
- throw new SignatureError('MISSING_NONCE', `Missing ${this.options.nonceHeader} header`)
277
- }
278
- await this.validateNonce(nonce)
279
- }
280
-
281
- // Get secret key
282
- const secret = await this.getSecret(req)
283
- if (!secret) {
284
- throw new SignatureError('INVALID_KEY', 'Invalid or missing API key')
285
- }
286
-
287
- // Build string to sign
288
- const stringToSign = await this.buildStringToSign(req, timestamp || '', nonce || undefined)
289
-
290
- // Calculate expected signature
291
- const expectedSignature = await this.calculateSignature(stringToSign, secret)
292
-
293
- // Compare signatures (timing-safe)
294
- if (!this.timingSafeEqual(signature, expectedSignature)) {
295
- throw new SignatureError('SIGNATURE_MISMATCH', 'Invalid signature')
296
- }
297
-
298
- // Store nonce if replay protection is enabled
299
- if (this.options.requireNonce && nonce && this.options.nonceStore) {
300
- await this.options.nonceStore.set(nonce, this.options.maxAge)
301
- }
302
- }
303
-
304
- private async getSecret(req: EnhancedRequest): Promise<string | null> {
305
- if (typeof this.options.secret === 'string') {
306
- return this.options.secret
307
- }
308
-
309
- const keyId = req.headers.get(this.options.keyIdHeader)
310
- if (!keyId) {
311
- throw new SignatureError('MISSING_KEY_ID', `Missing ${this.options.keyIdHeader} header`)
312
- }
313
-
314
- return this.options.secret(keyId)
315
- }
316
-
317
- private validateTimestamp(timestamp: string): void {
318
- const requestTime = Number.parseInt(timestamp, 10)
319
-
320
- if (Number.isNaN(requestTime)) {
321
- throw new SignatureError('EXPIRED_TIMESTAMP', 'Invalid timestamp format')
322
- }
323
-
324
- const now = Math.floor(Date.now() / 1000)
325
- const age = now - requestTime
326
-
327
- if (age > this.options.maxAge) {
328
- throw new SignatureError('EXPIRED_TIMESTAMP', `Request timestamp expired (${age}s old, max ${this.options.maxAge}s)`)
329
- }
330
-
331
- // Check for future timestamps (with small tolerance)
332
- if (age < -30) {
333
- throw new SignatureError('FUTURE_TIMESTAMP', 'Request timestamp is in the future')
334
- }
335
- }
336
-
337
- private async validateNonce(nonce: string): Promise<void> {
338
- if (!this.options.nonceStore) {
339
- return
340
- }
341
-
342
- const exists = await this.options.nonceStore.has(nonce)
343
- if (exists) {
344
- throw new SignatureError('NONCE_REUSED', 'Nonce has already been used (possible replay attack)')
345
- }
346
- }
347
-
348
- private async buildStringToSign(req: EnhancedRequest, timestamp: string, nonce?: string): Promise<string> {
349
- // Use custom string builder if provided
350
- if (this.options.stringToSign) {
351
- return this.options.stringToSign(req, timestamp, nonce)
352
- }
353
-
354
- const url = new URL(req.url)
355
- const parts: string[] = []
356
-
357
- for (const part of this.options.signedParts) {
358
- switch (part) {
359
- case 'method':
360
- parts.push(req.method.toUpperCase())
361
- break
362
- case 'path':
363
- parts.push(url.pathname)
364
- break
365
- case 'query':
366
- parts.push(url.search)
367
- break
368
- case 'timestamp':
369
- parts.push(timestamp)
370
- break
371
- case 'nonce':
372
- if (nonce)
373
- parts.push(nonce)
374
- break
375
- case 'body':
376
- if (req.body) {
377
- const body = await req.clone().text()
378
- parts.push(body)
379
- }
380
- break
381
- case 'headers':
382
- for (const header of this.options.signedHeaders) {
383
- const value = req.headers.get(header)
384
- if (value) {
385
- parts.push(`${header.toLowerCase()}:${value}`)
386
- }
387
- }
388
- break
389
- }
390
- }
391
-
392
- return parts.join('\n')
393
- }
394
-
395
- private async calculateSignature(data: string, secret: string): Promise<string> {
396
- const encoder = new TextEncoder()
397
- const keyData = encoder.encode(secret)
398
- const messageData = encoder.encode(data)
399
-
400
- const algorithmName = {
401
- sha256: 'SHA-256',
402
- sha384: 'SHA-384',
403
- sha512: 'SHA-512',
404
- }[this.options.algorithm]
405
-
406
- const key = await crypto.subtle.importKey(
407
- 'raw',
408
- keyData,
409
- { name: 'HMAC', hash: algorithmName },
410
- false,
411
- ['sign'],
412
- )
413
-
414
- const signature = await crypto.subtle.sign('HMAC', key, messageData)
415
-
416
- if (this.options.encoding === 'base64') {
417
- return btoa(String.fromCharCode(...new Uint8Array(signature)))
418
- }
419
-
420
- return Array.from(new Uint8Array(signature))
421
- .map(b => b.toString(16).padStart(2, '0'))
422
- .join('')
423
- }
424
-
425
- private timingSafeEqual(a: string, b: string): boolean {
426
- if (a.length !== b.length) {
427
- return false
428
- }
429
-
430
- let result = 0
431
- for (let i = 0; i < a.length; i++) {
432
- result |= a.charCodeAt(i) ^ b.charCodeAt(i)
433
- }
434
-
435
- return result === 0
436
- }
437
-
438
- private defaultErrorResponse(error: SignatureError): Response {
439
- return new Response(
440
- JSON.stringify({
441
- error: {
442
- code: error.code,
443
- message: error.message,
444
- },
445
- }),
446
- {
447
- status: error.statusCode,
448
- headers: {
449
- 'Content-Type': 'application/json',
450
- 'WWW-Authenticate': 'HMAC-SHA256',
451
- },
452
- },
453
- )
454
- }
455
- }
456
-
457
- /**
458
- * Factory function to create request signing middleware
459
- */
460
- export function requestSigning(options: RequestSigningOptions): RequestSigning {
461
- return new RequestSigning(options)
462
- }
463
-
464
- /**
465
- * Helper to sign a request (for clients)
466
- */
467
- export async function signRequest(
468
- request: Request,
469
- secret: string,
470
- options: {
471
- algorithm?: SignatureAlgorithm
472
- signedParts?: SignedPart[]
473
- signedHeaders?: string[]
474
- signatureHeader?: string
475
- timestampHeader?: string
476
- nonceHeader?: string
477
- keyId?: string
478
- keyIdHeader?: string
479
- encoding?: 'hex' | 'base64'
480
- } = {},
481
- ): Promise<Request> {
482
- const {
483
- algorithm = 'sha256',
484
- signedParts = ['method', 'path', 'timestamp', 'body'],
485
- signedHeaders = [],
486
- signatureHeader = 'X-Signature',
487
- timestampHeader = 'X-Timestamp',
488
- nonceHeader = 'X-Nonce',
489
- keyId,
490
- keyIdHeader = 'X-Key-Id',
491
- encoding = 'hex',
492
- } = options
493
-
494
- const timestamp = Math.floor(Date.now() / 1000).toString()
495
- const nonce = crypto.randomUUID()
496
-
497
- const url = new URL(request.url)
498
- const parts: string[] = []
499
-
500
- for (const part of signedParts) {
501
- switch (part) {
502
- case 'method':
503
- parts.push(request.method.toUpperCase())
504
- break
505
- case 'path':
506
- parts.push(url.pathname)
507
- break
508
- case 'query':
509
- parts.push(url.search)
510
- break
511
- case 'timestamp':
512
- parts.push(timestamp)
513
- break
514
- case 'nonce':
515
- parts.push(nonce)
516
- break
517
- case 'body':
518
- if (request.body) {
519
- const body = await request.clone().text()
520
- parts.push(body)
521
- }
522
- break
523
- case 'headers':
524
- for (const header of signedHeaders) {
525
- const value = request.headers.get(header)
526
- if (value) {
527
- parts.push(`${header.toLowerCase()}:${value}`)
528
- }
529
- }
530
- break
531
- }
532
- }
533
-
534
- const stringToSign = parts.join('\n')
535
-
536
- // Calculate signature
537
- const encoder = new TextEncoder()
538
- const keyData = encoder.encode(secret)
539
- const messageData = encoder.encode(stringToSign)
540
-
541
- const algorithmName = {
542
- sha256: 'SHA-256',
543
- sha384: 'SHA-384',
544
- sha512: 'SHA-512',
545
- }[algorithm]
546
-
547
- const key = await crypto.subtle.importKey(
548
- 'raw',
549
- keyData,
550
- { name: 'HMAC', hash: algorithmName },
551
- false,
552
- ['sign'],
553
- )
554
-
555
- const signatureBuffer = await crypto.subtle.sign('HMAC', key, messageData)
556
-
557
- let signature: string
558
- if (encoding === 'base64') {
559
- signature = btoa(String.fromCharCode(...new Uint8Array(signatureBuffer)))
560
- }
561
- else {
562
- signature = Array.from(new Uint8Array(signatureBuffer))
563
- .map(b => b.toString(16).padStart(2, '0'))
564
- .join('')
565
- }
566
-
567
- // Create new request with signature headers
568
- const headers = new Headers(request.headers)
569
- headers.set(signatureHeader, signature)
570
- headers.set(timestampHeader, timestamp)
571
- headers.set(nonceHeader, nonce)
572
-
573
- if (keyId) {
574
- headers.set(keyIdHeader, keyId)
575
- }
576
-
577
- return new Request(request.url, {
578
- method: request.method,
579
- headers,
580
- body: request.body,
581
- redirect: request.redirect,
582
- integrity: request.integrity,
583
- signal: request.signal,
584
- })
585
- }
586
-
587
- /**
588
- * Verify a signature (utility function)
589
- */
590
- export async function verifySignature(
591
- stringToSign: string,
592
- signature: string,
593
- secret: string,
594
- algorithm: SignatureAlgorithm = 'sha256',
595
- encoding: 'hex' | 'base64' = 'hex',
596
- ): Promise<boolean> {
597
- const encoder = new TextEncoder()
598
- const keyData = encoder.encode(secret)
599
- const messageData = encoder.encode(stringToSign)
600
-
601
- const algorithmName = {
602
- sha256: 'SHA-256',
603
- sha384: 'SHA-384',
604
- sha512: 'SHA-512',
605
- }[algorithm]
606
-
607
- const key = await crypto.subtle.importKey(
608
- 'raw',
609
- keyData,
610
- { name: 'HMAC', hash: algorithmName },
611
- false,
612
- ['sign'],
613
- )
614
-
615
- const signatureBuffer = await crypto.subtle.sign('HMAC', key, messageData)
616
-
617
- let expectedSignature: string
618
- if (encoding === 'base64') {
619
- expectedSignature = btoa(String.fromCharCode(...new Uint8Array(signatureBuffer)))
620
- }
621
- else {
622
- expectedSignature = Array.from(new Uint8Array(signatureBuffer))
623
- .map(b => b.toString(16).padStart(2, '0'))
624
- .join('')
625
- }
626
-
627
- // Timing-safe comparison
628
- if (signature.length !== expectedSignature.length) {
629
- return false
630
- }
631
-
632
- let result = 0
633
- for (let i = 0; i < signature.length; i++) {
634
- result |= signature.charCodeAt(i) ^ expectedSignature.charCodeAt(i)
635
- }
636
-
637
- return result === 0
638
- }