From 58afbc6298f4b39984fde94bffa6cfd8e6213697 Mon Sep 17 00:00:00 2001
From: regalijan <r@regalijan.com>
Date: Thu, 19 Oct 2023 16:49:15 -0400
Subject: [PATCH] Create view upload endpoint

---
 functions/api/uploads/[[id]].ts | 35 +++++++++++++++++++++++++++++++++
 1 file changed, 35 insertions(+)
 create mode 100644 functions/api/uploads/[[id]].ts

diff --git a/functions/api/uploads/[[id]].ts b/functions/api/uploads/[[id]].ts
new file mode 100644
index 0000000..178d22f
--- /dev/null
+++ b/functions/api/uploads/[[id]].ts
@@ -0,0 +1,35 @@
+export async function onRequestGet(context: RequestContext) {
+  const { current_user: currentUser } = context.data;
+
+  if (!(currentUser?.permissions & (1 << 5)))
+    return new Response('{"error":"Forbidden"}', {
+      headers: {
+        "content-type": "application/json",
+      },
+      status: 403,
+    });
+
+  const attachment = context.params.id as string;
+  const unsignedURL = `https://mediaproxy.carcrushers.cc/${attachment}?Expires=${(
+    Math.round(Date.now() / 1000) + 1800
+  ).toString()}`;
+  const signingKey = await crypto.subtle.importKey(
+    "raw",
+    new TextEncoder().encode(atob(context.env.URL_SIGNING_KEY)),
+    { hash: "SHA-1", name: "HMAC" },
+    false,
+    ["sign"]
+  );
+  const signature = await crypto.subtle.sign(
+    "HMAC",
+    signingKey,
+    new TextEncoder().encode(unsignedURL)
+  );
+
+  return Response.redirect(
+    `${unsignedURL}&Signature=${btoa(new TextDecoder().decode(signature))
+      .replaceAll("+", "-")
+      .replaceAll("/", "_")
+      .replaceAll("=", "")}`
+  );
+}