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.

move to workspace.ts

Kiran K8e6d829985f2
diff --git a/apps/web/app/api/analytics/events/export/route.ts b/apps/web/app/api/analytics/events/export/route.ts
index 04715f4afe..5dc5b5a025 100644
--- a/apps/web/app/api/analytics/events/export/route.ts
+++ b/apps/web/app/api/analytics/events/export/route.ts
@@ -1,6 +1,5 @@
import { getEvents } from "@/lib/analytics/get-events";
import { convertToCSV, validDateRangeForPlan } from "@/lib/analytics/utils";
-import { throwIfNoAccess } from "@/lib/api/tokens/permissions";
import { withWorkspace } from "@/lib/auth";
import { getDomainViaEdge } from "@/lib/planetscale";
import { eventsQuerySchema } from "@/lib/zod/schemas/analytics";
@@ -38,9 +37,7 @@ const columnAccessors = {
// GET /api/analytics/events/export – get export data for analytics
export const GET = withWorkspace(
- async ({ searchParams, workspace, link, scopes }) => {
- throwIfNoAccess({ scopes, requiredScopes: ["analytics.read"] });
-
+ async ({ searchParams, workspace, link }) => {
const parsedParams = eventsQuerySchema
.and(
z.object({
@@ -94,5 +91,6 @@ export const GET = withWorkspace(
},
{
needNotExceededClicks: true,
+ requiredScopes: ["analytics.read"],
},
);
diff --git a/apps/web/app/api/analytics/events/route.ts b/apps/web/app/api/analytics/events/route.ts
index 261d3997f2..824da4268d 100644
--- a/apps/web/app/api/analytics/events/route.ts
+++ b/apps/web/app/api/analytics/events/route.ts
@@ -1,15 +1,12 @@
import { getEvents } from "@/lib/analytics/get-events";
import { validDateRangeForPlan } from "@/lib/analytics/utils";
-import { throwIfNoAccess } from "@/lib/api/tokens/permissions";
import { withWorkspace } from "@/lib/auth";
import { getDomainViaEdge } from "@/lib/planetscale";
import { eventsQuerySchema } from "@/lib/zod/schemas/analytics";
import { NextResponse } from "next/server";
export const GET = withWorkspace(
- async ({ searchParams, workspace, link, scopes }) => {
- throwIfNoAccess({ scopes, requiredScopes: ["analytics.read"] });
-
+ async ({ searchParams, workspace, link }) => {
const parsedParams = eventsQuerySchema.parse(searchParams);
let { event, domain, key, interval, start, end } = parsedParams;
@@ -40,5 +37,6 @@ export const GET = withWorkspace(
{
needNotExceededClicks: true,
betaFeature: true,
+ requiredScopes: ["analytics.read"],
},
);
diff --git a/apps/web/app/api/analytics/export/route.ts b/apps/web/app/api/analytics/export/route.ts
index 733cfed781..6d337be619 100644
--- a/apps/web/app/api/analytics/export/route.ts
+++ b/apps/web/app/api/analytics/export/route.ts
@@ -1,7 +1,6 @@
import { VALID_ANALYTICS_ENDPOINTS } from "@/lib/analytics/constants";
import { getAnalytics } from "@/lib/analytics/get-analytics";
import { convertToCSV, validDateRangeForPlan } from "@/lib/analytics/utils";
-import { throwIfNoAccess } from "@/lib/api/tokens/permissions";
import { withWorkspace } from "@/lib/auth";
import { getDomainViaEdge } from "@/lib/planetscale";
import { analyticsQuerySchema } from "@/lib/zod/schemas/analytics";
@@ -9,9 +8,7 @@ import JSZip from "jszip";
// GET /api/analytics/[endpoint]/export – get export data for analytics
export const GET = withWorkspace(
- async ({ searchParams, workspace, link, scopes }) => {
- throwIfNoAccess({ scopes, requiredScopes: ["analytics.read"] });
-
+ async ({ searchParams, workspace, link }) => {
const parsedParams = analyticsQuerySchema.parse(searchParams);
const { domain, key, interval, start, end } = parsedParams;
@@ -66,5 +63,6 @@ export const GET = withWorkspace(
},
{
needNotExceededClicks: true,
+ requiredScopes: ["analytics.read"],
},
);
diff --git a/apps/web/app/api/analytics/public-stats/route.ts b/apps/web/app/api/analytics/public-stats/route.ts
index 51966dc0ac..d04cb989aa 100644
--- a/apps/web/app/api/analytics/public-stats/route.ts
+++ b/apps/web/app/api/analytics/public-stats/route.ts
@@ -1,4 +1,3 @@
-import { throwIfNoAccess } from "@/lib/api/tokens/permissions";
import { withWorkspace } from "@/lib/auth";
import { getDomainOrLink } from "@/lib/planetscale";
import { prisma } from "@/lib/prisma";
@@ -11,29 +10,35 @@ const updatePublicStatsSchema = z.object({
});
// GET /api/analytics – get the publicStats setting for a link
-export const GET = withWorkspace(async ({ searchParams, scopes }) => {
- throwIfNoAccess({ scopes, requiredScopes: ["links.read"] });
-
- const { domain, key } = domainKeySchema.parse(searchParams);
- const response = await getDomainOrLink({ domain, key });
- return NextResponse.json(response);
-});
+export const GET = withWorkspace(
+ async ({ searchParams }) => {
+ const { domain, key } = domainKeySchema.parse(searchParams);
+ const response = await getDomainOrLink({ domain, key });
+ return NextResponse.json(response);
+ },
+ {
+ requiredScopes: ["links.read"],
+ },
+);
// PUT /api/analytics – update the publicStats setting for a link
-export const PUT = withWorkspace(async ({ req, searchParams, scopes }) => {
- throwIfNoAccess({ scopes, requiredScopes: ["links.write"] });
-
- const { domain, key } = domainKeySchema.parse(searchParams);
- const { publicStats } = updatePublicStatsSchema.parse(await req.json());
- const response =
- key === "_root"
- ? await prisma.domain.update({
- where: { slug: domain },
- data: { publicStats },
- })
- : await prisma.link.update({
- where: { domain_key: { domain, key } },
- data: { publicStats },
- });
- return NextResponse.json(response);
-});
+export const PUT = withWorkspace(
+ async ({ req, searchParams }) => {
+ const { domain, key } = domainKeySchema.parse(searchParams);
+ const { publicStats } = updatePublicStatsSchema.parse(await req.json());
+ const response =
+ key === "_root"
+ ? await prisma.domain.update({
+ where: { slug: domain },
+ data: { publicStats },
+ })
+ : await prisma.link.update({
+ where: { domain_key: { domain, key } },
+ data: { publicStats },
+ });
+ return NextResponse.json(response);
+ },
+ {
+ requiredScopes: ["links.write"],
+ },
+);
diff --git a/apps/web/app/api/analytics/route.ts b/apps/web/app/api/analytics/route.ts
index 5d2d1596cf..a334bf32ac 100644
--- a/apps/web/app/api/analytics/route.ts
+++ b/apps/web/app/api/analytics/route.ts
@@ -1,7 +1,6 @@
import { VALID_ANALYTICS_ENDPOINTS } from "@/lib/analytics/constants";
import { getAnalytics } from "@/lib/analytics/get-analytics";
import { validDateRangeForPlan } from "@/lib/analytics/utils";
-import { throwIfNoAccess } from "@/lib/api/tokens/permissions";
import { withWorkspace } from "@/lib/auth";
import { getDomainViaEdge } from "@/lib/planetscale";
import {
@@ -12,9 +11,7 @@ import { NextResponse } from "next/server";
// GET /api/analytics – get analytics
export const GET = withWorkspace(
- async ({ params, searchParams, workspace, link, scopes }) => {
- throwIfNoAccess({ scopes, requiredScopes: ["analytics.read"] });
-
+ async ({ params, searchParams, workspace, link }) => {
let { eventType: oldEvent, endpoint: oldType } =
analyticsPathParamsSchema.parse(params);
@@ -66,5 +63,6 @@ export const GET = withWorkspace(
},
{
needNotExceededClicks: true,
+ requiredScopes: ["analytics.read"],
},
);
diff --git a/apps/web/app/api/domains/[domain]/primary/route.ts b/apps/web/app/api/domains/[domain]/primary/route.ts
index 6f8e1e073f..3b660cabc9 100644
--- a/apps/web/app/api/domains/[domain]/primary/route.ts
+++ b/apps/web/app/api/domains/[domain]/primary/route.ts
@@ -1,4 +1,3 @@
-import { throwIfNoAccess } from "@/lib/api/tokens/permissions";
import { withWorkspace } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { DomainSchema } from "@/lib/zod/schemas/domains";
@@ -6,9 +5,7 @@ import { NextResponse } from "next/server";
// POST /api/domains/[domain]/primary – set a domain as primary
export const POST = withWorkspace(
- async ({ headers, workspace, domain, scopes }) => {
- throwIfNoAccess({ scopes, requiredScopes: ["domains.write"] });
-
+ async ({ headers, workspace, domain }) => {
const responses = await Promise.all([
prisma.domain.update({
where: {
@@ -37,6 +34,6 @@ export const POST = withWorkspace(
},
{
domainChecks: true,
- requiredRole: ["owner"],
+ requiredScopes: ["domains.write"],
},
);
diff --git a/apps/web/app/api/domains/[domain]/route.ts b/apps/web/app/api/domains/[domain]/route.ts
index bc9b89c64e..ccf18a0a8e 100644
--- a/apps/web/app/api/domains/[domain]/route.ts
+++ b/apps/web/app/api/domains/[domain]/route.ts
@@ -6,7 +6,6 @@ import {
validateDomain,
} from "@/lib/api/domains";
import { DubApiError } from "@/lib/api/errors";
-import { throwIfNoAccess } from "@/lib/api/tokens/permissions";
import { parseRequestBody } from "@/lib/api/utils";
import { withWorkspace } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
@@ -19,9 +18,7 @@ import { NextResponse } from "next/server";
// GET /api/domains/[domain] – get a workspace's domain
export const GET = withWorkspace(
- async ({ domain, scopes }) => {
- throwIfNoAccess({ scopes, requiredScopes: ["domains.read"] });
-
+ async ({ domain }) => {
const data = await prisma.domain.findUnique({
where: {
slug: domain,
@@ -53,14 +50,13 @@ export const GET = withWorkspace(
},
{
domainChecks: true,
+ requiredScopes: ["domains.read"],
},
);
// PUT /api/domains/[domain] – edit a workspace's domain
export const PATCH = withWorkspace(
- async ({ req, workspace, domain, scopes }) => {
- throwIfNoAccess({ scopes, requiredScopes: ["domains.write"] });
-
+ async ({ req, workspace, domain }) => {
const body = await parseRequestBody(req);
const {
slug: newDomain,
@@ -133,20 +129,18 @@ export const PATCH = withWorkspace(
},
{
domainChecks: true,
- requiredRole: ["owner"],
+ requiredScopes: ["domains.write"],
},
);
// DELETE /api/domains/[domain] - delete a workspace's domain
export const DELETE = withWorkspace(
- async ({ domain, scopes }) => {
- throwIfNoAccess({ scopes, requiredScopes: ["domains.write"] });
-
+ async ({ domain }) => {
await deleteDomainAndLinks(domain);
return NextResponse.json({ slug: domain });
},
{
domainChecks: true,
- requiredRole: ["owner"],
+ requiredScopes: ["domains.write"],
},
);
diff --git a/apps/web/app/api/domains/[domain]/transfer/route.ts b/apps/web/app/api/domains/[domain]/transfer/route.ts
index 7bc0cf490a..2288e1633e 100644
--- a/apps/web/app/api/domains/[domain]/transfer/route.ts
+++ b/apps/web/app/api/domains/[domain]/transfer/route.ts
@@ -1,7 +1,6 @@
import { getAnalytics } from "@/lib/analytics/get-analytics";
import { setRootDomain } from "@/lib/api/domains";
import { DubApiError } from "@/lib/api/errors";
-import { throwIfNoAccess } from "@/lib/api/tokens/permissions";
import { withWorkspace } from "@/lib/auth";
import { qstash } from "@/lib/cron";
import { prisma } from "@/lib/prisma";
@@ -14,9 +13,7 @@ import { NextResponse } from "next/server";
// POST /api/domains/[domain]/transfer – transfer a domain to another workspace
export const POST = withWorkspace(
- async ({ req, headers, session, params, workspace, scopes }) => {
- throwIfNoAccess({ scopes, requiredScopes: ["domains.write"] });
-
+ async ({ req, headers, session, params, workspace }) => {
const { domain } = params;
const { newWorkspaceId } = transferDomainBodySchema.parse(await req.json());
@@ -159,5 +156,7 @@ export const POST = withWorkspace(
return NextResponse.json(DomainSchema.parse(domainResponse), { headers });
},
- { requiredRole: ["owner"] },
+ {
+ requiredScopes: ["domains.write"],
+ },
);
diff --git a/apps/web/app/api/domains/[domain]/verify/route.ts b/apps/web/app/api/domains/[domain]/verify/route.ts
index 7791bc27d0..66245972af 100644
--- a/apps/web/app/api/domains/[domain]/verify/route.ts
+++ b/apps/web/app/api/domains/[domain]/verify/route.ts
@@ -3,7 +3,6 @@ import {
getDomainResponse,
verifyDomain,
} from "@/lib/api/domains";
-import { throwIfNoAccess } from "@/lib/api/tokens/permissions";
import { withWorkspace } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { DomainVerificationStatusProps } from "@/lib/types";
@@ -12,79 +11,91 @@ import { NextResponse } from "next/server";
export const maxDuration = 30;
// GET /api/domains/[domain]/verify - get domain verification status
-export const GET = withWorkspace(async ({ domain, scopes }) => {
- throwIfNoAccess({ scopes, requiredScopes: ["domains.write"] });
+export const GET = withWorkspace(
+ async ({ domain }) => {
+ 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({
status,
- response: { configJson, domainJson, verificationJson },
+ response: { configJson, domainJson, prismaResponse },
});
- }
-
- 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({
- status,
- response: { configJson, domainJson, prismaResponse },
- });
-});
+ },
+ {
+ requiredScopes: ["domains.write"],
+ },
+);
diff --git a/apps/web/app/api/domains/default/route.ts b/apps/web/app/api/domains/default/route.ts
index 0cce985f24..f466dce40f 100644
--- a/apps/web/app/api/domains/default/route.ts
+++ b/apps/web/app/api/domains/default/route.ts
@@ -1,4 +1,3 @@
-import { throwIfNoAccess } from "@/lib/api/tokens/permissions";
import { withWorkspace } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import z from "@/lib/zod";
@@ -6,61 +5,67 @@ import { DUB_DOMAINS_ARRAY } from "@dub/utils";
import { NextResponse } from "next/server";
// GET /api/domains/default - get default domains
-export const GET = withWorkspace(async ({ workspace, scopes }) => {
- throwIfNoAccess({ scopes, requiredScopes: ["domains.write"] });
+export const GET = withWorkspace(
+ async ({ workspace }) => {
+ const defaultDomains = await prisma.defaultDomains.findUnique({
+ where: {
+ projectId: workspace.id,
+ },
+ select: {
+ dubsh: true,
+ chatgpt: true,
+ sptifi: true,
+ gitnew: true,
+ amznid: true,
+ loooooooong: true,
+ },
+ });
- const defaultDomains = await prisma.defaultDomains.findUnique({
- where: {
- projectId: workspace.id,
- },
- select: {
- dubsh: true,
- chatgpt: true,
- sptifi: true,
- gitnew: true,
- amznid: true,
- loooooooong: true,
- },
- });
+ if (!defaultDomains) {
+ return NextResponse.json([]);
+ }
- if (!defaultDomains) {
- return NextResponse.json([]);
- }
+ const defaultDomainsArray = Object.keys(defaultDomains)
+ .filter((key) => defaultDomains[key])
+ .map((domain) =>
+ DUB_DOMAINS_ARRAY.find((d) => d.replace(".", "") === domain),
+ );
- const defaultDomainsArray = Object.keys(defaultDomains)
- .filter((key) => defaultDomains[key])
- .map((domain) =>
- DUB_DOMAINS_ARRAY.find((d) => d.replace(".", "") === domain),
- );
-
- return NextResponse.json(defaultDomainsArray);
-});
+ return NextResponse.json(defaultDomainsArray);
+ },
+ {
+ requiredScopes: ["domains.write"],
+ },
+);
const updateDefaultDomainsSchema = z.object({
defaultDomains: z.array(z.enum(DUB_DOMAINS_ARRAY as [string, ...string[]])),
});
// PUT /api/domains/default - edit default domains
-export const PUT = withWorkspace(async ({ req, workspace, scopes }) => {
- throwIfNoAccess({ scopes, requiredScopes: ["domains.write"] });
-
- const { defaultDomains } = await updateDefaultDomainsSchema.parseAsync(
- await req.json(),
- );
+export const PUT = withWorkspace(
+ async ({ req, workspace }) => {
+ const { defaultDomains } = await updateDefaultDomainsSchema.parseAsync(
+ await req.json(),
+ );
- const response = await prisma.defaultDomains.update({
- where: {
- projectId: workspace.id,
- },
- data: {
- dubsh: defaultDomains.includes("dub.sh"),
- chatgpt: defaultDomains.includes("chatg.pt"),
- sptifi: defaultDomains.includes("spti.fi"),
- gitnew: defaultDomains.includes("git.new"),
- amznid: defaultDomains.includes("amzn.id"),
- loooooooong: defaultDomains.includes("loooooooo.ng"),
- },
- });
+ const response = await prisma.defaultDomains.update({
+ where: {
+ projectId: workspace.id,
+ },
+ data: {
+ dubsh: defaultDomains.includes("dub.sh"),
+ chatgpt: defaultDomains.includes("chatg.pt"),
+ sptifi: defaultDomains.includes("spti.fi"),
+ gitnew: defaultDomains.includes("git.new"),
+ amznid: defaultDomains.includes("amzn.id"),
+ loooooooong: defaultDomains.includes("loooooooo.ng"),
+ },
+ });
- return NextResponse.json(response);
-});
+ return NextResponse.json(response);
+ },
+ {
+ requiredScopes: ["domains.write"],
+ },
+);
diff --git a/apps/web/app/api/domains/route.ts b/apps/web/app/api/domains/route.ts
index 9c8f60626c..366f6b6edf 100644
--- a/apps/web/app/api/domains/route.ts
+++ b/apps/web/app/api/domains/route.ts
@@ -4,7 +4,6 @@ import {
validateDomain,
} from "@/lib/api/domains";
import { DubApiError, exceededLimitError } from "@/lib/api/errors";
-import { throwIfNoAccess } from "@/lib/api/tokens/permissions";
import { parseRequestBody } from "@/lib/api/utils";
import { withWorkspace } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
@@ -14,93 +13,99 @@ import { waitUntil } from "@vercel/functions";
import { NextResponse } from "next/server";
// GET /api/domains – get all domains for a workspace
-export const GET = withWorkspace(async ({ workspace, scopes }) => {
- throwIfNoAccess({ scopes, requiredScopes: ["domains.read"] });
-
- 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, scopes }) => {
- throwIfNoAccess({ scopes, requiredScopes: ["domains.write"] });
+export const POST = withWorkspace(
+ async ({ req, workspace }) => {
+ const body = await parseRequestBody(req);
+ const {
+ slug: domain,
+ target,
+ type,
+ expiredUrl,
+ placeholder,
+ noindex,
+ } = addDomainBodySchema.parse(body);
- const body = await parseRequestBody(req);
- const {
- slug: domain,
- target,
- type,
- expiredUrl,
- placeholder,
- noindex,
- } = addDomainBodySchema.parse(body);
+ if (workspace.domains.length >= workspace.domainsLimit) {
+ return new Response(
+ exceededLimitError({
+ plan: workspace.plan,
+ limit: workspace.domainsLimit,
+ type: "domains",
+ }),
+ { status: 403 },
+ );
+ }
- if (workspace.domains.length >= workspace.domainsLimit) {
- return new Response(
- exceededLimitError({
- plan: workspace.plan,
- limit: workspace.domainsLimit,
- type: "domains",
- }),
- { status: 403 },
- );
- }
+ const validDomain = await validateDomain(domain);
- const validDomain = await validateDomain(domain);
+ if (validDomain.error && validDomain.code) {
+ throw new DubApiError({
+ code: validDomain.code,
+ message: validDomain.error,
+ });
+ }
+ const vercelResponse = await addDomainToVercel(domain);
- if (validDomain.error && validDomain.code) {
- throw new DubApiError({
- code: validDomain.code,
- message: validDomain.error,
- });
- }
- const vercelResponse = await addDomainToVercel(domain);
-
- 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 });
+ }
+ /*
If the domain is being added, we need to:
1. Add the domain to Vercel
2. If there's a landing page set, update the root domain in Redis
3. If the workspace has no domains (meaning this is the first domain added), set it as primary
*/
- const response = await prisma.domain.create({
- data: {
- slug: domain,
- type,
- projectId: workspace.id,
- primary: workspace.domains.length === 0,
- ...(placeholder && { placeholder }),
- ...(workspace.plan !== "free" && {
- target,
- expiredUrl,
- noindex: noindex === undefined ? true : noindex,
- }),
- },
- });
+ const response = await prisma.domain.create({
+ data: {
+ slug: domain,
+ type,
+ projectId: workspace.id,
+ primary: workspace.domains.length === 0,
+ ...(placeholder && { placeholder }),
+ ...(workspace.plan !== "free" && {
+ target,
+ expiredUrl,
+ noindex: noindex === undefined ? true : noindex,
+ }),
+ },
+ });
- waitUntil(
- setRootDomain({
- id: response.id,
- domain,
- domainCreatedAt: response.createdAt,
- projectId: workspace.id,
- ...(workspace.plan !== "free" && {
- url: target || undefined,
- noindex: noindex === undefined ? true : noindex,
+ waitUntil(
+ setRootDomain({
+ id: response.id,
+ domain,
+ domainCreatedAt: response.createdAt,
+ projectId: workspace.id,
+ ...(workspace.plan !== "free" && {
+ url: target || undefined,
+ noindex: noindex === undefined ? true : noindex,
+ }),
+ rewrite: type === "rewrite",
}),
- rewrite: type === "rewrite",
- }),
- );
+ );
- return NextResponse.json(DomainSchema.parse(response), { status: 201 });
-});
+ return NextResponse.json(DomainSchema.parse(response), { status: 201 });
+ },
+ {
+ requiredScopes: ["domains.write"],
+ },
+);
diff --git a/apps/web/app/api/links/route.ts b/apps/web/app/api/links/route.ts
index c20950e827..c263daa653 100644
--- a/apps/web/app/api/links/route.ts
+++ b/apps/web/app/api/links/route.ts
@@ -1,6 +1,5 @@
import { DubApiError, ErrorCodes } from "@/lib/api/errors";
import { createLink, getLinksForWorkspace, processLink } from "@/lib/api/links";
-import { throwIfNoAccess } from "@/lib/api/tokens/permissions";
import { parseRequestBody } from "@/lib/api/utils";
import { withWorkspace } from "@/lib/auth";
import { ratelimit } from "@/lib/upstash";
@@ -13,9 +12,7 @@ import { NextResponse } from "next/server";
// GET /api/links – get all links for a workspace
export const GET = withWorkspace(
- async ({ req, headers, workspace, scopes }) => {
- throwIfNoAccess({ scopes, requiredScopes: ["links.read", "links.write"] });
-
+ async ({ req, headers, workspace }) => {
const searchParams = getSearchParamsWithArray(req.url);
const {
@@ -49,13 +46,14 @@ export const GET = withWorkspace(
headers,
});
},
+ {
+ requiredScopes: ["links.read"],
+ },
);
// POST /api/links – create a new link
export const POST = withWorkspace(
- async ({ req, headers, session, workspace, scopes }) => {
- throwIfNoAccess({ scopes, requiredScopes: ["links.write"] });
-
+ async ({ req, headers, session, workspace }) => {
const bodyRaw = await parseRequestBody(req);
const body = createLinkBodySchema.parse(bodyRaw);
@@ -105,5 +103,6 @@ export const POST = withWorkspace(
{
needNotExceededLinks: true,
allowAnonymous: true,
+ requiredScopes: ["links.write"],
},
);
diff --git a/apps/web/app/api/tokens/route.ts b/apps/web/app/api/tokens/route.ts
index e8ecf21ab1..f391af9d22 100644
--- a/apps/web/app/api/tokens/route.ts
+++ b/apps/web/app/api/tokens/route.ts
@@ -21,7 +21,8 @@ export const POST = withWorkspace(async ({ req, session, workspace }) => {
if (isMachine) {
machineUser = await prisma.user.create({
data: {
- name: "Machine user",
+ name: "Machine",
+ image: "https://api.dicebear.com/9.x/bottts/svg",
isMachine: true,
},
});
diff --git a/apps/web/lib/auth/workspace.ts b/apps/web/lib/auth/workspace.ts
index f0f7747111..845734973a 100644
--- a/apps/web/lib/auth/workspace.ts
+++ b/apps/web/lib/auth/workspace.ts
@@ -19,6 +19,7 @@ import {
User,
} from "@prisma/client";
import { waitUntil } from "@vercel/functions";
+import { throwIfNoAccess } from "../api/tokens/permissions";
import { Scope, scopes as allScopes, roleToScopes } from "../api/tokens/scopes";
import { isBetaTester } from "../edge-config";
import { hashToken } from "./hash-token";
@@ -70,6 +71,7 @@ export const withWorkspace = (
skipLinkChecks, // special case for /api/links/exists – skip link checks
domainChecks, // if the action needs to check if the domain belongs to the workspace
betaFeature, // if the action is a beta feature
+ requiredScopes = [],
}: {
requiredPlan?: Array<PlanProps>;
requiredRole?: Array<"owner" | "member">;
@@ -80,6 +82,7 @@ export const withWorkspace = (
skipLinkChecks?: boolean;
domainChecks?: boolean;
betaFeature?: boolean;
+ requiredScopes?: Scope[];
} = {},
) => {
return async (
@@ -290,6 +293,14 @@ export const withWorkspace = (
});
}
+ // For session requests, find the scopes based on the user's role
+ if (!apiKey) {
+ scopes = roleToScopes[workspace.users[0].role];
+ }
+
+ // Check user has permission to make the action
+ throwIfNoAccess({ scopes, requiredScopes });
+
// beta feature checks
if (betaFeature) {
const betaTester = await isBetaTester(workspace.id);
@@ -301,11 +312,6 @@ export const withWorkspace = (
}
}
- // For session requests, find the scopes based on the user's role
- if (!apiKey) {
- scopes = roleToScopes[workspace.users[0].role];
- }
-
// 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) {