From 3db33d24600ecb407eac210da2b0a1cf4e486beb Mon Sep 17 00:00:00 2001 From: Olaf Rosendahl Date: Fri, 17 Nov 2023 13:13:37 +0100 Subject: [PATCH] fix: crypto --- ...l.$teamSlug.$projectSlug.pageview-next.tsx | 2 +- .../api.$teamSlug.$projectSlug.pageview.tsx | 21 ++++++++++++------- 2 files changed, 15 insertions(+), 8 deletions(-) diff --git a/web/app/routes/api-internal.$teamSlug.$projectSlug.pageview-next.tsx b/web/app/routes/api-internal.$teamSlug.$projectSlug.pageview-next.tsx index 7784c10..2e2af63 100644 --- a/web/app/routes/api-internal.$teamSlug.$projectSlug.pageview-next.tsx +++ b/web/app/routes/api-internal.$teamSlug.$projectSlug.pageview-next.tsx @@ -82,7 +82,7 @@ export const action = async ({ request, params }: ActionFunctionArgs) => { return json({ ok: true }, { status: 202 }); } catch (e) { - console.error('[API-Internal - Pageview]', e); + console.error('[API-Internal - PageviewNext]', e); return json({ ok: false }, { status: 400 }); } }; diff --git a/web/app/routes/api.$teamSlug.$projectSlug.pageview.tsx b/web/app/routes/api.$teamSlug.$projectSlug.pageview.tsx index c6fd50c..4517cb4 100644 --- a/web/app/routes/api.$teamSlug.$projectSlug.pageview.tsx +++ b/web/app/routes/api.$teamSlug.$projectSlug.pageview.tsx @@ -18,11 +18,17 @@ export const config = { runtime: 'edge' }; export const getPageViewUserIdHash = async (ip: string, userAgent: string, date: Date): Promise => { invariant(process.env.SECRET_KEY, 'Expected environment variable "SECRET_KEY" to be set when tracking page visitors'); const day = format(date, 'yyyy-MM-dd'); - const msgUint8 = new TextEncoder().encode(`${ip}_${userAgent}_${day}_${process.env.SECRET_KEY}`); // encode as (utf-8) Uint8Array - const hashBuffer = await crypto.subtle.digest('SHA-256', msgUint8); // hash the message - const hashArray = Array.from(new Uint8Array(hashBuffer)); // convert buffer to byte array - const hashHex = hashArray.map((b) => b.toString(16).padStart(2, '0')).join(''); // convert bytes to hex string - return hashHex; + const userId = `${ip}_${userAgent}_${day}_${process.env.SECRET_KEY}`; + try { + const msgUint8 = new TextEncoder().encode(userId); // encode as (utf-8) Uint8Array + const hashBuffer = await crypto.subtle.digest('SHA-256', msgUint8); // hash the message + const hashArray = Array.from(new Uint8Array(hashBuffer)); // convert buffer to byte array + const hashHex = hashArray.map((b) => b.toString(16).padStart(2, '0')).join(''); // convert bytes to hex string + return hashHex; + } catch (e) { + console.error('[API - UserIdHash]', e); + return userId; + } }; export const getPageViewUserAgentData = (ua: UserAgentData): PageviewRequestData['userAgentData'] => { @@ -40,7 +46,8 @@ const getPageViewNextRequest = async (request: Request): Promise