From: Ardis Lu Date: Tue, 12 Jul 2022 04:59:59 +0000 (-0700) Subject: Add error handling instead of using default values X-Git-Url: https://git.ardis.lu/?a=commitdiff_plain;h=3fab4e9d7122e0a3ca9d6e6d3cc33648b5f997b2;p=cloudflare-workers Add error handling instead of using default values --- diff --git a/hash/index.js b/hash/index.js index de4696d..78b241f 100644 --- a/hash/index.js +++ b/hash/index.js @@ -1,17 +1,28 @@ export default { async fetch(request) { const url = new URL(request.url); - let algorithm = 'SHA-256'; - let query = 'Example string'; + let algorithm; + let query; + + // Parse URLSearchParams for (const [key, value] of url.searchParams) { - if (key.toLowerCase() === 'algorithm' && ['SHA-1', 'SHA-256', 'SHA-384', 'SHA-512'].includes(value.toUpperCase())) { - algorithm = value; + const normalizedKey = key.toLowerCase(); + if ((normalizedKey === 'a' || normalizedKey === 'algorithm') && /^SHA-?(1|256|384|512)$/i.test(value)) { + algorithm = value.includes('-') ? value : `SHA-${value.slice(3)}`; // Insert a '-' character if it's not present; crypto.subtle.digest() requires it. } - else if ((key.toLowerCase() === 'q' || key.toLowerCase() === 'query') && value) { // Intentionally excluding falsy values and not just null because empty strings are no good + else if ((normalizedKey === 'q' || normalizedKey === 'query') && value) { // Intentionally fail for falsy values because a null or empty string is also invalid query = value; } } + // Handling bad params + if (algorithm === undefined) { + return new Response('Invalid algorithm provided. Provide one of the following values for the parameter "a" or "algorithm": SHA-1, SHA-256, SHA-384, or SHA-512.', { status: 400 }); + } + else if (query === undefined) { + return new Response('Invalid query provided. Provide a value for the parameter "q" or "query".', { status: 400 }); + } + // Convert query string to byte array and hash it, then convert hashed byte array to hex string const inputArray = new TextEncoder().encode(query); const digest = await crypto.subtle.digest(algorithm, inputArray);