The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
use web Crypto API for edge compatible
Kiran K94348692333a
diff --git a/apps/web/app/api/admin/impersonate/route.ts b/apps/web/app/api/admin/impersonate/route.tsindex a0ee58f01f..5d996d5722 100644--- a/apps/web/app/api/admin/impersonate/route.ts+++ b/apps/web/app/api/admin/impersonate/route.ts@@ -91,7 +91,7 @@ async function getImpersonateUrl(email: string) {await prisma.verificationToken.create({data: {identifier: email,- token: hashToken(token),+ token: await hashToken(token),expires: new Date(Date.now() + 60000),},});diff --git a/apps/web/app/api/track/conversions/route.ts b/apps/web/app/api/track/conversions/route.tsindex 21f9e0f76d..e84733fde2 100644--- a/apps/web/app/api/track/conversions/route.ts+++ b/apps/web/app/api/track/conversions/route.ts@@ -1,16 +1,12 @@import { parseRequestBody } from "@/lib/api/utils";-import { withSessionEdge } from "@/lib/auth";+import { withSessionEdge } from "@/lib/auth/edge";import { getClickEvent, recordConversion } from "@/lib/tinybird";import { conversionRequestSchema } from "@/lib/zod/schemas/conversions";import { NextResponse } from "next/server";-// export const runtime = "edge";+export const runtime = "edge";-// TODO:-// Support Edge and waitUntil-// Replace withWorkspace--// POST /api/track/conversions – post conversion event+// POST /api/track/conversions – Post a conversion eventexport const POST = withSessionEdge(async ({ req }) => {const body = await parseRequestBody(req);const parsed = conversionRequestSchema.parse(body);diff --git a/apps/web/app/api/user/tokens/route.ts b/apps/web/app/api/user/tokens/route.tsindex 486397a3e0..eabb50c505 100644--- a/apps/web/app/api/user/tokens/route.ts+++ b/apps/web/app/api/user/tokens/route.ts@@ -34,7 +34,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 = hashToken(token, {+ const hashedKey = await hashToken(token, {noSecret: true,});// take first 3 and last 4 characters of the keydiff --git a/apps/web/lib/api/users.ts b/apps/web/lib/api/users.tsindex dd11015076..dc38480fae 100644--- a/apps/web/lib/api/users.ts+++ b/apps/web/lib/api/users.ts@@ -44,7 +44,7 @@ export async function inviteUser({await prisma.verificationToken.create({data: {identifier: email,- token: hashToken(token),+ token: await hashToken(token),expires,},});diff --git a/apps/web/lib/auth/edge.ts b/apps/web/lib/auth/edge.tsindex 8b7848b68e..5b6920cf3b 100644--- a/apps/web/lib/auth/edge.ts+++ b/apps/web/lib/auth/edge.ts@@ -1,9 +1,9 @@import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";-import prisma from "@/lib/prisma";+import { hashToken } from "@/lib/auth/hash";import { getSearchParams } from "@dub/utils";+import { getToken, updateTokenLastUsed } from "../planetscale";import { ratelimit } from "../upstash";import { WithSessionHandler } from "./session";-import { hashToken } from "./utils";export const withSessionEdge =(handler: WithSessionHandler) =>@@ -31,25 +31,8 @@ export const withSessionEdge =}const apiKey = authorizationHeader.replace("Bearer ", "");- const hashedKey = hashToken(apiKey, {- noSecret: true,- });-- // Find user by token- const user = await prisma.user.findFirst({- where: {- tokens: {- some: {- hashedKey,- },- },- },- select: {- id: true,- name: true,- email: true,- },- });+ const hashedKey = await hashToken(apiKey, { noSecret: true });+ const user = await getToken(hashedKey);if (!user) {throw new DubApiError({@@ -79,14 +62,7 @@ export const withSessionEdge =}// Update token last used- await prisma.token.update({- where: {- hashedKey,- },- data: {- lastUsed: new Date(),- },- });+ await updateTokenLastUsed(hashedKey);const session = {user: {diff --git a/apps/web/lib/auth/hash.ts b/apps/web/lib/auth/hash.tsindex acbd622e47..20fbd974de 100644--- a/apps/web/lib/auth/hash.ts+++ b/apps/web/lib/auth/hash.ts@@ -1,6 +1,7 @@-import { createHash } from "crypto";--export const hashToken = (+// 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,@@ -8,7 +9,13 @@ export const hashToken = (noSecret?: boolean;} = {},) => {- return createHash("sha256")- .update(`${token}${noSecret ? "" : process.env.NEXTAUTH_SECRET}`)- .digest("hex");+ 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/index.ts b/apps/web/lib/auth/index.tsindex 57f450a406..56caca89ac 100644--- a/apps/web/lib/auth/index.ts+++ b/apps/web/lib/auth/index.ts@@ -1,5 +1,4 @@export * from "./admin";-export * from "./edge";export * from "./options";export * from "./session";export * from "./utils";diff --git a/apps/web/lib/auth/session.ts b/apps/web/lib/auth/session.tsindex 07563a5bcc..45600e1430 100644--- a/apps/web/lib/auth/session.ts+++ b/apps/web/lib/auth/session.ts@@ -37,7 +37,7 @@ export const withSession =}const apiKey = authorizationHeader.replace("Bearer ", "");- const hashedKey = hashToken(apiKey, {+ const hashedKey = await hashToken(apiKey, {noSecret: true,});diff --git a/apps/web/lib/auth/workspace.ts b/apps/web/lib/auth/workspace.tsindex 4783052077..bdf1d56468 100644--- a/apps/web/lib/auth/workspace.ts+++ b/apps/web/lib/auth/workspace.ts@@ -132,7 +132,7 @@ export const withWorkspace = (}if (apiKey) {- const hashedKey = hashToken(apiKey, {+ const hashedKey = await hashToken(apiKey, {noSecret: true,});diff --git a/apps/web/lib/planetscale.ts b/apps/web/lib/planetscale.tsindex 0e2646c5e4..17c275eee5 100644--- a/apps/web/lib/planetscale.ts+++ b/apps/web/lib/planetscale.ts@@ -1,5 +1,6 @@import { nanoid, punyEncode } from "@dub/utils";import { connect } from "@planetscale/database";+import { User } from "@prisma/client";import { DomainProps, WorkspaceProps } from "./types";export const DATABASE_URL =@@ -139,3 +140,20 @@ export async function getRandomKey({return key;}}++export const getToken = async (hashedKey: string) => {+ const { rows } = await conn.execute<User>(+ // "SELECT User.id, User.name, User.email FROM Token JOIN User ON Token.userId = User.id WHERE hashedKey = ? LIMIT 1",+ "SELECT * FROM User WHERE User.ID IN (SELECT userId FROM Token WHERE hashedKey = ? AND userId IS NOT NULL) LIMIT 1",+ [hashedKey],+ );++ return rows.length > 0 ? rows[0] : null;+};++export const updateTokenLastUsed = async (hashedKey: string) => {+ return await conn.execute(+ "UPDATE Token SET lastUsed = NOW() WHERE hashedKey = ?",+ [hashedKey],+ );+};