The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
add webhook form
Kiran Kddf0f0e66cda
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/webhooks/[webhookId]/edit/page-client.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/webhooks/[webhookId]/edit/page-client.tsxnew file mode 100644index 0000000000..be9762470c--- /dev/null+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/webhooks/[webhookId]/edit/page-client.tsx@@ -0,0 +1,45 @@+"use client";++import { clientAccessCheck } from "@/lib/api/tokens/permissions";+import useWorkspace from "@/lib/swr/use-workspace";+import { WebhookProps } from "@/lib/types";+import AddEditWebhookForm from "@/ui/webhooks/add-edit-webhook-form";+import WebhookHeader from "@/ui/webhooks/webhook-header";+import { MaxWidthWrapper } from "@dub/ui";+import { fetcher } from "@dub/utils";+import { redirect } from "next/navigation";+import useSWR from "swr";++// TODO:+// Finish the remaining++export default function UpdateWebhookPageClient({+ webhookId,+}: {+ webhookId: string;+}) {+ const { slug, flags, role, id: workspaceId } = useWorkspace();++ const { error: permissionsError } = clientAccessCheck({+ action: "webhooks.write",+ role,+ });++ if (!flags?.webhooks || permissionsError) {+ redirect(`/${slug}/settings`);+ }++ const { data: webhook, isLoading } = useSWR<WebhookProps>(+ `/api/webhooks/${webhookId}?workspaceId=${workspaceId}`,+ fetcher,+ );++ return (+ <>+ <WebhookHeader webhookId={webhookId} />+ <MaxWidthWrapper className="max-w-screen-lg space-y-6">+ <AddEditWebhookForm webhook={null} />+ </MaxWidthWrapper>+ </>+ );+}diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/webhooks/[webhookId]/edit/page.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/webhooks/[webhookId]/edit/page.tsxnew file mode 100644index 0000000000..569b80adb5--- /dev/null+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/webhooks/[webhookId]/edit/page.tsx@@ -0,0 +1,11 @@+import UpdateWebhookPageClient from "./page-client";++export default async function UpdateWebhookPage({+ params,+}: {+ params: { webhookId: string };+}) {+ const { webhookId } = params;++ return <UpdateWebhookPageClient webhookId={webhookId} />;+}diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/webhooks/[webhookId]/page-client.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/webhooks/[webhookId]/page-client.tsxnew file mode 100644index 0000000000..c295a2c74d--- /dev/null+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/webhooks/[webhookId]/page-client.tsx@@ -0,0 +1,43 @@+"use client";++import { clientAccessCheck } from "@/lib/api/tokens/permissions";+import useWorkspace from "@/lib/swr/use-workspace";+import WebhookHeader from "@/ui/webhooks/webhook-header";+import { MaxWidthWrapper } from "@dub/ui";+import { fetcher } from "@dub/utils";+import { redirect } from "next/navigation";+import useSWR from "swr";++export default function WebhookLogsPageClient({+ webhookId,+}: {+ webhookId: string;+}) {+ const { slug, flags, role, id: workspaceId } = useWorkspace();++ const { error: permissionsError } = clientAccessCheck({+ action: "webhooks.read",+ role,+ });++ if (!flags?.webhooks || permissionsError) {+ redirect(`/${slug}/settings`);+ }++ const { data, isLoading, error } = useSWR<any[]>(+ `/api/webhooks/${webhookId}/logs?workspaceId=${workspaceId}`,+ fetcher,+ {+ keepPreviousData: true,+ },+ );++ return (+ <>+ <WebhookHeader webhookId={webhookId} />+ <MaxWidthWrapper className="max-w-screen-lg space-y-6">+ <></>+ </MaxWidthWrapper>+ </>+ );+}diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/webhooks/[webhookId]/page.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/webhooks/[webhookId]/page.tsxnew file mode 100644index 0000000000..714f01599c--- /dev/null+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/webhooks/[webhookId]/page.tsx@@ -0,0 +1,11 @@+import WebhookLogsPageClient from "./page-client";++export default async function WebhookLogsPage({+ params,+}: {+ params: { webhookId: string };+}) {+ const { webhookId } = params;++ return <WebhookLogsPageClient webhookId={webhookId} />;+}diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/webhooks/new/page-client.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/webhooks/new/page-client.tsxnew file mode 100644index 0000000000..9c604e9915--- /dev/null+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/webhooks/new/page-client.tsx@@ -0,0 +1,44 @@+"use client";++import { clientAccessCheck } from "@/lib/api/tokens/permissions";+import useWorkspace from "@/lib/swr/use-workspace";+import AddEditWebhookForm from "@/ui/webhooks/add-edit-webhook-form";+import { MaxWidthWrapper } from "@dub/ui";+import { ChevronLeft } from "lucide-react";+import Link from "next/link";+import { redirect } from "next/navigation";++export default function NewWebhookPageClient({+ newSecret,+}: {+ newSecret: string;+}) {+ const { slug, flags, role } = useWorkspace();++ const { error: permissionsError } = clientAccessCheck({+ action: "webhooks.write",+ role,+ });++ if (!flags?.webhooks || permissionsError) {+ redirect(`/${slug}/settings`);+ }++ return (+ <>+ <MaxWidthWrapper className="grid max-w-screen-lg gap-8">+ <Link+ href={`/${slug}/settings/webhooks`}+ className="flex items-center gap-x-1"+ >+ <ChevronLeft className="size-4" />+ <p className="text-sm font-medium text-gray-500">Back to webhooks</p>+ </Link>+ </MaxWidthWrapper>++ <MaxWidthWrapper className="max-w-screen-lg space-y-6">+ <AddEditWebhookForm webhook={null} newSecret={newSecret} />+ </MaxWidthWrapper>+ </>+ );+}diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/webhooks/new/page.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/webhooks/new/page.tsxnew file mode 100644index 0000000000..4c19a1862b--- /dev/null+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/webhooks/new/page.tsx@@ -0,0 +1,15 @@+import { createToken } from "@/lib/api/oauth/utils";+import {+ WEBHOOK_SECRET_LENGTH,+ WEBHOOK_SECRET_PREFIX,+} from "@/lib/webhook/constants";+import NewWebhookPageClient from "./page-client";++export default async function NewWebhookPage() {+ const newSecret = createToken({+ prefix: WEBHOOK_SECRET_PREFIX,+ length: WEBHOOK_SECRET_LENGTH,+ });++ return <NewWebhookPageClient newSecret={newSecret} />;+}diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/webhooks/page-client.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/webhooks/page-client.tsxnew file mode 100644index 0000000000..fe1ba4fdba--- /dev/null+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/webhooks/page-client.tsx@@ -0,0 +1,84 @@+"use client";++import { clientAccessCheck } from "@/lib/api/tokens/permissions";+import useWorkspace from "@/lib/swr/use-workspace";+import { WebhookProps } from "@/lib/types";+import EmptyState from "@/ui/shared/empty-state";+import WebhookCard from "@/ui/webhooks/webhook-card";+import WebhookPlaceholder from "@/ui/webhooks/webhook-placeholder";+import { Button, Cube, TooltipContent } from "@dub/ui";+import { InfoTooltip } from "@dub/ui/src/tooltip";+import { fetcher } from "@dub/utils";+import { redirect, useRouter } from "next/navigation";+import useSWR from "swr";++export default function WebhooksPageClient() {+ const router = useRouter();+ const { slug, id: workspaceId, flags, role } = useWorkspace();++ if (!flags?.webhooks) {+ redirect(`/${slug}/settings`);+ }++ const { data: webhooks, isLoading } = useSWR<WebhookProps[]>(+ `/api/webhooks?workspaceId=${workspaceId}`,+ fetcher,+ );++ const { error: permissionsError } = clientAccessCheck({+ action: "webhooks.write",+ role,+ });++ return (+ <div className="grid gap-5">+ <div className="flex flex-wrap justify-between gap-6">+ <div className="flex items-center gap-x-2">+ <h1 className="text-2xl font-semibold tracking-tight text-black">+ Webhooks+ </h1>+ <InfoTooltip+ content={+ <TooltipContent+ title="Webhooks allow you to receive HTTP requests whenever a specific event (eg: someone clicked your link) occurs in Dub."+ href="https://dub.co/docs/webhooks"+ target="_blank"+ cta="Learn more"+ />+ }+ />+ </div>+ <div className="flex w-full items-center gap-3 sm:w-auto">+ <Button+ className="flex h-10 items-center justify-center whitespace-nowrap rounded-lg border px-4 text-sm"+ text="Add Webhook"+ onClick={() => router.push(`/${slug}/settings/webhooks/new`)}+ disabledTooltip={permissionsError}+ />+ </div>+ </div>++ <div className="animate-fade-in">+ {!isLoading ? (+ webhooks && webhooks.length > 0 ? (+ <div className="grid grid-cols-1 gap-3">+ {webhooks.map((webhook) => (+ <WebhookCard {...webhook} key={webhook.id} />+ ))}+ </div>+ ) : (+ <div className="flex flex-col items-center gap-4 rounded-xl border border-gray-200 py-10">+ <EmptyState icon={Cube} title="No webhooks added yet." />+ </div>+ )+ ) : (+ <div className="grid grid-cols-1 gap-3">+ {Array.from({ length: 3 }).map((_, idx) => (+ <WebhookPlaceholder />+ ))}+ </div>+ )}+ </div>+ </div>+ );+}diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/webhooks/page.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/webhooks/page.tsxindex 96760a40e2..af274b35ff 100644--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/webhooks/page.tsx+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/webhooks/page.tsx@@ -1,3 +1,5 @@-export default function WebhooksPage() {- return <div>Webhooks</div>;+import WebhooksPageClient from "./page-client";++export default async function WebhooksPage() {+ return <WebhooksPageClient />;}diff --git a/apps/web/lib/edge-config/get-feature-flags.ts b/apps/web/lib/edge-config/get-feature-flags.tsindex f4ec738738..e721291b7c 100644--- a/apps/web/lib/edge-config/get-feature-flags.ts+++ b/apps/web/lib/edge-config/get-feature-flags.ts@@ -18,8 +18,9 @@ export const getFeatureFlags = async ({const workspaceFeatures: Record<BetaFeatures, boolean> = {conversions: false,- integrations: false,+ integrations: true,dublink: false,+ webhooks: true,};if (!process.env.NEXT_PUBLIC_IS_DUB || !process.env.EDGE_CONFIG) {diff --git a/apps/web/lib/types.ts b/apps/web/lib/types.tsindex b30a798605..8d194b4111 100644--- a/apps/web/lib/types.ts+++ b/apps/web/lib/types.ts@@ -2,11 +2,12 @@ import z from "@/lib/zod";import { metaTagsSchema } from "@/lib/zod/schemas/metatags";import { DirectorySyncProviders } from "@boxyhq/saml-jackson";import { Link, Project } from "@prisma/client";-import { webhookTriggers } from "./webhook/constants";+import { WEBHOOK_TRIGGERS } from "./webhook/constants";import { integrationSchema } from "./zod/schemas/integration";import { createLinkBodySchema } from "./zod/schemas/links";import { oAuthAppSchema } from "./zod/schemas/oauth";import { tokenSchema } from "./zod/schemas/token";+import { createWebhookSchema, webhookSchema } from "./zod/schemas/webhooks";export type LinkProps = Link;@@ -71,7 +72,11 @@ export type PlanProps = (typeof plans)[number];export type RoleProps = (typeof roles)[number];-export type BetaFeatures = "conversions" | "integrations" | "dublink";+export type BetaFeatures =+ | "conversions"+ | "integrations"+ | "dublink"+ | "webhooks";export interface WorkspaceProps extends Project {logo: string | null;@@ -238,11 +243,8 @@ export type InstalledIntegrationInfoProps = Pick<} | null;};-export type WebhookTrigger = (typeof webhookTriggers)[number];+export type WebhookTrigger = (typeof WEBHOOK_TRIGGERS)[number];-export type WebhookEventPayload = {- id: string;- event: WebhookTrigger;- createdAt: string;- data: any; // FIXME: add type-};+export type WebhookProps = z.infer<typeof webhookSchema>;++export type NewWebhook = z.infer<typeof createWebhookSchema>;diff --git a/apps/web/lib/webhook/constants.ts b/apps/web/lib/webhook/constants.tsindex 6e627ff3c1..1a8fb92907 100644--- a/apps/web/lib/webhook/constants.ts+++ b/apps/web/lib/webhook/constants.ts@@ -1,3 +1,7 @@-export const webhookSources = ["zapier", "make", "user"] as const;+export const WEBHOOK_SOURCES = ["zapier", "make", "user"] as const;-export const webhookTriggers = ["link.created", "link.clicked"] as const;+export const WEBHOOK_TRIGGERS = ["link.created", "link.clicked"] as const;++export const WEBHOOK_SECRET_LENGTH = 16;++export const WEBHOOK_SECRET_PREFIX = `whsec_`;\ No newline at end of filediff --git a/apps/web/lib/webhook/publish.ts b/apps/web/lib/webhook/publish.tsindex c85252d923..8c4a10fa49 100644--- a/apps/web/lib/webhook/publish.ts+++ b/apps/web/lib/webhook/publish.ts@@ -3,7 +3,7 @@ import { APP_DOMAIN_WITH_NGROK, nanoid } from "@dub/utils";import { Webhook } from "@prisma/client";import { WebhookTrigger } from "../types";import { webhookPayloadSchema } from "../zod/schemas/webhooks";-import { createWebhookSignature } from "./utils";+import { createWebhookSignature } from "./signature";interface SendToWebhookArgs {webhookUrl?: string;diff --git a/apps/web/lib/webhook/signature.ts b/apps/web/lib/webhook/signature.tsnew file mode 100644index 0000000000..1446e8cb56--- /dev/null+++ b/apps/web/lib/webhook/signature.ts@@ -0,0 +1,33 @@+// Create a signature for a webhook request+// Edge friendly+export const createWebhookSignature = async (secret: string, rawBody: any) => {+ if (!secret) {+ throw new Error("A secret must be provided to create a webhook signature.");+ }++ const keyData = new TextEncoder().encode(secret);+ const messageData = new TextEncoder().encode(rawBody);++ const cryptoKey = await crypto.subtle.importKey(+ "raw",+ keyData,+ { name: "HMAC", hash: "SHA-256" },+ false,+ ["sign"],+ );++ const signature = await crypto.subtle.sign("HMAC", cryptoKey, messageData);+ const signatureArray = Array.from(new Uint8Array(signature));+ const hexSignature = signatureArray+ .map((byte) => byte.toString(16).padStart(2, "0"))+ .join("");++ console.log("Webhook signature", hexSignature);++ return hexSignature;++ // return crypto+ // .createHmac("sha256", secret)+ // .update(JSON.stringify(rawBody))+ // .digest("hex");+};diff --git a/apps/web/lib/webhook/utils.ts b/apps/web/lib/webhook/utils.tsdeleted file mode 100644index ec72c68f59..0000000000--- a/apps/web/lib/webhook/utils.ts+++ /dev/null@@ -1,13 +0,0 @@-import crypto from "crypto";--// Create a signature for a webhook request-export const createWebhookSignature = (secret: string, rawBody: any) => {- if (!secret) {- throw new Error("A secret must be provided to create a webhook signature.");- }-- return crypto- .createHmac("sha256", secret)- .update(JSON.stringify(rawBody))- .digest("hex");-};diff --git a/apps/web/lib/zod/schemas/webhooks.ts b/apps/web/lib/zod/schemas/webhooks.tsindex 6038dd1a6d..ec2e81875c 100644--- a/apps/web/lib/zod/schemas/webhooks.ts+++ b/apps/web/lib/zod/schemas/webhooks.ts@@ -1,23 +1,28 @@-import { webhookTriggers } from "@/lib/webhook/constants";+import {+ WEBHOOK_SECRET_PREFIX,+ WEBHOOK_TRIGGERS,+} from "@/lib/webhook/constants";import { z } from "zod";+//whsec_646072a9e9c28e22c8170ec50eba8e0f5dda32a21ac663771d9e901fe6bb25c1+export const webhookSchema = z.object({id: z.string(),linkId: z.string().optional(),name: z.string(),url: z.string(),secret: z.string(),- active: z.boolean().default(true),- triggers: z.array(z.enum(webhookTriggers)),+ triggers: z.array(z.enum(WEBHOOK_TRIGGERS)),createdAt: z.string(),updatedAt: z.string(),});export const createWebhookSchema = z.object({- name: z.string().min(3).max(50),+ name: z.string().min(1).max(30),url: z.string().url().max(190),- secret: z.string().length(40),- triggers: z.array(z.enum(webhookTriggers)),+ secret: z.string().startsWith(WEBHOOK_SECRET_PREFIX),+ triggers: z.array(z.enum(WEBHOOK_TRIGGERS)),+ linkId: z.string().optional(),});export const updateWebhookSchema = createWebhookSchema.partial();@@ -26,7 +31,7 @@ export const webhookEventSchemaTB = z.object({event_id: z.string(),webhook_id: z.string(),url: z.string(),- event_type: z.enum(webhookTriggers),+ event_type: z.enum(WEBHOOK_TRIGGERS),status_code: z.number(),request: z.string(),response: z.string(),@@ -34,7 +39,7 @@ export const webhookEventSchemaTB = z.object({// Represents the schema of the payload sent to the webhook endpointexport const webhookPayloadSchema = z.object({- event: z.enum(webhookTriggers),+ event: z.enum(WEBHOOK_TRIGGERS),webhookId: z.string(),createdAt: z.string(),data: z.any(),diff --git a/apps/web/prisma/schema/webhook.prisma b/apps/web/prisma/schema/webhook.prismaindex 9748c871f9..f68ddbc9f1 100644--- a/apps/web/prisma/schema/webhook.prisma+++ b/apps/web/prisma/schema/webhook.prisma@@ -12,7 +12,6 @@ model Webhook {name Stringurl Stringsecret String- active Boolean @default(true)triggers JsoncreatedAt DateTime @default(now())updatedAt DateTime @updatedAtdiff --git a/apps/web/ui/webhooks/add-edit-webhook-form.tsx b/apps/web/ui/webhooks/add-edit-webhook-form.tsxnew file mode 100644index 0000000000..de0b266725--- /dev/null+++ b/apps/web/ui/webhooks/add-edit-webhook-form.tsx@@ -0,0 +1,221 @@+"use client";++import { clientAccessCheck } from "@/lib/api/tokens/permissions";+import useWorkspace from "@/lib/swr/use-workspace";+import { NewWebhook, WebhookProps } from "@/lib/types";+import { WEBHOOK_TRIGGERS } from "@/lib/webhook/constants";+import { Button, Checkbox, InfoTooltip } from "@dub/ui";+import { cn } from "@dub/utils";+import { redirect, useRouter } from "next/navigation";+import { FormEvent, useMemo, useState } from "react";+import { toast } from "sonner";+import { mutate } from "swr";++const defaultValues: NewWebhook = {+ name: "",+ linkId: "",+ url: "",+ secret: "",+ triggers: ["link.created"],+};++export default function AddEditWebhookForm({+ webhook,+ newSecret,+}: {+ webhook: WebhookProps | null;+ newSecret?: string;+}) {+ const router = useRouter();+ const [saving, setSaving] = useState(false);+ const { slug: workspaceSlug, id: workspaceId, flags, role } = useWorkspace();++ if (!flags?.webhooks) {+ redirect(`/${workspaceSlug}`);+ }++ const [data, setData] = useState<NewWebhook | WebhookProps>(+ webhook || {+ ...defaultValues,+ ...(newSecret && { secret: newSecret }),+ },+ );++ const { error: permissionsError } = clientAccessCheck({+ action: "webhooks.write",+ role,+ });++ // Determine the endpoint+ const endpoint = useMemo(() => {+ if (webhook) {+ return {+ method: "PATCH",+ url: `/api/webhooks/${webhook.id}?workspaceId=${workspaceId}`,+ successMessage: "Webhook updated!",+ };+ } else {+ return {+ method: "POST",+ url: `/api/webhooks?workspaceId=${workspaceId}`,+ successMessage: "Webhook created!",+ };+ }+ }, [webhook]);++ // 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),+ });++ setSaving(false);+ const result = await response.json();++ if (response.ok) {+ mutate(`/api/webhooks/${result.id}?workspaceId=${workspaceId}`, result);+ toast.success(endpoint.successMessage);++ if (endpoint.method === "POST") {+ router.push(`/${workspaceSlug}/settings/webhooks`);+ }+ } else {+ toast.error(result.error.message);+ }+ };++ const { name, url, secret, triggers, linkId } = data;++ const buttonDisabled = !name || !url || !triggers.length || saving;+ const canManageWebhook = !permissionsError;++ return (+ <>+ <form+ onSubmit={onSubmit}+ className="flex flex-col space-y-5 pb-20 text-left"+ >+ <div>+ <label htmlFor="name" className="flex items-center space-x-2">+ <h2 className="text-sm font-medium text-gray-900">Name</h2>+ <InfoTooltip content="An easily identifiable name for your webhook." />+ </label>+ <div className="relative mt-2 rounded-md shadow-sm">+ <input+ className={cn(+ "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",+ {+ "cursor-not-allowed bg-gray-50": !canManageWebhook,+ },+ )}+ required+ value={name}+ onChange={(e) => setData({ ...data, name: e.target.value })}+ autoFocus+ autoComplete="off"+ placeholder="Webhook name"+ disabled={!canManageWebhook}+ />+ </div>+ </div>++ <div>+ <label htmlFor="url" className="flex items-center space-x-2">+ <h2 className="text-sm font-medium text-gray-900">Endpoint URL</h2>+ <InfoTooltip content="The URL where the webhook will send POST requests." />+ </label>+ <div className="relative mt-2 rounded-md shadow-sm">+ <input+ className={cn(+ "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",+ {+ "cursor-not-allowed bg-gray-50": !canManageWebhook,+ },+ )}+ required+ value={url}+ onChange={(e) => setData({ ...data, url: e.target.value })}+ autoComplete="off"+ placeholder="https://example.com/webhook"+ disabled={!canManageWebhook}+ />+ </div>+ </div>++ <div>+ <label htmlFor="secret" className="flex items-center space-x-2">+ <h2 className="text-sm font-medium text-gray-900">+ Signing secret+ </h2>+ <InfoTooltip content="A secret token used to sign the webhook payload." />+ </label>+ <div className="relative mt-2 rounded-md shadow-sm">+ <input+ className="block w-full cursor-not-allowed rounded-md border-gray-300 bg-gray-50 text-gray-900 placeholder-gray-400 focus:border-gray-500 focus:outline-none focus:ring-gray-500 sm:text-sm"+ required+ value={secret}+ onChange={(e) => setData({ ...data, url: e.target.value })}+ autoComplete="off"+ readOnly+ disabled+ />+ </div>+ </div>++ <div>+ <label htmlFor="triggers" className="flex items-center space-x-2">+ <h2 className="text-sm font-medium text-gray-900">+ Events to send+ </h2>+ <InfoTooltip content="Select the events that will trigger the webhook." />+ </label>+ <div className="mt-3 flex flex-col gap-4">+ {WEBHOOK_TRIGGERS.map((trigger) => (+ <div key={trigger} className="group flex gap-2">+ <Checkbox+ value={trigger}+ id={trigger}+ checked={triggers.includes(trigger)}+ disabled={!canManageWebhook}+ onCheckedChange={(checked) => {+ if (checked) {+ setData({ ...data, triggers: [...triggers, trigger] });+ } else {+ setData({+ ...data,+ triggers: triggers.filter((t) => t !== trigger),+ });+ }+ }}+ />+ <label+ htmlFor={trigger}+ className="select-none text-sm font-medium text-gray-600 group-hover:text-gray-800"+ >+ {trigger}+ </label>+ </div>+ ))}+ </div>+ </div>++ <Button+ text={webhook ? "Save changes" : "Create"}+ disabled={buttonDisabled}+ loading={saving}+ type="submit"+ {...(permissionsError && {+ disabledTooltip: permissionsError,+ })}+ />+ </form>+ </>+ );+}diff --git a/apps/web/ui/webhooks/webhook-card.tsx b/apps/web/ui/webhooks/webhook-card.tsxnew file mode 100644index 0000000000..753c4af5f8--- /dev/null+++ b/apps/web/ui/webhooks/webhook-card.tsx@@ -0,0 +1,34 @@+import useWorkspace from "@/lib/swr/use-workspace";+import { WebhookProps } from "@/lib/types";+import { TokenAvatar } from "@dub/ui";+import { formatDate } from "@dub/utils";+import Link from "next/link";++export default function WebhookCard(webhook: WebhookProps) {+ const { slug } = useWorkspace();++ return (+ <Link+ href={`/${slug}/settings/webhooks/${webhook.id}`}+ className="hover:drop-shadow-card-hover relative rounded-xl border border-gray-200 bg-white px-5 py-4 transition-[filter]"+ >+ <div className="flex items-center gap-x-3">+ <div className="rounded-md border border-gray-200 bg-gradient-to-t from-gray-100 p-2.5">+ <TokenAvatar id={webhook.name} className="size-6" />+ </div>+ <div>+ <div className="flex items-center gap-1">+ <p className="font-semibold text-gray-700">{webhook.name}</p>+ <span className="text-gray-400 text-sm">{webhook.url}</span>+ </div>+ <div className="flex items-center gap-1 text-sm text-gray-500">+ Last updated+ <span className="font-medium text-gray-700">+ {formatDate(webhook.updatedAt, { year: undefined })}+ </span>+ </div>+ </div>+ </div>+ </Link>+ );+}diff --git a/apps/web/ui/webhooks/webhook-header.tsx b/apps/web/ui/webhooks/webhook-header.tsxnew file mode 100644index 0000000000..952a192174--- /dev/null+++ b/apps/web/ui/webhooks/webhook-header.tsx@@ -0,0 +1,116 @@+"use client";++import { clientAccessCheck } from "@/lib/api/tokens/permissions";+import useWorkspace from "@/lib/swr/use-workspace";+import { WebhookProps } from "@/lib/types";+import { useRemoveOAuthAppModal } from "@/ui/modals/remove-oauth-app-modal";+import { ThreeDots } from "@/ui/shared/icons";+import { Button, MaxWidthWrapper, Popover, TokenAvatar } from "@dub/ui";+import { fetcher } from "@dub/utils";+import { ChevronLeft, RefreshCcw, Trash } from "lucide-react";+import Link from "next/link";+import { notFound } from "next/navigation";+import { useState } from "react";+import useSWR from "swr";++export default function WebhookHeader({ webhookId }: { webhookId: string }) {+ const { slug, id: workspaceId, role } = useWorkspace();+ const [openPopover, setOpenPopover] = useState(false);++ const { data: webhook, isLoading } = useSWR<WebhookProps>(+ `/api/webhooks/${webhookId}?workspaceId=${workspaceId}`,+ fetcher,+ );++ const { RemoveOAuthAppModal, setShowRemoveOAuthAppModal } =+ useRemoveOAuthAppModal({+ // @ts-ignore+ // Fix it+ webhook: {},+ });++ const { error: permissionsError } = clientAccessCheck({+ action: "oauth_apps.write",+ role,+ });++ if (!isLoading && !webhook) {+ return notFound();+ }++ return (+ <>+ <MaxWidthWrapper className="grid max-w-screen-lg gap-8">+ <RemoveOAuthAppModal />+ <Link+ href={`/${slug}/settings/webhooks`}+ className="flex items-center gap-x-1"+ >+ <ChevronLeft className="size-4" />+ <p className="text-sm font-medium text-gray-500">Back to webhooks</p>+ </Link>+ <div className="flex items-center justify-between gap-2">+ {isLoading ? (+ <div className="flex items-center gap-x-3">+ <div className="rounded-md border border-gray-200 bg-gradient-to-t from-gray-100 p-2">+ <TokenAvatar id="placeholder-oauth-app" className="size-8" />+ </div>+ <div className="flex flex-col gap-2">+ <div className="h-3 w-20 rounded-full bg-gray-100"></div>+ <div className="h-3 w-80 rounded-full bg-gray-100"></div>+ </div>+ </div>+ ) : (+ <div className="flex items-center gap-x-3">+ <div className="rounded-md border border-gray-200 bg-gradient-to-t from-gray-100 p-2">+ <TokenAvatar id={webhook?.name!} className="size-8" />+ </div>+ <div>+ <p className="font-semibold text-gray-700">{webhook?.name}</p>+ <p className="text-sm text-gray-500">{webhook?.url}</p>+ </div>+ </div>+ )}++ <Popover+ content={+ <div className="grid w-screen gap-px p-2 sm:w-48">+ <Button+ text="Update webhook"+ variant="outline"+ icon={<RefreshCcw className="h-4 w-4" />}+ className="h-9 justify-start px-2 font-medium"+ onClick={async () => {+ setOpenPopover(false);+ }}+ />+ <Button+ text="Remove webhook"+ variant="danger-outline"+ icon={<Trash className="h-4 w-4" />}+ className="h-9 justify-start px-2"+ onClick={() => {+ setShowRemoveOAuthAppModal(true);+ }}+ />+ </div>+ }+ align="end"+ openPopover={openPopover}+ setOpenPopover={setOpenPopover}+ >+ <Button+ variant="outline"+ className="flex w-8 rounded-md border border-gray-200 px-2 transition-[border-color] duration-200"+ icon={<ThreeDots className="h-5 w-5 shrink-0 text-gray-500" />}+ onClick={() => setOpenPopover(!openPopover)}+ {...(permissionsError && {+ disabledTooltip: permissionsError,+ })}+ />+ </Popover>+ </div>+ </MaxWidthWrapper>+ </>+ );+}diff --git a/apps/web/ui/webhooks/webhook-placeholder.tsx b/apps/web/ui/webhooks/webhook-placeholder.tsxnew file mode 100644index 0000000000..56f601b44d--- /dev/null+++ b/apps/web/ui/webhooks/webhook-placeholder.tsx@@ -0,0 +1,13 @@+export default function WebhookPlaceholder() {+ return (+ <div className="relative grid gap-4 rounded-xl border border-gray-200 bg-white px-5 py-4">+ <div className="flex items-center gap-2">+ <div className="flex h-10 w-10 items-center justify-center rounded bg-gray-100" />+ <div className="flex flex-col gap-1">+ <div className="h-3 w-20 rounded-full bg-gray-100"></div>+ <div className="h-3 w-28 rounded-full bg-gray-100"></div>+ </div>+ </div>+ </div>+ );+}