Skip to content

Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.

feat: add webhook events

Marc Seitz14dd4ffc76f4
diff --git a/app/api/webhooks/callback/route.ts b/app/api/webhooks/callback/route.ts
new file mode 100644
index 00000000..95b64a91
--- /dev/null
+++ b/app/api/webhooks/callback/route.ts
@@ -0,0 +1,45 @@
+import { receiver } from "@/lib/cron";
+import { recordWebhookEvent } from "@/lib/tinybird/publish";
+import {
+ webhookCallbackSchema,
+ webhookPayloadSchema,
+} from "@/lib/zod/schemas/webhooks";
+
+// POST /api/webhooks/callback – listen to webhooks status from QStash
+export const POST = async (req: Request) => {
+ const rawBody = await req.json();
+
+ console.log("Upstash-Signature", req.headers.get("Upstash-Signature"));
+ const isValid = await receiver.verify({
+ signature: req.headers.get("Upstash-Signature") || "",
+ body: JSON.stringify(rawBody),
+ });
+ if (!isValid) {
+ return new Response("Unauthorized", { status: 401 });
+ }
+
+ const { url, status, body, sourceBody, sourceMessageId } =
+ webhookCallbackSchema.parse(rawBody);
+
+ const request = Buffer.from(sourceBody, "base64").toString("utf-8");
+ const response = Buffer.from(body, "base64").toString("utf-8");
+
+ const { id: eventId, event } = webhookPayloadSchema.parse(
+ JSON.parse(request),
+ );
+
+ const webhookId = new URL(req.url).searchParams.get("webhookId");
+
+ await recordWebhookEvent({
+ url,
+ event,
+ event_id: eventId,
+ http_status: status,
+ webhook_id: webhookId || "",
+ request_body: request,
+ response_body: response,
+ message_id: sourceMessageId,
+ });
+
+ return new Response("OK");
+};
diff --git a/components/webhooks/webhook-events.tsx b/components/webhooks/webhook-events.tsx
new file mode 100644
index 00000000..4761fe8a
--- /dev/null
+++ b/components/webhooks/webhook-events.tsx
@@ -0,0 +1,157 @@
+"use client";
+
+import { PropsWithChildren, useState } from "react";
+
+import { CircleCheck, CircleXIcon, CopyIcon } from "lucide-react";
+import { useTheme } from "next-themes";
+import { Prism as SyntaxHighlighter } from "react-syntax-highlighter";
+import {
+ materialDark,
+ materialLight,
+} from "react-syntax-highlighter/dist/esm/styles/prism";
+
+import { useCopyToClipboard } from "@/lib/utils/use-copy-to-clipboard";
+import { useMediaQuery } from "@/lib/utils/use-media-query";
+
+import { Button } from "../ui/button";
+import { ScrollArea } from "../ui/scroll-area";
+import {
+ Sheet,
+ SheetContent,
+ SheetDescription,
+ SheetHeader,
+ SheetTitle,
+} from "../ui/sheet";
+import { ButtonTooltip } from "../ui/tooltip";
+
+export type EventListProps = PropsWithChildren<{
+ events: any[];
+}>;
+
+const WebhookEvent = ({ event }: { event: any }) => {
+ const { copyToClipboard, isCopied } = useCopyToClipboard({ timeout: 2000 });
+ const isSuccess = event.http_status >= 200 && event.http_status < 300;
+ const { isMobile } = useMediaQuery();
+ const [isOpen, setIsOpen] = useState(false);
+ const { theme, systemTheme } = useTheme();
+ const isLight =
+ theme === "light" || (theme === "system" && systemTheme === "light");
+
+ // Custom style overrides for react-syntax-highlighter
+ const customStyle = {
+ margin: 0,
+ padding: "0.5rem",
+ fontSize: "0.875rem",
+ };
+
+ return (
+ <>
+ <button
+ type="button"
+ onClick={() => setIsOpen(true)}
+ className="flex items-center justify-between gap-5 px-3.5 py-3 hover:bg-gray-50 focus:outline-none dark:hover:bg-gray-800"
+ >
+ <div className="flex items-center gap-5">
+ <div className="flex items-center gap-2.5">
+ <ButtonTooltip
+ content={
+ isSuccess
+ ? "This webhook was successfully delivered."
+ : "This webhook failed to deliver – it will be retried."
+ }
+ >
+ <div>
+ {isSuccess ? (
+ <CircleCheck className="size-4 text-green-500" />
+ ) : (
+ <CircleXIcon className="size-4 text-destructive" />
+ )}
+ </div>
+ </ButtonTooltip>
+ <div className="text-sm text-foreground">{event.http_status}</div>
+ </div>
+ <div className="text-sm text-foreground">{event.event}</div>
+ </div>
+
+ <div className="text-xs text-muted-foreground">
+ {(() => {
+ const date = new Date(event.timestamp);
+ const localDate = new Date(
+ date.getTime() - date.getTimezoneOffset() * 60000,
+ );
+ return isMobile
+ ? localDate.toLocaleTimeString()
+ : localDate.toLocaleString();
+ })()}
+ </div>
+ </button>
+ <Sheet open={isOpen} onOpenChange={setIsOpen}>
+ <SheetContent className="flex w-[90%] flex-col justify-between border-l border-gray-200 bg-background px-4 text-foreground dark:border-gray-800 dark:bg-gray-900 sm:w-[600px] sm:max-w-2xl md:px-5">
+ <SheetHeader className="text-start">
+ <SheetTitle>{event.event}</SheetTitle>
+ <SheetDescription className="group flex items-center gap-2">
+ <p className="font-mono text-sm text-gray-500">
+ {event.event_id}
+ </p>
+ <Button
+ variant="ghost"
+ size="icon"
+ onClick={() =>
+ copyToClipboard(event.event_id, "Copied to clipboard")
+ }
+ >
+ <CopyIcon className="size-4 opacity-0 transition-opacity group-hover:opacity-100" />
+ </Button>
+ </SheetDescription>
+ </SheetHeader>
+ <ScrollArea className="flex-grow">
+ <div className="grid gap-4 border-t border-gray-200 bg-transparent py-4">
+ <h4 className="font-semibold">Response</h4>
+ <div className="flex items-center gap-8">
+ <p className="text-sm text-gray-500">HTTP status code</p>
+ <p className="text-sm text-gray-700">{event.http_status}</p>
+ </div>
+ <div className="overflow-y-scroll">
+ <SyntaxHighlighter
+ language="json"
+ showLineNumbers
+ customStyle={customStyle}
+ style={isLight ? materialLight : materialDark}
+ lineNumberStyle={{ textAlign: "right", minWidth: "3.25em" }}
+ >
+ {JSON.stringify(event.response_body, null, 2)}
+ </SyntaxHighlighter>
+ </div>
+ </div>
+ <div className="grid gap-4 border-t border-gray-200 bg-transparent py-4">
+ <h4 className="font-semibold">Request</h4>
+ <div className="overflow-y-scroll">
+ <SyntaxHighlighter
+ language="json"
+ showLineNumbers
+ style={isLight ? materialLight : materialDark}
+ customStyle={customStyle}
+ lineNumberStyle={{ textAlign: "right", minWidth: "3.25em" }}
+ >
+ {JSON.stringify(event.request_body, null, 2)}
+ </SyntaxHighlighter>
+ </div>
+ </div>
+ </ScrollArea>
+ </SheetContent>
+ </Sheet>
+ </>
+ );
+};
+
+export const WebhookEventList = ({ events }: EventListProps) => {
+ return (
+ <div className="overflow-hidden rounded-md border border-gray-200 dark:border-gray-600">
+ <div className="flex flex-col divide-y divide-gray-200 dark:divide-gray-600">
+ {events.map((event, index) => (
+ <WebhookEvent key={index} event={event} />
+ ))}
+ </div>
+ </div>
+ );
+};
diff --git a/lib/api/views/record-visit.ts b/lib/api/views/record-visit.ts
new file mode 100644
index 00000000..979a4568
--- /dev/null
+++ b/lib/api/views/record-visit.ts
@@ -0,0 +1,196 @@
+import { IncomingHttpHeaders } from "http";
+
+import { getFeatureFlags } from "@/lib/featureFlags";
+import prisma from "@/lib/prisma";
+import { Geo } from "@/lib/types";
+import { getDomainWithoutWWW, log } from "@/lib/utils";
+import { capitalize } from "@/lib/utils";
+import { LOCALHOST_GEO_DATA, getGeoData } from "@/lib/utils/geo";
+import { userAgentFromString } from "@/lib/utils/user-agent";
+import { sendWebhooks } from "@/lib/webhook/send-webhooks";
+
+interface LinkViewProps {
+ viewId: string;
+ linkId: string;
+ teamId: string;
+ documentId?: string;
+ dataroomId?: string;
+ headers: IncomingHttpHeaders;
+}
+
+export async function recordVisit({
+ viewId,
+ linkId,
+ teamId,
+ documentId,
+ dataroomId,
+ headers,
+}: LinkViewProps) {
+ try {
+ if (!viewId || !linkId || !teamId) {
+ throw new Error("Missing required parameters");
+ }
+
+ const features = await getFeatureFlags({ teamId });
+ if (!features.incomingWebhooks) {
+ // webhooks are not enabled for this team
+ return;
+ }
+
+ // Get webhooks for team
+ const webhooks = await prisma.webhook.findMany({
+ where: {
+ teamId,
+ triggers: {
+ array_contains: ["link.viewed"],
+ },
+ },
+ select: {
+ pId: true,
+ url: true,
+ secret: true,
+ },
+ });
+
+ if (!webhooks || (webhooks && webhooks.length === 0)) {
+ // No webhooks for team, so we don't need to send webhooks
+ return;
+ }
+
+ // Get geo data
+ const geo: Geo =
+ process.env.VERCEL === "1" ? getGeoData(headers) : LOCALHOST_GEO_DATA;
+
+ const referer = headers.referer;
+ const ua = userAgentFromString(headers["user-agent"]);
+
+ // Get link information
+ const link = await prisma.link.findUnique({
+ where: { id: linkId, teamId },
+ });
+
+ if (!link) {
+ throw new Error("Link not found");
+ }
+
+ // Prepare link data for webhook
+ const linkData = {
+ id: link.id,
+ url: link.domainId
+ ? `https://${link.domainSlug}/${link.slug}`
+ : `https://www.papermark.io/view/${link.id}`,
+ domain:
+ link.domainId && link.domainSlug ? link.domainSlug : "papermark.io",
+ key: link.domainId && link.slug ? link.slug : `view/${link.id}`,
+ name: link.name,
+ expiresAt: link.expiresAt?.toISOString() || null,
+ hasPassword: !!link.password,
+ allowList: link.allowList,
+ denyList: link.denyList,
+ enabledEmailProtection: link.emailProtected,
+ enabledEmailVerification: link.emailAuthenticated,
+ allowDownload: link.allowDownload ?? false,
+ isArchived: link.isArchived,
+ enabledNotification: link.enableNotification ?? false,
+ enabledFeedback: link.enableFeedback ?? false,
+ enabledQuestion: link.enableQuestion ?? false,
+ enabledScreenshotProtection: link.enableScreenshotProtection ?? false,
+ enabledScreenShieldPercentage: !!link.screenShieldPercentage,
+ enabledAgreement: link.enableAgreement ?? false,
+ enabledWatermark: link.enableWatermark ?? false,
+ metaTitle: link.metaTitle,
+ metaDescription: link.metaDescription,
+ metaImage: link.metaImage,
+ metaFavicon: link.metaFavicon,
+ documentId: link.documentId,
+ dataroomId: link.dataroomId,
+ groupId: link.groupId,
+ linkType: link.linkType,
+ teamId: teamId,
+ createdAt: link.createdAt.toISOString(),
+ updatedAt: link.updatedAt.toISOString(),
+ };
+
+ // Get view information
+ const view = await prisma.view.findUnique({
+ where: { id: viewId, linkId },
+ select: {
+ id: true,
+ viewedAt: true,
+ viewerEmail: true,
+ verified: true,
+ },
+ });
+
+ if (!view) {
+ throw new Error("View not found");
+ }
+
+ // Prepare view data for webhook
+ const viewData = {
+ viewedAt: view.viewedAt.toISOString(),
+ viewId: view.id,
+ email: view.viewerEmail,
+ emailVerified: view.verified,
+ country: geo?.country || null,
+ city: geo?.city || null,
+ device: ua.device.type ? capitalize(ua.device.type) : "Desktop",
+ browser: ua.browser.name || null,
+ os: ua.os.name || null,
+ ua: ua.ua || null,
+ referer: referer ? (getDomainWithoutWWW(referer) ?? null) : null,
+ };
+
+ // Get document and dataroom information for webhook in parallel
+ const [document, dataroom] = await Promise.all([
+ documentId
+ ? prisma.document.findUnique({
+ where: { id: documentId, teamId },
+ select: { id: true, name: true, contentType: true },
+ })
+ : null,
+ dataroomId
+ ? prisma.dataroom.findUnique({
+ where: { id: dataroomId, teamId },
+ select: { id: true, name: true },
+ })
+ : null,
+ ]);
+
+ // Prepare webhook payload
+ const webhookData = {
+ view: viewData,
+ link: linkData,
+ ...(document && {
+ document: {
+ id: document.id,
+ name: document.name,
+ contentType: document.contentType,
+ teamId: teamId,
+ },
+ }),
+ ...(dataroom && {
+ dataroom: {
+ id: dataroom.id,
+ name: dataroom.name,
+ teamId: teamId,
+ },
+ }),
+ };
+
+ // Send webhooks
+ if (webhooks.length > 0) {
+ await sendWebhooks({
+ webhooks,
+ trigger: "link.viewed",
+ data: webhookData,
+ });
+ }
+ } catch (error) {
+ log({
+ message: `Error sending webhooks for link view: ${error}`,
+ type: "error",
+ mention: true,
+ });
+ }
+}
diff --git a/lib/tinybird/datasources/webhook_events.datasource b/lib/tinybird/datasources/webhook_events.datasource
new file mode 100644
index 00000000..c07fba53
--- /dev/null
+++ b/lib/tinybird/datasources/webhook_events.datasource
@@ -0,0 +1,19 @@
+VERSION 1
+
+DESCRIPTION >
+ Webhook events are events when a webhook is triggered
+
+SCHEMA >
+ `timestamp` DateTime64(3) `json:$.timestamp` DEFAULT now(),
+ `event_id` String `json:$.event_id`,
+ `webhook_id` String `json:$.webhook_id`,
+ `url` String `json:$.url`,
+ `event` LowCardinality(String) `json:$.event`,
+ `http_status` UInt16 `json:$.http_status`,
+ `request_body` String `json:$.request_body`,
+ `response_body` String `json:$.response_body`,
+ `message_id` String `json:$.message_id`
+
+ENGINE "MergeTree"
+ENGINE_PARTITION_KEY "toYYYYMM(timestamp)"
+ENGINE_SORTING_KEY "timestamp, webhook_id, event_id"
diff --git a/lib/tinybird/endpoints/get_webhook_events.pipe b/lib/tinybird/endpoints/get_webhook_events.pipe
new file mode 100644
index 00000000..7a9460f1
--- /dev/null
+++ b/lib/tinybird/endpoints/get_webhook_events.pipe
@@ -0,0 +1,14 @@
+VERSION 1
+
+NODE endpoint
+SQL >
+ %
+ SELECT
+ *
+ FROM
+ webhook_events__v1
+ WHERE
+ webhook_id = {{ String(webhookId, required=True) }}
+ ORDER BY
+ timestamp DESC
+ LIMIT 100
diff --git a/lib/tinybird/pipes.ts b/lib/tinybird/pipes.ts
index 36054213..e7be41e8 100644
--- a/lib/tinybird/pipes.ts
+++ b/lib/tinybird/pipes.ts
@@ -1,6 +1,8 @@
import { Tinybird } from "@chronark/zod-bird";
import { z } from "zod";
+import { WEBHOOK_TRIGGERS } from "../webhook/constants";
+
const tb = new Tinybird({ token: process.env.TINYBIRD_TOKEN! });
export const getTotalAvgPageDuration = tb.buildPipe({
@@ -84,3 +86,21 @@ export const getDocumentDurationPerViewer = tb.buildPipe({
sum_duration: z.number(),
}),
});
+
+export const getWebhookEvents = tb.buildPipe({
+ pipe: "get_webhook_events__v1",
+ parameters: z.object({
+ webhookId: z.string(),
+ }),
+ data: z.object({
+ event_id: z.string(),
+ webhook_id: z.string(),
+ message_id: z.string(), // QStash message ID
+ event: z.enum(WEBHOOK_TRIGGERS),
+ url: z.string(),
+ http_status: z.number(),
+ request_body: z.string(),
+ response_body: z.string(),
+ timestamp: z.string(),
+ }),
+});
diff --git a/lib/tinybird/publish.ts b/lib/tinybird/publish.ts
index ef1b6e64..32acd4aa 100644
--- a/lib/tinybird/publish.ts
+++ b/lib/tinybird/publish.ts
@@ -1,6 +1,8 @@
import { Tinybird } from "@chronark/zod-bird";
import { z } from "zod";
+import { WEBHOOK_TRIGGERS } from "../webhook/constants";
+
const tb = new Tinybird({ token: process.env.TINYBIRD_TOKEN! });
export const publishPageView = tb.buildIngestEndpoint({
@@ -36,3 +38,17 @@ export const publishPageView = tb.buildIngestEndpoint({
referer_url: z.string().optional().default("(direct)"),
}),
});
+
+export const recordWebhookEvent = tb.buildIngestEndpoint({
+ datasource: "webhook_events__v1",
+ event: z.object({
+ event_id: z.string(),
+ webhook_id: z.string(),
+ message_id: z.string(), // QStash message ID
+ event: z.enum(WEBHOOK_TRIGGERS),
+ url: z.string(),
+ http_status: z.number(),
+ request_body: z.string(),
+ response_body: z.string(),
+ }),
+});
diff --git a/lib/webhook/constants.ts b/lib/webhook/constants.ts
new file mode 100644
index 00000000..ee4e3401
--- /dev/null
+++ b/lib/webhook/constants.ts
@@ -0,0 +1,34 @@
+export const TEAM_LEVEL_WEBHOOK_TRIGGERS = [
+ "document.created",
+ "document.updated",
+ "document.deleted",
+ "dataroom.created",
+] as const;
+
+export const DOCUMENT_LEVEL_WEBHOOK_TRIGGERS = [
+ "link.created",
+ "link.updated",
+] as const;
+
+export const LINK_LEVEL_WEBHOOK_TRIGGERS = [
+ "link.viewed",
+ "link.downloaded",
+] as const;
+
+export const WEBHOOK_TRIGGERS = [
+ ...TEAM_LEVEL_WEBHOOK_TRIGGERS,
+ ...DOCUMENT_LEVEL_WEBHOOK_TRIGGERS,
+ ...LINK_LEVEL_WEBHOOK_TRIGGERS,
+] as const;
+
+export const WEBHOOK_TRIGGER_DESCRIPTIONS = {
+ "link.created": "Link created",
+ "link.updated": "Link updated",
+ "link.deleted": "Link deleted",
+ "link.viewed": "Link viewed",
+ "link.downloaded": "Link downloaded",
+ "document.created": "Document created",
+ "document.updated": "Document updated",
+ "document.deleted": "Document deleted",
+ "dataroom.created": "Data room created",
+} as const;
diff --git a/lib/webhook/send-webhooks.ts b/lib/webhook/send-webhooks.ts
new file mode 100644
index 00000000..ca0af89b
--- /dev/null
+++ b/lib/webhook/send-webhooks.ts
@@ -0,0 +1,61 @@
+import { Webhook } from "@prisma/client";
+import { z } from "zod";
+
+import { qstash } from "@/lib/cron";
+import { webhookPayloadSchema } from "@/lib/zod/schemas/webhooks";
+
+import { createWebhookSignature } from "./signature";
+import { prepareWebhookPayload } from "./transform";
+import { EventDataProps, WebhookTrigger } from "./types";
+
+// Send webhooks to multiple webhooks
+export const sendWebhooks = async ({
+ webhooks,
+ trigger,
+ data,
+}: {
+ webhooks: Pick<Webhook, "pId" | "url" | "secret">[];
+ trigger: WebhookTrigger;
+ data: EventDataProps;
+}) => {
+ if (webhooks.length === 0) {
+ return;
+ }
+
+ const payload = prepareWebhookPayload(trigger, data);
+
+ return await Promise.all(
+ webhooks.map((webhook) =>
+ publishWebhookEventToQStash({ webhook, payload }),
+ ),
+ );
+};
+
+// Publish webhook event to QStash
+const publishWebhookEventToQStash = async ({
+ webhook,
+ payload,
+}: {
+ webhook: Pick<Webhook, "pId" | "url" | "secret">;
+ payload: z.infer<typeof webhookPayloadSchema>;
+}) => {
+ const callbackUrl = `${process.env.NEXT_PUBLIC_BASE_URL}/api/webhooks/callback?webhookId=${webhook.pId}`;
+ const signature = await createWebhookSignature(webhook.secret, payload);
+
+ const response = await qstash.publishJSON({
+ url: webhook.url,
+ body: payload,
+ headers: {
+ "X-Papermark-Signature": signature,
+ "Upstash-Hide-Headers": "true",
+ },
+ callback: callbackUrl,
+ failureCallback: callbackUrl,
+ });
+
+ if (!response.messageId) {
+ console.error("Failed to publish webhook event to QStash", response);
+ }
+
+ return response;
+};
diff --git a/lib/webhook/signature.ts b/lib/webhook/signature.ts
new file mode 100644
index 00000000..db3f5318
--- /dev/null
+++ b/lib/webhook/signature.ts
@@ -0,0 +1,24 @@
+export const createWebhookSignature = async (secret: string, body: 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(JSON.stringify(body));
+
+ 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("");
+
+ return hexSignature;
+};
diff --git a/lib/webhook/transform.ts b/lib/webhook/transform.ts
new file mode 100644
index 00000000..bd360e94
--- /dev/null
+++ b/lib/webhook/transform.ts
@@ -0,0 +1,15 @@
+import { newId } from "@/lib/id-helper";
+import { webhookPayloadSchema } from "@/lib/zod/schemas/webhooks";
+
+import { WebhookTrigger } from "./types";
+
+export const prepareWebhookPayload = (trigger: WebhookTrigger, data: any) => {
+ const payload = webhookPayloadSchema.parse({
+ id: newId("webhookEvent"),
+ event: trigger,
+ data: data,
+ createdAt: new Date().toISOString(),
+ });
+
+ return payload;
+};
diff --git a/lib/webhook/types.ts b/lib/webhook/types.ts
new file mode 100644
index 00000000..5fbda57e
--- /dev/null
+++ b/lib/webhook/types.ts
@@ -0,0 +1,11 @@
+import { z } from "zod";
+
+import { webhookPayloadSchema } from "../zod/schemas/webhooks";
+import { WEBHOOK_TRIGGER_DESCRIPTIONS } from "./constants";
+
+export type WebhookTrigger = keyof typeof WEBHOOK_TRIGGER_DESCRIPTIONS;
+
+export type WebhookPayload = z.infer<typeof webhookPayloadSchema>;
+
+// TODO: only show the link.viewed data props for now
+export type EventDataProps = WebhookPayload["data"];
diff --git a/lib/zod/schemas/webhooks.ts b/lib/zod/schemas/webhooks.ts
new file mode 100644
index 00000000..91c8824a
--- /dev/null
+++ b/lib/zod/schemas/webhooks.ts
@@ -0,0 +1,111 @@
+import { z } from "zod";
+
+import { WEBHOOK_TRIGGERS } from "@/lib/webhook/constants";
+
+export const createWebhookSchema = z.object({
+ name: z.string().min(1).max(40),
+ url: z.string().url().max(190),
+ secret: z.string().startsWith("whsec_"),
+ triggers: z.array(z.enum(WEBHOOK_TRIGGERS)),
+});
+
+export const updateWebhookSchema = createWebhookSchema.partial();
+
+// Base event schema
+const baseEventSchema = z.object({
+ id: z.string().startsWith("evt_"),
+ event: z.enum(WEBHOOK_TRIGGERS),
+ createdAt: z.string().datetime(),
+});
+
+// View Event schema
+const viewEventSchema = z.object({
+ viewedAt: z.string().datetime(),
+ viewId: z.string(),
+ email: z.string().email().nullable(),
+ emailVerified: z.boolean().default(false),
+ country: z.string().nullable(),
+ city: z.string().nullable(),
+ device: z.string().nullable(),
+ browser: z.string().nullable(),
+ os: z.string().nullable(),
+ ua: z.string().nullable(),
+ referer: z.string().nullable(),
+});
+
+// Link Event schema
+const linkEventSchema = z.object({
+ id: z.string(),
+ url: z
+ .string()
+ .describe(
+ "This is the full URL of the link e.g. https://www.papermark.io/view/1234566",
+ ),
+ name: z.string().nullable(),
+ domain: z.string(),
+ key: z.string(),
+ expiresAt: z.string().datetime().nullable(),
+ hasPassword: z.boolean().default(false),
+ allowList: z.array(z.string()),
+ denyList: z.array(z.string()),
+ enabledEmailProtection: z.boolean().default(false),
+ enabledEmailVerification: z.boolean().default(false),
+ allowDownload: z.boolean().default(false),
+ isArchived: z.boolean().default(false),
+ enabledNotification: z.boolean().default(true),
+ enabledFeedback: z.boolean().default(false),
+ enabledQuestion: z.boolean().default(false),
+ enabledScreenshotProtection: z.boolean().default(false),
+ enabledScreenShieldPercentage: z.boolean().default(false),
+ enabledAgreement: z.boolean().default(false),
+ enabledWatermark: z.boolean().default(false),
+
+ metaTitle: z.string().nullable(),
+ metaDescription: z.string().nullable(),
+ metaImage: z.string().nullable(),
+ metaFavicon: z.string().nullable(),
+
+ documentId: z.string().nullable(),
+ dataroomId: z.string().nullable(),
+ groupId: z.string().nullable(),
+
+ linkType: z.enum(["DOCUMENT_LINK", "DATAROOM_LINK"]),
+ teamId: z.string(),
+ createdAt: z.string().datetime(),
+ updatedAt: z.string().datetime(),
+});
+
+// Complete webhook payload schema
+export const webhookPayloadSchema = baseEventSchema.extend({
+ data: z.object({
+ view: viewEventSchema,
+ link: linkEventSchema,
+ document: z
+ .object({
+ id: z.string(),
+ name: z.string(),
+ contentType: z.string().nullable(),
+ teamId: z.string(),
+ })
+ .optional(),
+ dataroom: z
+ .object({
+ id: z.string(),
+ name: z.string(),
+ teamId: z.string(),
+ })
+ .optional(),
+ }),
+});
+
+export type WebhookPayload = z.infer<typeof webhookPayloadSchema>;
+
+// Schema of response sent to the webhook callback URL by QStash
+export const webhookCallbackSchema = z.object({
+ status: z.number(),
+ url: z.string(),
+ createdAt: z.number(),
+ sourceMessageId: z.string(),
+ body: z.string().optional().default(""), // Response from the original webhook URL
+ sourceBody: z.string(), // Original request payload from Papermark
+});
diff --git a/next.config.mjs b/next.config.mjs
index 059b58eb..ab2131b0 100644
--- a/next.config.mjs
+++ b/next.config.mjs
@@ -6,7 +6,7 @@ const nextConfig = {
minimumCacheTTL: 2592000, // 30 days
remotePatterns: prepareRemotePatterns(),
},
- transpilePackages: ["@trigger.dev/react"],
+ transpilePackages: ["@trigger.dev/react", "react-syntax-highlighter"],
skipTrailingSlashRedirect: true,
assetPrefix:
process.env.NODE_ENV === "production" &&
diff --git a/package-lock.json b/package-lock.json
index e4d6f9bf..544f5a13 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -105,6 +105,7 @@
"react-notion-x": "^7.2.5",
"react-pdf": "^8.0.2",
"react-phone-number-input": "^3.4.9",
+ "react-syntax-highlighter": "^15.6.1",
"react-textarea-autosize": "^8.5.5",
"react-zoom-pan-pinch": "^3.6.1",
"resend": "^4.0.0",
@@ -135,6 +136,7 @@
"@types/node": "^20",
"@types/react": "^18",
"@types/react-dom": "^18",
+ "@types/react-syntax-highlighter": "^15.5.13",
"@types/ua-parser-js": "^0.7.39",
"prettier": "^3.3.3",
"prettier-plugin-tailwindcss": "^0.6.9",
@@ -6632,6 +6634,15 @@
"@types/react": "*"
}
},
+ "node_modules/@types/react-syntax-highlighter": {
+ "version": "15.5.13",
+ "resolved": "https://registry.npmjs.org/@types/react-syntax-highlighter/-/react-syntax-highlighter-15.5.13.tgz",
+ "integrity": "sha512-uLGJ87j6Sz8UaBAooU0T6lWJ0dBmjZgN1PZTrj05TNql2/XpC6+4HhMT5syIdFUUt+FASfCeLLv4kBygNU+8qA==",
+ "dev": true,
+ "dependencies": {
+ "@types/react": "*"
+ }
+ },
"node_modules/@types/shimmer": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/@types/shimmer/-/shimmer-1.2.0.tgz",
@@ -7837,6 +7848,24 @@
"url": "https://github.com/chalk/chalk?sponsor=1"
}
},
+ "node_modules/character-entities": {
+ "version": "1.2.4",
+ "resolved": "https://registry.npmjs.org/character-entities/-/character-entities-1.2.4.tgz",
+ "integrity": "sha512-iBMyeEHxfVnIakwOuDXpVkc54HijNgCyQB2w0VfGQThle6NXn50zU6V/u+LDhxHcDUPojn6Kpga3PTAD8W1bQw==",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
+ "node_modules/character-reference-invalid": {
+ "version": "1.1.4",
+ "resolved": "https://registry.npmjs.org/character-reference-invalid/-/character-reference-invalid-1.1.4.tgz",
+ "integrity": "sha512-mKKUkUbhPpQlCOfIuZkvSEgktjPFIsZKRRbC6KWVEMvlzblj3i3asQv5ODsrwt0N3pHAEvjP8KTQPHkp0+6jOg==",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
"node_modules/charenc": {
"version": "0.0.2",
"resolved": "https://registry.npmjs.org/charenc/-/charenc-0.0.2.tgz",
@@ -9711,6 +9740,18 @@
"reusify": "^1.0.4"
}
},
+ "node_modules/fault": {
+ "version": "1.0.4",
+ "resolved": "https://registry.npmjs.org/fault/-/fault-1.0.4.tgz",
+ "integrity": "sha512-CJ0HCB5tL5fYTEA7ToAq5+kTwd++Borf1/bifxd9iT70QcXr4MRrO3Llf8Ifs70q+SJcGHFtnIE/Nw6giCtECA==",
+ "dependencies": {
+ "format": "^0.2.0"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
"node_modules/fflate": {
"version": "0.4.8",
"resolved": "https://registry.npmjs.org/fflate/-/fflate-0.4.8.tgz",
@@ -9823,6 +9864,14 @@
"resolved": "https://registry.npmjs.org/form-data-encoder/-/form-data-encoder-1.7.2.tgz",
"integrity": "sha512-qfqtYan3rxrnCk1VYaA4H+Ms9xdpPqvLZa6xmMgFvhO32x7/3J/ExcTd6qpxM0vH2GdMI+poehyBZvqfMTto8A=="
},
+ "node_modules/format": {
+ "version": "0.2.2",
+ "resolved": "https://registry.npmjs.org/format/-/format-0.2.2.tgz",
+ "integrity": "sha512-wzsgA6WOq+09wrU1tsJ09udeR/YZRaeArL9e1wPbFg3GG2yDnC2ldKpxs4xunpFF9DgqCqOIra3bc1HWrJ37Ww==",
+ "engines": {
+ "node": ">=0.4.x"
+ }
+ },
"node_modules/formdata-node": {
"version": "4.4.1",
"resolved": "https://registry.npmjs.org/formdata-node/-/formdata-node-4.4.1.tgz",
@@ -10286,6 +10335,87 @@
"node": ">= 0.4"
}
},
+ "node_modules/hast-util-parse-selector": {
+ "version": "2.2.5",
+ "resolved": "https://registry.npmjs.org/hast-util-parse-selector/-/hast-util-parse-selector-2.2.5.tgz",
+ "integrity": "sha512-7j6mrk/qqkSehsM92wQjdIgWM2/BW61u/53G6xmC8i1OmEdKLHbk419QKQUjz6LglWsfqoiHmyMRkP1BGjecNQ==",
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/hastscript": {
+ "version": "6.0.0",
+ "resolved": "https://registry.npmjs.org/hastscript/-/hastscript-6.0.0.tgz",
+ "integrity": "sha512-nDM6bvd7lIqDUiYEiu5Sl/+6ReP0BMk/2f4U/Rooccxkj0P5nm+acM5PrGJ/t5I8qPGiqZSE6hVAwZEdZIvP4w==",
+ "dependencies": {
+ "@types/hast": "^2.0.0",
+ "comma-separated-tokens": "^1.0.0",
+ "hast-util-parse-selector": "^2.0.0",
+ "property-information": "^5.0.0",
+ "space-separated-tokens": "^1.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/hastscript/node_modules/@types/hast": {
+ "version": "2.3.10",
+ "resolved": "https://registry.npmjs.org/@types/hast/-/hast-2.3.10.tgz",
+ "integrity": "sha512-McWspRw8xx8J9HurkVBfYj0xKoE25tOFlHGdx4MJ5xORQrMGZNqJhVQWaIbm6Oyla5kYOXtDiopzKRJzEOkwJw==",
+ "dependencies": {
+ "@types/unist": "^2"
+ }
+ },
+ "node_modules/hastscript/node_modules/@types/unist": {
+ "version": "2.0.11",
+ "resolved": "https://registry.npmjs.org/@types/unist/-/unist-2.0.11.tgz",
+ "integrity": "sha512-CmBKiL6NNo/OqgmMn95Fk9Whlp2mtvIv+KNpQKN2F4SjvrEesubTRWGYSg+BnWZOnlCaSTU1sMpsBOzgbYhnsA=="
+ },
+ "node_modules/hastscript/node_modules/comma-separated-tokens": {
+ "version": "1.0.8",
+ "resolved": "https://registry.npmjs.org/comma-separated-tokens/-/comma-separated-tokens-1.0.8.tgz",
+ "integrity": "sha512-GHuDRO12Sypu2cV70d1dkA2EUmXHgntrzbpvOB+Qy+49ypNfGgFQIC2fhhXbnyrJRynDCAARsT7Ou0M6hirpfw==",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
+ "node_modules/hastscript/node_modules/property-information": {
+ "version": "5.6.0",
+ "resolved": "https://registry.npmjs.org/property-information/-/property-information-5.6.0.tgz",
+ "integrity": "sha512-YUHSPk+A30YPv+0Qf8i9Mbfe/C0hdPXk1s1jPVToV8pk8BQtpw10ct89Eo7OWkutrwqvT0eicAxlOg3dOAu8JA==",
+ "dependencies": {
+ "xtend": "^4.0.0"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
+ "node_modules/hastscript/node_modules/space-separated-tokens": {
+ "version": "1.1.5",
+ "resolved": "https://registry.npmjs.org/space-separated-tokens/-/space-separated-tokens-1.1.5.tgz",
+ "integrity": "sha512-q/JSVd1Lptzhf5bkYm4ob4iWPjx0KiRe3sRFBNrVqbJkFaBm5vbbowy1mymoPNLRa52+oadOhJ+K49wsSeSjTA==",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
+ "node_modules/highlight.js": {
+ "version": "10.7.3",
+ "resolved": "https://registry.npmjs.org/highlight.js/-/highlight.js-10.7.3.tgz",
+ "integrity": "sha512-tzcUFauisWKNHaRkN4Wjl/ZA07gENAjFl3J/c480dprkGTg5EQstgaNFqBfUqCq54kZRIEcreTsAgF/m2quD7A==",
+ "engines": {
+ "node": "*"
+ }
+ },
+ "node_modules/highlightjs-vue": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/highlightjs-vue/-/highlightjs-vue-1.0.0.tgz",
+ "integrity": "sha512-PDEfEF102G23vHmPhLyPboFCD+BkMGu+GuJe2d9/eH4FsCwvgBpnc9n0pGE+ffKdph38s6foEZiEjdgHdzp+IA=="
+ },
"node_modules/html-to-text": {
"version": "9.0.5",
"resolved": "https://registry.npmjs.org/html-to-text/-/html-to-text-9.0.5.tgz",
@@ -10480,6 +10610,28 @@
"loose-envify": "^1.0.0"
}
},
+ "node_modules/is-alphabetical": {
+ "version": "1.0.4",
+ "resolved": "https://registry.npmjs.org/is-alphabetical/-/is-alphabetical-1.0.4.tgz",
+ "integrity": "sha512-DwzsA04LQ10FHTZuL0/grVDk4rFoVH1pjAToYwBrHSxcrBIGQuXrQMtD5U1b0U2XVgKZCTLLP8u2Qxqhy3l2Vg==",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
+ "node_modules/is-alphanumerical": {
+ "version": "1.0.4",
+ "resolved": "https://registry.npmjs.org/is-alphanumerical/-/is-alphanumerical-1.0.4.tgz",
+ "integrity": "sha512-UzoZUr+XfVz3t3v4KyGEniVL9BDRoQtY7tOyrRybkVNjDFWyo1yhXNGrrBTQxp3ib9BLAWs7k2YKBQsFRkZG9A==",
+ "dependencies": {
+ "is-alphabetical": "^1.0.0",
+ "is-decimal": "^1.0.0"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
"node_modules/is-arguments": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/is-arguments/-/is-arguments-1.1.1.tgz",
@@ -10636,6 +10788,15 @@
"url": "https://github.com/sponsors/ljharb"
}
},
+ "node_modules/is-decimal": {
+ "version": "1.0.4",
+ "resolved": "https://registry.npmjs.org/is-decimal/-/is-decimal-1.0.4.tgz",
+ "integrity": "sha512-RGdriMmQQvZ2aqaQq3awNA6dCGtKpiDFcOzrTWrDAT2MiWrKQVPmxLGHl7Y2nNu6led0kEyoX0enY0qXYsv9zw==",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
"node_modules/is-extglob": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz",
@@ -10688,6 +10849,15 @@
"node": ">=0.10.0"
}
},
+ "node_modules/is-hexadecimal": {
+ "version": "1.0.4",
+ "resolved": "https://registry.npmjs.org/is-hexadecimal/-/is-hexadecimal-1.0.4.tgz",
+ "integrity": "sha512-gyPJuv83bHMpocVYoqof5VDiZveEoGoFL8m3BXNb2VW8Xs+rz9kqO8LOQ5DH6EsuvilT1ApazU0pyl+ytbPtlw==",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
"node_modules/is-interactive": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/is-interactive/-/is-interactive-1.0.0.tgz",
@@ -11427,6 +11597,19 @@
"loose-envify": "cli.js"
}
},
+ "node_modules/lowlight": {
+ "version": "1.20.0",
+ "resolved": "https://registry.npmjs.org/lowlight/-/lowlight-1.20.0.tgz",
+ "integrity": "sha512-8Ktj+prEb1RoCPkEOrPMYUN/nCggB7qAWe3a7OpMjWQkh3l2RD5wKRQ+o8Q8YuI9RG/xs95waaI/E6ym/7NsTw==",
+ "dependencies": {
+ "fault": "^1.0.0",
+ "highlight.js": "~10.7.0"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
"node_modules/lru-cache": {
"version": "6.0.0",
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz",
@@ -12577,6 +12760,32 @@
"node": ">=6"
}
},
+ "node_modules/parse-entities": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/parse-entities/-/parse-entities-2.0.0.tgz",
+ "integrity": "sha512-kkywGpCcRYhqQIchaWqZ875wzpS/bMKhz5HnN3p7wveJTkTtyAB/AlnS0f8DFSqYW1T82t6yEAkEcB+A1I3MbQ==",
+ "dependencies": {
+ "character-entities": "^1.0.0",
+ "character-entities-legacy": "^1.0.0",
+ "character-reference-invalid": "^1.0.0",
+ "is-alphanumerical": "^1.0.0",
+ "is-decimal": "^1.0.0",
+ "is-hexadecimal": "^1.0.0"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
+ "node_modules/parse-entities/node_modules/character-entities-legacy": {
+ "version": "1.1.4",
+ "resolved": "https://registry.npmjs.org/character-entities-legacy/-/character-entities-legacy-1.1.4.tgz",
+ "integrity": "sha512-3Xnr+7ZFS1uxeiUDvV02wQ+QDbc55o97tIV5zHScSPJpcLm/r0DFPcoY3tYRp+VZukxuMeKgXYmsXQHO05zQeA==",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
"node_modules/parseley": {
"version": "0.12.1",
"resolved": "https://registry.npmjs.org/parseley/-/parseley-0.12.1.tgz",
@@ -13947,6 +14156,22 @@
}
}
},
+ "node_modules/react-syntax-highlighter": {
+ "version": "15.6.1",
+ "resolved": "https://registry.npmjs.org/react-syntax-highlighter/-/react-syntax-highlighter-15.6.1.tgz",
+ "integrity": "sha512-OqJ2/vL7lEeV5zTJyG7kmARppUjiB9h9udl4qHQjjgEos66z00Ia0OckwYfRxCSFrW8RJIBnsBwQsHZbVPspqg==",
+ "dependencies": {
+ "@babel/runtime": "^7.3.1",
+ "highlight.js": "^10.4.1",
+ "highlightjs-vue": "^1.0.0",
+ "lowlight": "^1.17.0",
+ "prismjs": "^1.27.0",
+ "refractor": "^3.6.0"
+ },
+ "peerDependencies": {
+ "react": ">= 0.14.0"
+ }
+ },
"node_modules/react-textarea-autosize": {
"version": "8.5.5",
"resolved": "https://registry.npmjs.org/react-textarea-autosize/-/react-textarea-autosize-8.5.5.tgz",
@@ -14092,6 +14317,28 @@
"url": "https://github.com/sponsors/ljharb"
}
},
+ "node_modules/refractor": {
+ "version": "3.6.0",
+ "resolved": "https://registry.npmjs.org/refractor/-/refractor-3.6.0.tgz",
+ "integrity": "sha512-MY9W41IOWxxk31o+YvFCNyNzdkc9M20NoZK5vq6jkv4I/uh2zkWcfudj0Q1fovjUQJrNewS9NMzeTtqPf+n5EA==",
+ "dependencies": {
+ "hastscript": "^6.0.0",
+ "parse-entities": "^2.0.0",
+ "prismjs": "~1.27.0"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
+ "node_modules/refractor/node_modules/prismjs": {
+ "version": "1.27.0",
+ "resolved": "https://registry.npmjs.org/prismjs/-/prismjs-1.27.0.tgz",
+ "integrity": "sha512-t13BGPUlFDR7wRB5kQDG4jjl7XeuH6jbJGt11JHPL96qwsEHNX2+68tFXqc1/k+/jALsbSWJKUOT/hcYAZ5LkA==",
+ "engines": {
+ "node": ">=6"
+ }
+ },
"node_modules/regenerator-runtime": {
"version": "0.14.1",
"resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.14.1.tgz",
@@ -16154,6 +16401,14 @@
"node": ">=0.4.0"
}
},
+ "node_modules/xtend": {
+ "version": "4.0.2",
+ "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz",
+ "integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==",
+ "engines": {
+ "node": ">=0.4"
+ }
+ },
"node_modules/y18n": {
"version": "5.0.8",
"resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz",
diff --git a/package.json b/package.json
index 5074775b..ea3a0498 100644
--- a/package.json
+++ b/package.json
@@ -116,6 +116,7 @@
"react-notion-x": "^7.2.5",
"react-pdf": "^8.0.2",
"react-phone-number-input": "^3.4.9",
+ "react-syntax-highlighter": "^15.6.1",
"react-textarea-autosize": "^8.5.5",
"react-zoom-pan-pinch": "^3.6.1",
"resend": "^4.0.0",
@@ -146,6 +147,7 @@
"@types/node": "^20",
"@types/react": "^18",
"@types/react-dom": "^18",
+ "@types/react-syntax-highlighter": "^15.5.13",
"@types/ua-parser-js": "^0.7.39",
"prettier": "^3.3.3",
"prettier-plugin-tailwindcss": "^0.6.9",
diff --git a/pages/api/teams/[teamId]/webhooks/[id]/events.ts b/pages/api/teams/[teamId]/webhooks/[id]/events.ts
new file mode 100644
index 00000000..656915ba
--- /dev/null
+++ b/pages/api/teams/[teamId]/webhooks/[id]/events.ts
@@ -0,0 +1,62 @@
+import { NextApiRequest, NextApiResponse } from "next";
+
+import { authOptions } from "@/pages/api/auth/[...nextauth]";
+import { getServerSession } from "next-auth/next";
+
+import prisma from "@/lib/prisma";
+import { getWebhookEvents } from "@/lib/tinybird/pipes";
+import { CustomUser } from "@/lib/types";
+
+export default async function handler(
+ req: NextApiRequest,
+ res: NextApiResponse,
+) {
+ const session = await getServerSession(req, res, authOptions);
+ if (!session) {
+ return res.status(401).json({ error: "Unauthorized" });
+ }
+
+ const { teamId, id: webhookId } = req.query as { teamId: string; id: string };
+ const userId = (session.user as CustomUser).id;
+
+ const userTeam = await prisma.userTeam.findFirst({
+ where: {
+ userId,
+ teamId,
+ },
+ });
+
+ if (!userTeam) {
+ return res.status(403).json({ error: "Forbidden" });
+ }
+
+ if (req.method === "GET") {
+ try {
+ const { pId } = await prisma.webhook.findUniqueOrThrow({
+ where: {
+ id: webhookId,
+ teamId,
+ },
+ select: {
+ pId: true,
+ },
+ });
+
+ const events = await getWebhookEvents({
+ webhookId: pId,
+ });
+
+ const parsedEvents = events.data.map((event) => ({
+ ...event,
+ request_body: JSON.parse(event.request_body as string),
+ }));
+
+ return res.status(200).json(parsedEvents);
+ } catch (error) {
+ console.error(error);
+ return res.status(500).json({ error: "Internal server error" });
+ }
+ }
+
+ return res.status(405).json({ error: "Method not allowed" });
+}
diff --git a/pages/api/teams/[teamId]/webhooks/[id]/index.ts b/pages/api/teams/[teamId]/webhooks/[id]/index.ts
new file mode 100644
index 00000000..dfd31e12
--- /dev/null
+++ b/pages/api/teams/[teamId]/webhooks/[id]/index.ts
@@ -0,0 +1,93 @@
+import { NextApiRequest, NextApiResponse } from "next";
+
+import { authOptions } from "@/pages/api/auth/[...nextauth]";
+import { getServerSession } from "next-auth/next";
+
+import prisma from "@/lib/prisma";
+import { CustomUser } from "@/lib/types";
+import { updateWebhookSchema } from "@/lib/zod/schemas/webhooks";
+
+export default async function handler(
+ req: NextApiRequest,
+ res: NextApiResponse,
+) {
+ const session = await getServerSession(req, res, authOptions);
+ if (!session) {
+ return res.status(401).json({ error: "Unauthorized" });
+ }
+
+ const { teamId, id } = req.query as { teamId: string; id: string };
+ const userId = (session.user as CustomUser).id;
+
+ const userTeam = await prisma.userTeam.findFirst({
+ where: {
+ userId,
+ teamId,
+ },
+ });
+
+ if (!userTeam) {
+ return res.status(403).json({ error: "Forbidden" });
+ }
+
+ if (req.method === "GET") {
+ try {
+ const webhook = await prisma.webhook.findFirst({
+ where: {
+ id,
+ teamId,
+ },
+ });
+
+ if (!webhook) {
+ return res.status(404).json({ error: "Webhook not found" });
+ }
+
+ return res.status(200).json(webhook);
+ } catch (error) {
+ console.error(error);
+ return res.status(500).json({ error: "Internal server error" });
+ }
+ }
+
+ if (req.method === "PATCH") {
+ try {
+ const { name, triggers } = updateWebhookSchema.parse(req.body);
+
+ const webhook = await prisma.webhook.update({
+ where: {
+ id,
+ teamId,
+ },
+ data: {
+ name,
+ triggers,
+ },
+ });
+
+ return res.status(200).json(webhook);
+ } catch (error) {
+ console.error(error);
+ return res.status(500).json({ error: "Internal server error" });
+ }
+ }
+
+ if (req.method === "DELETE") {
+ try {
+ await prisma.webhook.delete({
+ where: {
+ id,
+ teamId,
+ },
+ });
+
+ return res.status(204).end();
+ } catch (error) {
+ console.error(error);
+ return res.status(500).json({ error: "Internal server error" });
+ }
+ }
+
+ res.setHeader("Allow", ["GET", "PATCH", "DELETE"]);
+ return res.status(405).json({ error: `Method ${req.method} Not Allowed` });
+}
diff --git a/pages/api/teams/[teamId]/webhooks/index.ts b/pages/api/teams/[teamId]/webhooks/index.ts
index 7d06ad3d..552dac01 100644
--- a/pages/api/teams/[teamId]/webhooks/index.ts
+++ b/pages/api/teams/[teamId]/webhooks/index.ts
@@ -1,176 +1,74 @@
import { NextApiRequest, NextApiResponse } from "next";
import { authOptions } from "@/pages/api/auth/[...nextauth]";
-import { getServerSession } from "next-auth";
+import { getServerSession } from "next-auth/next";
-import { getFeatureFlags } from "@/lib/featureFlags";
+import { newId } from "@/lib/id-helper";
import prisma from "@/lib/prisma";
import { CustomUser } from "@/lib/types";
-import { generateWebhookId } from "@/lib/webhooks";
+import { createWebhookSchema } from "@/lib/zod/schemas/webhooks";
export default async function handle(
req: NextApiRequest,
res: NextApiResponse,
) {
+ const session = await getServerSession(req, res, authOptions);
+ if (!session) {
+ return res.status(401).json({ error: "Unauthorized" });
+ }
+
const { teamId } = req.query as { teamId: string };
+ const userId = (session.user as CustomUser).id;
+
+ const userTeam = await prisma.userTeam.findFirst({
+ where: {
+ userId: userId,
+ teamId: teamId,
+ },
+ });
- // Check feature flag
- const features = await getFeatureFlags({ teamId });
- if (!features.webhooks) {
- return res
- .status(403)
- .json({ error: "This feature is not available for your team" });
+ if (!userTeam) {
+ return res.status(404).json({ error: "Team not found" });
}
if (req.method === "GET") {
+ // GET /api/teams/:teamId/webhooks
try {
- const session = await getServerSession(req, res, authOptions);
- if (!session) {
- return res.status(401).json({ error: "Unauthorized" });
- }
-
- const userId = (session.user as CustomUser).id;
-
- // Check if user is in team
- const { role } = await prisma.userTeam.findUniqueOrThrow({
+ const webhooks = await prisma.webhook.findMany({
where: {
- userId_teamId: {
- userId,
- teamId,
- },
- },
- select: {
- role: true,
+ teamId: teamId,
},
});
- if (!role || role !== "ADMIN") {
- return res.status(403).json({ error: "Unauthorized" });
- }
-
- // Fetch webhooks
- const webhooks = await prisma.incomingWebhook.findMany({
- where: {
- teamId,
- },
- select: {
- id: true,
- name: true,
- externalId: true,
- createdAt: true,
- },
- orderBy: {
- createdAt: "desc",
- },
- });
-
- // Transform the response to match the interface
- const transformedWebhooks = webhooks.map((webhook) => ({
- id: webhook.id,
- name: webhook.name,
- webhookId: webhook.externalId,
- createdAt: webhook.createdAt,
- }));
-
- return res.status(200).json(transformedWebhooks);
+ return res.status(200).json(webhooks);
} catch (error) {
- console.error(error);
- return res.status(500).json({ error: "Error fetching webhooks" });
- }
- }
-
- if (req.method === "POST") {
- const session = await getServerSession(req, res, authOptions);
- if (!session) {
- return res.status(401).json({ error: "Unauthorized" });
+ console.error("Error fetching webhooks:", error);
+ return res.status(500).json({ error: "Failed to fetch webhooks" });
}
-
- const { teamId } = req.query as { teamId: string };
- const userId = (session.user as CustomUser).id;
-
+ } else if (req.method === "POST") {
+ // POST /api/teams/:teamId/webhooks
try {
- // Check if user has access to team
- const userTeam = await prisma.userTeam.findFirst({
- where: {
- teamId,
- userId,
- },
- });
-
- if (!userTeam) {
- return res.status(401).json({ error: "Unauthorized" });
- }
-
- const { name } = req.body;
- if (!name) {
- return res.status(400).json({ error: "Name is required" });
- }
+ const { name, url, secret, triggers } = createWebhookSchema.parse(
+ req.body,
+ );
- // Generate webhook ID and secret
- const webhookId = generateWebhookId(teamId);
+ const webhookId = newId("webhook");
- // Create incoming webhook
- const incomingWebhook = await prisma.incomingWebhook.create({
+ const webhook = await prisma.webhook.create({
data: {
- name: "New Incoming Webhook",
- externalId: webhookId,
- teamId,
+ pId: webhookId,
+ name: name,
+ url: url,
+ secret: secret,
+ triggers: triggers,
+ teamId: teamId,
},
});
- return res.status(200).json({
- name: incomingWebhook.name,
- webhookId: incomingWebhook.externalId,
- });
+ return res.status(201).json(webhook);
} catch (error) {
console.error("Error creating webhook:", error);
- return res.status(500).json({ error: "Internal server error" });
- }
- }
-
- if (req.method === "DELETE") {
- try {
- const session = await getServerSession(req, res, authOptions);
- if (!session) {
- return res.status(401).json({ error: "Unauthorized" });
- }
-
- const { teamId } = req.query as { teamId: string };
- const { webhookId } = req.body;
- const userId = (session.user as CustomUser).id;
-
- // Check if user is in team and has admin role
- const { role } = await prisma.userTeam.findUniqueOrThrow({
- where: {
- userId_teamId: {
- userId,
- teamId,
- },
- },
- select: {
- role: true,
- },
- });
-
- // Only admins can delete webhooks
- if (role !== "ADMIN") {
- return res
- .status(403)
- .json({ error: "Forbidden: Admin access required" });
- }
-
- // Delete the webhook
- await prisma.incomingWebhook.delete({
- where: {
- id: webhookId,
- teamId, // Ensure webhook belongs to the team
- },
- });
-
- return res.status(200).json({ message: "Webhook deleted successfully" });
- } catch (error) {
- console.error(error);
- return res.status(500).json({ error: "Error deleting webhook" });
+ return res.status(500).json({ error: "Failed to create webhook" });
}
}
diff --git a/pages/api/views.ts b/pages/api/views.ts
index f9abf15f..f310c3b2 100644
--- a/pages/api/views.ts
+++ b/pages/api/views.ts
@@ -5,6 +5,7 @@ import { getServerSession } from "next-auth/next";
import { hashToken } from "@/lib/api/auth/token";
import sendNotification from "@/lib/api/notification-helper";
+import { recordVisit } from "@/lib/api/views/record-visit";
import { sendOtpVerificationEmail } from "@/lib/emails/send-email-otp-verification";
import { getFile } from "@/lib/files/get-file";
import { newId } from "@/lib/id-helper";
@@ -526,6 +527,19 @@ export default async function handle(
console.timeEnd("sendemail");
}
+ // Prepare webhook for view
+ if (newView) {
+ waitUntil(
+ recordVisit({
+ viewId: newView.id,
+ linkId,
+ teamId: link.teamId!,
+ documentId,
+ headers: req.headers,
+ }),
+ );
+ }
+
const returnObject = {
message: "View recorded",
viewId: !isPreview && newView ? newView.id : undefined,
diff --git a/pages/settings/webhooks/[id]/index.tsx b/pages/settings/webhooks/[id]/index.tsx
new file mode 100644
index 00000000..ffe99582
--- /dev/null
+++ b/pages/settings/webhooks/[id]/index.tsx
@@ -0,0 +1,396 @@
+import { useRouter } from "next/router";
+
+import { useEffect, useState } from "react";
+
+import { useTeam } from "@/context/team-context";
+import { Webhook } from "@prisma/client";
+import { format } from "date-fns";
+import { ArrowLeft, Check, Copy, WebhookIcon } from "lucide-react";
+import { toast } from "sonner";
+import useSWR from "swr";
+
+import AppLayout from "@/components/layouts/app";
+import { SettingsHeader } from "@/components/settings/settings-header";
+import { Button } from "@/components/ui/button";
+import { Card } from "@/components/ui/card";
+import { Checkbox } from "@/components/ui/checkbox";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
+import { WebhookEventList } from "@/components/webhooks/webhook-events";
+
+import { cn, fetcher } from "@/lib/utils";
+
+import { documentEvents, linkEvents, teamEvents } from "../new";
+
+type WebhookFormData = {
+ name: string;
+ triggers: string[];
+};
+
+export default function WebhookDetail() {
+ const router = useRouter();
+ const { id } = router.query;
+ const teamInfo = useTeam();
+ const teamId = teamInfo?.currentTeam?.id;
+ const [isEditing, setIsEditing] = useState(false);
+ const [isCopied, setIsCopied] = useState(false);
+
+ const { data: webhook, mutate } = useSWR<Webhook>(
+ teamId && id ? `/api/teams/${teamId}/webhooks/${id}` : null,
+ fetcher,
+ );
+
+ const { data: webhookEvents } = useSWR<any[]>(
+ teamId && id ? `/api/teams/${teamId}/webhooks/${id}/events` : null,
+ fetcher,
+ {
+ keepPreviousData: true,
+ },
+ );
+
+ const [formData, setFormData] = useState<WebhookFormData>({
+ name: "",
+ triggers: [],
+ });
+
+ useEffect(() => {
+ if (webhook) {
+ setFormData({
+ name: webhook.name,
+ triggers: webhook.triggers as string[],
+ });
+ }
+ }, [webhook]);
+
+ const handleUpdate = async () => {
+ try {
+ const response = await fetch(`/api/teams/${teamId}/webhooks/${id}`, {
+ method: "PATCH",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(formData),
+ });
+
+ if (!response.ok) throw new Error("Failed to update webhook");
+
+ await mutate();
+ setIsEditing(false);
+ toast.success("Webhook updated successfully");
+ } catch (error) {
+ toast.error("Failed to update webhook");
+ }
+ };
+
+ return (
+ <AppLayout>
+ <main className="relative mx-2 mb-10 mt-4 space-y-8 overflow-hidden px-1 sm:mx-3 md:mx-5 md:mt-5 lg:mx-7 lg:mt-8 xl:mx-10">
+ <SettingsHeader />
+
+ <Button
+ variant="ghost"
+ size="sm"
+ className="mb-2 flex items-center gap-2 pl-0 text-muted-foreground"
+ onClick={() => router.push("/settings/webhooks")}
+ >
+ <ArrowLeft className="h-4 w-4" />
+ Back to webhooks
+ </Button>
+
+ <div>
+ <div className="mb-4 flex items-center justify-between md:mb-8 lg:mb-12">
+ <div className="space-y-1">
+ <h3 className="text-lg font-semibold tracking-tight text-foreground">
+ {webhook?.name}
+ </h3>
+ <p className="flex flex-row items-center gap-2 font-mono text-sm text-muted-foreground">
+ {webhook?.url}
+ </p>
+ </div>
+ </div>
+
+ <Tabs defaultValue="events" className="space-y-4">
+ <TabsList>
+ <TabsTrigger value="events">Events</TabsTrigger>
+ <TabsTrigger value="settings">Settings</TabsTrigger>
+ </TabsList>
+
+ <TabsContent value="events" className="space-y-4">
+ {!webhookEvents || webhookEvents.length === 0 ? (
+ <div className="flex flex-col items-center justify-center space-y-4 rounded-lg border border-dashed py-12">
+ <div className="rounded-full bg-gray-100 p-3">
+ <WebhookIcon className="h-6 w-6 text-gray-600" />
+ </div>
+ <div className="text-center">
+ <h3 className="font-medium">No webhook events yet</h3>
+ <p className="mt-1 text-sm text-gray-500">
+ Events will appear here when they are triggered
+ </p>
+ </div>
+ </div>
+ ) : (
+ <div className="space-y-4">
+ <WebhookEventList events={webhookEvents} />
+ </div>
+ )}
+ </TabsContent>
+
+ <TabsContent value="settings" className="space-y-4">
+ <Card className="p-6 dark:bg-transparent">
+ <div className="space-y-6">
+ <div className="space-y-2">
+ <Label htmlFor="name">Name</Label>
+ <Input
+ id="name"
+ value={isEditing ? formData.name : webhook?.name}
+ onChange={(e) =>
+ setFormData({ ...formData, name: e.target.value })
+ }
+ disabled={!isEditing}
+ className={cn(
+ "disabled:cursor-not-allowed disabled:opacity-60",
+ isEditing && "cursor-text",
+ )}
+ />
+ </div>
+
+ <div className="space-y-4">
+ <div className="space-y-1">
+ <Label>Events</Label>
+ <p className="text-sm text-muted-foreground">
+ Select the events the webhook will listen to. At least
+ one must be selected.
+ </p>
+ </div>
+
+ <div className="grid grid-cols-3 gap-8">
+ <div className="space-y-4">
+ <h4 className="text-sm font-light">Team Events</h4>
+ <div className="space-y-4">
+ {teamEvents.map((event) => (
+ <div
+ key={event.id}
+ className="flex items-center space-x-2"
+ >
+ <Checkbox
+ id={event.id}
+ checked={formData?.triggers?.includes(
+ event.value,
+ )}
+ onCheckedChange={(checked) => {
+ setFormData((prev) => ({
+ ...prev,
+ triggers: checked
+ ? [...prev.triggers, event.value]
+ : prev.triggers.filter(
+ (e) => e !== event.value,
+ ),
+ }));
+ }}
+ disabled={true}
+ />
+ <Label htmlFor={event.id}>{event.label}</Label>
+ </div>
+ ))}
+ </div>
+ </div>
+
+ <div className="space-y-4">
+ <h4 className="text-sm font-light">Document Events</h4>
+ <div className="space-y-4">
+ {documentEvents.map((event) => (
+ <div
+ key={event.id}
+ className="flex items-center space-x-2"
+ >
+ <Checkbox
+ id={event.id}
+ checked={formData?.triggers.includes(
+ event.value,
+ )}
+ onCheckedChange={(checked) => {
+ setFormData((prev) => ({
+ ...prev,
+ triggers: checked
+ ? [...prev.triggers, event.value]
+ : prev.triggers.filter(
+ (e) => e !== event.value,
+ ),
+ }));
+ }}
+ disabled={true}
+ />
+ <Label htmlFor={event.id}>{event.label}</Label>
+ </div>
+ ))}
+ </div>
+ </div>
+
+ <div className="space-y-4">
+ <h4 className="text-sm font-light">Link Events</h4>
+ <div className="space-y-4">
+ {linkEvents.map((event) => (
+ <div
+ key={event.id}
+ className="flex items-center space-x-2"
+ >
+ <Checkbox
+ id={event.id}
+ checked={formData?.triggers.includes(
+ event.value,
+ )}
+ disabled={
+ !isEditing ||
+ event.value === "link.downloaded"
+ }
+ onCheckedChange={(checked) => {
+ setFormData((prev) => ({
+ ...prev,
+ triggers: checked
+ ? [...prev.triggers, event.value]
+ : prev.triggers.filter(
+ (e) => e !== event.value,
+ ),
+ }));
+ }}
+ />
+ <Label htmlFor={event.id}>{event.label}</Label>
+ </div>
+ ))}
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <div className="space-y-2">
+ <div className="space-y-1">
+ <Label htmlFor="url">Endpoint</Label>
+ <p className="text-sm text-muted-foreground">
+ Webhooks events will be sent as{" "}
+ <span className="rounded-sm bg-muted px-1 font-mono ring-1 ring-muted-foreground/30">
+ POST
+ </span>{" "}
+ request to this URL. This cannot be changed after
+ creation.
+ </p>
+ </div>
+ <div className="rounded-md border border-input bg-muted px-3 py-2 font-mono text-sm text-muted-foreground">
+ {webhook?.url}
+ </div>
+ </div>
+
+ <div className="space-y-2">
+ <div className="space-y-1">
+ <Label htmlFor="secret">Signing Secret</Label>
+ <p className="text-sm text-muted-foreground">
+ This secret will be used to sign the webhook payload.
+ This cannot be changed after creation.
+ </p>
+ </div>
+ <div className="relative">
+ <div className="rounded-md border border-input bg-muted px-3 py-2 font-mono text-sm text-muted-foreground">
+ {webhook?.secret}
+ </div>
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon"
+ className="absolute right-1 top-1/2 h-8 w-8 -translate-y-1/2"
+ onClick={() => {
+ navigator.clipboard.writeText(webhook?.secret || "");
+ toast.success("Copied to clipboard!");
+ setIsCopied(true);
+ setTimeout(() => setIsCopied(false), 2000);
+ }}
+ >
+ {isCopied ? (
+ <Check className="h-4 w-4" />
+ ) : (
+ <Copy className="h-4 w-4" />
+ )}
+ </Button>
+ </div>
+ </div>
+
+ <div className="space-y-2">
+ <div className="space-y-1">
+ <Label>Webhook ID</Label>
+ <p className="text-sm text-muted-foreground">
+ This ID can be used to identify the webhook or for
+ debugging purposes.
+ </p>
+ </div>
+ <p className="font-mono text-sm text-muted-foreground">
+ {webhook?.pId}
+ </p>
+ </div>
+
+ <div className="pt-4">
+ {isEditing ? (
+ <div className="flex gap-2">
+ <Button onClick={handleUpdate}>Save Changes</Button>
+ <Button
+ variant="outline"
+ className="dark:bg-transparent dark:hover:bg-muted"
+ onClick={() => setIsEditing(false)}
+ >
+ Cancel
+ </Button>
+ </div>
+ ) : (
+ <Button onClick={() => setIsEditing(true)}>
+ Click to edit webhook
+ </Button>
+ )}
+ </div>
+ </div>
+ </Card>
+
+ <Card className="border-destructive p-6">
+ <div className="space-y-4">
+ <div>
+ <h4 className="text-lg font-medium text-destructive">
+ Delete Webhook
+ </h4>
+ <p className="text-sm text-muted-foreground">
+ Once you delete a webhook, there is no going back. This
+ action cannot be undone.
+ </p>
+ </div>
+ <Button
+ variant="destructive"
+ onClick={async () => {
+ if (
+ confirm(
+ "Are you sure you want to delete this webhook? This action cannot be undone.",
+ )
+ ) {
+ try {
+ const response = await fetch(
+ `/api/teams/${teamId}/webhooks/${id}`,
+ {
+ method: "DELETE",
+ },
+ );
+
+ if (!response.ok)
+ throw new Error("Failed to delete webhook");
+
+ toast.success("Webhook deleted successfully");
+ router.push("/settings/webhooks");
+ } catch (error) {
+ toast.error("Failed to delete webhook");
+ }
+ }
+ }}
+ >
+ Delete Webhook
+ </Button>
+ </div>
+ </Card>
+ </TabsContent>
+ </Tabs>
+ </div>
+ </main>
+ </AppLayout>
+ );
+}
diff --git a/pages/settings/webhooks/index.tsx b/pages/settings/webhooks/index.tsx
new file mode 100644
index 00000000..b64bb86c
--- /dev/null
+++ b/pages/settings/webhooks/index.tsx
@@ -0,0 +1,104 @@
+import Link from "next/link";
+import { useRouter } from "next/router";
+
+import { useTeam } from "@/context/team-context";
+import { format } from "date-fns";
+import { CircleHelpIcon, CopyIcon, WebhookIcon } from "lucide-react";
+import { toast } from "sonner";
+import useSWR from "swr";
+
+import AppLayout from "@/components/layouts/app";
+import { SettingsHeader } from "@/components/settings/settings-header";
+import { Avatar, AvatarFallback } from "@/components/ui/avatar";
+import { Button } from "@/components/ui/button";
+import { BadgeTooltip } from "@/components/ui/tooltip";
+
+import { fetcher } from "@/lib/utils";
+
+interface Webhook {
+ id: string;
+ name: string;
+ url: string;
+ createdAt: string;
+}
+
+export default function WebhookSettings() {
+ const router = useRouter();
+ const teamInfo = useTeam();
+ const teamId = teamInfo?.currentTeam?.id;
+
+ const { data: webhooks } = useSWR<Webhook[]>(
+ teamId ? `/api/teams/${teamId}/webhooks` : null,
+ fetcher,
+ );
+
+ return (
+ <AppLayout>
+ <main className="relative mx-2 mb-10 mt-4 space-y-8 overflow-hidden px-1 sm:mx-3 md:mx-5 md:mt-5 lg:mx-7 lg:mt-8 xl:mx-10">
+ <SettingsHeader />
+ <div>
+ <div className="mb-4 flex items-center justify-between md:mb-8 lg:mb-12">
+ <div className="space-y-1">
+ <h3 className="text-2xl font-semibold tracking-tight text-foreground">
+ Webhooks
+ </h3>
+ <p className="flex flex-row items-center gap-2 text-sm text-muted-foreground">
+ Send data to external services when events happen in Papermark
+ <BadgeTooltip content="Send data to external services when events happen in Papermark">
+ <CircleHelpIcon className="h-4 w-4 shrink-0 text-muted-foreground hover:text-foreground" />
+ </BadgeTooltip>
+ </p>
+ </div>
+ <Button onClick={() => router.push("/settings/webhooks/new")}>
+ Create Webhook
+ </Button>
+ </div>
+
+ {/* Webhooks List */}
+ {!webhooks || webhooks.length === 0 ? (
+ <div className="flex flex-col items-center justify-center space-y-4 py-12">
+ <div className="rounded-full bg-gray-100 p-3">
+ <WebhookIcon className="h-6 w-6 text-gray-600" />
+ </div>
+ <div className="text-center">
+ <h3 className="font-medium">No webhooks configured</h3>
+ <p className="mt-1 max-w-sm text-sm text-gray-500">
+ Webhooks allow you to receive HTTP requests whenever specific
+ events occur in your account.
+ </p>
+ </div>
+ </div>
+ ) : (
+ <div className="grid grid-cols-1 gap-3">
+ {webhooks.map((webhook) => (
+ <Link
+ key={webhook.id}
+ href={`/settings/webhooks/${webhook.id}`}
+ className="rounded-xl border border-gray-200 bg-white p-4 transition-[filter] dark:border-gray-400 dark:bg-secondary sm:p-5"
+ >
+ <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">
+ <Avatar className="size-6">
+ <AvatarFallback>
+ {webhook.name.slice(0, 2).toUpperCase()}
+ </AvatarFallback>
+ </Avatar>
+ </div> */}
+ <div>
+ <div className="flex items-center gap-1">
+ <span className="font-semibold">{webhook.name}</span>
+ </div>
+ <div className="flex items-center gap-1 text-sm text-muted-foreground">
+ {webhook.url}
+ </div>
+ </div>
+ </div>
+ </Link>
+ ))}
+ </div>
+ )}
+ </div>
+ </main>
+ </AppLayout>
+ );
+}
diff --git a/pages/settings/webhooks/new.tsx b/pages/settings/webhooks/new.tsx
new file mode 100644
index 00000000..f71e53f3
--- /dev/null
+++ b/pages/settings/webhooks/new.tsx
@@ -0,0 +1,330 @@
+"use client";
+
+import { useRouter } from "next/router";
+
+import { useEffect, useState } from "react";
+
+import { useTeam } from "@/context/team-context";
+import { ArrowLeft, Check } from "lucide-react";
+import { toast } from "sonner";
+
+import AppLayout from "@/components/layouts/app";
+import { SettingsHeader } from "@/components/settings/settings-header";
+import Copy from "@/components/shared/icons/copy";
+import { Button } from "@/components/ui/button";
+import { Card, CardContent } from "@/components/ui/card";
+import { Checkbox } from "@/components/ui/checkbox";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+
+import { newId } from "@/lib/id-helper";
+
+interface WebhookEvent {
+ id: string;
+ label: string;
+ value: string;
+}
+
+export const teamEvents: WebhookEvent[] = [
+ {
+ id: "document-created",
+ label: "Document Created",
+ value: "document.created",
+ },
+ {
+ id: "document-updated",
+ label: "Document Updated",
+ value: "document.updated",
+ },
+ {
+ id: "document-deleted",
+ label: "Document Deleted",
+ value: "document.deleted",
+ },
+ {
+ id: "dataroom-created",
+ label: "Dataroom Created",
+ value: "dataroom.created",
+ },
+];
+
+export const documentEvents: WebhookEvent[] = [
+ { id: "link-created", label: "Link Created", value: "link.created" },
+ { id: "link-updated", label: "Link Updated", value: "link.updated" },
+];
+
+export const linkEvents: WebhookEvent[] = [
+ { id: "link-viewed", label: "Link Viewed", value: "link.viewed" },
+ { id: "link-downloaded", label: "Link Downloaded", value: "link.downloaded" },
+];
+
+export default function NewWebhook() {
+ const router = useRouter();
+ const teamInfo = useTeam();
+ const teamId = teamInfo?.currentTeam?.id;
+
+ const [isLoading, setIsLoading] = useState(false);
+ const [isCopied, setIsCopied] = useState(false);
+ const [formData, setFormData] = useState({
+ name: "",
+ url: "",
+ secret: "",
+ triggers: [] as string[],
+ });
+
+ useEffect(() => {
+ const generatedSecret = newId("webhookSecret");
+ setFormData((prev) => ({ ...prev, secret: generatedSecret }));
+ }, []);
+
+ const createWebhook = async () => {
+ try {
+ setIsLoading(true);
+ const response = await fetch(`/api/teams/${teamId}/webhooks`, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify(formData),
+ });
+
+ if (!response.ok) {
+ throw new Error("Failed to create webhook");
+ }
+
+ toast.success("Webhook created successfully");
+ router.push("/settings/webhooks");
+ } catch (error) {
+ toast.error("Failed to create webhook");
+ } finally {
+ setIsLoading(false);
+ }
+ };
+
+ return (
+ <AppLayout>
+ <main className="relative mx-2 mb-10 mt-4 space-y-8 overflow-hidden px-1 sm:mx-3 md:mx-5 md:mt-5 lg:mx-7 lg:mt-8 xl:mx-10">
+ <SettingsHeader />
+
+ <Button
+ variant="ghost"
+ size="sm"
+ className="mb-2 flex items-center gap-2 pl-0 text-muted-foreground"
+ onClick={() => router.push("/settings/webhooks")}
+ >
+ <ArrowLeft className="h-4 w-4" />
+ Back to webhooks
+ </Button>
+
+ <div className="w-full max-w-3xl">
+ <form
+ onSubmit={(e) => {
+ e.preventDefault();
+ createWebhook();
+ }}
+ className="space-y-8"
+ >
+ <div className="space-y-2">
+ <Label htmlFor="name">Name</Label>
+ <p className="text-sm text-muted-foreground">
+ This name will be used to identify the webhook in the dashboard.
+ </p>
+ <Input
+ id="name"
+ placeholder="My Webhook"
+ value={formData.name}
+ onChange={(e) =>
+ setFormData((prev) => ({ ...prev, name: e.target.value }))
+ }
+ required
+ data-1p-ignore
+ autoComplete="off"
+ autoFocus
+ />
+ </div>
+
+ <div className="space-y-4">
+ <div className="space-y-1">
+ <Label>Events</Label>
+ <p className="text-sm text-muted-foreground">
+ Select the events the webhook will listen to. At least one
+ must be selected.
+ </p>
+ </div>
+
+ <Card className="dark:bg-muted">
+ <CardContent className="py-6">
+ <div className="space-y-6">
+ <div className="grid grid-cols-3 gap-8">
+ <div className="space-y-4">
+ <h4 className="text-sm font-light">Team Events</h4>
+ <div className="space-y-4">
+ {teamEvents.map((event) => (
+ <div
+ key={event.id}
+ className="flex items-center space-x-2"
+ >
+ <Checkbox
+ id={event.id}
+ checked={formData.triggers.includes(
+ event.value,
+ )}
+ disabled={true}
+ onCheckedChange={(checked) => {
+ setFormData((prev) => ({
+ ...prev,
+ triggers: checked
+ ? [...prev.triggers, event.value]
+ : prev.triggers.filter(
+ (e) => e !== event.value,
+ ),
+ }));
+ }}
+ />
+ <Label htmlFor={event.id}>{event.label}</Label>
+ </div>
+ ))}
+ </div>
+ </div>
+
+ <div className="space-y-4">
+ <h4 className="text-sm font-light">Document Events</h4>
+ <div className="space-y-4">
+ {documentEvents.map((event) => (
+ <div
+ key={event.id}
+ className="flex items-center space-x-2"
+ >
+ <Checkbox
+ id={event.id}
+ checked={formData.triggers.includes(
+ event.value,
+ )}
+ disabled={true}
+ onCheckedChange={(checked) => {
+ setFormData((prev) => ({
+ ...prev,
+ triggers: checked
+ ? [...prev.triggers, event.value]
+ : prev.triggers.filter(
+ (e) => e !== event.value,
+ ),
+ }));
+ }}
+ />
+ <Label htmlFor={event.id}>{event.label}</Label>
+ </div>
+ ))}
+ </div>
+ </div>
+
+ <div className="space-y-4">
+ <h4 className="text-sm font-light">Link Events</h4>
+ <div className="space-y-4">
+ {linkEvents.map((event) => (
+ <div
+ key={event.id}
+ className="flex items-center space-x-2"
+ >
+ <Checkbox
+ id={event.id}
+ checked={formData.triggers.includes(
+ event.value,
+ )}
+ disabled={event.value === "link.downloaded"}
+ onCheckedChange={(checked) => {
+ setFormData((prev) => ({
+ ...prev,
+ triggers: checked
+ ? [...prev.triggers, event.value]
+ : prev.triggers.filter(
+ (e) => e !== event.value,
+ ),
+ }));
+ }}
+ />
+ <Label htmlFor={event.id}>{event.label}</Label>
+ </div>
+ ))}
+ </div>
+ </div>
+ </div>
+ </div>
+ </CardContent>
+ </Card>
+ </div>
+
+ <div className="space-y-2">
+ <Label htmlFor="url">Endpoint</Label>
+ <p className="text-sm text-muted-foreground">
+ Webhooks events will be sent as{" "}
+ <span className="rounded-sm bg-muted px-1 font-mono ring-1 ring-muted-foreground/30">
+ POST
+ </span>{" "}
+ request to this URL.
+ </p>
+ <Input
+ id="url"
+ placeholder="https://your-domain.com/webhooks"
+ value={formData.url}
+ onChange={(e) =>
+ setFormData((prev) => ({ ...prev, url: e.target.value }))
+ }
+ required
+ />
+ </div>
+
+ <div className="space-y-2">
+ <Label htmlFor="secret">Signing Secret</Label>
+ <p className="text-sm text-muted-foreground">
+ This secret will be used to sign the webhook payload.
+ </p>
+ <div className="relative">
+ <Input
+ id="secret"
+ placeholder="whsec_1234567890abcdef"
+ type="text"
+ value={formData.secret}
+ readOnly
+ className="pr-10 font-mono"
+ />
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon"
+ className="absolute right-1 top-1/2 h-8 w-8 -translate-y-1/2"
+ onClick={() => {
+ navigator.clipboard.writeText(formData.secret);
+ toast.success("Copied to clipboard!");
+ setIsCopied(true);
+ setTimeout(() => setIsCopied(false), 2000);
+ }}
+ >
+ {isCopied ? (
+ <Check className="h-4 w-4" />
+ ) : (
+ <Copy className="h-4 w-4" />
+ )}
+ </Button>
+ </div>
+ </div>
+
+ <div className="flex space-x-4">
+ <Button type="submit" disabled={isLoading}>
+ {isLoading ? "Creating..." : "Create Webhook"}
+ </Button>
+ <Button
+ type="button"
+ variant="outline"
+ className="dark:bg-transparent dark:hover:bg-muted"
+ onClick={() => router.push("/settings/webhooks")}
+ >
+ Cancel
+ </Button>
+ </div>
+ </form>
+ </div>
+ </main>
+ </AppLayout>
+ );
+}
diff --git a/prisma/migrations/20241208000000_add_webhooks/migration.sql b/prisma/migrations/20241208000000_add_webhooks/migration.sql
new file mode 100644
index 00000000..d9ae322a
--- /dev/null
+++ b/prisma/migrations/20241208000000_add_webhooks/migration.sql
@@ -0,0 +1,24 @@
+-- CreateTable
+CREATE TABLE "Webhook" (
+ "id" TEXT NOT NULL,
+ "pId" TEXT NOT NULL,
+ "name" TEXT NOT NULL,
+ "url" TEXT NOT NULL,
+ "secret" TEXT NOT NULL,
+ "triggers" JSONB NOT NULL,
+ "teamId" TEXT NOT NULL,
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updatedAt" TIMESTAMP(3) NOT NULL,
+
+ CONSTRAINT "Webhook_pkey" PRIMARY KEY ("id")
+);
+
+-- CreateIndex
+CREATE UNIQUE INDEX "Webhook_pId_key" ON "Webhook"("pId");
+
+-- CreateIndex
+CREATE INDEX "Webhook_teamId_idx" ON "Webhook"("teamId");
+
+-- AddForeignKey
+ALTER TABLE "Webhook" ADD CONSTRAINT "Webhook_teamId_fkey" FOREIGN KEY ("teamId") REFERENCES "Team"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+
diff --git a/prisma/schema.prisma b/prisma/schema.prisma
index 149be35f..22a2daf1 100644
--- a/prisma/schema.prisma
+++ b/prisma/schema.prisma
@@ -89,6 +89,7 @@ model Team {
incomingWebhooks IncomingWebhook[]
restrictedTokens RestrictedToken[]
+ webhooks Webhook[]
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@ -690,3 +691,20 @@ model RestrictedToken {
@@index([userId])
@@index([teamId])
}
+
+model Webhook {
+ id String @id @default(cuid())
+ pId String @unique // public ID for the webhook
+ name String
+ url String
+ secret String // signing secret for the webhook
+ triggers Json
+
+ teamId String
+ team Team @relation(fields: [teamId], references: [id], onDelete: Cascade)
+
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+
+ @@index([teamId])
+}