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.

Merge branch 'main' into kiran/eng-281-restricted-api-keys

Kiran K57eac64741c8
diff --cc apps/web/app/api/analytics/events/export/route.ts
index 3ce2bb6915,9a61f50319..e7c04f5ec7
--- a/apps/web/app/api/analytics/events/export/route.ts
+++ b/apps/web/app/api/analytics/events/export/route.ts
@@@ -35,57 -38,59 +38,64 @@@ const columnAccessors =
};
// GET /api/analytics/events/export – get export data for analytics
-export const GET = withWorkspace(async ({ searchParams, workspace }) => {
- throwIfClicksUsageExceeded(workspace);
+export const GET = withWorkspace(
- async ({ searchParams, workspace, link }) => {
++ async ({ searchParams, workspace }) => {
++ throwIfClicksUsageExceeded(workspace);
+
- const parsedParams = eventsQuerySchema
- .and(
- z.object({
- columns: z
- .string()
- .transform((c) => c.split(","))
- .pipe(z.string().array()),
- }),
- )
- .parse(searchParams);
+ const parsedParams = eventsQuerySchema
+ .and(
+ z.object({
+ columns: z
+ .string()
+ .transform((c) => c.split(","))
+ .pipe(z.string().array()),
+ }),
+ )
+ .parse(searchParams);
- const { event, domain, key, interval, start, end, columns } = parsedParams;
+
- const { event, domain, interval, start, end, columns, key } = parsedParams;
++ const { event, domain, interval, start, end, columns, key } = parsedParams;
+
- if (domain) {
- await getDomainOrThrow({ workspace, domain });
- }
++ if (domain) {
++ await getDomainOrThrow({ workspace, domain });
++ }
+
- const link =
- domain && key ? await getLinkOrThrow({ workspace, domain, key }) : null;
++ const link =
++ domain && key ? await getLinkOrThrow({ workspace, domain, key }) : null;
- validDateRangeForPlan({
- plan: workspace.plan,
- interval,
- start,
- end,
- throwError: true,
- });
+ validDateRangeForPlan({
+ plan: workspace.plan,
+ interval,
+ start,
+ end,
+ throwError: true,
+ });
- const linkId = link ? link.id : null;
-
- const response = await getEvents({
- ...parsedParams,
- ...(link && { linkId: link.id }),
- workspaceId: workspace.id,
- limit: 100000,
- });
+ const response = await getEvents({
+ ...parsedParams,
- ...(linkId && { linkId }),
++ ...(link && { linkId: link.id }),
+ workspaceId: workspace.id,
+ limit: 100000,
+ });
- const data = response.map((row) =>
- Object.fromEntries(
- columns.map((c) => [
- columnNames?.[c] ?? capitalize(c),
- columnAccessors[c]?.(row) ?? row?.[c],
- ]),
- ),
- );
+ const data = response.map((row) =>
+ Object.fromEntries(
+ columns.map((c) => [
+ columnNames?.[c] ?? capitalize(c),
+ columnAccessors[c]?.(row) ?? row?.[c],
+ ]),
+ ),
+ );
- const csvData = convertToCSV(data);
+ const csvData = convertToCSV(data);
- return new Response(csvData, {
- headers: {
- "Content-Type": "application/csv",
- "Content-Disposition": `attachment; filename=${event}_export.csv`,
- },
- });
-});
+ return new Response(csvData, {
+ headers: {
+ "Content-Type": "application/csv",
+ "Content-Disposition": `attachment; filename=${event}_export.csv`,
+ },
+ });
+ },
+ {
- needNotExceededClicks: true,
+ requiredScopes: ["analytics.read"],
+ },
+);
diff --cc apps/web/app/api/analytics/events/route.ts
index 95a13be0e9,4d7afd5824..803aa249d6
--- a/apps/web/app/api/analytics/events/route.ts
+++ b/apps/web/app/api/analytics/events/route.ts
@@@ -30,8 -50,6 +50,7 @@@ export const GET = withWorkspace
return NextResponse.json(response);
},
{
- needNotExceededClicks: true,
betaFeature: true,
+ requiredScopes: ["analytics.read"],
},
);
diff --cc apps/web/app/api/analytics/export/route.ts
index d84782a7b4,721e8ae77d..547f31da50
--- a/apps/web/app/api/analytics/export/route.ts
+++ b/apps/web/app/api/analytics/export/route.ts
@@@ -6,58 -9,60 +9,65 @@@ import { analyticsQuerySchema } from "@
import JSZip from "jszip";
// GET /api/analytics/export – get export data for analytics
-export const GET = withWorkspace(async ({ searchParams, workspace }) => {
- throwIfClicksUsageExceeded(workspace);
+export const GET = withWorkspace(
- async ({ searchParams, workspace, link }) => {
++ async ({ searchParams, workspace }) => {
++ throwIfClicksUsageExceeded(workspace);
+
- const parsedParams = analyticsQuerySchema.parse(searchParams);
+ const parsedParams = analyticsQuerySchema.parse(searchParams);
- const { interval, start, end } = parsedParams;
+
- const { interval, start, end, linkId, domain, key } = parsedParams;
++ const { interval, start, end, linkId, domain, key } = parsedParams;
+
- if (domain) {
- await getDomainOrThrow({ workspace, domain });
- }
++ if (domain) {
++ await getDomainOrThrow({ workspace, domain });
++ }
+
- const link =
- domain && key ? await getLinkOrThrow({ workspace, domain, key }) : null;
++ const link =
++ domain && key ? await getLinkOrThrow({ workspace, domain, key }) : null;
- validDateRangeForPlan({
- plan: workspace.plan,
- interval,
- start,
- end,
- throwError: true,
- });
+ validDateRangeForPlan({
+ plan: workspace.plan,
+ interval,
+ start,
+ end,
+ throwError: true,
+ });
- const linkId = link ? link.id : null;
-
- const zip = new JSZip();
+ const zip = new JSZip();
- await Promise.all(
- VALID_ANALYTICS_ENDPOINTS.map(async (endpoint) => {
- // no need to fetch top links data if linkId is defined
- // since this is just a single link
- if (endpoint === "top_links" && linkId) return;
- // we're not fetching top URLs data if linkId is not defined
- if (endpoint === "top_urls" && !linkId) return;
- // skip clicks count
- if (endpoint === "count") return;
+ await Promise.all(
+ VALID_ANALYTICS_ENDPOINTS.map(async (endpoint) => {
+ // no need to fetch top links data if linkId is defined
+ // since this is just a single link
+ if (endpoint === "top_links" && linkId) return;
+ // we're not fetching top URLs data if linkId is not defined
+ if (endpoint === "top_urls" && !linkId) return;
+ // skip clicks count
+ if (endpoint === "count") return;
- const response = await getAnalytics({
- ...parsedParams,
- workspaceId: workspace.id,
- ...(link && { linkId: link.id }),
- event: "clicks",
- groupBy: endpoint,
- });
- if (!response || response.length === 0) return;
+ const response = await getAnalytics({
+ ...parsedParams,
+ workspaceId: workspace.id,
- ...(linkId && { linkId }),
++ ...(link && { linkId: link.id }),
+ event: "clicks",
+ groupBy: endpoint,
+ });
+ if (!response || response.length === 0) return;
- const csvData = convertToCSV(response);
- zip.file(`${endpoint}.csv`, csvData);
- }),
- );
+ const csvData = convertToCSV(response);
+ zip.file(`${endpoint}.csv`, csvData);
+ }),
+ );
- const zipData = await zip.generateAsync({ type: "nodebuffer" });
+ const zipData = await zip.generateAsync({ type: "nodebuffer" });
- return new Response(zipData, {
- headers: {
- "Content-Type": "application/zip",
- "Content-Disposition": "attachment; filename=analytics_export.zip",
- },
- });
-});
+ return new Response(zipData, {
+ headers: {
+ "Content-Type": "application/zip",
+ "Content-Disposition": "attachment; filename=analytics_export.zip",
+ },
+ });
+ },
+ {
- needNotExceededClicks: true,
+ requiredScopes: ["analytics.read"],
+ },
+);
diff --cc apps/web/app/api/analytics/public-stats/route.ts
index 67208a9533,6a90abeaed..e93be7ce4e
--- a/apps/web/app/api/analytics/public-stats/route.ts
+++ b/apps/web/app/api/analytics/public-stats/route.ts
@@@ -10,31 -11,34 +11,44 @@@ const updatePublicStatsSchema = z.objec
});
// GET /api/analytics/public-stats – get the publicStats setting for a link
-export const GET = withWorkspace(async ({ searchParams, workspace }) => {
- const { domain, key } = domainKeySchema.parse(searchParams);
-
- await getDomainOrThrow({
- workspace,
- domain,
- dubDomainChecks: true,
- });
-
- const response = await getLinkViaEdge(domain, key);
- return NextResponse.json({ publicStats: response?.publicStats });
-});
+export const GET = withWorkspace(
- async ({ searchParams }) => {
++ async ({ searchParams, workspace }) => {
+ const { domain, key } = domainKeySchema.parse(searchParams);
++
++ await getDomainOrThrow({
++ workspace,
++ domain,
++ dubDomainChecks: true,
++ });
++
+ const response = await getLinkViaEdge(domain, key);
+ return NextResponse.json({ publicStats: response?.publicStats });
+ },
+ {
+ requiredScopes: ["links.read"],
+ },
+);
// PUT /api/analytics/public-stats – update the publicStats setting for a link
-export const PUT = withWorkspace(async ({ req, searchParams, workspace }) => {
- const { domain, key } = domainKeySchema.parse(searchParams);
- const { publicStats } = updatePublicStatsSchema.parse(await req.json());
-
- await getDomainOrThrow({
- workspace,
- domain,
- dubDomainChecks: true,
- });
-
- const response = await prisma.link.update({
- where: { domain_key: { domain, key } },
- data: { publicStats },
- });
-
- return NextResponse.json(response);
-});
+export const PUT = withWorkspace(
- async ({ req, searchParams }) => {
++ async ({ req, searchParams, workspace }) => {
+ const { domain, key } = domainKeySchema.parse(searchParams);
+ const { publicStats } = updatePublicStatsSchema.parse(await req.json());
+
++ await getDomainOrThrow({
++ workspace,
++ domain,
++ dubDomainChecks: true,
++ });
++
+ const response = await prisma.link.update({
+ where: { domain_key: { domain, key } },
+ data: { publicStats },
+ });
+
+ return NextResponse.json(response);
+ },
+ {
+ requiredScopes: ["links.write"],
+ },
+);
diff --cc apps/web/app/api/analytics/route.ts
index 9008c4a497,6150c2f517..0bc92cf80a
--- a/apps/web/app/api/analytics/route.ts
+++ b/apps/web/app/api/analytics/route.ts
@@@ -56,8 -85,4 +85,7 @@@ export const GET = withWorkspace
return NextResponse.json(response);
},
+ {
- needNotExceededClicks: true,
+ requiredScopes: ["analytics.read"],
+ },
);
diff --cc apps/web/app/api/domains/[domain]/primary/route.ts
index 67796b3f94,453c4448c9..48d358d227
--- a/apps/web/app/api/domains/[domain]/primary/route.ts
+++ b/apps/web/app/api/domains/[domain]/primary/route.ts
@@@ -33,7 -41,6 +41,6 @@@ export const POST = withWorkspace
return NextResponse.json(DomainSchema.parse(domainRecord), { headers });
},
{
- domainChecks: true,
- requiredRole: ["owner"],
+ requiredScopes: ["domains.write"],
},
);
diff --cc apps/web/app/api/domains/[domain]/route.ts
index e8fd547d23,72cfb25365..1ed1dbdb66
--- a/apps/web/app/api/domains/[domain]/route.ts
+++ b/apps/web/app/api/domains/[domain]/route.ts
@@@ -18,22 -19,15 +19,20 @@@ import { waitUntil } from "@vercel/func
import { NextResponse } from "next/server";
// GET /api/domains/[domain] – get a workspace's domain
-export const GET = withWorkspace(async ({ workspace, params }) => {
- const domainRecord = await getDomainOrThrow({
- workspace,
- domain: params.domain,
- dubDomainChecks: true,
- });
+export const GET = withWorkspace(
- async ({ domain, workspace }) => {
- const domainRecord = await prisma.domain.findUnique({
- where: {
- slug: domain,
- projectId: workspace.id,
- },
++ async ({ workspace, params }) => {
++ const domainRecord = await getDomainOrThrow({
++ workspace,
++ domain: params.domain,
++ dubDomainChecks: true,
+ });
- return NextResponse.json(DomainSchema.parse(domainRecord));
-});
+ return NextResponse.json(DomainSchema.parse(domainRecord));
+ },
+ {
- domainChecks: true,
+ requiredScopes: ["domains.read"],
+ },
+);
// PUT /api/domains/[domain] – edit a workspace's domain
export const PATCH = withWorkspace(
@@@ -123,8 -125,7 +130,7 @@@
return NextResponse.json(DomainSchema.parse(domainRecord));
},
{
- domainChecks: true,
- requiredRole: ["owner"],
+ requiredScopes: ["domains.write"],
},
);
@@@ -135,7 -143,6 +148,6 @@@ export const DELETE = withWorkspace
return NextResponse.json({ slug: domain });
},
{
- domainChecks: true,
- requiredRole: ["owner"],
+ requiredScopes: ["domains.write"],
},
);
diff --cc apps/web/app/api/domains/[domain]/verify/route.ts
index 66245972af,8768b6a681..df03c31ce6
--- a/apps/web/app/api/domains/[domain]/verify/route.ts
+++ b/apps/web/app/api/domains/[domain]/verify/route.ts
@@@ -11,83 -12,49 +12,89 @@@ import { NextResponse } from "next/serv
export const maxDuration = 30;
// GET /api/domains/[domain]/verify - get domain verification status
-export const GET = withWorkspace(async ({ params, workspace }) => {
- const { slug: domain } = await getDomainOrThrow({
- workspace,
- domain: params.domain,
- dubDomainChecks: true,
- });
+export const GET = withWorkspace(
- async ({ domain }) => {
++ async ({ params, workspace }) => {
++ const { slug: domain } = await getDomainOrThrow({
++ workspace,
++ domain: params.domain,
++ dubDomainChecks: true,
++ });
++
+ let status: DomainVerificationStatusProps = "Valid Configuration";
- let status: DomainVerificationStatusProps = "Valid Configuration";
+ const [domainJson, configJson] = await Promise.all([
+ getDomainResponse(domain),
+ getConfigResponse(domain),
+ ]);
- const [domainJson, configJson] = await Promise.all([
- getDomainResponse(domain),
- getConfigResponse(domain),
- ]);
+ if (domainJson?.error?.code === "not_found") {
+ // domain not found on Vercel project
+ status = "Domain Not Found";
+ return NextResponse.json({
+ status,
+ response: { configJson, domainJson },
+ });
+ } else if (domainJson.error) {
+ status = "Unknown Error";
+ return NextResponse.json({
+ status,
+ response: { configJson, domainJson },
+ });
+ }
+
+ /**
+ * Domain has DNS conflicts
+ */
+ if (configJson?.conflicts.length > 0) {
+ status = "Conflicting DNS Records";
+ return NextResponse.json({
+ status,
+ response: { configJson, domainJson },
+ });
+ }
- if (domainJson?.error?.code === "not_found") {
- // domain not found on Vercel project
- status = "Domain Not Found";
- return NextResponse.json({ status, response: { configJson, domainJson } });
- } else if (domainJson.error) {
- status = "Unknown Error";
- return NextResponse.json({ status, response: { configJson, domainJson } });
- }
+ /**
+ * If domain is not verified, we try to verify now
+ */
+ if (!domainJson.verified) {
+ status = "Pending Verification";
+ const verificationJson = await verifyDomain(domain);
- /**
- * Domain has DNS conflicts
- */
- if (configJson?.conflicts.length > 0) {
- status = "Conflicting DNS Records";
- return NextResponse.json({ status, response: { configJson, domainJson } });
- }
+ if (verificationJson && verificationJson.verified) {
+ /**
+ * Domain was just verified
+ */
+ status = "Valid Configuration";
+ }
- /**
- * If domain is not verified, we try to verify now
- */
- if (!domainJson.verified) {
- status = "Pending Verification";
- const verificationJson = await verifyDomain(domain);
+ return NextResponse.json({
+ status,
+ response: { configJson, domainJson, verificationJson },
+ });
+ }
- if (verificationJson && verificationJson.verified) {
- /**
- * Domain was just verified
- */
- status = "Valid Configuration";
+ let prismaResponse: any = null;
+ if (!configJson.misconfigured) {
+ prismaResponse = await prisma.domain.update({
+ where: {
+ slug: domain,
+ },
+ data: {
+ verified: true,
+ lastChecked: new Date(),
+ },
+ });
+ } else {
+ status = "Invalid Configuration";
+ prismaResponse = await prisma.domain.update({
+ where: {
+ slug: domain,
+ },
+ data: {
+ verified: false,
+ lastChecked: new Date(),
+ },
+ });
}
return NextResponse.json({
diff --cc apps/web/app/api/domains/route.ts
index bb5ff3d2f1,eba4a36bd3..312f6c1c0d
--- a/apps/web/app/api/domains/route.ts
+++ b/apps/web/app/api/domains/route.ts
@@@ -11,82 -11,77 +11,88 @@@ import { NextResponse } from "next/serv
import { z } from "zod";
// GET /api/domains – get all domains for a workspace
-export const GET = withWorkspace(async ({ workspace }) => {
- const domains = await prisma.domain.findMany({
- where: {
- projectId: workspace.id,
- },
- });
+export const GET = withWorkspace(
+ async ({ workspace }) => {
+ const domains = await prisma.domain.findMany({
+ where: {
+ projectId: workspace.id,
+ },
+ });
- return NextResponse.json(z.array(DomainSchema).parse(domains));
-});
+ return NextResponse.json(z.array(DomainSchema).parse(domains));
+ },
+ {
+ requiredScopes: ["domains.read"],
+ },
+);
// POST /api/domains - add a domain
-export const POST = withWorkspace(async ({ req, workspace }) => {
- const body = await parseRequestBody(req);
- const { slug, placeholder, expiredUrl } = createDomainBodySchema.parse(body);
+export const POST = withWorkspace(
+ async ({ req, workspace }) => {
+ const body = await parseRequestBody(req);
+ const { slug, placeholder, expiredUrl } =
+ createDomainBodySchema.parse(body);
- if (workspace.domains.length >= workspace.domainsLimit) {
- const totalDomains = await prisma.domain.count({
- where: {
- projectId: workspace.id,
- },
- });
++ const totalDomains = await prisma.domain.count({
++ where: {
++ projectId: workspace.id,
++ },
++ });
+
- if (totalDomains >= workspace.domainsLimit) {
- return new Response(
- exceededLimitError({
- plan: workspace.plan,
- limit: workspace.domainsLimit,
- type: "domains",
- }),
- { status: 403 },
- );
- }
++ if (totalDomains >= workspace.domainsLimit) {
+ return new Response(
+ exceededLimitError({
+ plan: workspace.plan,
+ limit: workspace.domainsLimit,
+ type: "domains",
+ }),
+ { status: 403 },
+ );
+ }
- if (workspace.plan === "free" && expiredUrl) {
- throw new DubApiError({
- code: "forbidden",
- message:
- "You can only use Default Expiration URLs on a Pro plan and above. Upgrade to Pro to use these features.",
- });
- }
+ if (workspace.plan === "free" && expiredUrl) {
+ throw new DubApiError({
+ code: "forbidden",
+ message:
+ "You can only use Default Expiration URLs on a Pro plan and above. Upgrade to Pro to use these features.",
+ });
+ }
- const validDomain = await validateDomain(slug);
+ const validDomain = await validateDomain(slug);
- if (validDomain.error && validDomain.code) {
- throw new DubApiError({
- code: validDomain.code,
- message: validDomain.error,
- });
- }
+ if (validDomain.error && validDomain.code) {
+ throw new DubApiError({
+ code: validDomain.code,
+ message: validDomain.error,
+ });
+ }
- const vercelResponse = await addDomainToVercel(slug);
+ const vercelResponse = await addDomainToVercel(slug);
- if (
- vercelResponse.error &&
- vercelResponse.error.code !== "domain_already_in_use" // ignore this error
- ) {
- return new Response(vercelResponse.error.message, { status: 422 });
- }
+ if (
+ vercelResponse.error &&
+ vercelResponse.error.code !== "domain_already_in_use" // ignore this error
+ ) {
+ return new Response(vercelResponse.error.message, { status: 422 });
+ }
- const domainRecord = await prisma.domain.create({
- data: {
- slug: slug,
- projectId: workspace.id,
- primary: totalDomains === 0,
- ...(placeholder && { placeholder }),
- ...(workspace.plan !== "free" && {
- expiredUrl,
- }),
- },
- });
+ const domainRecord = await prisma.domain.create({
+ data: {
+ slug: slug,
+ projectId: workspace.id,
- primary: workspace.domains.length === 0,
++ primary: totalDomains === 0,
+ ...(placeholder && { placeholder }),
+ ...(workspace.plan !== "free" && {
+ expiredUrl,
+ }),
+ },
+ });
- return NextResponse.json(DomainSchema.parse(domainRecord), {
- status: 201,
- });
-});
+ return NextResponse.json(DomainSchema.parse(domainRecord), {
+ status: 201,
+ });
+ },
+ {
+ requiredScopes: ["domains.write"],
+ },
+);
diff --cc apps/web/app/api/links/[linkId]/route.ts
index 2f4d9652fd,acdf5fc025..f7efe8d6f5
--- a/apps/web/app/api/links/[linkId]/route.ts
+++ b/apps/web/app/api/links/[linkId]/route.ts
@@@ -14,43 -15,36 +15,41 @@@ import { deepEqual } from "@dub/utils"
import { NextResponse } from "next/server";
// GET /api/links/[linkId] – get a link
-export const GET = withWorkspace(async ({ headers, workspace, params }) => {
- const link = await getLinkOrThrow({
- workspace,
- linkId: params.linkId,
- });
-
- const tags = await prisma.tag.findMany({
- where: {
- links: {
- some: {
- linkId: link.id,
+export const GET = withWorkspace(
- async ({ headers, link }) => {
- if (!link) {
- throw new DubApiError({
- code: "not_found",
- message: "Link not found.",
- });
- }
++ async ({ headers, workspace, params }) => {
++ const link = await getLinkOrThrow({
++ workspace,
++ linkId: params.linkId,
++ });
+
+ 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(
@@@ -148,18 -136,18 +144,18 @@@
export const PUT = PATCH;
// DELETE /api/links/[linkId] – delete a link
-export const DELETE = withWorkspace(async ({ headers, workspace, params }) => {
- const link = await getLinkOrThrow({
- workspace,
- linkId: params.linkId,
- });
-
- await deleteLink(link.id);
-
- return NextResponse.json(
- { id: link.id },
- {
- headers,
- },
- );
-});
+export const DELETE = withWorkspace(
- async ({ headers, link }) => {
- await deleteLink(link!.id);
++ async ({ headers, params, workspace }) => {
++ const link = await getLinkOrThrow({
++ workspace,
++ linkId: params.linkId,
++ });
+
- return NextResponse.json(
- { id: link!.id },
- {
- headers,
- },
- );
++ await deleteLink(link.id);
++
++ return NextResponse.json({ id: link.id }, { headers });
+ },
+ {
+ requiredScopes: ["links.write"],
+ },
+);
diff --cc apps/web/app/api/links/bulk/route.ts
index 03d767d4e8,24cd04f757..a8bcd2d898
--- a/apps/web/app/api/links/bulk/route.ts
+++ b/apps/web/app/api/links/bulk/route.ts
@@@ -124,8 -127,4 +127,7 @@@ export const POST = withWorkspace
headers,
});
},
+ {
- needNotExceededLinks: true,
+ requiredScopes: ["links.write"],
+ },
);
diff --cc apps/web/app/api/links/route.ts
index c263daa653,39394866f3..acb2efcb6c
--- a/apps/web/app/api/links/route.ts
+++ b/apps/web/app/api/links/route.ts
@@@ -11,45 -13,44 +13,49 @@@ import { LOCALHOST_IP, getSearchParamsW
import { NextResponse } from "next/server";
// GET /api/links – get all links for a workspace
-export const GET = withWorkspace(async ({ req, headers, workspace }) => {
- const searchParams = getSearchParamsWithArray(req.url);
+export const GET = withWorkspace(
+ async ({ req, headers, workspace }) => {
+ const searchParams = getSearchParamsWithArray(req.url);
- const {
- domain,
- tagId,
- tagIds,
- search,
- sort,
- page,
- userId,
- showArchived,
- withTags,
- includeUser,
- } = getLinksQuerySchemaExtended.parse(searchParams);
+ const {
+ domain,
+ tagId,
+ tagIds,
+ search,
+ sort,
+ page,
+ userId,
+ showArchived,
+ withTags,
+ includeUser,
+ } = getLinksQuerySchemaExtended.parse(searchParams);
- if (domain) {
- await getDomainOrThrow({ workspace, domain });
- }
++ if (domain) {
++ await getDomainOrThrow({ workspace, domain });
++ }
+
- const response = await getLinksForWorkspace({
- workspaceId: workspace.id,
- domain,
- tagId,
- tagIds,
- search,
- sort,
- page,
- userId,
- showArchived,
- withTags,
- includeUser,
- });
+ const response = await getLinksForWorkspace({
+ workspaceId: workspace.id,
+ domain,
+ tagId,
+ tagIds,
+ search,
+ sort,
+ page,
+ userId,
+ showArchived,
+ withTags,
+ includeUser,
+ });
- return NextResponse.json(response, {
- headers,
- });
-});
+ return NextResponse.json(response, {
+ headers,
+ });
+ },
+ {
+ requiredScopes: ["links.read"],
+ },
+);
// POST /api/links – create a new link
export const POST = withWorkspace(
@@@ -101,8 -105,6 +110,7 @@@
}
},
{
- needNotExceededLinks: true,
allowAnonymous: true,
+ requiredScopes: ["links.write"],
},
);
diff --cc apps/web/app/api/workspaces/[idOrSlug]/route.ts
index 953ab19d33,0c2f1394f1..8aede833c5
--- a/apps/web/app/api/workspaces/[idOrSlug]/route.ts
+++ b/apps/web/app/api/workspaces/[idOrSlug]/route.ts
@@@ -33,23 -33,28 +33,33 @@@ 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);
- const domains = await prisma.domain.findMany({
- where: {
- projectId: workspace.id,
- },
- select: {
- slug: true,
- primary: true,
- },
- });
+export const GET = withWorkspace(
+ async ({ workspace, headers }) => {
+ const betaTester = await isBetaTester(workspace.id);
++ const domains = await prisma.domain.findMany({
++ where: {
++ projectId: workspace.id,
++ },
++ select: {
++ slug: true,
++ primary: true,
++ },
++ });
- return NextResponse.json(
- WorkspaceSchema.parse({
- ...workspace,
- id: `ws_${workspace.id}`,
- domains,
- betaTester,
- }),
- { headers },
- );
-});
+ return NextResponse.json(
+ WorkspaceSchema.parse({
+ ...workspace,
+ id: `ws_${workspace.id}`,
++ domains,
+ betaTester,
+ }),
+ { headers },
+ );
+ },
+ {
+ requiredScopes: ["workspaces.read"],
+ },
+);
// PATCH /api/workspaces/[idOrSlug] – update a specific workspace by id or slug
export const PATCH = withWorkspace(
diff --cc apps/web/lib/auth/workspace.ts
index dccf57afaf,5cf55f8766..fd2dfcc514
--- a/apps/web/lib/auth/workspace.ts
+++ b/apps/web/lib/auth/workspace.ts
@@@ -1,21 -1,9 +1,11 @@@
- import {
- DubApiError,
- exceededLimitError,
- handleAndReturnErrorResponse,
- } from "@/lib/api/errors";
+ import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";
import { prisma } from "@/lib/prisma";
- import { PlanProps, WorkspaceProps } from "@/lib/types";
+ import { PlanProps, WorkspaceWithUsers } from "@/lib/types";
import { ratelimit } from "@/lib/upstash";
- import {
- API_DOMAIN,
- DUB_WORKSPACE_ID,
- getSearchParams,
- isDubDomain,
- } from "@dub/utils";
- import { Link as LinkProps } from "@prisma/client";
+ import { API_DOMAIN, getSearchParams } from "@dub/utils";
import { waitUntil } from "@vercel/functions";
+import { throwIfNoAccess } from "../api/tokens/permissions";
+import { Scope, roleScopesMapping } from "../api/tokens/scopes";
import { isBetaTester } from "../edge-config";
import { hashToken } from "./hash-token";
import { Session, getSession } from "./utils";
@@@ -28,19 -16,13 +18,15 @@@ interface WithWorkspaceHandler
headers,
session,
workspace,
- domain,
- link,
+ scopes,
}: {
req: Request;
params: Record<string, string>;
searchParams: Record<string, string>;
headers?: Record<string, string>;
session: Session;
- workspace: WorkspaceProps;
- domain: string;
- link?: LinkProps;
+ scopes: Scope[];
+ workspace: WorkspaceWithUsers;
}): Promise<Response>;
}
@@@ -56,24 -38,16 +42,16 @@@ export const withWorkspace =
"business extra",
"enterprise",
], // if the action needs a specific plan
- needNotExceededClicks, // if the action needs the user to not have exceeded their clicks usage
- needNotExceededLinks, // if the action needs the user to not have exceeded their links usage
- requiredRole = ["owner", "member"],
allowAnonymous, // special case for /api/links (POST /api/links) – allow no session
- skipLinkChecks, // special case for /api/links/exists – skip link checks
- domainChecks, // if the action needs to check if the domain belongs to the workspace
- allowSelf, // special case for removing yourself from a workspace
betaFeature, // if the action is a beta feature
+ requiredScopes = [],
+ skipScopeChecks, // if the action doesn't need to check for required scopes
}: {
requiredPlan?: Array<PlanProps>;
- needNotExceededClicks?: boolean;
- needNotExceededLinks?: boolean;
- requiredRole?: Array<"owner" | "member">;
allowAnonymous?: boolean;
- skipLinkChecks?: boolean;
- domainChecks?: boolean;
- allowSelf?: boolean;
betaFeature?: boolean;
+ requiredScopes?: Scope[];
+ skipScopeChecks?: boolean;
} = {},
) => {
return async (
@@@ -184,13 -132,11 +154,14 @@@
});
}
+ // Rate limit checks for API keys
+ const rateLimit = token?.rateLimit || 600;
+
const { success, limit, reset, remaining } = await ratelimit(
- 600,
+ rateLimit,
"1 m",
).limit(apiKey);
+
headers = {
"Retry-After": reset.toString(),
"X-RateLimit-Limit": limit.toString(),
@@@ -354,77 -258,6 +293,17 @@@
});
}
+ // beta feature checks
+ if (betaFeature) {
+ const betaTester = await isBetaTester(workspace.id);
+ if (!betaTester) {
+ throw new DubApiError({
+ code: "forbidden",
+ message: "Unauthorized: Beta feature.",
+ });
+ }
+ }
+
- // edge case where linkId is an externalId and workspaceId was not provided (they must've used projectSlug instead)
- // in this case, we need to try fetching the link again
- if (linkId && linkId.startsWith("ext_") && !link && !workspaceId) {
- link = (await prisma.link.findUnique({
- where: {
- projectId_externalId: {
- projectId: workspace.id,
- externalId: linkId.replace("ext_", ""),
- },
- },
- })) as LinkProps;
- }
-
- // if domain is defined:
- // - it's a dub domain and domainChecks is required, check if the user is part of the dub workspace
- // - it's a custom domain, check if the domain belongs to the workspace
- if (domain) {
- if (isDubDomain(domain)) {
- if (domainChecks && workspace.id !== DUB_WORKSPACE_ID) {
- throw new DubApiError({
- code: "forbidden",
- message: "Domain does not belong to workspace.",
- });
- }
- } else if (!workspace.domains.find((d) => d.slug === domain)) {
- throw new DubApiError({
- code: "forbidden",
- message: "Domain does not belong to workspace.",
- });
- }
- }
-
- // clicks usage overage checks
- if (needNotExceededClicks && workspace.usage > workspace.usageLimit) {
- throw new DubApiError({
- code: "forbidden",
- message: exceededLimitError({
- plan: workspace.plan,
- limit: workspace.usageLimit,
- type: "clicks",
- }),
- });
- }
-
- // links usage overage checks
- if (
- needNotExceededLinks &&
- workspace.linksUsage > workspace.linksLimit &&
- (workspace.plan === "free" || workspace.plan === "pro")
- ) {
- throw new DubApiError({
- code: "forbidden",
- message: exceededLimitError({
- plan: workspace.plan,
- limit: workspace.linksLimit,
- type: "links",
- }),
- });
- }
-
// plan checks
if (!requiredPlan.includes(workspace.plan)) {
throw new DubApiError({
@@@ -464,9 -286,6 +332,7 @@@
headers,
session,
workspace,
- domain,
- link,
+ scopes,
});
} catch (error) {
return handleAndReturnErrorResponse(error, headers);