Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

add waitUntil, moved hashToken to utils

Steven Tey33ce5b245ed3
diff --git a/apps/web/app/api/admin/impersonate/route.ts b/apps/web/app/api/admin/impersonate/route.ts
index 5d996d5722..1c1e05ddf9 100644
--- a/apps/web/app/api/admin/impersonate/route.ts
+++ b/apps/web/app/api/admin/impersonate/route.ts
@@ -1,5 +1,4 @@
-import { withAdmin } from "@/lib/auth";
-import { hashToken } from "@/lib/auth/hash";
+import { hashToken, withAdmin } from "@/lib/auth";
import prisma from "@/lib/prisma";
import { DUB_DOMAINS_ARRAY } from "@dub/utils";
import { randomBytes } from "crypto";
diff --git a/apps/web/app/api/track/conversions/route.ts b/apps/web/app/api/track/conversions/route.ts
index 038cada0b7..fe97f67596 100644
--- a/apps/web/app/api/track/conversions/route.ts
+++ b/apps/web/app/api/track/conversions/route.ts
@@ -1,5 +1,5 @@
import { parseRequestBody } from "@/lib/api/utils";
-import { withSessionEdge } from "@/lib/auth/edge";
+import { withSessionEdge } from "@/lib/auth/session-edge";
import { getClickEvent, recordConversion } from "@/lib/tinybird";
import { conversionRequestSchema } from "@/lib/zod/schemas/conversions";
import { internal_runWithWaitUntil as waitUntil } from "next/dist/server/web/internal-edge-wait-until";
diff --git a/apps/web/app/api/user/tokens/route.ts b/apps/web/app/api/user/tokens/route.ts
index eabb50c505..71779df720 100644
--- a/apps/web/app/api/user/tokens/route.ts
+++ b/apps/web/app/api/user/tokens/route.ts
@@ -1,5 +1,4 @@
-import { withSession } from "@/lib/auth";
-import { hashToken } from "@/lib/auth/hash";
+import { hashToken, withSession } from "@/lib/auth";
import { qstash } from "@/lib/cron";
import prisma from "@/lib/prisma";
import { APP_DOMAIN_WITH_NGROK, nanoid } from "@dub/utils";
@@ -34,9 +33,7 @@ export const GET = withSession(async ({ session }) => {
export const POST = withSession(async ({ req, session }) => {
const { name } = await req.json();
const token = nanoid(24);
- const hashedKey = await hashToken(token, {
- noSecret: true,
- });
+ const hashedKey = await hashToken(token);
// take first 3 and last 4 characters of the key
const partialKey = `${token.slice(0, 3)}...${token.slice(-4)}`;
await Promise.all([
diff --git a/apps/web/lib/api/users.ts b/apps/web/lib/api/users.ts
index dc38480fae..1482864ca9 100644
--- a/apps/web/lib/api/users.ts
+++ b/apps/web/lib/api/users.ts
@@ -1,5 +1,4 @@
-import { Session } from "@/lib/auth";
-import { hashToken } from "@/lib/auth/hash";
+import { Session, hashToken } from "@/lib/auth";
import prisma from "@/lib/prisma";
import { WorkspaceProps } from "@/lib/types";
import { TWO_WEEKS_IN_SECONDS } from "@dub/utils";
@@ -44,7 +43,7 @@ export async function inviteUser({
await prisma.verificationToken.create({
data: {
identifier: email,
- token: await hashToken(token),
+ token: await hashToken(token, { secret: true }),
expires,
},
});
diff --git a/apps/web/lib/auth/hash.ts b/apps/web/lib/auth/hash.ts
deleted file mode 100644
index 20fbd974de..0000000000
--- a/apps/web/lib/auth/hash.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-// TODO:
-// Check hashToken work as expected in all cases
-// https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest
-export const hashToken = async (
- token: string,
- {
- noSecret = false,
- }: {
- noSecret?: boolean;
- } = {},
-) => {
- const encoder = new TextEncoder();
-
- const data = encoder.encode(
- `${token}${noSecret ? "" : process.env.NEXTAUTH_SECRET}`,
- );
- const hashBuffer = await crypto.subtle.digest("SHA-256", data);
- const hashArray = Array.from(new Uint8Array(hashBuffer));
-
- return hashArray.map((b) => b.toString(16).padStart(2, "0")).join("");
-};
diff --git a/apps/web/lib/auth/edge.ts b/apps/web/lib/auth/session-edge.ts
similarity index 90%
rename from apps/web/lib/auth/edge.ts
rename to apps/web/lib/auth/session-edge.ts
index 5b6920cf3b..959f34640a 100644
--- a/apps/web/lib/auth/edge.ts
+++ b/apps/web/lib/auth/session-edge.ts
@@ -1,6 +1,7 @@
import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";
-import { hashToken } from "@/lib/auth/hash";
+import { hashToken } from "@/lib/auth";
import { getSearchParams } from "@dub/utils";
+import { internal_runWithWaitUntil as waitUntil } from "next/dist/server/web/internal-edge-wait-until";
import { getToken, updateTokenLastUsed } from "../planetscale";
import { ratelimit } from "../upstash";
import { WithSessionHandler } from "./session";
@@ -31,7 +32,7 @@ export const withSessionEdge =
}
const apiKey = authorizationHeader.replace("Bearer ", "");
- const hashedKey = await hashToken(apiKey, { noSecret: true });
+ const hashedKey = await hashToken(apiKey);
const user = await getToken(hashedKey);
if (!user) {
@@ -62,7 +63,7 @@ export const withSessionEdge =
}
// Update token last used
- await updateTokenLastUsed(hashedKey);
+ waitUntil(() => updateTokenLastUsed(hashedKey));
const session = {
user: {
diff --git a/apps/web/lib/auth/session.ts b/apps/web/lib/auth/session.ts
index 45600e1430..d96281105e 100644
--- a/apps/web/lib/auth/session.ts
+++ b/apps/web/lib/auth/session.ts
@@ -1,5 +1,5 @@
import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";
-import { hashToken } from "@/lib/auth/hash";
+import { hashToken } from "@/lib/auth";
import prisma from "@/lib/prisma";
import { getSearchParams } from "@dub/utils";
import { ratelimit } from "../upstash";
@@ -37,9 +37,7 @@ export const withSession =
}
const apiKey = authorizationHeader.replace("Bearer ", "");
- const hashedKey = await hashToken(apiKey, {
- noSecret: true,
- });
+ const hashedKey = await hashToken(apiKey);
const user = await prisma.user.findFirst({
where: {
diff --git a/apps/web/lib/auth/utils.ts b/apps/web/lib/auth/utils.ts
index 4de897b43d..5264325504 100644
--- a/apps/web/lib/auth/utils.ts
+++ b/apps/web/lib/auth/utils.ts
@@ -13,3 +13,22 @@ export interface Session {
export const getSession = async () => {
return getServerSession(authOptions) as Promise<Session>;
};
+
+export const hashToken = async (
+ token: string,
+ {
+ secret = false,
+ }: {
+ secret?: boolean;
+ } = {},
+) => {
+ const encoder = new TextEncoder();
+
+ const data = encoder.encode(
+ `${token}${secret ? process.env.NEXTAUTH_SECRET : ""}`,
+ );
+ const hashBuffer = await crypto.subtle.digest("SHA-256", data);
+ const hashArray = Array.from(new Uint8Array(hashBuffer));
+
+ return hashArray.map((b) => b.toString(16).padStart(2, "0")).join("");
+};
diff --git a/apps/web/lib/auth/workspace.ts b/apps/web/lib/auth/workspace.ts
index bdf1d56468..ec955584b6 100644
--- a/apps/web/lib/auth/workspace.ts
+++ b/apps/web/lib/auth/workspace.ts
@@ -1,5 +1,5 @@
import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";
-import { hashToken } from "@/lib/auth/hash";
+import { hashToken } from "@/lib/auth";
import prisma from "@/lib/prisma";
import {
API_DOMAIN,
@@ -132,9 +132,7 @@ export const withWorkspace = (
}
if (apiKey) {
- const hashedKey = await hashToken(apiKey, {
- noSecret: true,
- });
+ const hashedKey = await hashToken(apiKey);
const user = await prisma.user.findFirst({
where: {
diff --git a/packages/utils/src/functions/hash-string.ts b/packages/utils/src/functions/hash-string.ts
new file mode 100644
index 0000000000..a6a98c3406
--- /dev/null
+++ b/packages/utils/src/functions/hash-string.ts
@@ -0,0 +1,16 @@
+export async function hashStringSHA256(str: string) {
+ // Encode the string into bytes
+ const encoder = new TextEncoder();
+ const data = encoder.encode(str);
+
+ // Hash the data with SHA-256
+ const hashBuffer = await crypto.subtle.digest("SHA-256", data);
+
+ // Convert the buffer to a hexadecimal string
+ const hashArray = Array.from(new Uint8Array(hashBuffer));
+ const hashHex = hashArray
+ .map((b) => b.toString(16).padStart(2, "0"))
+ .join("");
+
+ return hashHex;
+}
diff --git a/packages/utils/src/functions/hash.ts b/packages/utils/src/functions/hash.ts
deleted file mode 100644
index 0d4203401f..0000000000
--- a/packages/utils/src/functions/hash.ts
+++ /dev/null
@@ -1,33 +0,0 @@
-export async function generateMD5Hash(message: string) {
- // Convert the message string to a Uint8Array
- const encoder = new TextEncoder();
- const data = encoder.encode(message);
-
- // Generate the hash using the SubtleCrypto interface
- const hashBuffer = await crypto.subtle.digest("MD5", data);
-
- // Convert the hash to a hexadecimal string
- const hashArray = Array.from(new Uint8Array(hashBuffer));
- const hashHex = hashArray
- .map((byte) => byte.toString(16).padStart(2, "0"))
- .join("");
-
- return hashHex;
-}
-
-export async function hashStringSHA256(str: string) {
- // Encode the string into bytes
- const encoder = new TextEncoder();
- const data = encoder.encode(str);
-
- // Hash the data with SHA-256
- const hashBuffer = await crypto.subtle.digest("SHA-256", data);
-
- // Convert the buffer to a hexadecimal string
- const hashArray = Array.from(new Uint8Array(hashBuffer));
- const hashHex = hashArray
- .map((b) => b.toString(16).padStart(2, "0"))
- .join("");
-
- return hashHex;
-}
diff --git a/packages/utils/src/functions/index.ts b/packages/utils/src/functions/index.ts
index 87c6ee521e..84e2f5653b 100644
--- a/packages/utils/src/functions/index.ts
+++ b/packages/utils/src/functions/index.ts
@@ -7,7 +7,7 @@ export * from "./deep-equal";
export * from "./domains";
export * from "./fetch-with-timeout";
export * from "./fetcher";
-export * from "./hash";
+export * from "./hash-string";
export * from "./is-iframeable";
export * from "./link-constructor";
export * from "./log";