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 scope check

Kiran K3bd6a55234b5
diff --git a/apps/web/app/api/domains/default/route.ts b/apps/web/app/api/domains/default/route.ts
index f466dce40f..6eb0fd9577 100644
--- a/apps/web/app/api/domains/default/route.ts
+++ b/apps/web/app/api/domains/default/route.ts
@@ -34,7 +34,7 @@ export const GET = withWorkspace(
return NextResponse.json(defaultDomainsArray);
},
{
- requiredScopes: ["domains.write"],
+ requiredScopes: ["domains.read"],
},
);
diff --git a/apps/web/app/api/links/[linkId]/route.ts b/apps/web/app/api/links/[linkId]/route.ts
index a02258bda2..2e4fcad9c1 100644
--- a/apps/web/app/api/links/[linkId]/route.ts
+++ b/apps/web/app/api/links/[linkId]/route.ts
@@ -14,38 +14,43 @@ import { deepEqual } from "@dub/utils";
import { NextResponse } from "next/server";
// GET /api/links/[linkId] – get a link
-export const GET = withWorkspace(async ({ headers, link }) => {
- if (!link) {
- throw new DubApiError({
- code: "not_found",
- message: "Link not found.",
- });
- }
+export const GET = withWorkspace(
+ async ({ headers, link }) => {
+ if (!link) {
+ throw new DubApiError({
+ code: "not_found",
+ message: "Link not found.",
+ });
+ }
- const tags = await prisma.tag.findMany({
- where: {
- links: {
- some: {
- linkId: link.id,
+ const tags = await prisma.tag.findMany({
+ where: {
+ links: {
+ some: {
+ linkId: link.id,
+ },
},
},
- },
- select: {
- id: true,
- name: true,
- color: true,
- },
- });
-
- const response = transformLink({
- ...link,
- tags: tags.map((tag) => {
- return { tag };
- }),
- });
-
- return NextResponse.json(response, { headers });
-});
+ select: {
+ id: true,
+ name: true,
+ color: true,
+ },
+ });
+
+ const response = transformLink({
+ ...link,
+ tags: tags.map((tag) => {
+ return { tag };
+ }),
+ });
+
+ return NextResponse.json(response, { headers });
+ },
+ {
+ requiredScopes: ["links.read"],
+ },
+);
// PATCH /api/links/[linkId] – update a link
export const PATCH = withWorkspace(
@@ -128,19 +133,27 @@ export const PATCH = withWorkspace(
});
}
},
+ {
+ requiredScopes: ["links.write"],
+ },
);
// backwards compatibility
export const PUT = PATCH;
// DELETE /api/links/[linkId] – delete a link
-export const DELETE = withWorkspace(async ({ headers, link }) => {
- await deleteLink(link!.id);
-
- return NextResponse.json(
- { id: link!.id },
- {
- headers,
- },
- );
-});
+export const DELETE = withWorkspace(
+ async ({ headers, link }) => {
+ await deleteLink(link!.id);
+
+ return NextResponse.json(
+ { id: link!.id },
+ {
+ headers,
+ },
+ );
+ },
+ {
+ requiredScopes: ["links.write"],
+ },
+);
diff --git a/apps/web/app/api/links/[linkId]/transfer/route.ts b/apps/web/app/api/links/[linkId]/transfer/route.ts
index bbdac7166a..35ed4e86a9 100644
--- a/apps/web/app/api/links/[linkId]/transfer/route.ts
+++ b/apps/web/app/api/links/[linkId]/transfer/route.ts
@@ -139,4 +139,7 @@ export const POST = withWorkspace(
headers,
});
},
+ {
+ requiredScopes: ["links.write"],
+ },
);
diff --git a/apps/web/app/api/links/bulk/route.ts b/apps/web/app/api/links/bulk/route.ts
index d8a34431d6..03d767d4e8 100644
--- a/apps/web/app/api/links/bulk/route.ts
+++ b/apps/web/app/api/links/bulk/route.ts
@@ -126,5 +126,6 @@ export const POST = withWorkspace(
},
{
needNotExceededLinks: true,
+ requiredScopes: ["links.write"],
},
);
diff --git a/apps/web/app/api/links/count/route.ts b/apps/web/app/api/links/count/route.ts
index 8c3bd12894..22f4292d3d 100644
--- a/apps/web/app/api/links/count/route.ts
+++ b/apps/web/app/api/links/count/route.ts
@@ -18,4 +18,7 @@ export const GET = withWorkspace(
headers,
});
},
+ {
+ requiredScopes: ["links.read"],
+ },
);
diff --git a/apps/web/app/api/links/info/route.ts b/apps/web/app/api/links/info/route.ts
index 6bdfb9544f..64bf3a277f 100644
--- a/apps/web/app/api/links/info/route.ts
+++ b/apps/web/app/api/links/info/route.ts
@@ -6,55 +6,61 @@ import { getLinkInfoQuerySchema } from "@/lib/zod/schemas/links";
import { NextResponse } from "next/server";
// GET /api/links/info – get the info for a link
-export const GET = withWorkspace(async ({ headers, searchParams, link }) => {
- const { domain, key, linkId, externalId } =
- getLinkInfoQuerySchema.parse(searchParams);
+export const GET = withWorkspace(
+ async ({ headers, searchParams, link }) => {
+ const { domain, key, linkId, externalId } =
+ getLinkInfoQuerySchema.parse(searchParams);
- if (!domain && !key && !linkId && !externalId) {
- throw new DubApiError({
- code: "bad_request",
- message:
- "You must provide a domain and a key or a linkId or an externalId to retrieve a link.",
- docUrl: "https://dub.co/docs/api-reference/endpoint/retrieve-a-link",
- });
- }
-
- if (!link) {
- if (externalId && !externalId.startsWith("ext_")) {
+ if (!domain && !key && !linkId && !externalId) {
throw new DubApiError({
code: "bad_request",
- message: "Invalid externalId. Did you forget to prefix it with `ext_`?",
+ message:
+ "You must provide a domain and a key or a linkId or an externalId to retrieve a link.",
+ docUrl: "https://dub.co/docs/api-reference/endpoint/retrieve-a-link",
});
}
- throw new DubApiError({
- code: "not_found",
- message: "Link not found.",
- });
- }
- const tags = await prisma.tag.findMany({
- where: {
- links: {
- some: {
- linkId: link.id,
+ if (!link) {
+ if (externalId && !externalId.startsWith("ext_")) {
+ throw new DubApiError({
+ code: "bad_request",
+ message:
+ "Invalid externalId. Did you forget to prefix it with `ext_`?",
+ });
+ }
+ throw new DubApiError({
+ code: "not_found",
+ message: "Link not found.",
+ });
+ }
+
+ const tags = await prisma.tag.findMany({
+ where: {
+ links: {
+ some: {
+ linkId: link.id,
+ },
},
},
- },
- select: {
- id: true,
- name: true,
- color: true,
- },
- });
+ select: {
+ id: true,
+ name: true,
+ color: true,
+ },
+ });
- const response = transformLink({
- ...link,
- tags: tags.map((tag) => {
- return { tag };
- }),
- });
+ const response = transformLink({
+ ...link,
+ tags: tags.map((tag) => {
+ return { tag };
+ }),
+ });
- return NextResponse.json(response, {
- headers,
- });
-});
+ return NextResponse.json(response, {
+ headers,
+ });
+ },
+ {
+ requiredScopes: ["links.read"],
+ },
+);
diff --git a/apps/web/app/api/links/sync/route.ts b/apps/web/app/api/links/sync/route.ts
index 7888201b70..901beae4a0 100644
--- a/apps/web/app/api/links/sync/route.ts
+++ b/apps/web/app/api/links/sync/route.ts
@@ -6,71 +6,76 @@ import { SimpleLinkProps } from "@/lib/types";
import { NextResponse } from "next/server";
// POST /api/links/sync – sync user's publicly created links to their accounts
-export const POST = withWorkspace(async ({ req, session, workspace }) => {
- let links: SimpleLinkProps[] = [];
- try {
- links = await req.json();
- if (!Array.isArray(links)) {
- throw new Error("Invalid request body.");
+export const POST = withWorkspace(
+ async ({ req, session, workspace }) => {
+ let links: SimpleLinkProps[] = [];
+ try {
+ links = await req.json();
+ if (!Array.isArray(links)) {
+ throw new Error("Invalid request body.");
+ }
+ } catch (e) {
+ return new Response("Invalid request body.", { status: 400 });
}
- } catch (e) {
- return new Response("Invalid request body.", { status: 400 });
- }
- const unclaimedLinks = await Promise.all(
- links.map(async (link) => {
- return await prisma.link.findUnique({
- where: {
- domain_key: {
- domain: link.domain,
- key: link.key,
+ const unclaimedLinks = await Promise.all(
+ links.map(async (link) => {
+ return await prisma.link.findUnique({
+ where: {
+ domain_key: {
+ domain: link.domain,
+ key: link.key,
+ },
+ userId: null,
},
- userId: null,
- },
- include: {
- tags: true,
- },
- });
- }),
- ).then((links) => links.filter((link) => link !== null));
+ include: {
+ tags: true,
+ },
+ });
+ }),
+ ).then((links) => links.filter((link) => link !== null));
- if (unclaimedLinks.length === 0) {
- return new Response("No links created.", { status: 200 });
- }
+ if (unclaimedLinks.length === 0) {
+ return new Response("No links created.", { status: 200 });
+ }
- if (workspace.linksUsage + unclaimedLinks.length > workspace.linksLimit) {
- return new Response(
- exceededLimitError({
- plan: workspace.plan,
- limit: workspace.linksLimit,
- type: "links",
- }),
- { status: 403 },
- );
- }
+ if (workspace.linksUsage + unclaimedLinks.length > workspace.linksLimit) {
+ return new Response(
+ exceededLimitError({
+ plan: workspace.plan,
+ limit: workspace.linksLimit,
+ type: "links",
+ }),
+ { status: 403 },
+ );
+ }
- const response = await Promise.allSettled([
- prisma.link.updateMany({
- where: {
- id: {
- in: unclaimedLinks.map((link) => link!.id),
+ const response = await Promise.allSettled([
+ prisma.link.updateMany({
+ where: {
+ id: {
+ in: unclaimedLinks.map((link) => link!.id),
+ },
+ },
+ data: {
+ userId: session.user.id,
+ projectId: workspace.id,
+ publicStats: false,
},
- },
- data: {
- userId: session.user.id,
- projectId: workspace.id,
- publicStats: false,
- },
- }),
- propagateBulkLinkChanges(
- unclaimedLinks.map((link) => ({
- ...link!,
- userId: session.user.id,
- projectId: workspace.id,
- publicStats: false,
- })),
- ),
- ]);
+ }),
+ propagateBulkLinkChanges(
+ unclaimedLinks.map((link) => ({
+ ...link!,
+ userId: session.user.id,
+ projectId: workspace.id,
+ publicStats: false,
+ })),
+ ),
+ ]);
- return NextResponse.json(response);
-});
+ return NextResponse.json(response);
+ },
+ {
+ requiredScopes: ["links.write"],
+ },
+);
diff --git a/apps/web/app/api/links/upsert/route.ts b/apps/web/app/api/links/upsert/route.ts
index 4a5dcb9bb8..4f9861e98a 100644
--- a/apps/web/app/api/links/upsert/route.ts
+++ b/apps/web/app/api/links/upsert/route.ts
@@ -151,4 +151,7 @@ export const PUT = withWorkspace(
}
}
},
+ {
+ requiredScopes: ["links.write"],
+ },
);
diff --git a/apps/web/app/api/tags/[id]/route.ts b/apps/web/app/api/tags/[id]/route.ts
index e84ae00f8c..8b42bb51da 100644
--- a/apps/web/app/api/tags/[id]/route.ts
+++ b/apps/web/app/api/tags/[id]/route.ts
@@ -6,104 +6,114 @@ import { updateTagBodySchema } from "@/lib/zod/schemas/tags";
import { NextResponse } from "next/server";
// PATCH /api/workspaces/[idOrSlug]/tags/[id] – update a tag for a workspace
-export const PATCH = withWorkspace(async ({ req, params, workspace }) => {
- const { id } = params;
- const { name, color } = updateTagBodySchema.parse(await req.json());
+export const PATCH = withWorkspace(
+ async ({ req, params, workspace }) => {
+ const { id } = params;
+ const { name, color } = updateTagBodySchema.parse(await req.json());
- const tag = await prisma.tag.findFirst({
- where: {
- id,
- projectId: workspace.id,
- },
- });
-
- if (!tag) {
- throw new DubApiError({
- code: "not_found",
- message: "Tag not found.",
- });
- }
-
- try {
- const response = await prisma.tag.update({
+ const tag = await prisma.tag.findFirst({
where: {
id,
- },
- data: {
- name,
- color,
+ projectId: workspace.id,
},
});
- return NextResponse.json(response);
- } catch (error) {
- if (error.code === "P2002") {
+
+ if (!tag) {
throw new DubApiError({
- code: "conflict",
- message: "A tag with that name already exists.",
+ code: "not_found",
+ message: "Tag not found.",
});
}
- throw error;
- }
-});
+ try {
+ const response = await prisma.tag.update({
+ where: {
+ id,
+ },
+ data: {
+ name,
+ color,
+ },
+ });
+ return NextResponse.json(response);
+ } catch (error) {
+ if (error.code === "P2002") {
+ throw new DubApiError({
+ code: "conflict",
+ message: "A tag with that name already exists.",
+ });
+ }
+
+ throw error;
+ }
+ },
+ {
+ requiredScopes: ["tags.write"],
+ },
+);
export const PUT = PATCH;
// DELETE /api/workspaces/[idOrSlug]/tags/[id] – delete a tag for a workspace
-export const DELETE = withWorkspace(async ({ params, workspace }) => {
- const { id } = params;
- try {
- const response = await prisma.tag.delete({
- where: {
- id,
- projectId: workspace.id,
- },
- include: {
- links: {
- select: {
- link: {
- select: {
- id: true,
- domain: true,
- key: true,
- url: true,
- createdAt: true,
+export const DELETE = withWorkspace(
+ async ({ params, workspace }) => {
+ const { id } = params;
+ try {
+ const response = await prisma.tag.delete({
+ where: {
+ id,
+ projectId: workspace.id,
+ },
+ include: {
+ links: {
+ select: {
+ link: {
+ select: {
+ id: true,
+ domain: true,
+ key: true,
+ url: true,
+ createdAt: true,
+ },
},
},
},
},
- },
- });
-
- if (!response) {
- throw new DubApiError({
- code: "not_found",
- message: "Tag not found.",
});
- }
- // update links metadata in tinybird after deleting a tag
- await recordLink(
- response.links.map(({ link }) => ({
- link_id: link.id,
- domain: link.domain,
- key: link.key,
- url: link.url,
- tag_ids: [],
- workspace_id: workspace.id,
- created_at: link.createdAt,
- })),
- );
+ if (!response) {
+ throw new DubApiError({
+ code: "not_found",
+ message: "Tag not found.",
+ });
+ }
- return NextResponse.json(response);
- } catch (error) {
- if (error.code === "P2025") {
- throw new DubApiError({
- code: "not_found",
- message: "Tag not found.",
- });
- }
+ // update links metadata in tinybird after deleting a tag
+ await recordLink(
+ response.links.map(({ link }) => ({
+ link_id: link.id,
+ domain: link.domain,
+ key: link.key,
+ url: link.url,
+ tag_ids: [],
+ workspace_id: workspace.id,
+ created_at: link.createdAt,
+ })),
+ );
- throw error;
- }
-});
+ return NextResponse.json(response);
+ } catch (error) {
+ if (error.code === "P2025") {
+ throw new DubApiError({
+ code: "not_found",
+ message: "Tag not found.",
+ });
+ }
+
+ throw error;
+ }
+ },
+ {
+ requiredScopes: ["tags.write"],
+ },
+);
diff --git a/apps/web/app/api/tags/route.ts b/apps/web/app/api/tags/route.ts
index f13dbf59c0..887d58867d 100644
--- a/apps/web/app/api/tags/route.ts
+++ b/apps/web/app/api/tags/route.ts
@@ -6,68 +6,78 @@ import { COLORS_LIST, randomBadgeColor } from "@/ui/links/tag-badge";
import { NextResponse } from "next/server";
// GET /api/tags - get all tags for a workspace
-export const GET = withWorkspace(async ({ workspace, headers }) => {
- const tags = await prisma.tag.findMany({
- where: {
- projectId: workspace.id,
- },
- select: {
- id: true,
- name: true,
- color: true,
- },
- orderBy: {
- name: "asc",
- },
- });
- return NextResponse.json(tags, { headers });
-});
+export const GET = withWorkspace(
+ async ({ workspace, headers }) => {
+ const tags = await prisma.tag.findMany({
+ where: {
+ projectId: workspace.id,
+ },
+ select: {
+ id: true,
+ name: true,
+ color: true,
+ },
+ orderBy: {
+ name: "asc",
+ },
+ });
+ return NextResponse.json(tags, { headers });
+ },
+ {
+ requiredScopes: ["tags.read"],
+ },
+);
// POST /api/workspaces/[idOrSlug]/tags - create a tag for a workspace
-export const POST = withWorkspace(async ({ req, workspace, headers }) => {
- const tagsCount = await prisma.tag.count({
- where: {
- projectId: workspace.id,
- },
- });
-
- if (tagsCount >= workspace.tagsLimit) {
- throw new DubApiError({
- code: "exceeded_limit",
- message: exceededLimitError({
- plan: workspace.plan,
- limit: workspace.tagsLimit,
- type: "tags",
- }),
+export const POST = withWorkspace(
+ async ({ req, workspace, headers }) => {
+ const tagsCount = await prisma.tag.count({
+ where: {
+ projectId: workspace.id,
+ },
});
- }
- const { tag, color } = createTagBodySchema.parse(await req.json());
+ if (tagsCount >= workspace.tagsLimit) {
+ throw new DubApiError({
+ code: "exceeded_limit",
+ message: exceededLimitError({
+ plan: workspace.plan,
+ limit: workspace.tagsLimit,
+ type: "tags",
+ }),
+ });
+ }
- const existingTag = await prisma.tag.findFirst({
- where: {
- projectId: workspace.id,
- name: tag,
- },
- });
+ const { tag, color } = createTagBodySchema.parse(await req.json());
- if (existingTag) {
- throw new DubApiError({
- code: "conflict",
- message: "A tag with that name already exists.",
+ const existingTag = await prisma.tag.findFirst({
+ where: {
+ projectId: workspace.id,
+ name: tag,
+ },
});
- }
- const response = await prisma.tag.create({
- data: {
- name: tag,
- color:
- color && COLORS_LIST.map(({ color }) => color).includes(color)
- ? color
- : randomBadgeColor(),
- projectId: workspace.id,
- },
- });
+ if (existingTag) {
+ throw new DubApiError({
+ code: "conflict",
+ message: "A tag with that name already exists.",
+ });
+ }
+
+ const response = await prisma.tag.create({
+ data: {
+ name: tag,
+ color:
+ color && COLORS_LIST.map(({ color }) => color).includes(color)
+ ? color
+ : randomBadgeColor(),
+ projectId: workspace.id,
+ },
+ });
- return NextResponse.json(response, { headers, status: 201 });
-});
+ return NextResponse.json(response, { headers, status: 201 });
+ },
+ {
+ requiredScopes: ["tags.write"],
+ },
+);
diff --git a/apps/web/app/api/tokens/[id]/route.ts b/apps/web/app/api/tokens/[id]/route.ts
index 1871834bfa..0c378d584f 100644
--- a/apps/web/app/api/tokens/[id]/route.ts
+++ b/apps/web/app/api/tokens/[id]/route.ts
@@ -6,107 +6,122 @@ 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,
- isMachine: true,
+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,
+ isMachine: true,
+ },
},
},
- },
- });
-
- if (!token) {
- throw new DubApiError({
- code: "not_found",
- message: `Token with id ${params.id} not found.`,
});
- }
- return NextResponse.json(tokenSchema.parse(token));
-});
+ if (!token) {
+ throw new DubApiError({
+ code: "not_found",
+ message: `Token with id ${params.id} not found.`,
+ });
+ }
+
+ return NextResponse.json(tokenSchema.parse(token));
+ },
+ {
+ requiredScopes: ["tokens.read"],
+ },
+);
// PATCH /api/tokens/:id - update a specific token
-export const PATCH = withWorkspace(async ({ workspace, params, req }) => {
- const { scopes } = updateTokenSchema.parse(await parseRequestBody(req));
+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,
- isMachine: true,
+ 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,
+ isMachine: true,
+ },
},
},
- },
- });
+ });
- return NextResponse.json(tokenSchema.parse(token));
-});
+ return NextResponse.json(tokenSchema.parse(token));
+ },
+ {
+ requiredScopes: ["tokens.write"],
+ },
+);
// 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,
- isMachine: 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.isMachine) {
- await prisma.user.delete({
+export const DELETE = withWorkspace(
+ async ({ workspace, params }) => {
+ const token = await prisma.restrictedToken.delete({
where: {
- id: token.user.id,
+ id: params.id,
+ projectId: workspace.id,
+ },
+ select: {
+ id: true,
+ user: {
+ select: {
+ id: true,
+ isMachine: true,
+ },
+ },
},
});
- }
- // TODO:
- // Send email to user that their token has been deleted
+ // 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.isMachine) {
+ 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,
- });
-});
+ return NextResponse.json({
+ id: token.id,
+ });
+ },
+ {
+ requiredScopes: ["tokens.write"],
+ },
+);
diff --git a/apps/web/app/api/tokens/route.ts b/apps/web/app/api/tokens/route.ts
index f391af9d22..1363ff08f4 100644
--- a/apps/web/app/api/tokens/route.ts
+++ b/apps/web/app/api/tokens/route.ts
@@ -10,88 +10,98 @@ 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, isMachine, scopes } = createTokenSchema.parse(
- await parseRequestBody(req),
- );
+export const POST = withWorkspace(
+ async ({ req, session, workspace }) => {
+ const { name, isMachine, scopes } = createTokenSchema.parse(
+ await parseRequestBody(req),
+ );
- let machineUser: User | null = null;
+ let machineUser: User | null = null;
- // Create machine user if needed
- if (isMachine) {
- machineUser = await prisma.user.create({
- data: {
- name: "Machine",
- image: "https://api.dicebear.com/9.x/bottts/svg",
- isMachine: true,
- },
- });
+ // Create machine user if needed
+ if (isMachine) {
+ machineUser = await prisma.user.create({
+ data: {
+ name: "Machine",
+ image: "https://api.dicebear.com/9.x/bottts/svg",
+ isMachine: true,
+ },
+ });
+
+ // Add machine user to workspace
+ await prisma.projectUsers.create({
+ data: {
+ role: "member",
+ userId: machineUser.id,
+ projectId: workspace.id,
+ },
+ });
+ }
- // Add machine user to workspace
- await prisma.projectUsers.create({
+ // 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: {
- role: "member",
- userId: machineUser.id,
+ name,
+ hashedKey,
+ partialKey,
+ userId: isMachine ? machineUser?.id! : session.user.id,
projectId: workspace.id,
+ scopes: scopes && scopes.length > 0 ? scopes.join(" ") : null,
},
});
- }
-
- // 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: isMachine ? machineUser?.id! : session.user.id,
- projectId: workspace.id,
- scopes: scopes && scopes.length > 0 ? scopes.join(" ") : null,
- },
- });
-
- waitUntil(
- sendEmail({
- email: session.user.email,
- subject: "New API Key Created",
- react: APIKeyCreated({
+ waitUntil(
+ sendEmail({
email: session.user.email,
- apiKeyName: name,
+ subject: "New API Key Created",
+ react: APIKeyCreated({
+ email: session.user.email,
+ apiKeyName: name,
+ }),
}),
- }),
- );
+ );
- return NextResponse.json({ token });
-});
+ return NextResponse.json({ token });
+ },
+ {
+ requiredScopes: ["tokens.write"],
+ },
+);
// 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,
- isMachine: true,
+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,
+ isMachine: true,
+ },
},
},
- },
- orderBy: [{ lastUsed: "desc" }, { createdAt: "desc" }],
- });
+ orderBy: [{ lastUsed: "desc" }, { createdAt: "desc" }],
+ });
- return NextResponse.json(tokenSchema.array().parse(tokens));
-});
+ return NextResponse.json(tokenSchema.array().parse(tokens));
+ },
+ {
+ requiredScopes: ["tokens.read"],
+ },
+);
diff --git a/apps/web/app/api/workspaces/[idOrSlug]/invites/reset/route.ts b/apps/web/app/api/workspaces/[idOrSlug]/invites/reset/route.ts
index daea9ed4fb..e4cabf6d18 100644
--- a/apps/web/app/api/workspaces/[idOrSlug]/invites/reset/route.ts
+++ b/apps/web/app/api/workspaces/[idOrSlug]/invites/reset/route.ts
@@ -17,6 +17,6 @@ export const POST = withWorkspace(
return NextResponse.json(response);
},
{
- requiredRole: ["owner"],
+ requiredScopes: ["workspaces.write"],
},
);
diff --git a/apps/web/app/api/workspaces/[idOrSlug]/invites/route.tsx b/apps/web/app/api/workspaces/[idOrSlug]/invites/route.tsx
index 064746b891..6e35de3a4a 100644
--- a/apps/web/app/api/workspaces/[idOrSlug]/invites/route.tsx
+++ b/apps/web/app/api/workspaces/[idOrSlug]/invites/route.tsx
@@ -10,18 +10,23 @@ const emailInviteSchema = z.object({
});
// GET /api/workspaces/[idOrSlug]/invites – get invites for a specific workspace
-export const GET = withWorkspace(async ({ workspace }) => {
- const invites = await prisma.projectInvite.findMany({
- where: {
- projectId: workspace.id,
- },
- select: {
- email: true,
- createdAt: true,
- },
- });
- return NextResponse.json(invites);
-});
+export const GET = withWorkspace(
+ async ({ workspace }) => {
+ const invites = await prisma.projectInvite.findMany({
+ where: {
+ projectId: workspace.id,
+ },
+ select: {
+ email: true,
+ createdAt: true,
+ },
+ });
+ return NextResponse.json(invites);
+ },
+ {
+ requiredScopes: ["workspaces.read"],
+ },
+);
// POST /api/workspaces/[idOrSlug]/invites – invite a teammate
export const POST = withWorkspace(
@@ -77,7 +82,7 @@ export const POST = withWorkspace(
return NextResponse.json({ message: "Invite sent" });
},
{
- requiredRole: ["owner"],
+ requiredScopes: ["workspaces.write"],
},
);
@@ -96,6 +101,6 @@ export const DELETE = withWorkspace(
return NextResponse.json(response);
},
{
- requiredRole: ["owner"],
+ requiredScopes: ["workspaces.write"],
},
);
diff --git a/apps/web/app/api/workspaces/[idOrSlug]/logo/route.ts b/apps/web/app/api/workspaces/[idOrSlug]/logo/route.ts
index 83dc896fe4..a252ec13fe 100644
--- a/apps/web/app/api/workspaces/[idOrSlug]/logo/route.ts
+++ b/apps/web/app/api/workspaces/[idOrSlug]/logo/route.ts
@@ -23,6 +23,6 @@ export const POST = withWorkspace(
return NextResponse.json(response);
},
{
- requiredRole: ["owner"],
+ requiredScopes: ["workspaces.write"],
},
);
diff --git a/apps/web/app/api/workspaces/[idOrSlug]/route.ts b/apps/web/app/api/workspaces/[idOrSlug]/route.ts
index c6a11b1a2a..953ab19d33 100644
--- a/apps/web/app/api/workspaces/[idOrSlug]/route.ts
+++ b/apps/web/app/api/workspaces/[idOrSlug]/route.ts
@@ -33,18 +33,23 @@ const updateWorkspaceSchema = z.object({
});
// GET /api/workspaces/[idOrSlug] – get a specific workspace by id or slug
-export const GET = withWorkspace(async ({ workspace, headers }) => {
- const betaTester = await isBetaTester(workspace.id);
+export const GET = withWorkspace(
+ async ({ workspace, headers }) => {
+ const betaTester = await isBetaTester(workspace.id);
- return NextResponse.json(
- WorkspaceSchema.parse({
- ...workspace,
- id: `ws_${workspace.id}`,
- betaTester,
- }),
- { headers },
- );
-});
+ return NextResponse.json(
+ WorkspaceSchema.parse({
+ ...workspace,
+ id: `ws_${workspace.id}`,
+ betaTester,
+ }),
+ { headers },
+ );
+ },
+ {
+ requiredScopes: ["workspaces.read"],
+ },
+);
// PATCH /api/workspaces/[idOrSlug] – update a specific workspace by id or slug
export const PATCH = withWorkspace(
@@ -88,7 +93,7 @@ export const PATCH = withWorkspace(
}
},
{
- requiredRole: ["owner"],
+ requiredScopes: ["workspaces.write"],
},
);
@@ -102,6 +107,6 @@ export const DELETE = withWorkspace(
return NextResponse.json(workspace);
},
{
- requiredRole: ["owner"],
+ requiredScopes: ["workspaces.write"],
},
);
diff --git a/apps/web/app/api/workspaces/[idOrSlug]/saml/route.ts b/apps/web/app/api/workspaces/[idOrSlug]/saml/route.ts
index 9e0c80ac04..a799bc51fd 100644
--- a/apps/web/app/api/workspaces/[idOrSlug]/saml/route.ts
+++ b/apps/web/app/api/workspaces/[idOrSlug]/saml/route.ts
@@ -24,25 +24,30 @@ const deleteSAMLConnectionSchema = z.object({
});
// GET /api/workspaces/[idOrSlug]/saml – get SAML connections for a specific workspace
-export const GET = withWorkspace(async ({ workspace }) => {
- const { apiController } = await jackson();
+export const GET = withWorkspace(
+ async ({ workspace }) => {
+ const { apiController } = await jackson();
- const connections = await apiController.getConnections({
- tenant: workspace.id,
- product: "Dub",
- });
+ const connections = await apiController.getConnections({
+ tenant: workspace.id,
+ product: "Dub",
+ });
- const response = {
- connections,
- issuer: samlAudience,
- acs:
- process.env.NODE_ENV === "production"
- ? "https://api.dub.co/auth/saml/callback"
- : `${APP_DOMAIN_WITH_NGROK}/api/auth/saml/callback`,
- };
+ const response = {
+ connections,
+ issuer: samlAudience,
+ acs:
+ process.env.NODE_ENV === "production"
+ ? "https://api.dub.co/auth/saml/callback"
+ : `${APP_DOMAIN_WITH_NGROK}/api/auth/saml/callback`,
+ };
- return NextResponse.json(response);
-});
+ return NextResponse.json(response);
+ },
+ {
+ requiredScopes: ["workspaces.read"],
+ },
+);
// POST /api/workspaces/[idOrSlug]/saml – create a new SAML connection
export const POST = withWorkspace(
@@ -64,13 +69,12 @@ export const POST = withWorkspace(
return NextResponse.json(data);
},
{
- requiredRole: ["owner"],
+ requiredScopes: ["workspaces.write"],
requiredPlan: ["enterprise"],
},
);
// DELETE /api/workspaces/[idOrSlug]/saml – delete all SAML connections
-
export const DELETE = withWorkspace(
async ({ searchParams }) => {
const { clientID, clientSecret } =
@@ -86,6 +90,6 @@ export const DELETE = withWorkspace(
return NextResponse.json({ response: "removed SAML connection" });
},
{
- requiredRole: ["owner"],
+ requiredScopes: ["workspaces.write"],
},
);
diff --git a/apps/web/app/api/workspaces/[idOrSlug]/scim/route.ts b/apps/web/app/api/workspaces/[idOrSlug]/scim/route.ts
index 86539b9523..e44ae37ad5 100644
--- a/apps/web/app/api/workspaces/[idOrSlug]/scim/route.ts
+++ b/apps/web/app/api/workspaces/[idOrSlug]/scim/route.ts
@@ -14,25 +14,30 @@ const deleteDirectorySchema = z.object({
});
// GET /api/workspaces/[idOrSlug]/scim – get all SCIM directories
-export const GET = withWorkspace(async ({ workspace }) => {
- const { directorySyncController } = await jackson();
+export const GET = withWorkspace(
+ async ({ workspace }) => {
+ const { directorySyncController } = await jackson();
- const { data, error } =
- await directorySyncController.directories.getByTenantAndProduct(
- workspace.id,
- "Dub",
- );
- if (error) {
- throw new DubApiError({
- code: "internal_server_error",
- message: error.message,
- });
- }
+ const { data, error } =
+ await directorySyncController.directories.getByTenantAndProduct(
+ workspace.id,
+ "Dub",
+ );
+ if (error) {
+ throw new DubApiError({
+ code: "internal_server_error",
+ message: error.message,
+ });
+ }
- return NextResponse.json({
- directories: data,
- });
-});
+ return NextResponse.json({
+ directories: data,
+ });
+ },
+ {
+ requiredScopes: ["workspaces.read"],
+ },
+);
// POST /api/workspaces/[idOrSlug]/scim – create a new SCIM directory
export const POST = withWorkspace(
@@ -56,13 +61,12 @@ export const POST = withWorkspace(
return NextResponse.json(data);
},
{
- requiredRole: ["owner"],
+ requiredScopes: ["workspaces.write"],
requiredPlan: ["enterprise"],
},
);
// DELETE /api/workspaces/[idOrSlug]/scim – delete a SCIM directory
-
export const DELETE = withWorkspace(
async ({ searchParams }) => {
const { directoryId } = deleteDirectorySchema.parse(searchParams);
@@ -82,6 +86,6 @@ export const DELETE = withWorkspace(
return NextResponse.json(data);
},
{
- requiredRole: ["owner"],
+ requiredScopes: ["workspaces.write"],
},
);
diff --git a/apps/web/app/api/workspaces/[idOrSlug]/users/route.ts b/apps/web/app/api/workspaces/[idOrSlug]/users/route.ts
index 81043b8d96..8e2bdc00f5 100644
--- a/apps/web/app/api/workspaces/[idOrSlug]/users/route.ts
+++ b/apps/web/app/api/workspaces/[idOrSlug]/users/route.ts
@@ -19,31 +19,36 @@ const removeUserSchema = z.object({
});
// GET /api/workspaces/[idOrSlug]/users – get users for a specific workspace
-export const GET = withWorkspace(async ({ workspace }) => {
- const users = await prisma.projectUsers.findMany({
- where: {
- projectId: workspace.id,
- },
- select: {
- role: true,
- user: {
- select: {
- id: true,
- name: true,
- email: true,
- image: true,
+export const GET = withWorkspace(
+ async ({ workspace }) => {
+ const users = await prisma.projectUsers.findMany({
+ where: {
+ projectId: workspace.id,
+ },
+ select: {
+ role: true,
+ user: {
+ select: {
+ id: true,
+ name: true,
+ email: true,
+ image: true,
+ },
},
+ createdAt: true,
},
- createdAt: true,
- },
- });
- return NextResponse.json(
- users.map((u) => ({
- ...u.user,
- role: u.role,
- })),
- );
-});
+ });
+ return NextResponse.json(
+ users.map((u) => ({
+ ...u.user,
+ role: u.role,
+ })),
+ );
+ },
+ {
+ requiredScopes: ["workspaces.read"],
+ },
+);
// PUT /api/workspaces/[idOrSlug]/users – update a user's role for a specific workspace
export const PUT = withWorkspace(
@@ -63,12 +68,11 @@ export const PUT = withWorkspace(
return NextResponse.json(response);
},
{
- requiredRole: ["owner"],
+ requiredScopes: ["workspaces.write"],
},
);
// DELETE /api/workspaces/[idOrSlug]/users – remove a user from a workspace
-
export const DELETE = withWorkspace(
async ({ searchParams, workspace, session }) => {
const { userId } = removeUserSchema.parse(searchParams);
@@ -120,7 +124,7 @@ export const DELETE = withWorkspace(
return NextResponse.json(response);
},
{
- requiredRole: ["owner"],
+ requiredScopes: ["workspaces.write"],
allowSelf: true,
},
);
diff --git a/apps/web/lib/api/tokens/scopes.ts b/apps/web/lib/api/tokens/scopes.ts
index 5527928b0c..dd985bf8e7 100644
--- a/apps/web/lib/api/tokens/scopes.ts
+++ b/apps/web/lib/api/tokens/scopes.ts
@@ -19,6 +19,10 @@ export const scopes = [
// Domains
"domains.read",
"domains.write",
+
+ // API tokens
+ "tokens.read",
+ "tokens.write",
] as const;
export type Scope = (typeof scopes)[number];
diff --git a/apps/web/lib/auth/workspace-edge.ts b/apps/web/lib/auth/workspace-edge.ts
index d8a7e4d3ba..1d3140f26e 100644
--- a/apps/web/lib/auth/workspace-edge.ts
+++ b/apps/web/lib/auth/workspace-edge.ts
@@ -121,6 +121,7 @@ export const withWorkspaceEdge = (
id: true,
name: true,
email: true,
+ isMachine: true,
},
},
},
@@ -164,6 +165,7 @@ export const withWorkspaceEdge = (
id: token.user.id,
name: token.user.name || "",
email: token.user.email || "",
+ isMachine: token.user.isMachine,
},
};
} else {
diff --git a/apps/web/lib/auth/workspace.ts b/apps/web/lib/auth/workspace.ts
index 845734973a..e836b178b2 100644
--- a/apps/web/lib/auth/workspace.ts
+++ b/apps/web/lib/auth/workspace.ts
@@ -299,7 +299,9 @@ export const withWorkspace = (
}
// Check user has permission to make the action
- throwIfNoAccess({ scopes, requiredScopes });
+ if (requiredScopes.length > 0) {
+ throwIfNoAccess({ scopes, requiredScopes });
+ }
// beta feature checks
if (betaFeature) {