```// Function to generate a nonce (e.g., a timestamp) function generateNonce() { return Date.now().toString(); } // Function to generate HMAC signature using Web Crypto API async function generateHMAC(nonce, apiKey, secretKey) { const key = await crypto.subtle.importKey( 'raw', new TextEncoder().encode(secretKey), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign'] ); const signature = await crypto.subtle.sign( 'HMAC', key, new TextEncoder().encode(nonce + apiKey) ); return Array.from(new Uint8Array(signature)) .map(b => b.toString(16).padStart(2, '0')) .join(''); } // Main request handler export async function onRequest(context) { const { request } = context; const url = new URL(request.url); const secretKey = context.env.SECRET_KEY; // Defined in the Cloudflare Workers environment const apiKey = context.env.API_KEY; // Defined in the Cloudflare Workers environment // CORS check for allowed domains //if (!checkCors(url.origin)) { // return new Response('CORS check failed', { status: 403 }); //} // Handle /v1/signature path if (url.pathname === '/v1/signature') { const nonce = generateNonce(); const signature = await generateHMAC(nonce, apiKey, secretKey); return new Response( JSON.stringify({ apiKey, signature, nonce, }) ); } return new Response('Not Found', { status: 404 }); } // CORS preflight handler for OPTIONS method //async function handleOptions(context) { // const { request } = context; // const url = new URL(request.url); // // if (!checkCors(url.origin)) { // return new Response('CORS check failed', { status: 403 }); // } // // return new Response(null, { // status: 204, // headers: { // 'Access-Control-Allow-Origin': "*", // 'Access-Control-Allow-Methods': 'GET, OPTIONS', // }, // }); //} // Event listener for requests addEventListener('fetch', (event) => { const request = event.request; //if (request.method === 'OPTIONS') { // event.respondWith(handleOptions(event)); // Handle preflight requests //} else { // event.respondWith(onRequest(event)); // Handle GET and other requests //} }); ```