The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
add, update and list OAuth apps
Kiran Kdb8cbe68070d
diff --git a/apps/web/app/api/oauth-clients/[clientId]/route.ts b/apps/web/app/api/oauth-apps/[clientId]/route.tssimilarity index 85%rename from apps/web/app/api/oauth-clients/[clientId]/route.tsrename to apps/web/app/api/oauth-apps/[clientId]/route.tsindex db48233695..8276600f89 100644--- a/apps/web/app/api/oauth-clients/[clientId]/route.ts+++ b/apps/web/app/api/oauth-apps/[clientId]/route.ts@@ -28,14 +28,14 @@ export const GET = withWorkspace(return NextResponse.json(oAuthClientSchema.parse(app));},{- requiredScopes: ["oauth_clients.read"],+ requiredScopes: ["oauth_apps.read"],},);// PATCH /api/oauth-clients/[clientId] – update an OAuth clientexport const PATCH = withWorkspace(async ({ req, params, workspace }) => {- const { name, description, website, redirectUri, scopes } =+ const { name, developer, website, redirectUri, scopes } =updateOAuthClientSchema.parse(await parseRequestBody(req));const app = await prisma.oAuthClient.update({@@ -45,19 +45,17 @@ export const PATCH = withWorkspace(},data: {...(name && { name }),- ...(description && { description }),+ ...(developer && { developer }),...(website && { website }),...(redirectUri && { redirectUri }),- ...(scopes && {- scopes: scopes.length > 0 ? [...new Set(scopes)].join(" ") : null,- }),+ ...(scopes && { scopes: [...new Set(scopes)].join(" ") }),},});return NextResponse.json(oAuthClientSchema.parse(app));},{- requiredScopes: ["oauth_clients.write"],+ requiredScopes: ["oauth_apps.write"],},);@@ -87,6 +85,6 @@ export const DELETE = withWorkspace(return NextResponse.json({ id: params.clientId });},{- requiredScopes: ["oauth_clients.write"],+ requiredScopes: ["oauth_apps.write"],},);diff --git a/apps/web/app/api/oauth-clients/route.ts b/apps/web/app/api/oauth-apps/route.tssimilarity index 84%rename from apps/web/app/api/oauth-clients/route.tsrename to apps/web/app/api/oauth-apps/route.tsindex 42e18d3d92..9d0072d6a7 100644--- a/apps/web/app/api/oauth-clients/route.ts+++ b/apps/web/app/api/oauth-apps/route.ts@@ -13,7 +13,7 @@ import { z } from "zod";// POST /api/oauth-clients - create a new OAuth clientexport const POST = withWorkspace(async ({ req, workspace }) => {- const { name, description, website, redirectUri, scopes } =+ const { name, developer, website, redirectUri, scopes } =createOAuthClientSchema.parse(await parseRequestBody(req));const clientSecret = `dub_${nanoid(TOKEN_LENGTH.clientSecret)}`;@@ -22,11 +22,10 @@ export const POST = withWorkspace(data: {projectId: workspace.id,name,- description,+ developer,website,redirectUri,- scopes:- scopes && scopes.length > 0 ? [...new Set(scopes)].join(" ") : null,+ scopes: [...new Set(scopes)].join(" "),clientId: nanoid(TOKEN_LENGTH.clientId),clientSecretHashed: await hashToken(clientSecret),},@@ -41,7 +40,7 @@ export const POST = withWorkspace();},{- requiredScopes: ["oauth_clients.write"],+ requiredScopes: ["oauth_apps.write"],},);@@ -57,6 +56,6 @@ export const GET = withWorkspace(return NextResponse.json(z.array(oAuthClientSchema).parse(clients));},{- requiredScopes: ["oauth_clients.read"],+ requiredScopes: ["oauth_apps.read"],},);diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/oauth-apps/page-client.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/oauth-apps/page-client.tsxindex 165a66b3a3..ac2ffdff71 100644--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/oauth-apps/page-client.tsx+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/oauth-apps/page-client.tsx@@ -1,43 +1,44 @@"use client";import useWorkspace from "@/lib/swr/use-workspace";-import { OAuthClientProps } from "@/lib/types";-import { useAddEditTokenModal } from "@/ui/modals/add-edit-token-modal";+import { OAuthAppProps } from "@/lib/types";+import { useAddEditAppModal } from "@/ui/modals/add-edit-oauth-app-modal";import { useTokenCreatedModal } from "@/ui/modals/token-created-modal";import EmptyState from "@/ui/shared/empty-state";import { Delete } from "@/ui/shared/icons";import { Button, LoadingSpinner, Popover, TokenAvatar } from "@dub/ui";import { Key } from "@dub/ui/src/icons";-import { fetcher, timeAgo } from "@dub/utils";+import { fetcher } from "@dub/utils";import { Edit3, MoreVertical } from "lucide-react";import { useState } from "react";import useSWR from "swr";export default function OAuthAppPageClient() {const { id: workspaceId } = useWorkspace();- const { data: clients, isLoading } = useSWR<OAuthClientProps[]>(- `/api/oauth-clients?workspaceId=${workspaceId}`,+ const { data: apps, isLoading } = useSWR<OAuthAppProps[]>(+ `/api/oauth-apps?workspaceId=${workspaceId}`,fetcher,);const [createdToken, setCreatedToken] = useState<string | null>(null);+const { TokenCreatedModal, setShowTokenCreatedModal } = useTokenCreatedModal({token: createdToken || "",});- const onTokenCreated = (token: string) => {+ const onAppCreated = (token: string) => {setCreatedToken(token);setShowTokenCreatedModal(true);};- const { AddEditTokenModal, AddTokenButton } = useAddEditTokenModal({- onTokenCreated,+ const { AddEditAppModal, AddAppButton } = useAddEditAppModal({+ onAppCreated,});return (<><TokenCreatedModal />- <AddEditTokenModal />+ <AddEditAppModal /><div className="rounded-lg border border-gray-200 bg-white"><div className="flex flex-col items-center justify-between gap-4 space-y-3 border-b border-gray-200 p-5 sm:flex-row sm:space-y-0 sm:p-10"><div className="flex max-w-screen-sm flex-col space-y-3">@@ -54,22 +55,21 @@ export default function OAuthAppPageClient() {</a></p></div>- <AddTokenButton />+ <AddAppButton /></div>- {isLoading || !clients ? (+ {isLoading || !apps ? (<div className="flex flex-col items-center justify-center space-y-4 py-20"><LoadingSpinner className="h-6 w-6 text-gray-500" />- <p className="text-sm text-gray-500">Fetching API keys...</p>+ <p className="text-sm text-gray-500">Fetching OAuth apps...</p></div>- ) : clients.length > 0 ? (+ ) : apps.length > 0 ? (<div><div className="grid grid-cols-5 border-b border-gray-200 px-5 py-2 text-sm font-medium text-gray-500 sm:px-10">- <div className="col-span-4">Name</div>- <div className="text-center">Last updated</div>+ <div className="col-span-3">Name</div></div><div className="divide-y divide-gray-200">- {clients.map((token) => (- <OAuthClientRow key={token.clientId} {...token} />+ {apps.map((token) => (+ <AppRow key={token.clientId} {...token} />))}</div></div>@@ -77,9 +77,9 @@ export default function OAuthAppPageClient() {<div className="flex flex-col items-center justify-center gap-y-4 py-20"><EmptyStateicon={Key}- title="No API keys found for this workspace"+ title="No OAuth Applications found for this workspace"/>- <AddTokenButton />+ <AddAppButton /></div>)}</div>@@ -87,17 +87,12 @@ export default function OAuthAppPageClient() {);}-const OAuthClientRow = (oauthClient: OAuthClientProps) => {+const AppRow = (app: OAuthAppProps) => {const [openPopover, setOpenPopover] = useState(false);- // const { setShowAddEditTokenModal, AddEditTokenModal } = useAddEditTokenModal({- // token: {- // id: token.id,- // name: token.name,- // isMachine: token.user.isMachine,- // scopes: mapScopesToResource(token.scopes),- // },- // });+ const { AddEditAppModal, setShowAddEditAppModal } = useAddEditAppModal({+ app,+ });// const { DeleteTokenModal, setShowDeleteTokenModal } = useDeleteTokenModal({// token,@@ -105,42 +100,36 @@ const OAuthClientRow = (oauthClient: OAuthClientProps) => {return (<>- {/* <AddEditTokenModal />- <DeleteTokenModal /> */}+ <AddEditAppModal />+ {/* <DeleteTokenModal /> */}<div className="relative grid grid-cols-5 items-center px-5 py-3 sm:px-10">- <div className="col-span-4 flex items-center space-x-3">- <TokenAvatar id={oauthClient.clientId} />+ <div className="col-span-3 flex items-center space-x-3">+ <TokenAvatar id={app.clientId} /><div className="flex flex-col space-y-px">- <p className="font-semibold text-gray-700">{oauthClient.name}</p>+ <p className="font-semibold text-gray-700">{app.name}</p><div className="flex items-center gap-x-2"><p className="text-sm text-gray-500" suppressHydrationWarning>- {oauthClient.scopes.length} access scopes+ {app.scopes.length} access scopes</p></div></div></div>- <div- className="text-center text-sm text-gray-500"- suppressHydrationWarning- >- {timeAgo(oauthClient.updatedAt, { withAgo: true })}- </div><Popovercontent={<div className="w-full sm:w-48"><div className="grid gap-px p-2"><Button- text="Edit API Key"+ text="Edit App"variant="outline"icon={<Edit3 className="h-4 w-4" />}className="h-9 justify-start px-2 font-medium"onClick={() => {setOpenPopover(false);- // setShowAddEditTokenModal(true);+ setShowAddEditAppModal(true);}}/><Button- text="Delete API Key"+ text="Delete App"variant="danger-outline"icon={<Delete className="h-4 w-4" />}className="h-9 justify-start px-2 font-medium"diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/tokens/page-client.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/tokens/page-client.tsxindex 2f213201d7..23830fb207 100644--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/tokens/page-client.tsx+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/tokens/page-client.tsx@@ -1,6 +1,6 @@"use client";-import { scopesToName } from "@/lib/api/tokens/scopes";+import { mapScopeToResource, scopesToName } from "@/lib/api/tokens/scopes";import useWorkspace from "@/lib/swr/use-workspace";import { TokenProps } from "@/lib/types";import { useAddEditTokenModal } from "@/ui/modals/add-edit-token-modal";@@ -99,7 +99,7 @@ const TokenRow = (token: TokenProps) => {id: token.id,name: token.name,isMachine: token.user.isMachine,- scopes: mapScopesToResource(token.scopes),+ scopes: mapScopeToResource(token.scopes),},});@@ -175,15 +175,3 @@ const TokenRow = (token: TokenProps) => {</>);};--const mapScopesToResource = (scopes: string[]) => {- const result = scopes.map((scope) => {- const [resource] = scope.split(".");-- return {- [resource]: scope,- };- });-- return Object.assign({}, ...result);-};diff --git a/apps/web/lib/api/tokens/scopes.ts b/apps/web/lib/api/tokens/scopes.tsindex b3eba9d61f..d903fc74e9 100644--- a/apps/web/lib/api/tokens/scopes.ts+++ b/apps/web/lib/api/tokens/scopes.ts@@ -13,254 +13,63 @@ export const availableScopes = ["tokens.read","tokens.write","conversions.write",- "oauth_clients.write",- "oauth_clients.read",+ "oauth_apps.read",+ "oauth_apps.write","apis.all", // All API scopes"apis.read", // All read scopes] as const;-export type Scope = (typeof availableScopes)[number];--type Resource =- | "links"- | "analytics"- | "workspaces"- | "domains"- | "tags"- | "tokens"- | "conversions"- | "oauth_clients";--type Permission = {- permission: string;- scope: Scope;- description: string;- roles: Role[];- resource: Resource;-};--export const resourcePermissions = [+export const resources = [{name: "Links",key: "links",description: "Create, read, update, and delete links",betaFeature: false,- permissions: [- {- permission: "Read",- scope: "links.read",- description: "Read links",- roles: ["owner", "member"],- },- {- permission: "Write",- scope: "links.write",- description: "Update and delete links",- roles: ["owner", "member"],- },- ],},{name: "Analytics",key: "analytics",description: "Read analytics",betaFeature: false,- permissions: [- {- permission: "Read",- scope: "analytics.read",- description: "Read analytics and events",- roles: ["owner", "member"],- },- ],},{name: "Workspaces",key: "workspaces",description: "Read, update, and delete workspaces",betaFeature: false,- permissions: [- {- permission: "Read",- scope: "workspaces.read",- description: "Read workspaces",- roles: ["owner", "member"],- },- {- permission: "Write",- scope: "workspaces.write",- description: "Update and delete workspaces",- roles: ["owner"],- },- ],},{name: "Domains",key: "domains",description: "Create, read, update, and delete domains",betaFeature: false,- permissions: [- {- permission: "Read",- scope: "domains.read",- description: "Read domains",- roles: ["owner", "member"],- },- {- permission: "Write",- scope: "domains.write",- description: "Update and delete domains",- roles: ["owner"],- },- ],},{name: "Tags",key: "tags",description: "Create, read, update, and delete tags",betaFeature: false,- permissions: [- {- permission: "Read",- scope: "tags.read",- description: "Read tags",- roles: ["owner", "member"],- },- {- permission: "Write",- scope: "tags.write",- description: "Update and delete tags",- roles: ["owner", "member"],- },- ],},{name: "API Keys",key: "tokens",description: "Create, read, update, and delete API keys",betaFeature: false,- permissions: [- {- permission: "Read",- scope: "tokens.read",- description: "Read tokens",- roles: ["owner", "member"],- },- {- permission: "Write",- scope: "tokens.write",- description: "Update and delete tokens",- roles: ["owner", "member"],- },- ],},{name: "Conversions",key: "conversions",description: "Track conversions (customer, lead, sales)",betaFeature: true,- permissions: [- {- permission: "Write",- scope: "conversions.write",- description: "Track customer, lead, and sales events",- roles: ["owner"],- },- ],},{name: "OAuth Apps",- key: "oauth_clients",- description: "OAuth apps (create, read, update, delete)",- betaFeature: true,- permissions: [- {- permission: "Read",- scope: "oauth_clients.read",- description: "Read OAuth apps",- roles: ["owner", "member"],- },- {- permission: "Write",- scope: "oauth_clients.write",- description: "Create, update, and delete OAuth apps",- roles: ["owner"],- },- ],+ key: "oauth_apps",+ description: "Create, read, update, and delete OAuth apps",+ betaFeature: false,},] as const;-// Map roles to scopes-// { owner: ["workspace.write"], member: ["workspace.read"] }-export const roleScopesMapping = resourcePermissions.reduce<- Record<Role, Scope[]>->(- (acc, { permissions }) => {- permissions.forEach(({ scope, roles }) => {- roles.forEach((role) => {- if (!acc[role]) {- acc[role] = [];- }-- acc[role].push(scope);- });- });-- return acc;- },- {} as Record<Role, Scope[]>,-);--export const scopeMapping = {- "apis.all": availableScopes,- "apis.read": availableScopes.filter((scope) => scope.endsWith(".read")),- "workspaces.write": ["workspaces.write", "workspaces.read"],- "links.write": ["links.write", "links.read"],- "tags.write": ["tags.write", "tags.read"],- "domains.write": ["domains.write", "domains.read"],- "tokens.write": ["tokens.write", "tokens.read"],- "oauth_apps.write": ["oauth_apps.write", "oauth_apps.read"],-};--export const scopePresets = [- {- value: "all_access",- label: "All",- description: "full access to all resources",- },- {- value: "read_only",- label: "Read Only",- description: "read-only access to all resources",- },- {- value: "restricted",- label: "Restricted",- description: "restricted access to some resources",- },-];--export const scopesToName = (scopes: string[]) => {- if (scopes.includes("apis.all")) {- return {- name: "All access",- description: "full access to all resources",- };- }-- if (scopes.includes("apis.read")) {- return {- name: "Read-only",- description: "read-only access to all resources",- };- }-- return {- name: "Restricted",- description: "restricted access to some resources",- };-};-export const permissions: Permission[] = [{permission: "Read",@@ -268,6 +77,7 @@ export const permissions: Permission[] = [description: "Read access to links",roles: ["owner", "member"],resource: "links",+ betaFeature: false,},{permission: "Write",@@ -275,6 +85,7 @@ export const permissions: Permission[] = [description: "Read and Write access to links",roles: ["owner", "member"],resource: "links",+ betaFeature: false,},{permission: "Read",@@ -282,6 +93,7 @@ export const permissions: Permission[] = [description: "Read access to analytics and events",roles: ["owner", "member"],resource: "analytics",+ betaFeature: false,},{permission: "Read",@@ -289,6 +101,7 @@ export const permissions: Permission[] = [description: "Read access to workspace",roles: ["owner", "member"],resource: "workspaces",+ betaFeature: false,},{permission: "Write",@@ -296,6 +109,7 @@ export const permissions: Permission[] = [description: "Read and Write access to workspace",roles: ["owner"],resource: "workspaces",+ betaFeature: false,},{permission: "Read",@@ -303,6 +117,7 @@ export const permissions: Permission[] = [description: "Read access to domains",roles: ["owner", "member"],resource: "domains",+ betaFeature: false,},{permission: "Write",@@ -310,6 +125,7 @@ export const permissions: Permission[] = [description: "Read and Write access to domains",roles: ["owner"],resource: "domains",+ betaFeature: false,},{permission: "Read",@@ -317,6 +133,7 @@ export const permissions: Permission[] = [description: "Read access to tags",roles: ["owner", "member"],resource: "tags",+ betaFeature: false,},{permission: "Write",@@ -324,6 +141,7 @@ export const permissions: Permission[] = [description: "Read and Write access to tags",roles: ["owner", "member"],resource: "tags",+ betaFeature: false,},{permission: "Read",@@ -331,6 +149,7 @@ export const permissions: Permission[] = [description: "Read access to Workspace API keys",roles: ["owner", "member"],resource: "tokens",+ betaFeature: false,},{permission: "Write",@@ -338,6 +157,7 @@ export const permissions: Permission[] = [description: "Read and Write access to Workspace API keys",roles: ["owner", "member"],resource: "tokens",+ betaFeature: false,},{permission: "Write",@@ -346,24 +166,77 @@ export const permissions: Permission[] = ["Read and Write access to conversions. Able to track customer, lead, and sales events",roles: ["owner"],resource: "conversions",+ betaFeature: true,},{permission: "Read",- scope: "oauth_clients.read",- description: "Read access to OAuth clients",+ scope: "oauth_apps.read",+ description: "Read access to OAuth apps.",roles: ["owner", "member"],- resource: "oauth_clients",+ resource: "oauth_apps",+ betaFeature: false,},{permission: "Write",- scope: "oauth_clients.write",- description: "Read and Write access to OAuth clients",+ scope: "oauth_apps.write",+ description: "Read and Write access to OAuth apps.",roles: ["owner"],- resource: "oauth_clients",+ resource: "oauth_apps",+ betaFeature: false,+ },+] as const;++export const scopeMapping = {+ "apis.all": availableScopes,+ "apis.read": availableScopes.filter((scope) => scope.endsWith(".read")),+ "workspaces.write": ["workspaces.write", "workspaces.read"],+ "links.write": ["links.write", "links.read"],+ "tags.write": ["tags.write", "tags.read"],+ "domains.write": ["domains.write", "domains.read"],+ "tokens.write": ["tokens.write", "tokens.read"],+ "oauth_apps.write": ["oauth_apps.write", "oauth_apps.read"],+};++export const scopePresets = [+ {+ value: "all_access",+ label: "All",+ description: "full access to all resources",+ },+ {+ value: "read_only",+ label: "Read Only",+ description: "read-only access to all resources",+ },+ {+ value: "restricted",+ label: "Restricted",+ description: "restricted access to some resources",},];-export const scopesByResource = permissions.reduce<+export const scopesToName = (scopes: string[]) => {+ if (scopes.includes("apis.all")) {+ return {+ name: "All access",+ description: "full access to all resources",+ };+ }++ if (scopes.includes("apis.read")) {+ return {+ name: "Read-only",+ description: "read-only access to all resources",+ };+ }++ return {+ name: "Restricted",+ description: "restricted access to some resources",+ };+};++export const permissionsByResource = permissions.reduce<Record<Resource, Permission[]>>((acc, permission) => {@@ -379,3 +252,48 @@ export const scopesByResource = permissions.reduce<},{} as Record<Resource, Permission[]>,);++export const scopesByRole = permissions.reduce<Record<Role, Scope[]>>(+ (acc, permission) => {+ const { roles } = permission;++ roles.forEach((role) => {+ if (!acc[role]) {+ acc[role] = [];+ }++ acc[role].push(permission.scope);+ });++ return acc;+ },+ {} as Record<Role, Scope[]>,+);++// { links: 'links.read', tags: 'tags.read', ... }+export const mapScopeToResource = (scopes: string[]) => {+ const result = scopes.map((scope) => {+ const [resource] = scope.split(".");++ return {+ [resource]: scope,+ };+ });++ return Object.assign({}, ...result) as Record<Resource, Scope>;+};++export type Scope = (typeof availableScopes)[number];++type Resource = (typeof resources)[number]["key"];++type Permission = {+ permission: string;+ scope: Scope;+ description: string;+ roles: Role[];+ resource: Resource;+ betaFeature: boolean;+};++export type ResourceScopeMapping = Record<Resource, Scope>;diff --git a/apps/web/lib/auth/workspace-edge.ts b/apps/web/lib/auth/workspace-edge.tsindex a1c3960bfa..3b7d38beb7 100644--- a/apps/web/lib/auth/workspace-edge.ts+++ b/apps/web/lib/auth/workspace-edge.ts@@ -11,7 +11,7 @@ import { StreamingTextResponse } from "ai";import { getToken } from "next-auth/jwt";import { NextRequest } from "next/server";import { throwIfNoAccess } from "../api/tokens/permissions";-import { Scope, roleScopesMapping } from "../api/tokens/scopes";+import { Scope, scopesByRole } from "../api/tokens/scopes";import { isBetaTester } from "../edge-config";import { prismaEdge } from "../prisma/edge";import { hashToken } from "./hash-token";@@ -256,7 +256,7 @@ export const withWorkspaceEdge = (if (token && "scopes" in token) {scopes = (token.scopes?.split(" ") as Scope[]) || [];} else {- scopes = roleScopesMapping[workspace.users[0].role];+ scopes = scopesByRole[workspace.users[0].role];}// Check user has permission to make the actiondiff --git a/apps/web/lib/auth/workspace.ts b/apps/web/lib/auth/workspace.tsindex aa7c213f2a..a78bdfb936 100644--- a/apps/web/lib/auth/workspace.ts+++ b/apps/web/lib/auth/workspace.ts@@ -5,7 +5,7 @@ import { ratelimit } from "@/lib/upstash";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 { Scope, scopesByRole } from "../api/tokens/scopes";import { isBetaTester } from "../edge-config";import { hashToken } from "./hash-token";import { Session, getSession } from "./utils";@@ -281,7 +281,7 @@ export const withWorkspace = (if (token && "scopes" in token) {scopes = (token.scopes?.split(" ") as Scope[]) || [];} else if (workspace.users.length > 0) {- scopes = roleScopesMapping[workspace.users[0].role];+ scopes = scopesByRole[workspace.users[0].role];}// Check user has permission to make the actiondiff --git a/apps/web/lib/types.ts b/apps/web/lib/types.tsindex 3d836f27f1..b3e71239bf 100644--- a/apps/web/lib/types.ts+++ b/apps/web/lib/types.ts@@ -3,8 +3,8 @@ import { metaTagsSchema } from "@/lib/zod/schemas/metatags";import { DirectorySyncProviders } from "@boxyhq/saml-jackson";import { Link } from "@prisma/client";import { createLinkBodySchema } from "./zod/schemas/links";-import { tokenSchema } from "./zod/schemas/token";import { oAuthClientSchema } from "./zod/schemas/oauth";+import { tokenSchema } from "./zod/schemas/token";export type LinkProps = Link;@@ -196,4 +196,4 @@ export type MetaTag = z.infer<typeof metaTagsSchema>;export type TokenProps = z.infer<typeof tokenSchema>;-export type OAuthClientProps = z.infer<typeof oAuthClientSchema>;\ No newline at end of file+export type OAuthAppProps = z.infer<typeof oAuthClientSchema>;diff --git a/apps/web/lib/zod/schemas/oauth.ts b/apps/web/lib/zod/schemas/oauth.tsindex a03fc28048..5bf8211397 100644--- a/apps/web/lib/zod/schemas/oauth.ts+++ b/apps/web/lib/zod/schemas/oauth.ts@@ -4,23 +4,23 @@ import { z } from "zod";export const oAuthClientSchema = z.object({clientId: z.string(),name: z.string(),- description: z.string().nullable(),+ developer: z.string(),website: z.string(),redirectUri: z.string(),scopes: z.string().nullable().transform((val) => val?.split(" ") ?? []),- createdAt: z.date(),- updatedAt: z.date(),});export const createOAuthClientSchema = z.object({name: z.string().min(1).max(255),- description: z.string().max(255).nullable(),+ developer: z.string().min(1).max(255),website: z.string().url().max(255),redirectUri: z.string().url().max(255),- scopes: z.array(z.enum(availableScopes)).default([]).optional(),+ scopes: z+ .array(z.enum(availableScopes))+ .min(1, "An OAuth app must have at least one scope"),});export const updateOAuthClientSchema = createOAuthClientSchema.partial();diff --git a/apps/web/prisma/schema.prisma b/apps/web/prisma/schema.prismaindex 5473003cb4..599efce97c 100644--- a/apps/web/prisma/schema.prisma+++ b/apps/web/prisma/schema.prisma@@ -364,8 +364,9 @@ model Customer {model OAuthClient {clientId String @id @uniquename String+ developer Stringwebsite String- description String?+ description String? // not usedclientSecretHashed StringredirectUri Stringscopes Stringdiff --git a/apps/web/ui/modals/add-edit-oauth-app-modal.tsx b/apps/web/ui/modals/add-edit-oauth-app-modal.tsxnew file mode 100644index 0000000000..ecb2fc12f0--- /dev/null+++ b/apps/web/ui/modals/add-edit-oauth-app-modal.tsx@@ -0,0 +1,341 @@+import {+ ResourceScopeMapping,+ Scope,+ mapScopeToResource,+ permissionsByResource,+ resources,+} from "@/lib/api/tokens/scopes";+import useWorkspace from "@/lib/swr/use-workspace";+import { OAuthAppProps } from "@/lib/types";+import {+ AnimatedSizeContainer,+ BlurImage,+ Button,+ ButtonProps,+ InfoTooltip,+ Logo,+ Modal,+ RadioGroup,+ RadioGroupItem,+} from "@dub/ui";+import {+ Dispatch,+ FormEvent,+ SetStateAction,+ useCallback,+ useMemo,+ useState,+} from "react";+import { toast } from "sonner";+import { mutate } from "swr";++const newApp: OAuthAppProps = {+ name: "",+ developer: "",+ website: "",+ clientId: "",+ redirectUri: "",+ scopes: [],+};++function AddEditAppModal({+ showAddEditAppModal,+ setShowAddEditAppModal,+ app,+ onAppCreated,+}: {+ showAddEditAppModal: boolean;+ setShowAddEditAppModal: Dispatch<SetStateAction<boolean>>;+ app?: OAuthAppProps;+ onAppCreated?: (App: string) => void;+}) {+ const [saving, setSaving] = useState(false);+ const [data, setData] = useState<OAuthAppProps>(app || newApp);+ const { id: workspaceId, logo, slug, betaTester } = useWorkspace();+ const [selectedScopes, setSelectedScopes] = useState<+ ResourceScopeMapping | {}+ >(mapScopeToResource(app?.scopes || []));++ // Determine the endpoint+ const endpoint = useMemo(() => {+ if (app) {+ return {+ method: "PATCH",+ url: `/api/oauth-apps/${app.clientId}?workspaceId=${workspaceId}`,+ successMessage: "OAuth app updated!",+ };+ } else {+ return {+ method: "POST",+ url: `/api/oauth-apps?workspaceId=${workspaceId}`,+ successMessage: "OAuth app created!",+ };+ }+ }, [app]);++ // Save the form data+ const onSubmit = async (e: FormEvent) => {+ e.preventDefault();+ setSaving(true);++ const response = await fetch(endpoint.url, {+ method: endpoint.method,+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ ...data,+ scopes: Object.values(selectedScopes).filter((v) => v),+ }),+ });++ const result = await response.json();++ if (response.ok) {+ mutate(`/api/oauth-apps?workspaceId=${workspaceId}`);+ toast.success(endpoint.successMessage);+ onAppCreated?.(result.App);+ setShowAddEditAppModal(false);+ } else {+ toast.error(result.error.message);+ setSaving(false);+ }+ };++ const { name, developer, website, redirectUri, scopes } = data;+ const buttonDisabled =+ !name ||+ !developer ||+ !website ||+ !redirectUri ||+ Object.values(scopes).filter((v) => v).length === 0;++ return (+ <>+ <Modal+ showModal={showAddEditAppModal}+ setShowModal={setShowAddEditAppModal}+ className="scrollbar-hide h-fit max-h-[95vh] overflow-auto"+ >+ <div className="flex flex-col items-center justify-center space-y-3 border-b border-gray-200 px-4 py-4 pt-8 sm:px-16">+ {logo ? (+ <BlurImage+ src={logo}+ alt={`Logo for ${slug}`}+ className="h-10 w-10 rounded-full border border-gray-200"+ width={20}+ height={20}+ />+ ) : (+ <Logo />+ )}+ <h1 className="text-lg font-medium">+ {app ? "Edit" : "Add New"} OAuth Application+ </h1>+ </div>++ <form+ onSubmit={onSubmit}+ className="flex flex-col space-y-4 bg-gray-50 px-4 py-8 text-left sm:px-10"+ >+ <div>+ <label htmlFor="name" className="flex items-center space-x-2">+ <h2 className="text-sm font-medium text-gray-900">+ Application name+ </h2>+ <InfoTooltip content="Application name will be displayed in the OAuth consent screen" />+ </label>+ <div className="relative mt-2 rounded-md shadow-sm">+ <input+ className="block w-full rounded-md border-gray-300 text-gray-900 placeholder-gray-400 focus:border-gray-500 focus:outline-none focus:ring-gray-500 sm:text-sm"+ required+ value={name}+ onChange={(e) => setData({ ...data, name: e.target.value })}+ autoFocus+ autoComplete="off"+ placeholder="My App"+ />+ </div>+ </div>++ <div>+ <label htmlFor="developer" className="flex items-center space-x-2">+ <h2 className="text-sm font-medium text-gray-900">+ Developer name+ </h2>+ <InfoTooltip content="The person or company developing this application" />+ </label>+ <div className="relative mt-2 rounded-md shadow-sm">+ <input+ className="block w-full rounded-md border-gray-300 text-gray-900 placeholder-gray-400 focus:border-gray-500 focus:outline-none focus:ring-gray-500 sm:text-sm"+ required+ value={developer}+ onChange={(e) =>+ setData({ ...data, developer: e.target.value })+ }+ placeholder="Acme Inc."+ />+ </div>+ </div>++ <div>+ <label htmlFor="website" className="flex items-center space-x-2">+ <h2 className="text-sm font-medium text-gray-900">Website URL</h2>+ <InfoTooltip content="URL to the developer's website or documentation" />+ </label>+ <div className="relative mt-2 rounded-md shadow-sm">+ <input+ className="block w-full rounded-md border-gray-300 text-gray-900 placeholder-gray-400 focus:border-gray-500 focus:outline-none focus:ring-gray-500 sm:text-sm"+ type="url"+ required+ value={website}+ onChange={(e) => setData({ ...data, website: e.target.value })}+ placeholder="https://acme.com"+ />+ </div>+ </div>++ <div>+ <label+ htmlFor="redirectUri"+ className="flex items-center space-x-2"+ >+ <h2 className="text-sm font-medium text-gray-900">+ Callback URL+ </h2>+ <InfoTooltip content="URL to redirect the user after authentication. Must use HTTPS, except for localhost" />+ </label>+ <div className="relative mt-2 rounded-md shadow-sm">+ <input+ className="block w-full rounded-md border-gray-300 text-gray-900 placeholder-gray-400 focus:border-gray-500 focus:outline-none focus:ring-gray-500 sm:text-sm"+ type="url"+ required+ value={redirectUri}+ onChange={(e) =>+ setData({ ...data, redirectUri: e.target.value })+ }+ placeholder="https://acme.com/callback"+ />+ </div>+ </div>++ <div className="flex flex-col gap-2">+ <h2 className="text-sm font-medium text-gray-900">+ Application permissions+ </h2>+ <p className="text-sm text-gray-500">+ These permissions will be presented to the user when adding an app+ to their workspace. Must choose at least one permission.+ </p>+ </div>++ <AnimatedSizeContainer height>+ <div className="flex flex-col divide-y text-sm">+ {resources+ .filter((resource) => resource.betaFeature === betaTester)+ .map((resource) => (+ <div+ className="flex items-center justify-between py-4"+ key={resource.key}+ >+ <div className="flex items-center gap-1.5 text-gray-500">+ <p>{resource.name}</p>+ <InfoTooltip content={resource.description} />+ </div>+ <div>+ <RadioGroup+ defaultValue={selectedScopes[resource.key] || ""}+ className="flex gap-4"+ onValueChange={(v: Scope) => {+ setSelectedScopes({+ ...selectedScopes,+ [resource.key]: v,+ });+ }}+ >+ <div className="flex items-center space-x-2">+ <RadioGroupItem value="" />+ <div>None</div>+ </div>+ {permissionsByResource[resource.key]?.map(+ (permission) => (+ <div+ className="flex items-center space-x-2"+ key={permission.scope}+ >+ <RadioGroupItem value={permission.scope} />+ <div>{permission.permission}</div>+ </div>+ ),+ )}+ </RadioGroup>+ </div>+ </div>+ ))}+ </div>+ </AnimatedSizeContainer>++ <Button+ text={app ? "Save changes" : "Create"}+ disabled={buttonDisabled}+ loading={saving}+ />+ </form>+ </Modal>+ </>+ );+}++function AddAppButton({+ setShowAddEditAppModal,+ buttonProps,+}: {+ setShowAddEditAppModal: Dispatch<SetStateAction<boolean>>;+ buttonProps?: Partial<ButtonProps>;+}) {+ return (+ <div>+ <Button+ text="Create"+ onClick={() => setShowAddEditAppModal(true)}+ {...buttonProps}+ />+ </div>+ );+}++export function useAddEditAppModal(+ {+ app,+ onAppCreated,+ }: {+ app?: OAuthAppProps;+ onAppCreated?: (App: string) => void;+ } = { onAppCreated: () => {} },+) {+ const [showAddEditAppModal, setShowAddEditAppModal] = useState(false);++ const AddEditAppModalCallback = useCallback(() => {+ return (+ <AddEditAppModal+ showAddEditAppModal={showAddEditAppModal}+ setShowAddEditAppModal={setShowAddEditAppModal}+ app={app}+ onAppCreated={onAppCreated}+ />+ );+ }, [showAddEditAppModal, setShowAddEditAppModal]);++ const AddAppButtonCallback = useCallback(() => {+ return <AddAppButton setShowAddEditAppModal={setShowAddEditAppModal} />;+ }, [setShowAddEditAppModal]);++ return useMemo(+ () => ({+ setShowAddEditAppModal,+ AddEditAppModal: AddEditAppModalCallback,+ AddAppButton: AddAppButtonCallback,+ }),+ [setShowAddEditAppModal, AddEditAppModalCallback, AddAppButtonCallback],+ );+}diff --git a/apps/web/ui/modals/add-edit-token-modal.tsx b/apps/web/ui/modals/add-edit-token-modal.tsxindex 028c357d65..01fa11878e 100644--- a/apps/web/ui/modals/add-edit-token-modal.tsx+++ b/apps/web/ui/modals/add-edit-token-modal.tsx@@ -1,6 +1,7 @@import {Scope,- resourcePermissions,+ permissionsByResource,+ resources,scopePresets,} from "@/lib/api/tokens/scopes";import useWorkspace from "@/lib/swr/use-workspace";@@ -251,11 +252,8 @@ function AddEditTokenModal({</div>{preset === "restricted" && (<div className="flex flex-col divide-y text-sm">- {resourcePermissions- .filter(- // filter out beta features- (resource) => !resource.betaFeature || betaTester,- )+ {resources+ .filter((resource) => resource.betaFeature === betaTester).map((resource) => (<divclassName="flex items-center justify-between py-4"@@ -283,15 +281,17 @@ function AddEditTokenModal({<RadioGroupItem value="" /><div>None</div></div>- {resource.permissions.map((permission) => (- <div- className="flex items-center space-x-2"- key={permission.scope}- >- <RadioGroupItem value={permission.scope} />- <div>{permission.permission}</div>- </div>- ))}+ {permissionsByResource[resource.key]?.map(+ (permission) => (+ <div+ className="flex items-center space-x-2"+ key={permission.scope}+ >+ <RadioGroupItem value={permission.scope} />+ <div>{permission.permission}</div>+ </div>+ ),+ )}</RadioGroup></div></div>