@snowcone-app/mockup-resolver 1.0.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/index.js ADDED
@@ -0,0 +1,397 @@
1
+ // Remove Node.js crypto import and use Web Crypto API
2
+ // Web Crypto API is available globally in Cloudflare Workers
3
+ /// <reference types="@cloudflare/workers-types" />
4
+ // Helper function to add CORS headers to a response
5
+ function addCorsHeaders(response, request) {
6
+ // Get the origin from the request
7
+ const origin = request.headers.get('Origin') || '*';
8
+ // Clone the response and add CORS headers
9
+ const corsResponse = new Response(response.body, response);
10
+ corsResponse.headers.set('Access-Control-Allow-Origin', origin);
11
+ corsResponse.headers.set('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
12
+ corsResponse.headers.set('Access-Control-Allow-Headers', 'Content-Type, X-API-Key, X-Client-ID');
13
+ return corsResponse;
14
+ }
15
+ // Authentication middleware
16
+ async function authenticate(request, env) {
17
+ console.log('\nšŸ” Authentication attempt');
18
+ // Get the URL from the request query parameters
19
+ const requestUrl = new URL(request.url);
20
+ const urlParam = requestUrl.searchParams.get('url');
21
+ // Check for backward compatibility - accountId in request URL
22
+ const legacyAccountId = requestUrl.searchParams.get('accountId');
23
+ if (legacyAccountId) {
24
+ console.log(`šŸ“ Using legacy accountId from request parameter: ${legacyAccountId}`);
25
+ }
26
+ // If there's no URL parameter, we can't proceed
27
+ if (!urlParam) {
28
+ // For backward compatibility, if there's no URL but there is an accountId,
29
+ // let it pass and the worker will handle the authentication logic itself
30
+ if (legacyAccountId) {
31
+ console.log(`āœ… Using legacy accountId parameter: ${legacyAccountId}`);
32
+ return { authenticated: true, accountId: legacyAccountId };
33
+ }
34
+ console.log('āŒ Missing required url parameter');
35
+ return {
36
+ authenticated: false,
37
+ error: 'Missing required url parameter',
38
+ };
39
+ }
40
+ // Parse the URL to sign/verify to extract accountId from it
41
+ let urlToProcess;
42
+ try {
43
+ // If it's a relative URL, add a base for parsing
44
+ if (urlParam.startsWith('/')) {
45
+ urlToProcess = new URL(urlParam, 'https://example.com');
46
+ }
47
+ else {
48
+ urlToProcess = new URL(urlParam);
49
+ }
50
+ }
51
+ catch (error) {
52
+ console.log(`āŒ Invalid URL format: ${urlParam}`);
53
+ return {
54
+ authenticated: false,
55
+ error: 'Invalid URL format in url parameter',
56
+ };
57
+ }
58
+ // Extract accountId from the URL to sign/verify
59
+ let accountId = urlToProcess.searchParams.get('accountId');
60
+ // For backward compatibility, if accountId is not in the URL to sign but is in the request URL,
61
+ // use that one instead
62
+ if (!accountId && legacyAccountId) {
63
+ console.log(`šŸ“ Using legacy accountId since it's not in the URL to sign: ${legacyAccountId}`);
64
+ accountId = legacyAccountId;
65
+ }
66
+ // Validate accountId requirement
67
+ if (!accountId) {
68
+ console.log('āŒ Missing required accountId in the URL to sign/verify');
69
+ return {
70
+ authenticated: false,
71
+ error: 'Missing required accountId in the URL to sign/verify',
72
+ };
73
+ }
74
+ // Validate accountId length
75
+ if (accountId.length < 6) {
76
+ console.log(`āŒ Invalid accountId: ${accountId} (must be at least 6 characters)`);
77
+ return {
78
+ authenticated: false,
79
+ error: 'Invalid accountId: must be at least 6 characters',
80
+ };
81
+ }
82
+ console.log(`āœ… Valid accountId format: ${accountId}`);
83
+ // Get account data from KV store
84
+ const accountDataStr = await env.ACCOUNTS.get(accountId);
85
+ if (!accountDataStr) {
86
+ console.log(`āŒ Unknown account: ${accountId}`);
87
+ return {
88
+ authenticated: false,
89
+ error: 'Unknown account',
90
+ };
91
+ }
92
+ // Parse account data
93
+ const accountData = JSON.parse(accountDataStr);
94
+ // Method 1: API Key Authentication (server-side)
95
+ const apiKey = request.headers.get('x-api-key');
96
+ if (apiKey) {
97
+ console.log('šŸ“ Using API Key authentication (server-side)');
98
+ // Check if API key exists for this account
99
+ if (!accountData.apiKeys || !accountData.apiKeys[apiKey]) {
100
+ console.log('āŒ Invalid API key for this account');
101
+ return {
102
+ authenticated: false,
103
+ error: 'Invalid API key for this account',
104
+ };
105
+ }
106
+ console.log(`āœ… Valid API key for account: ${accountId}`);
107
+ // TODO: Check rate limits for this API key if implemented
108
+ // const apiKeyData = accountData.apiKeys[apiKey];
109
+ // if (apiKeyData.rateLimit) { ... }
110
+ return { authenticated: true, accountId };
111
+ }
112
+ // Method 2: ClientID + Origin Validation (client-side/web)
113
+ // Check both header and URL parameter for clientId
114
+ const clientId = request.headers.get('x-client-id') || requestUrl.searchParams.get('clientId');
115
+ const origin = request.headers.get('Origin');
116
+ console.log(`\nšŸ”‘ Using Client ID authentication (client-side/web):`);
117
+ console.log(` Client ID: ${clientId}`);
118
+ console.log(` Origin: ${origin}`);
119
+ if (!clientId) {
120
+ console.log('āŒ No clientId provided');
121
+ return {
122
+ authenticated: false,
123
+ error: 'Authentication required: provide API key or clientId',
124
+ };
125
+ }
126
+ // Check if clientId exists for this account
127
+ if (!accountData.clientIds || !accountData.clientIds[clientId]) {
128
+ console.log(`āŒ Unknown clientId for this account: ${clientId}`);
129
+ return {
130
+ authenticated: false,
131
+ error: 'Unknown clientId for this account',
132
+ };
133
+ }
134
+ console.log(`āœ… Valid clientId for account: ${accountId}`);
135
+ // Get client data including allowed origins
136
+ const clientData = accountData.clientIds[clientId];
137
+ // For clientId authentication, also check origin (not needed for API keys)
138
+ const isAllowed = isOriginAllowed(origin, clientData.allowedOrigins);
139
+ console.log(`🌐 Origin allowed: ${isAllowed}`);
140
+ if (!isAllowed) {
141
+ console.log('āŒ Origin not allowed');
142
+ return {
143
+ authenticated: false,
144
+ error: 'Origin not allowed for this clientId',
145
+ };
146
+ }
147
+ // TODO: Check rate limits for this clientId if implemented
148
+ // if (clientData.rateLimit) { ... }
149
+ console.log('āœ… Authentication successful');
150
+ return { authenticated: true, accountId };
151
+ }
152
+ // Updated isOriginAllowed function to work with the new data structure
153
+ function isOriginAllowed(origin, allowedOrigins) {
154
+ console.log(`\nšŸ” Checking origin "${origin}"`);
155
+ console.log(`šŸ“‹ Allowed origins:`, allowedOrigins);
156
+ // If no origins are configured, allow all origins
157
+ if (!allowedOrigins || allowedOrigins.length === 0) {
158
+ return true;
159
+ }
160
+ // If origin is null, reject
161
+ if (!origin) {
162
+ return false;
163
+ }
164
+ // Parse the origin URL once
165
+ let originUrl;
166
+ try {
167
+ originUrl = new URL(origin);
168
+ console.log(`🌐 Parsed origin URL - hostname: ${originUrl.hostname}, protocol: ${originUrl.protocol}`);
169
+ }
170
+ catch (error) {
171
+ console.error(`āŒ Failed to parse origin URL: ${error}`);
172
+ return false;
173
+ }
174
+ // Check each allowed origin pattern
175
+ for (const pattern of allowedOrigins) {
176
+ console.log(`\nšŸ‘‰ Checking pattern: "${pattern}"`);
177
+ // If it's a wildcard pattern (e.g. *.example.com)
178
+ if (pattern.startsWith('*.')) {
179
+ const domain = pattern.slice(2).toLowerCase(); // Remove *. prefix and normalize case
180
+ console.log(`🌟 Wildcard pattern - domain: "${domain}"`);
181
+ // Convert hostname to lowercase for case-insensitive comparison
182
+ const hostname = originUrl.hostname.toLowerCase();
183
+ // Skip IP addresses for wildcard matching
184
+ if (/^(\d{1,3}\.){3}\d{1,3}$/.test(hostname)) {
185
+ console.log(`āŒ Wildcard patterns don't apply to IP addresses`);
186
+ continue;
187
+ }
188
+ // First check if the hostname is exactly the domain (should fail)
189
+ if (hostname === domain) {
190
+ console.log(`āŒ Hostname matches domain exactly, but wildcard requires subdomain`);
191
+ continue;
192
+ }
193
+ // Then check if it's a valid subdomain
194
+ if (hostname.endsWith(`.${domain}`)) {
195
+ // Get the subdomain part (everything before the last dot)
196
+ const subdomain = hostname.slice(0, -(domain.length + 1)); // +1 for the dot
197
+ console.log(`šŸ·ļø Potential subdomain: "${subdomain}"`);
198
+ // Valid if there's a subdomain and it doesn't contain dots (no nested subdomains)
199
+ if (subdomain && !subdomain.includes('.')) {
200
+ console.log(`āœ… Valid subdomain found`);
201
+ return true;
202
+ }
203
+ else {
204
+ console.log(`āŒ Invalid subdomain format or nested subdomain`);
205
+ }
206
+ }
207
+ else {
208
+ console.log(`āŒ Hostname does not match wildcard pattern`);
209
+ }
210
+ }
211
+ else {
212
+ // For exact matches, try parsing the pattern as a URL
213
+ try {
214
+ const patternUrl = new URL(pattern);
215
+ console.log(`šŸ” Comparing - origin: ${originUrl.hostname} (${originUrl.protocol}) with pattern: ${patternUrl.hostname} (${patternUrl.protocol})`);
216
+ // Compare hostname and protocol (case insensitive for hostname)
217
+ if (originUrl.hostname.toLowerCase() === patternUrl.hostname.toLowerCase() &&
218
+ originUrl.protocol === patternUrl.protocol) {
219
+ console.log(`āœ… Exact match found`);
220
+ return true;
221
+ }
222
+ }
223
+ catch (error) {
224
+ // If pattern is not a valid URL, do a direct string comparison
225
+ console.log(`šŸ” Falling back to direct string comparison`);
226
+ if (origin.toLowerCase() === pattern.toLowerCase()) {
227
+ console.log(`āœ… Direct string match found`);
228
+ return true;
229
+ }
230
+ }
231
+ }
232
+ }
233
+ console.log(`āŒ No matching patterns found`);
234
+ return false;
235
+ }
236
+ export async function signUrl(url, secretKey) {
237
+ // Encode the input URL and secret key
238
+ const encoder = new TextEncoder();
239
+ const urlData = encoder.encode(url);
240
+ console.log('🌸 🌸 🌸 Signing URL:', url);
241
+ console.log('Secret key:', secretKey);
242
+ // Import the secret key for HMAC
243
+ const key = await crypto.subtle.importKey('raw', encoder.encode(secretKey), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
244
+ // Sign the URL
245
+ const signature = await crypto.subtle.sign('HMAC', key, urlData);
246
+ // Convert to buffer-like object and truncate to first 8 bytes
247
+ const fullDigest = new Uint8Array(signature);
248
+ const truncatedDigest = fullDigest.slice(0, 8);
249
+ // Convert to hex string
250
+ const hexSignature = Array.from(truncatedDigest)
251
+ .map((b) => b.toString(16).padStart(2, '0'))
252
+ .join('');
253
+ return hexSignature;
254
+ }
255
+ export async function verifyUrl(url, signature, secretKey) {
256
+ const expectedSignature = await signUrl(url, secretKey);
257
+ // Constant-time comparison to prevent timing attacks
258
+ if (expectedSignature.length !== signature.length) {
259
+ return false;
260
+ }
261
+ let result = 0;
262
+ for (let i = 0; i < expectedSignature.length; i++) {
263
+ result |= expectedSignature.charCodeAt(i) ^ signature.charCodeAt(i);
264
+ }
265
+ return result === 0;
266
+ }
267
+ // Cloudflare Worker entry point
268
+ export default {
269
+ async fetch(request, env, ctx) {
270
+ try {
271
+ // Handle CORS preflight requests
272
+ if (request.method === 'OPTIONS') {
273
+ return addCorsHeaders(new Response(null, { status: 204 }), request);
274
+ }
275
+ // Validate required environment variables
276
+ if (!env.URL_SIGNING_SECRET) {
277
+ console.error('Missing required environment variable: URL_SIGNING_SECRET');
278
+ return addCorsHeaders(new Response(JSON.stringify({ error: 'Internal server error' }), {
279
+ status: 500,
280
+ headers: { 'Content-Type': 'application/json' },
281
+ }), request);
282
+ }
283
+ if (!env.ACCOUNTS) {
284
+ console.error('Missing required environment variable: ACCOUNTS');
285
+ return addCorsHeaders(new Response(JSON.stringify({ error: 'Internal server error' }), {
286
+ status: 500,
287
+ headers: { 'Content-Type': 'application/json' },
288
+ }), request);
289
+ }
290
+ // Parse the URL and remove the /v1/url-signer prefix
291
+ const url = new URL(request.url);
292
+ const path = url.pathname.replace('/v1/url-signer', '');
293
+ // Handle different endpoints
294
+ switch (path) {
295
+ case '/sign': {
296
+ const authResult = await authenticate(request, env);
297
+ if (!authResult.authenticated) {
298
+ return addCorsHeaders(new Response(JSON.stringify({ error: authResult.error }), {
299
+ status: 401,
300
+ headers: { 'Content-Type': 'application/json' },
301
+ }), request);
302
+ }
303
+ const urlToSign = url.searchParams.get('url');
304
+ if (!urlToSign) {
305
+ return addCorsHeaders(new Response(JSON.stringify({ error: 'Missing url parameter' }), {
306
+ status: 400,
307
+ headers: { 'Content-Type': 'application/json' },
308
+ }), request);
309
+ }
310
+ const signature = await signUrl(urlToSign, env.URL_SIGNING_SECRET);
311
+ const urlWithSignature = `${urlToSign}${urlToSign.includes('?') ? '&' : '?'}signature=${signature}`;
312
+ const response = new Response(JSON.stringify({
313
+ signature,
314
+ urlWithSignature,
315
+ }), {
316
+ headers: {
317
+ 'Content-Type': 'application/json',
318
+ },
319
+ });
320
+ return addCorsHeaders(response, request);
321
+ }
322
+ case '/verify': {
323
+ const urlToVerify = url.searchParams.get('url');
324
+ const signature = url.searchParams.get('signature');
325
+ if (!urlToVerify || !signature) {
326
+ return addCorsHeaders(new Response(JSON.stringify({ error: 'Missing url or signature parameter' }), {
327
+ status: 400,
328
+ headers: { 'Content-Type': 'application/json' },
329
+ }), request);
330
+ }
331
+ const isValid = await verifyUrl(urlToVerify, signature, env.URL_SIGNING_SECRET);
332
+ const response = new Response(JSON.stringify({ valid: isValid }), {
333
+ headers: { 'Content-Type': 'application/json' },
334
+ });
335
+ return addCorsHeaders(response, request);
336
+ }
337
+ default: {
338
+ // Show API documentation for root path
339
+ const response = new Response(JSON.stringify({
340
+ message: 'URL Signer API',
341
+ endpoints: [
342
+ '/v1/url-signer/sign?url=<url-to-sign>',
343
+ '/v1/url-signer/verify?url=<url-to-verify>&signature=<signature>',
344
+ ],
345
+ }), {
346
+ headers: { 'Content-Type': 'application/json' },
347
+ });
348
+ return addCorsHeaders(response, request);
349
+ }
350
+ }
351
+ }
352
+ catch (error) {
353
+ // Log the error for debugging
354
+ console.error('Worker error:', error);
355
+ // Return a generic error response to the client
356
+ return addCorsHeaders(new Response(JSON.stringify({
357
+ error: 'Internal server error',
358
+ message: error instanceof Error ? error.message : 'Unknown error',
359
+ }), {
360
+ status: 500,
361
+ headers: { 'Content-Type': 'application/json' },
362
+ }), request);
363
+ }
364
+ },
365
+ };
366
+ // Example wrangler.toml configuration:
367
+ /*
368
+ name = "url-signer"
369
+ ...
370
+ [vars]
371
+ SECRET_KEY = "your-secret-key"
372
+
373
+ [[kv_namespaces]]
374
+ binding = "ACCOUNTS"
375
+ id = "your-kv-namespace-id-for-accounts"
376
+ */
377
+ // Example account data structure:
378
+ /*
379
+ {
380
+ "account123": {
381
+ "apiKeys": {
382
+ "api_key_1": { "rateLimit": 1000 },
383
+ "api_key_2": { "rateLimit": 500 }
384
+ },
385
+ "clientIds": {
386
+ "client_id_1": {
387
+ "allowedOrigins": ["https://example.com", "*.example.org"],
388
+ "rateLimit": 100
389
+ },
390
+ "client_id_2": {
391
+ "allowedOrigins": ["https://app.example.com"],
392
+ "rateLimit": 200
393
+ }
394
+ }
395
+ }
396
+ }
397
+ */
package/dist/worker.js ADDED
@@ -0,0 +1,306 @@
1
+ /**
2
+ * GENERATED FILE - DO NOT EDIT DIRECTLY
3
+ * Generated from worker.js
4
+ * Generated at: 2025-05-01T23:58:26.854Z
5
+ */
6
+
7
+ /**
8
+ * URL Signer Worker
9
+ *
10
+ * Specialized edge Worker for signing URLs with minimal latency
11
+ * - Exports the core functionality of the URL signer service
12
+ * - This file will be built and copied to infra/cloudflare/workers/ during deployment
13
+ */
14
+
15
+ // Access environment variables and secrets
16
+ const SIGNING_SECRET = typeof SIGNING_SECRET !== 'undefined' ? SIGNING_SECRET : null
17
+
18
+ // Validate that required environment variables are set
19
+ if (!SIGNING_SECRET) {
20
+ console.error('SIGNING_SECRET environment variable is not set!')
21
+ // In production, you might want to return an error instead of continuing
22
+ }
23
+
24
+ // Add the fetch event listener for Cloudflare Worker
25
+ addEventListener('fetch', (event) => {
26
+ event.respondWith(handleRequest(event.request))
27
+ })
28
+
29
+ // Main request handler - used by the worker
30
+ export async function handleRequest(request) {
31
+ const url = new URL(request.url)
32
+ const path = url.pathname
33
+
34
+ // Handle CORS preflight requests
35
+ if (request.method === 'OPTIONS') {
36
+ return handleCors(request)
37
+ }
38
+
39
+ // Handle URL signing requests
40
+ if (path === '/v1/url-signer/sign') {
41
+ return await handleSignRequest(request, url)
42
+ }
43
+
44
+ // Handle URL verification requests
45
+ if (path === '/v1/url-signer/verify') {
46
+ return await handleVerifyRequest(request, url)
47
+ }
48
+
49
+ // Default response for unknown endpoints
50
+ return new Response(
51
+ JSON.stringify({
52
+ error: 'Unknown endpoint',
53
+ availableEndpoints: ['/v1/url-signer/sign', '/v1/url-signer/verify'],
54
+ }),
55
+ {
56
+ status: 404,
57
+ headers: {
58
+ 'Content-Type': 'application/json',
59
+ ...getCorsHeaders(request),
60
+ },
61
+ },
62
+ )
63
+ }
64
+
65
+ async function handleSignRequest(request, url) {
66
+ // Extract URL to sign from query parameters
67
+ const urlToSign = url.searchParams.get('url')
68
+ if (!urlToSign) {
69
+ return new Response(
70
+ JSON.stringify({
71
+ error: 'Missing url parameter',
72
+ }),
73
+ {
74
+ status: 400,
75
+ headers: {
76
+ 'Content-Type': 'application/json',
77
+ ...getCorsHeaders(request),
78
+ },
79
+ },
80
+ )
81
+ }
82
+
83
+ // Optional: Extract expiration from query parameters (in seconds)
84
+ const expiresIn = parseInt(url.searchParams.get('expiresIn') || '3600', 10)
85
+
86
+ // Generate signature
87
+ const expiresAt = Math.floor(Date.now() / 1000) + expiresIn
88
+ const signature = await generateSignature(urlToSign, expiresAt)
89
+
90
+ let signedUrl;
91
+ try {
92
+ // Handle both absolute and relative URLs, but keep track of whether input was relative
93
+ const isRelative = !/^https?:\/\//i.test(urlToSign);
94
+ let urlObj;
95
+
96
+ // If URL starts with protocol (http:// or https://), it's an absolute URL
97
+ if (!isRelative) {
98
+ urlObj = new URL(urlToSign);
99
+ } else {
100
+ // For relative URLs, extract the base from the request URL
101
+ const baseUrl = url.origin;
102
+ // Make sure the relative URL starts with / for proper joining
103
+ const relativePath = urlToSign.startsWith('/') ? urlToSign : `/${urlToSign}`;
104
+ urlObj = new URL(relativePath, baseUrl);
105
+ }
106
+
107
+ urlObj.searchParams.set('signature', signature);
108
+ urlObj.searchParams.set('expires', expiresAt.toString());
109
+
110
+ // If the original URL was relative, convert back to relative
111
+ if (isRelative) {
112
+ // Extract the path and query string to create a relative URL
113
+ signedUrl = urlObj.pathname + urlObj.search;
114
+ } else {
115
+ signedUrl = urlObj.toString();
116
+ }
117
+ } catch (error) {
118
+ // Fallback method for handling URLs that can't be parsed
119
+ const separator = urlToSign.includes('?') ? '&' : '?';
120
+ signedUrl = `${urlToSign}${separator}signature=${encodeURIComponent(signature)}&expires=${expiresAt}`;
121
+ }
122
+
123
+ return new Response(
124
+ JSON.stringify({
125
+ original: urlToSign,
126
+ signed: signedUrl,
127
+ expires: new Date(expiresAt * 1000).toISOString(),
128
+ expiresIn: expiresIn,
129
+ }),
130
+ {
131
+ headers: {
132
+ 'Content-Type': 'application/json',
133
+ ...getCorsHeaders(request),
134
+ },
135
+ },
136
+ )
137
+ }
138
+
139
+ async function handleVerifyRequest(request, url) {
140
+ // Extract URL to verify from query parameters
141
+ const urlToVerify = url.searchParams.get('url')
142
+ if (!urlToVerify) {
143
+ return new Response(
144
+ JSON.stringify({
145
+ error: 'Missing url parameter',
146
+ }),
147
+ {
148
+ status: 400,
149
+ headers: {
150
+ 'Content-Type': 'application/json',
151
+ ...getCorsHeaders(request),
152
+ },
153
+ },
154
+ )
155
+ }
156
+
157
+ try {
158
+ // Parse the URL to verify, handling both relative and absolute URLs
159
+ const isRelative = !/^https?:\/\//i.test(urlToVerify);
160
+ let urlObj;
161
+
162
+ // If URL starts with protocol (http:// or https://), it's an absolute URL
163
+ if (!isRelative) {
164
+ urlObj = new URL(urlToVerify);
165
+ } else {
166
+ // For relative URLs, extract the base from the request URL
167
+ const baseUrl = url.origin;
168
+ // Make sure the relative URL starts with / for proper joining
169
+ const relativePath = urlToVerify.startsWith('/') ? urlToVerify : `/${urlToVerify}`;
170
+ urlObj = new URL(relativePath, baseUrl);
171
+ }
172
+
173
+ // Extract signature and expiration from the URL
174
+ const signature = urlObj.searchParams.get('signature')
175
+ const expires = urlObj.searchParams.get('expires')
176
+
177
+ if (!signature || !expires) {
178
+ return new Response(
179
+ JSON.stringify({
180
+ valid: false,
181
+ error: 'Missing signature or expires parameter in URL',
182
+ }),
183
+ {
184
+ headers: {
185
+ 'Content-Type': 'application/json',
186
+ ...getCorsHeaders(request),
187
+ },
188
+ },
189
+ )
190
+ }
191
+
192
+ // Check if URL has expired
193
+ const expiresAt = parseInt(expires, 10)
194
+ const currentTime = Math.floor(Date.now() / 1000)
195
+
196
+ if (currentTime > expiresAt) {
197
+ return new Response(
198
+ JSON.stringify({
199
+ valid: false,
200
+ error: 'URL has expired',
201
+ expired: true,
202
+ expiresAt: new Date(expiresAt * 1000).toISOString(),
203
+ currentTime: new Date(currentTime * 1000).toISOString(),
204
+ }),
205
+ {
206
+ headers: {
207
+ 'Content-Type': 'application/json',
208
+ ...getCorsHeaders(request),
209
+ },
210
+ },
211
+ )
212
+ }
213
+
214
+ // Remove the signature from the URL for verification
215
+ const urlForVerification = new URL(urlObj.toString())
216
+ const providedSignature = urlForVerification.searchParams.get('signature')
217
+ urlForVerification.searchParams.delete('signature')
218
+
219
+ // Generate expected signature
220
+ let urlForSigning;
221
+ if (isRelative) {
222
+ urlForSigning = urlForVerification.pathname + urlForVerification.search;
223
+ } else {
224
+ urlForSigning = urlForVerification.toString();
225
+ }
226
+ const expectedSignature = await generateSignature(urlForSigning, expiresAt)
227
+
228
+ // Compare signatures
229
+ const isValid = providedSignature === expectedSignature
230
+
231
+ return new Response(
232
+ JSON.stringify({
233
+ valid: isValid,
234
+ url: urlToVerify,
235
+ expiresAt: new Date(expiresAt * 1000).toISOString(),
236
+ }),
237
+ {
238
+ headers: {
239
+ 'Content-Type': 'application/json',
240
+ ...getCorsHeaders(request),
241
+ },
242
+ },
243
+ )
244
+ } catch (error) {
245
+ return new Response(
246
+ JSON.stringify({
247
+ valid: false,
248
+ error: 'Invalid URL format or other error',
249
+ message: error.message,
250
+ }),
251
+ {
252
+ status: 400,
253
+ headers: {
254
+ 'Content-Type': 'application/json',
255
+ ...getCorsHeaders(request),
256
+ },
257
+ },
258
+ )
259
+ }
260
+ }
261
+
262
+ // Utility function to generate signature
263
+ export async function generateSignature(url, expiresAt) {
264
+ // Get the signing secret from environment variables
265
+ // In the actual Cloudflare Worker, this will be replaced with SIGNING_SECRET
266
+ const secret = typeof SIGNING_SECRET !== 'undefined' ? SIGNING_SECRET : 'development-secret-key'
267
+
268
+ // Create a string to sign
269
+ const stringToSign = `${url}|${expiresAt}`
270
+
271
+ // Convert the string and secret to ArrayBuffers
272
+ const encoder = new TextEncoder()
273
+ const stringBuffer = encoder.encode(stringToSign)
274
+ const secretBuffer = encoder.encode(secret)
275
+
276
+ // Create a key from the secret
277
+ const key = await crypto.subtle.importKey('raw', secretBuffer, { name: 'HMAC', hash: 'SHA-256' }, false, [
278
+ 'sign',
279
+ ])
280
+
281
+ // Sign the string
282
+ const signature = await crypto.subtle.sign('HMAC', key, stringBuffer)
283
+
284
+ // Convert the signature to a base64 string
285
+ const signatureArray = new Uint8Array(signature)
286
+ return btoa(String.fromCharCode(...signatureArray))
287
+ }
288
+
289
+ // CORS utility functions
290
+ export function getCorsHeaders(request) {
291
+ const origin = request.headers.get('Origin')
292
+
293
+ return {
294
+ 'Access-Control-Allow-Origin': origin || '*',
295
+ 'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
296
+ 'Access-Control-Allow-Headers': 'Content-Type, Authorization, X-API-Key',
297
+ 'Access-Control-Max-Age': '86400',
298
+ }
299
+ }
300
+
301
+ export function handleCors(request) {
302
+ return new Response(null, {
303
+ status: 204,
304
+ headers: getCorsHeaders(request),
305
+ })
306
+ }