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.

wip restricted token

Kiran K041a2d9a263e
diff --git a/apps/web/app/api/tokens/[id]/route.ts b/apps/web/app/api/tokens/[id]/route.ts
new file mode 100644
index 0000000000..13984982d7
--- /dev/null
+++ b/apps/web/app/api/tokens/[id]/route.ts
@@ -0,0 +1,112 @@
+import { DubApiError } from "@/lib/api/errors";
+import { parseRequestBody } from "@/lib/api/utils";
+import { withWorkspace } from "@/lib/auth";
+import { prisma } from "@/lib/prisma";
+import { tokenSchema, updateTokenSchema } from "@/lib/zod/schemas/token";
+import { NextResponse } from "next/server";
+
+// GET /api/tokens/:id - get info about a specific token
+export const GET = withWorkspace(async ({ workspace, params }) => {
+ const token = await prisma.restrictedToken.findUnique({
+ where: {
+ id: params.id,
+ projectId: workspace.id,
+ },
+ select: {
+ id: true,
+ name: true,
+ partialKey: true,
+ scopes: true,
+ lastUsed: true,
+ createdAt: true,
+ updatedAt: true,
+ user: {
+ select: {
+ id: true,
+ name: true,
+ image: true,
+ isBot: true,
+ },
+ },
+ },
+ });
+
+ if (!token) {
+ throw new DubApiError({
+ code: "not_found",
+ message: `Token with id ${params.id} not found.`,
+ });
+ }
+
+ return NextResponse.json(tokenSchema.parse(token));
+});
+
+// PATCH /api/tokens/:id - update a specific token
+export const PATCH = withWorkspace(async ({ workspace, params, req }) => {
+ const { scopes } = updateTokenSchema.parse(await parseRequestBody(req));
+
+ const token = await prisma.restrictedToken.update({
+ where: {
+ id: params.id,
+ projectId: workspace.id,
+ },
+ data: {
+ scopes: scopes.join(" "),
+ },
+ select: {
+ id: true,
+ name: true,
+ partialKey: true,
+ scopes: true,
+ lastUsed: true,
+ createdAt: true,
+ updatedAt: true,
+ user: {
+ select: {
+ id: true,
+ name: true,
+ image: true,
+ isBot: true,
+ },
+ },
+ },
+ });
+
+ return NextResponse.json(tokenSchema.parse(token));
+});
+
+// DELETE /api/tokens/:id - delete a specific token
+export const DELETE = withWorkspace(async ({ workspace, params }) => {
+ const token = await prisma.restrictedToken.delete({
+ where: {
+ id: params.id,
+ projectId: workspace.id,
+ },
+ select: {
+ id: true,
+ user: {
+ select: {
+ id: true,
+ isBot: true,
+ },
+ },
+ },
+ });
+
+ // If the user is a service account, delete the user as well
+ // It is one-to-one relationship between service account and token
+ if (token.user.isBot) {
+ await prisma.user.delete({
+ where: {
+ id: token.user.id,
+ },
+ });
+ }
+
+ // TODO:
+ // Send email to user that their token has been deleted
+
+ return NextResponse.json({
+ id: token.id,
+ });
+});
diff --git a/apps/web/app/api/tokens/route.ts b/apps/web/app/api/tokens/route.ts
new file mode 100644
index 0000000000..ab0b4d298e
--- /dev/null
+++ b/apps/web/app/api/tokens/route.ts
@@ -0,0 +1,87 @@
+import { parseRequestBody } from "@/lib/api/utils";
+import { hashToken, withWorkspace } from "@/lib/auth";
+import { prisma } from "@/lib/prisma";
+import { createTokenSchema, tokenSchema } from "@/lib/zod/schemas/token";
+import { nanoid } from "@dub/utils";
+import { User } from "@prisma/client";
+import { waitUntil } from "@vercel/functions";
+import { sendEmail } from "emails";
+import APIKeyCreated from "emails/api-key-created";
+import { NextResponse } from "next/server";
+
+// POST /api/tokens – create a new token for a workspace
+export const POST = withWorkspace(async ({ req, session, workspace }) => {
+ const { name, isBot, scopes } = createTokenSchema.parse(
+ await parseRequestBody(req),
+ );
+
+ let botUser: User | null = null;
+
+ // Create service account
+ if (isBot) {
+ botUser = await prisma.user.create({
+ data: {
+ name,
+ isBot: true,
+ },
+ });
+ }
+
+ // Create token
+ const token = `dub_${nanoid(24)}`;
+ const hashedKey = await hashToken(token);
+ const partialKey = `${token.slice(0, 3)}...${token.slice(-4)}`;
+
+ await prisma.restrictedToken.create({
+ data: {
+ name,
+ hashedKey,
+ partialKey,
+ userId: botUser ? botUser.id : session.user.id,
+ projectId: workspace.id,
+ scopes: scopes ? scopes.join(" ") : null,
+ },
+ });
+
+ waitUntil(
+ sendEmail({
+ email: session.user.email,
+ subject: "New API Key Created",
+ react: APIKeyCreated({
+ email: session.user.email,
+ apiKeyName: name,
+ }),
+ }),
+ );
+
+ return NextResponse.json({ token });
+});
+
+// GET /api/tokens - get all tokens for a workspace
+export const GET = withWorkspace(async ({ workspace }) => {
+ const tokens = await prisma.restrictedToken.findMany({
+ where: {
+ projectId: workspace.id,
+ },
+ select: {
+ id: true,
+ name: true,
+ partialKey: true,
+ scopes: true,
+ lastUsed: true,
+ createdAt: true,
+ updatedAt: true,
+ user: {
+ select: {
+ id: true,
+ name: true,
+ image: true,
+ isBot: true,
+ },
+ },
+ },
+ orderBy: [{ lastUsed: "desc" }, { createdAt: "desc" }],
+ });
+
+ return NextResponse.json(tokenSchema.array().parse(tokens));
+});
diff --git a/apps/web/app/api/tokens/scopes/route.ts b/apps/web/app/api/tokens/scopes/route.ts
new file mode 100644
index 0000000000..6d162dfe0c
--- /dev/null
+++ b/apps/web/app/api/tokens/scopes/route.ts
@@ -0,0 +1,8 @@
+import { scopes } from "@/lib/api/api-keys/scopes";
+import { withWorkspace } from "@/lib/auth";
+import { NextResponse } from "next/server";
+
+// GET /api/tokens/scopes – return the available scopes for the token
+export const GET = withWorkspace(async () => {
+ return NextResponse.json(scopes);
+});
diff --git a/apps/web/lib/api/api-keys/scopes.ts b/apps/web/lib/api/api-keys/scopes.ts
new file mode 100644
index 0000000000..2e0b61c02f
--- /dev/null
+++ b/apps/web/lib/api/api-keys/scopes.ts
@@ -0,0 +1,37 @@
+export const scopes = [
+ // Workspaces
+ "workspaces.read",
+
+ // Links
+ "links.read",
+ "links.write",
+
+ // Analytics
+ "analytics.read",
+
+ // Tags
+ "tags.read",
+ "tags.write",
+] as const;
+
+// TODO:
+// Make the structure of the scopes more dynamic so that it can be used in the UI
+
+// export const scopes
+// = [
+// {
+// name: "Links",
+// description: "Create, read, update, and delete links",
+// endpoints: ["/links"],
+// permissions: [
+// {
+// scope: "links.read",
+// description: "Read links",
+// },
+// {
+// scope: "links.write",
+// description: "Write links",
+// },
+// ],
+// },
+// ] as const;
diff --git a/apps/web/lib/api/errors.ts b/apps/web/lib/api/errors.ts
index 0a337ce0a6..c5a6131b80 100644
--- a/apps/web/lib/api/errors.ts
+++ b/apps/web/lib/api/errors.ts
@@ -140,6 +140,18 @@ export function handleApiError(error: any): ErrorResponse & { status: number } {
};
}
+ // Prisma record not found error
+ if (error.code === "P2025") {
+ return {
+ error: {
+ code: "not_found",
+ message: `${error.meta.cause} Please check the provided identifier.`,
+ doc_url: `${docErrorUrl}#not-found`,
+ },
+ status: 404,
+ };
+ }
+
// Fallback
// Unhandled errors are not user-facing, so we don't expose the actual error
return {
diff --git a/apps/web/lib/zod/schemas/token.ts b/apps/web/lib/zod/schemas/token.ts
new file mode 100644
index 0000000000..a999da5360
--- /dev/null
+++ b/apps/web/lib/zod/schemas/token.ts
@@ -0,0 +1,40 @@
+import { scopes } from "@/lib/api/api-keys/scopes";
+import z from "@/lib/zod";
+
+// Schema to validate the request body when creating a new token
+export const createTokenSchema = z.object({
+ name: z
+ .string({
+ required_error: "Name is required",
+ })
+ .min(1)
+ .max(50),
+ isBot: z.boolean().optional().default(false),
+ scopes: z.array(z.enum(scopes)).optional(),
+});
+
+// Schema to validate the request body when updating a token
+export const updateTokenSchema = createTokenSchema
+ .pick({
+ scopes: true,
+ })
+ .required();
+
+// Represent the shape of a token returned from the API
+export const tokenSchema = z.object({
+ id: z.string(),
+ name: z.string(),
+ partialKey: z.string(),
+ scopes: z
+ .string()
+ .nullable()
+ .transform((val) => val?.split(" ") ?? []),
+ lastUsed: z.date().nullable(),
+ createdAt: z.date(),
+ updatedAt: z.date(),
+ user: z.object({
+ id: z.string(),
+ name: z.string().nullable(),
+ isBot: z.boolean(),
+ }),
+});
diff --git a/apps/web/prisma/schema.prisma b/apps/web/prisma/schema.prisma
index 94db2e5854..ff3b82c5b0 100644
--- a/apps/web/prisma/schema.prisma
+++ b/apps/web/prisma/schema.prisma
@@ -13,19 +13,21 @@ generator client {
}
model User {
- id String @id @default(cuid())
- name String?
- email String? @unique
- emailVerified DateTime?
- image String?
+ id String @id @default(cuid())
+ name String?
+ email String? @unique
+ emailVerified DateTime?
+ image String?
+ isBot Boolean @default(false)
accounts Account[]
sessions Session[]
projects ProjectUsers[]
links Link[]
tokens Token[]
- createdAt DateTime @default(now())
- subscribed Boolean @default(true)
+ restrictedTokens RestrictedToken[]
+ createdAt DateTime @default(now())
+ subscribed Boolean @default(true)
source String?
defaultWorkspace String?
@@ -87,40 +89,60 @@ model Token {
@@index([userId])
}
+model RestrictedToken {
+ id String @id @default(cuid())
+ name String
+ hashedKey String @unique
+ partialKey String
+ scopes String? // space separated
+ expires DateTime?
+ lastUsed DateTime?
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+ userId String
+ projectId String
+
+ user User @relation(fields: [userId], references: [id], onDelete: Cascade)
+ project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
+
+ @@index([userId])
+}
+
model Project {
id String @id @default(cuid())
name String
slug String @unique
logo String?
- plan String @default("free")
- stripeId String? @unique // Stripe subscription ID
+ plan String @default("free")
+ stripeId String? @unique // Stripe subscription ID
billingCycleStart Int // day of the month when the billing cycle starts
- stripeConnectId String? @unique // for Stripe Connect
- inviteCode String? @unique
-
- usage Int @default(0)
- usageLimit Int @default(1000)
- aiUsage Int @default(0)
- aiLimit Int @default(10)
- linksUsage Int @default(0)
- linksLimit Int @default(25)
- domainsLimit Int @default(3)
- tagsLimit Int @default(5)
- usersLimit Int @default(1)
-
- createdAt DateTime @default(now())
- updatedAt DateTime @updatedAt
- usageLastChecked DateTime @default(now())
-
- users ProjectUsers[]
- invites ProjectInvite[]
- sentEmails SentEmail[]
- links Link[]
- domains Domain[]
- tags Tag[]
- customers Customer[]
- defaultDomains DefaultDomains[]
+ stripeConnectId String? @unique // for Stripe Connect
+ inviteCode String? @unique
+
+ usage Int @default(0)
+ usageLimit Int @default(1000)
+ aiUsage Int @default(0)
+ aiLimit Int @default(10)
+ linksUsage Int @default(0)
+ linksLimit Int @default(25)
+ domainsLimit Int @default(3)
+ tagsLimit Int @default(5)
+ usersLimit Int @default(1)
+
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+ usageLastChecked DateTime @default(now())
+
+ users ProjectUsers[]
+ invites ProjectInvite[]
+ sentEmails SentEmail[]
+ links Link[]
+ domains Domain[]
+ tags Tag[]
+ customers Customer[]
+ defaultDomains DefaultDomains[]
+ restrictedTokens RestrictedToken[]
@@index(usageLastChecked(sort: Asc))
}