Skip to content

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

refactor: add webhooks and rename incoming-webhooks

Marc Seitz3298d7f8faf8
diff --git a/components/settings/settings-header.tsx b/components/settings/settings-header.tsx
index fe28d157..0c157f5d 100644
--- a/components/settings/settings-header.tsx
+++ b/components/settings/settings-header.tsx
@@ -7,7 +7,11 @@ import { NavMenu } from "../navigation-menu";
export function SettingsHeader() {
const teamInfo = useTeam();
- const { data: features } = useSWR<{ tokens: boolean; webhooks: boolean }>(
+ const { data: features } = useSWR<{
+ tokens: boolean;
+ incomingWebhooks: boolean;
+ webhooks: boolean;
+ }>(
teamInfo?.currentTeam?.id
? `/api/feature-flags?teamId=${teamInfo.currentTeam.id}`
: null,
@@ -66,6 +70,12 @@ export function SettingsHeader() {
segment: "webhooks",
disabled: !features?.webhooks,
},
+ {
+ label: "Incoming Webhooks",
+ href: `/settings/incoming-webhooks`,
+ segment: "incoming-webhooks",
+ disabled: !features?.incomingWebhooks,
+ },
]}
/>
</header>
diff --git a/lib/featureFlags/index.ts b/lib/featureFlags/index.ts
index df9506cd..4db31988 100644
--- a/lib/featureFlags/index.ts
+++ b/lib/featureFlags/index.ts
@@ -2,17 +2,19 @@ import { get } from "@vercel/edge-config";
export type BetaFeatures =
| "tokens"
- | "webhooks"
+ | "incomingWebhooks"
| "roomChangeNotifications"
- | "embedding";
+ | "embedding"
+ | "webhooks";
type BetaFeaturesRecord = Record<BetaFeatures, string[]>;
export const getFeatureFlags = async ({ teamId }: { teamId?: string }) => {
const teamFeatures: Record<BetaFeatures, boolean> = {
tokens: false,
- webhooks: false,
+ incomingWebhooks: false,
roomChangeNotifications: false,
embedding: false,
+ webhooks: false,
};
// Return all features as true if edge config is not available
diff --git a/lib/webhooks/index.ts b/lib/incoming-webhooks/index.ts
similarity index 98%
rename from lib/webhooks/index.ts
rename to lib/incoming-webhooks/index.ts
index 795acaa9..2581e8af 100644
--- a/lib/webhooks/index.ts
+++ b/lib/incoming-webhooks/index.ts
@@ -1,4 +1,4 @@
-// lib/webhooks.ts
+// lib/incoming-webhooks.ts
import crypto from "crypto";
import { newId } from "../id-helper";
diff --git a/pages/api/teams/[teamId]/incoming-webhooks/index.ts b/pages/api/teams/[teamId]/incoming-webhooks/index.ts
new file mode 100644
index 00000000..85085ac4
--- /dev/null
+++ b/pages/api/teams/[teamId]/incoming-webhooks/index.ts
@@ -0,0 +1,178 @@
+import { NextApiRequest, NextApiResponse } from "next";
+
+import { authOptions } from "@/pages/api/auth/[...nextauth]";
+import { getServerSession } from "next-auth";
+
+import { getFeatureFlags } from "@/lib/featureFlags";
+import { generateWebhookId } from "@/lib/incoming-webhooks";
+import prisma from "@/lib/prisma";
+import { CustomUser } from "@/lib/types";
+
+export default async function handle(
+ req: NextApiRequest,
+ res: NextApiResponse,
+) {
+ const { teamId } = req.query as { teamId: string };
+
+ // 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 (req.method === "GET") {
+ 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({
+ where: {
+ userId_teamId: {
+ userId,
+ teamId,
+ },
+ },
+ select: {
+ role: true,
+ },
+ });
+
+ 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);
+ } 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" });
+ }
+
+ const { teamId } = req.query as { teamId: string };
+ const userId = (session.user as CustomUser).id;
+
+ 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" });
+ }
+
+ // Generate webhook ID and secret
+ const webhookId = generateWebhookId(teamId);
+
+ // Create incoming webhook
+ const incomingWebhook = await prisma.incomingWebhook.create({
+ data: {
+ name: "New Incoming Webhook",
+ externalId: webhookId,
+ teamId,
+ },
+ });
+
+ return res.status(200).json({
+ name: incomingWebhook.name,
+ webhookId: incomingWebhook.externalId,
+ });
+ } 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(405).json({ error: "Method not allowed" });
+}
diff --git a/pages/api/webhooks/services/[...path]/index.ts b/pages/api/webhooks/services/[...path]/index.ts
index f7369755..d37ff412 100644
--- a/pages/api/webhooks/services/[...path]/index.ts
+++ b/pages/api/webhooks/services/[...path]/index.ts
@@ -5,10 +5,10 @@ import { waitUntil } from "@vercel/functions";
import { hashToken } from "@/lib/api/auth/token";
import { createDocument } from "@/lib/documents/create-document";
import { putFileServer } from "@/lib/files/put-file-server";
+import { extractTeamId, isValidWebhookId } from "@/lib/incoming-webhooks";
import prisma from "@/lib/prisma";
import { ratelimit } from "@/lib/redis";
import { getSupportedContentType } from "@/lib/utils/get-content-type";
-import { extractTeamId, isValidWebhookId } from "@/lib/webhooks";
export const config = {
// in order to enable `waitUntil` function
diff --git a/pages/settings/webhooks.tsx b/pages/settings/incoming-webhooks.tsx
similarity index 95%
rename from pages/settings/webhooks.tsx
rename to pages/settings/incoming-webhooks.tsx
index 36955bde..82f74750 100644
--- a/pages/settings/webhooks.tsx
+++ b/pages/settings/incoming-webhooks.tsx
@@ -33,28 +33,28 @@ export default function WebhookSettings() {
const [isLoading, setIsLoading] = useState(false);
// Feature flag check
- const { data: features } = useSWR<{ webhooks: boolean }>(
+ const { data: features } = useSWR<{ incomingWebhooks: boolean }>(
teamId ? `/api/feature-flags?teamId=${teamId}` : null,
fetcher,
);
// Redirect if feature is not enabled
useEffect(() => {
- if (features && !features.webhooks) {
+ if (features && !features.incomingWebhooks) {
router.push("/settings/general");
toast.error("This feature is not available for your team");
}
}, [features, router]);
const { data: webhooks, mutate } = useSWR<Webhook[]>(
- teamId ? `/api/teams/${teamId}/webhooks` : null,
+ teamId ? `/api/teams/${teamId}/incoming-webhooks` : null,
fetcher,
);
const createWebhook = async () => {
try {
setIsLoading(true);
- const response = await fetch(`/api/teams/${teamId}/webhooks`, {
+ const response = await fetch(`/api/teams/${teamId}/incoming-webhooks`, {
method: "POST",
headers: {
"Content-Type": "application/json",
@@ -83,7 +83,7 @@ export default function WebhookSettings() {
const deleteWebhook = async (webhookId: string) => {
try {
- const response = await fetch(`/api/teams/${teamId}/webhooks`, {
+ const response = await fetch(`/api/teams/${teamId}/incoming-webhooks`, {
method: "DELETE",
headers: {
"Content-Type": "application/json",