The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Merge branch 'main' into kiran/eng-140-integrations-dub-oauth
Kiran Kf58ec217f3a2
diff --cc apps/web/lib/auth/workspace-edge.tsindex bcb8c37de8,57e579e641..402be4db7a--- a/apps/web/lib/auth/workspace-edge.ts+++ b/apps/web/lib/auth/workspace-edge.ts@@@ -9,13 -9,15 +9,14 @@@ import { API_DOMAIN, getSearchParams }import { waitUntil } from "@vercel/functions";import { StreamingTextResponse } from "ai";import { getToken } from "next-auth/jwt";+ import { AxiomRequest, withAxiom } from "next-axiom";import { NextRequest } from "next/server";-import { throwIfNoAccess } from "../api/tokens/permissions";import {PermissionAction,- Scope,getPermissionsByRole,- mapScopesToPermissions,-} from "../api/tokens/scopes";+} from "../api/rbac/permissions";+import { throwIfNoAccess } from "../api/tokens/permissions";+import { Scope, mapScopesToPermissions } from "../api/tokens/scopes";import { getFeatureFlags } from "../edge-config";import { prismaEdge } from "../prisma/edge";import { hashToken } from "./hash-token";@@@ -67,78 -69,184 +68,192 @@@ export const withWorkspaceEdge =requiredPermissions?: PermissionAction[];} = {},) => {- return async (- req: Request,- { params = {} }: { params: Record<string, string> | undefined },- ) => {- const searchParams = getSearchParams(req.url);-- let apiKey: string | undefined = undefined;- let headers = {};-- try {- const authorizationHeader = req.headers.get("Authorization");- if (authorizationHeader) {- if (!authorizationHeader.includes("Bearer ")) {+ return withAxiom(+ async (+ req: AxiomRequest,+ { params = {} }: { params: Record<string, string> | undefined },+ ) => {+ const searchParams = getSearchParams(req.url);++ let apiKey: string | undefined = undefined;+ let headers = {};++ try {+ const authorizationHeader = req.headers.get("Authorization");+ if (authorizationHeader) {+ if (!authorizationHeader.includes("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 session: Session | undefined;+ let workspaceId: string | undefined;+ let workspaceSlug: string | undefined;+ let permissions: PermissionAction[] = [];+ let token: any | null = null;+ 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+ // For restricted tokens, we find the workspaceId from the token+ if (!idOrSlug && !isRestrictedToken) {throw new DubApiError({- code: "bad_request",+ code: "not_found",message:- "Misconfigured authorization header. Did you forget to add 'Bearer '? Learn more: https://d.to/auth",+ "Workspace id not found. Did you forget to include a `workspaceId` query parameter? Learn more: https://d.to/id",});}- apiKey = authorizationHeader.replace("Bearer ", "");- }- let session: Session | undefined;- let workspaceId: string | undefined;- let workspaceSlug: string | undefined;- let permissions: PermissionAction[] = [];- let token: any | null = null;- 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- // For restricted tokens, we find the workspaceId from the token- if (!idOrSlug && !isRestrictedToken) {- throw new DubApiError({- code: "not_found",- message:- "Workspace id not found. Did you forget to include a `workspaceId` query parameter? Learn more: https://d.to/id",- });- }+ if (idOrSlug) {+ if (idOrSlug.startsWith("ws_")) {+ workspaceId = idOrSlug.replace("ws_", "");+ } else {+ workspaceSlug = idOrSlug;+ }+ }- if (idOrSlug) {- if (idOrSlug.startsWith("ws_")) {- workspaceId = idOrSlug.replace("ws_", "");+ if (apiKey) {+ const hashedKey = await hashToken(apiKey);+ const prismaArgs = {+ where: {+ hashedKey,+ },+ select: {+ ...(isRestrictedToken && {+ scopes: true,+ rateLimit: true,+ projectId: true,++ expires: true,+ }),+ user: {+ select: {+ id: true,+ name: true,+ email: true,+ isMachine: true,+ },+ },+ },+ };++ if (isRestrictedToken) {+ token = await prismaEdge.restrictedToken.findUnique(prismaArgs);+ } else {+ token = await prismaEdge.token.findUnique(prismaArgs);+ }++ 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: "forbidden",++ message: "Unauthorized: Access token expired.",++ });++ }+++ // Rate limit checks for API keys+ const rateLimit = token?.rateLimit || 600;++ const { success, limit, reset, remaining } = await ratelimit(+ rateLimit,+ "1 m",+ ).limit(apiKey);+ headers = {+ "Retry-After": reset.toString(),+ "X-RateLimit-Limit": limit.toString(),+ "X-RateLimit-Remaining": remaining.toString(),+ "X-RateLimit-Reset": reset.toString(),+ };++ if (!success) {+ throw new DubApiError({+ code: "rate_limit_exceeded",+ message: "Too many requests.",+ });+ }++ // Find workspaceId if it's a restricted token+ if (isRestrictedToken) {+ workspaceId = token.projectId;+ }++ waitUntil(+ // update last used time for the token+ (async () => {+ const prismaArgs = {+ where: {+ hashedKey,+ },+ data: {+ lastUsed: new Date(),+ },+ };++ if (isRestrictedToken) {+ await prismaEdge.restrictedToken.update(prismaArgs);+ } else {+ await prismaEdge.token.update(prismaArgs);+ }+ })(),+ );++ session = {+ user: {+ id: token.user.id,+ name: token.user.name || "",+ email: token.user.email || "",+ isMachine: token.user.isMachine,+ },+ };} else {- workspaceSlug = idOrSlug;+ session = (await getToken({+ req: req as NextRequest,+ secret: process.env.NEXTAUTH_SECRET,+ })) as unknown as Session;++ if (!session?.user?.id) {+ throw new DubApiError({+ code: "unauthorized",+ message: "Unauthorized: Login required.",+ });+ }}- }- if (apiKey) {- const hashedKey = await hashToken(apiKey);- const prismaArgs = {+ const workspace = (await prismaEdge.project.findUnique({where: {- hashedKey,+ id: workspaceId || undefined,+ slug: workspaceSlug || undefined,},- select: {- ...(isRestrictedToken && {- scopes: true,- rateLimit: true,- projectId: true,- expires: true,- }),- user: {+ include: {+ users: {+ where: {+ userId: session.user.id,+ },+ select: {+ role: true,+ },+ },+ domains: {select: {id: true,- name: true,- email: true,- isMachine: true,+ slug: true,+ primary: true,+ verified: true,},},},diff --cc apps/web/lib/auth/workspace.tsindex 072f0ecbf9,bb6a152f91..970f8465c1--- a/apps/web/lib/auth/workspace.ts+++ b/apps/web/lib/auth/workspace.ts@@@ -4,12 -4,14 +4,13 @@@ import { BetaFeatures, PlanProps, Worksimport { ratelimit } from "@/lib/upstash";import { API_DOMAIN, getSearchParams } from "@dub/utils";import { waitUntil } from "@vercel/functions";+ import { AxiomRequest, withAxiom } from "next-axiom";-import { throwIfNoAccess } from "../api/tokens/permissions";import {PermissionAction,- Scope,getPermissionsByRole,- mapScopesToPermissions,-} from "../api/tokens/scopes";+} from "../api/rbac/permissions";+import { throwIfNoAccess } from "../api/tokens/permissions";+import { Scope, mapScopesToPermissions } from "../api/tokens/scopes";import { getFeatureFlags } from "../edge-config";import { hashToken } from "./hash-token";import { Session, getSession } from "./utils";@@@ -58,89 -60,185 +59,192 @@@ export const withWorkspace =skipPermissionChecks?: boolean;} = {},) => {- return async (- req: Request,- { params = {} }: { params: Record<string, string> | undefined },- ) => {- const searchParams = getSearchParams(req.url);-- let apiKey: string | undefined = undefined;- let headers = {};-- try {- const authorizationHeader = req.headers.get("Authorization");- if (authorizationHeader) {- if (!authorizationHeader.includes("Bearer ")) {- throw new DubApiError({- code: "bad_request",- message:- "Misconfigured authorization header. Did you forget to add 'Bearer '? Learn more: https://d.to/auth",- });+ return withAxiom(+ async (+ req: AxiomRequest,+ { params = {} }: { params: Record<string, string> | undefined },+ ) => {+ const searchParams = getSearchParams(req.url);++ let apiKey: string | undefined = undefined;+ let headers = {};++ try {+ const authorizationHeader = req.headers.get("Authorization");+ if (authorizationHeader) {+ if (!authorizationHeader.includes("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 ", "");}- apiKey = authorizationHeader.replace("Bearer ", "");- }- let session: Session | undefined;- let workspaceId: string | undefined;- let workspaceSlug: string | undefined;- let permissions: PermissionAction[] = [];- let token: any | null = null;- 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- // For restricted tokens, we find the workspaceId from the token- if (!idOrSlug && !isRestrictedToken) {- // for /api/links (POST /api/links) – allow no session (but warn if user provides apiKey)- if (allowAnonymous && !apiKey) {- // @ts-expect-error- return await handler({- req,- params,- searchParams,- headers,- });- } else {- throw new DubApiError({- code: "not_found",- message:- "Workspace id not found. Did you forget to include a `workspaceId` query parameter? Learn more: https://d.to/id",- });+ let session: Session | undefined;+ let workspaceId: string | undefined;+ let workspaceSlug: string | undefined;+ let permissions: PermissionAction[] = [];+ let token: any | null = null;+ 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+ // For restricted tokens, we find the workspaceId from the token+ if (!idOrSlug && !isRestrictedToken) {+ // for /api/links (POST /api/links) – allow no session (but warn if user provides apiKey)+ if (allowAnonymous && !apiKey) {+ // @ts-expect-error+ return await handler({+ req,+ params,+ searchParams,+ headers,+ });+ } else {+ throw new DubApiError({+ code: "not_found",+ message:+ "Workspace id not found. Did you forget to include a `workspaceId` query parameter? Learn more: https://d.to/id",+ });+ }}- }- if (idOrSlug) {- if (idOrSlug.startsWith("ws_")) {- workspaceId = idOrSlug.replace("ws_", "");+ if (idOrSlug) {+ if (idOrSlug.startsWith("ws_")) {+ workspaceId = idOrSlug.replace("ws_", "");+ } else {+ workspaceSlug = idOrSlug;+ }+ }++ if (apiKey) {+ const hashedKey = await hashToken(apiKey);+ const prismaArgs = {+ where: {+ hashedKey,+ },+ select: {+ ...(isRestrictedToken && {+ scopes: true,+ rateLimit: true,+ projectId: true,+ }),+ user: {+ select: {+ id: true,+ name: true,+ email: true,+ isMachine: true,+ },+ },+ },+ };++ if (isRestrictedToken) {+ token = await prisma.restrictedToken.findUnique(prismaArgs);+ } else {+ token = await prisma.token.findUnique(prismaArgs);+ }++ 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: "forbidden",++ message: "Unauthorized: Access token expired.",++ });++ }+++ // Rate limit checks for API keys+ const rateLimit = token.rateLimit || 600;++ const { success, limit, reset, remaining } = await ratelimit(+ rateLimit,+ "1 m",+ ).limit(apiKey);++ headers = {+ "Retry-After": reset.toString(),+ "X-RateLimit-Limit": limit.toString(),+ "X-RateLimit-Remaining": remaining.toString(),+ "X-RateLimit-Reset": reset.toString(),+ };++ if (!success) {+ throw new DubApiError({+ code: "rate_limit_exceeded",+ message: "Too many requests.",+ });+ }++ // Find workspaceId if it's a restricted token+ if (isRestrictedToken) {+ workspaceId = token.projectId;+ }++ waitUntil(+ // update last used time for the token+ (async () => {+ const prismaArgs = {+ where: {+ hashedKey,+ },+ data: {+ lastUsed: new Date(),+ },+ };++ if (isRestrictedToken) {+ await prisma.restrictedToken.update(prismaArgs);+ } else {+ await prisma.token.update(prismaArgs);+ }+ })(),+ );++ session = {+ user: {+ id: token.user.id,+ name: token.user.name || "",+ email: token.user.email || "",+ isMachine: token.user.isMachine,+ },+ };} else {- workspaceSlug = idOrSlug;+ session = await getSession();++ if (!session?.user?.id) {+ throw new DubApiError({+ code: "unauthorized",+ message: "Unauthorized: Login required.",+ });+ }}- }- if (apiKey) {- const hashedKey = await hashToken(apiKey);- const prismaArgs = {+ const workspace = (await prisma.project.findUnique({where: {- hashedKey,+ id: workspaceId || undefined,+ slug: workspaceSlug || undefined,},- select: {- ...(isRestrictedToken && {- scopes: true,- rateLimit: true,- projectId: true,- expires: true,- }),- user: {+ include: {+ users: {+ where: {+ userId: session.user.id,+ },select: {- id: true,- name: true,- email: true,- isMachine: true,+ role: true,},},},