The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
import { DubApiError, handleApiError } from "@/lib/api/errors";
import { prisma } from "@/lib/prisma";
import { BetaFeatures, PlanProps, WorkspaceWithUsers } from "@/lib/types";
import { ratelimit } from "@/lib/upstash";
import { API_DOMAIN, getSearchParams } from "@dub/utils";
import { WorkspaceRole } from "@prisma/client";
import { waitUntil } from "@vercel/functions";
import { headers } from "next/headers";
import { NextResponse } from "next/server";
import { captureRequestLog } from "../api-logs/capture-request-log";
import { getRatelimitForPlan } from "../api/get-ratelimit-for-plan";
import {
PermissionAction,
getPermissionsByRole,
} from "../api/rbac/permissions";
import {
LEGACY_SCOPE_GRANTS,
LegacyScopeGrant,
Scope,
grantLegacyScopePermissions,
mapScopesToPermissions,
} from "../api/tokens/scopes";
import { throwIfNoAccess } from "../api/tokens/throw-if-no-access";
import { normalizeWorkspaceId } from "../api/workspaces/workspace-id";
import { withAxiomBodyLog } from "../axiom/server";
import { getFeatureFlags } from "../edge-config";
import { hashToken } from "./hash-token";
import { rateLimitRequest } from "./rate-limit-request";
import { TokenCacheItem, tokenCache } from "./token-cache";
import { Session, getSession } from "./utils";
const RATE_LIMIT_FOR_SESSIONS = {
api: {
limit: 600,
interval: "1 m",
},
analyticsApi: {
limit: 12,
interval: "1 s",
},
} as const;
interface WithWorkspaceHandler {
({
req,
params,
searchParams,
headers,
session,
workspace,
permissions,
token,
}: {
req: Request;
params: Record<string, string>;
searchParams: Record<string, string>;
headers?: Headers;
session: Session;
permissions: PermissionAction[];
workspace: WorkspaceWithUsers;
token: TokenCacheItem | null;
}): Promise<Response>;
}
export const withWorkspace = (
handler: WithWorkspaceHandler,
{
requiredPlan = ["free", "pro", "business", "advanced", "enterprise"], // if the action needs a specific plan
requiredPermissions = [],
requiredRoles = [],
legacyScopeGrants = [], // permissions that older restricted tokens keep on this route only
featureFlag, // if the action needs a specific feature flag
}: {
requiredPlan?: Array<PlanProps>;
requiredPermissions?: PermissionAction[];
requiredRoles?: WorkspaceRole[];
legacyScopeGrants?: LegacyScopeGrant[];
featureFlag?: BetaFeatures;
} = {},
) => {
return withAxiomBodyLog(
async (
req,
{ params: initialParams }: { params: Promise<Record<string, string>> },
) => {
// Clone the request early so handlers can read the body without cloning
// Keep the original for withAxiomBodyLog to read in onSuccess
const clonedReq = req.clone();
const reqForLog = clonedReq.clone();
const params = (await initialParams) || {};
const searchParams = getSearchParams(req.url);
let apiKey: string | undefined = undefined;
let requestHeaders = await headers();
let responseHeaders = new Headers();
let workspace: WorkspaceWithUsers | undefined;
let session: Session | undefined;
let token: TokenCacheItem | null = null;
const startTime = Date.now();
const url = new URL(req.url || "", API_DOMAIN);
try {
const authorizationHeader = requestHeaders.get("Authorization");
if (authorizationHeader) {
if (!authorizationHeader.startsWith("Bearer ")) {
throw new DubApiError({
code: "bad_request",
message:
"Misconfigured authorization header. Did you forget to add 'Bearer '? Learn more: https://d.to/auth",
});
}
apiKey = authorizationHeader.replace("Bearer ", "");
}
let workspaceId: string | undefined;
let workspaceSlug: string | undefined;
let permissions: PermissionAction[] = [];
const isRestrictedToken = apiKey?.startsWith("dub_");
const idOrSlug =
params?.idOrSlug ||
searchParams.workspaceId ||
params?.slug ||
searchParams.projectSlug;
/*
if there's no workspace ID or slug and it's not a restricted token:
- special case for anonymous link creation
- missing authorization header
- user is still using personal API keys
*/
if (!idOrSlug && !isRestrictedToken) {
// special case for anonymous link creation
if (
requestHeaders.has("dub-anonymous-link-creation") &&
["/links", "/api/links"].includes(req.nextUrl.pathname)
) {
// @ts-expect-error
return await handler({
req: clonedReq,
params,
searchParams,
headers: responseHeaders,
});
// missing authorization header
} else if (!authorizationHeader) {
throw new DubApiError({
code: "unauthorized",
message: "Missing Authorization header.",
});
// in case user is still using personal API keys
} else {
throw new DubApiError({
code: "not_found",
message:
"Workspace ID not found. Did you forget to include a `workspaceId` query parameter? It looks like you might be using personal API keys, we also recommend refactoring to workspace API keys: https://d.to/keys",
});
}
}
if (idOrSlug) {
if (idOrSlug.startsWith("ws_")) {
workspaceId = normalizeWorkspaceId(idOrSlug);
} else {
workspaceSlug = idOrSlug;
}
}
const isAnalytics =
url.pathname.includes("/analytics") ||
url.pathname.includes("/events");
if (apiKey) {
const hashedKey = await hashToken(apiKey);
let cachedToken = await tokenCache.get({
hashedKey,
});
// Entries cached before scope dates were stored would be treated as
// legacy and granted extra permissions, so reload them from the DB.
if (isRestrictedToken && cachedToken) {
const cachedScopeEffectiveSince = cachedToken.installationId
? cachedToken.installedIntegration?.createdAt
: cachedToken.createdAt;
if (cachedScopeEffectiveSince == null) {
cachedToken = null;
}
}
if (!cachedToken) {
const prismaArgs = {
where: {
hashedKey,
},
select: {
id: true,
expires: true,
...(isRestrictedToken && {
scopes: true,
createdAt: true,
projectId: true,
installationId: true,
installedIntegration: {
select: {
createdAt: true,
},
},
project: {
select: {
plan: true,
trialEndsAt: true,
},
},
}),
user: true,
},
};
if (isRestrictedToken) {
token = await prisma.restrictedToken.findUnique(prismaArgs);
} else {
token = await prisma.token.findUnique(prismaArgs);
}
}
token = cachedToken || token;
if (!token || !token.user) {
throw new DubApiError({
code: "unauthorized",
message: "Unauthorized: Invalid API key.",
});
}
if (token.expires && token.expires < new Date()) {
throw new DubApiError({
code: "unauthorized",
message: "Unauthorized: Access token expired.",
});
}
if (!cachedToken) {
waitUntil(
tokenCache.set({
hashedKey,
token,
}),
);
}
// Rate limit checks for API keys
let limit = 0;
let interval: `${number} s` | `${number} m` = isAnalytics
? "1 s"
: "1 m";
const planLimit = getRatelimitForPlan(token.project?.plan || "free", {
trialEndsAt: token.project?.trialEndsAt ?? null,
});
limit = planLimit.limits[isAnalytics ? "analyticsApi" : "api"];
const { success, headers } = await rateLimitRequest({
identifier: `workspace:ratelimit:${hashedKey}`,
requests: limit,
interval,
});
if (headers) {
for (const [key, value] of Object.entries(headers)) {
responseHeaders.set(key, value);
}
}
if (!success) {
throw new DubApiError({
code: "rate_limit_exceeded",
message: "Too many requests.",
});
}
// Find workspaceId if it's a restricted token
if (isRestrictedToken && token?.projectId) {
workspaceId = token.projectId;
}
waitUntil(
// update last used time for the token (only once every minute)
(async () => {
try {
const { success } = await ratelimit(1, "1 m").limit(
`last-used-${hashedKey}`,
);
if (success) {
const prismaArgs = {
where: {
hashedKey,
},
data: {
lastUsed: new Date(),
},
};
if (isRestrictedToken) {
await prisma.restrictedToken.update(prismaArgs);
} else {
await prisma.token.update(prismaArgs);
}
}
} catch (error) {
console.error(error);
}
})(),
);
session = {
user: {
id: token.user.id,
name: token.user.name || "",
email: token.user.email || "",
isMachine: token.user.isMachine,
},
};
} else {
session = await getSession();
if (!session?.user?.id) {
throw new DubApiError({
code: "unauthorized",
message: "Unauthorized: Login required.",
});
}
// Rate limit checks for session requests
const rateLimit =
RATE_LIMIT_FOR_SESSIONS[isAnalytics ? "analyticsApi" : "api"];
const { success, headers } = await rateLimitRequest({
identifier: `workspace:ratelimit:${session.user.id}`,
requests: rateLimit.limit,
interval: rateLimit.interval,
});
for (const [key, value] of Object.entries(headers)) {
responseHeaders.set(key, value);
}
if (!success) {
throw new DubApiError({
code: "rate_limit_exceeded",
message: "Too many requests.",
});
}
}
workspace = (await prisma.project.findUnique({
where: {
id: workspaceId || undefined,
slug: workspaceSlug || undefined,
},
include: {
users: {
where: {
userId: session.user.id,
},
select: {
role: true,
defaultFolderId: true,
workspacePreferences: !apiKey, // Hide from API
},
},
},
})) as WorkspaceWithUsers;
// workspace doesn't exist
if (!workspace || !workspace.users) {
// Clear so the catch path won't record this error against a partial/wrong workspace.
workspace = undefined;
throw new DubApiError({
code: "not_found",
message: "Workspace not found.",
});
}
// workspace exists but user is not part of it
if (workspace.users.length === 0) {
const pendingInvites = await prisma.projectInvite.findUnique({
where: {
email_projectId: {
email: session.user.email,
projectId: workspace.id,
},
},
select: {
expires: true,
},
});
// Clear so non-member denials are not attributed to this workspace
// in API logs or Axiom error context.
workspace = undefined;
if (!pendingInvites) {
throw new DubApiError({
code: "not_found",
message: "Workspace not found.",
});
} else if (pendingInvites.expires < new Date()) {
throw new DubApiError({
code: "invite_expired",
message: "Workspace invite expired.",
});
} else {
throw new DubApiError({
code: "invite_pending",
message: "Workspace invite pending.",
});
}
}
// Machine users have owner role by default
// Only workspace owners can create machine users
if (session.user.isMachine) {
workspace.users[0].role = "owner";
}
const rolePermissions = getPermissionsByRole(workspace.users[0].role);
permissions = rolePermissions;
// Find the subset of permissions that the user has access to based on the token scopes
// Empty/null scopes must fail closed (no permissions) — never inherit full role perms
if (isRestrictedToken) {
const tokenScopes = (token?.scopes?.split(" ").filter(Boolean) ??
[]) as Scope[];
permissions = mapScopesToPermissions(tokenScopes).filter((p) =>
rolePermissions.includes(p),
);
// OAuth access tokens are reissued on refresh, so grandfather the
// installation date. Workspace API keys use their own createdAt.
const scopeEffectiveSince = token?.installationId
? token.installedIntegration?.createdAt
: token?.createdAt;
permissions = grantLegacyScopePermissions({
permissions,
createdAt: scopeEffectiveSince,
grants: [...LEGACY_SCOPE_GRANTS, ...legacyScopeGrants],
}).filter((p) => rolePermissions.includes(p));
}
// Check user has permission to make the action
if (requiredPermissions.length > 0) {
throwIfNoAccess({
permissions,
requiredPermissions,
workspaceId: workspace.id,
externalRequest: Boolean(apiKey),
});
}
// role checks
if (
requiredRoles.length > 0 &&
!requiredRoles.includes(workspace.users[0].role)
) {
throw new DubApiError({
code: "forbidden",
message: `You don't have the required role to access this endpoint. Required role(s): ${requiredRoles.join(", ")}.`,
});
}
// beta feature checks
if (featureFlag) {
const flags = await getFeatureFlags({
workspaceId: workspace.id,
});
if (!flags[featureFlag]) {
throw new DubApiError({
code: "forbidden",
message: "Unauthorized: Beta feature.",
});
}
}
const normalizedWorkspacePlan = [
"business plus",
"business max",
"business extra",
].includes(workspace.plan)
? "business"
: workspace.plan;
// plan checks
if (!requiredPlan.includes(normalizedWorkspacePlan)) {
throw new DubApiError({
code: "forbidden",
message: "Unauthorized: Need higher plan.",
});
}
// analytics API checks
if (
normalizedWorkspacePlan === "free" &&
apiKey &&
url.pathname.includes("/analytics")
) {
throw new DubApiError({
code: "forbidden",
message: "Analytics API is only available on paid plans.",
});
}
const response = await handler({
req: clonedReq,
params,
searchParams,
headers: responseHeaders,
session,
workspace,
permissions,
token,
});
if (workspace?.users?.length) {
waitUntil(
captureRequestLog({
req: reqForLog,
response,
workspace,
session,
token,
url,
requestHeaders,
startTime,
}),
);
}
return response;
} catch (err) {
const { error, status } = handleApiError({
error: err,
workspace,
});
const response = NextResponse.json(
{ error },
{ headers: responseHeaders, status },
);
if (workspace?.users?.length) {
waitUntil(
captureRequestLog({
req: reqForLog,
response,
workspace,
session,
token,
url,
requestHeaders,
startTime,
}),
);
}
return response;
}
},
);
};