Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
feat(beta): add tokens and incoming webhooks
Marc Seitzfa91f0bdd22d
diff --git a/.env.example b/.env.exampleindex 53ed3b94..5d1b940c 100644--- a/.env.example+++ b/.env.example@@ -72,4 +72,12 @@ NEXT_PRIVATE_DOCUMENT_PASSWORD_KEY=my-superstrong-document-secret# [[REDIS LOCKER CONFIGURATION]]# For bulk upload using tus.io, we use a Redis-based locker to prevent corruption of the data.UPSTASH_REDIS_REST_LOCKER_URL=-UPSTASH_REDIS_REST_LOCKER_TOKEN=\ No newline at end of file+UPSTASH_REDIS_REST_LOCKER_TOKEN=++# [[VERIFICATION]]+# Secret used to generate the checksum for the verification URL+NEXT_PRIVATE_VERIFICATION_SECRET=++# [[INCOMING WEBHOOKS]]+NEXT_PUBLIC_WEBHOOK_BASE_URL=+NEXT_PUBLIC_WEBHOOK_BASE_HOST=diff --git a/app/api/feature-flags/route.ts b/app/api/feature-flags/route.tsnew file mode 100644index 00000000..041e4ab5--- /dev/null+++ b/app/api/feature-flags/route.ts@@ -0,0 +1,21 @@+import { NextResponse } from "next/server";++import { getFeatureFlags } from "@/lib/featureFlags";++export const runtime = "edge";++export async function GET(request: Request) {+ const { searchParams } = new URL(request.url);+ const teamId = searchParams.get("teamId");++ try {+ const features = await getFeatureFlags({ teamId: teamId || undefined });+ return NextResponse.json(features);+ } catch (error) {+ console.error("Error fetching feature flags:", error);+ return NextResponse.json(+ { error: "Failed to fetch feature flags" },+ { status: 500 },+ );+ }+}diff --git a/components/navigation-menu.tsx b/components/navigation-menu.tsxindex 9c84c414..6f815035 100644--- a/components/navigation-menu.tsx+++ b/components/navigation-menu.tsx@@ -15,6 +15,7 @@ type Props = {href: string;segment: string | null;tag?: string;+ disabled?: boolean;}[];className?: string;};@@ -29,13 +30,14 @@ export const NavMenu: React.FC<React.PropsWithChildren<Props>> = ({><div className="flex w-full items-center overflow-x-auto pl-1"><ul className="flex flex-row gap-4">- {navigation.map(({ label, href, segment, tag }) => (+ {navigation.map(({ label, href, segment, tag, disabled }) => (<NavItemkey={label}label={label}href={href}segment={segment}tag={tag}+ disabled={disabled}/>))}</ul>@@ -50,6 +52,7 @@ const NavItem: React.FC<Props["navigation"][0]> = ({href,segment,tag,+ disabled,}) => {const router = useRouter();// active is true if the segment included in the pathname, but not if it's the root pathname. unless the segment is the root pathname.@@ -68,6 +71,7 @@ const NavItem: React.FC<Props["navigation"][0]> = ({{"border-primary": active,// "animate-pulse": isPending,+ hidden: disabled,},)}>diff --git a/components/settings/settings-header.tsx b/components/settings/settings-header.tsxindex efb15273..68ecc99e 100644--- a/components/settings/settings-header.tsx+++ b/components/settings/settings-header.tsx@@ -1,6 +1,19 @@+import { useTeam } from "@/context/team-context";+import useSWR from "swr";++import { fetcher } from "@/lib/utils";+import { NavMenu } from "../navigation-menu";export function SettingsHeader() {+ const teamInfo = useTeam();+ const { data: features } = useSWR<{ tokens: boolean; webhooks: boolean }>(+ teamInfo?.currentTeam?.id+ ? `/api/feature-flags?teamId=${teamInfo.currentTeam.id}`+ : null,+ fetcher,+ );+return (<header><section className="mb-4 flex items-center justify-between md:mb-8 lg:mb-12">@@ -46,6 +59,18 @@ export function SettingsHeader() {href: `/settings/billing`,segment: "billing",},+ {+ label: "Tokens",+ href: `/settings/tokens`,+ segment: "tokens",+ disabled: !features?.tokens,+ },+ {+ label: "Webhooks",+ href: `/settings/webhooks`,+ segment: "webhooks",+ disabled: !features?.webhooks,+ },]}/></header>diff --git a/lib/documents/create-document.ts b/lib/documents/create-document.tsindex f7be48b5..c0a37963 100644--- a/lib/documents/create-document.ts+++ b/lib/documents/create-document.ts@@ -14,30 +14,36 @@ export const createDocument = async ({numPages,folderPathName,createLink = false,+ token,}: {documentData: DocumentData;teamId: string;numPages?: number;folderPathName?: string;createLink?: boolean;+ token?: string;}) => {// create a document in the database with the blob url- const response = await fetch(`/api/teams/${teamId}/documents`, {- method: "POST",- headers: {- "Content-Type": "application/json",+ const response = await fetch(+ `${process.env.NEXT_PUBLIC_BASE_URL}/api/teams/${teamId}/documents`,+ {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ ...(token ? { Authorization: `Bearer ${token}` } : {}),+ },+ body: JSON.stringify({+ name: documentData.name,+ url: documentData.key,+ storageType: documentData.storageType,+ numPages: numPages,+ folderPathName: folderPathName,+ type: documentData.supportedFileType,+ contentType: documentData.contentType,+ createLink: createLink,+ }),},- body: JSON.stringify({- name: documentData.name,- url: documentData.key,- storageType: documentData.storageType,- numPages: numPages,- folderPathName: folderPathName,- type: documentData.supportedFileType,- contentType: documentData.contentType,- createLink: createLink,- }),- });+ );if (!response.ok) {throw new Error(`HTTP error! status: ${response.status}`);diff --git a/lib/featureFlags/index.ts b/lib/featureFlags/index.tsnew file mode 100644index 00000000..4c718129--- /dev/null+++ b/lib/featureFlags/index.ts@@ -0,0 +1,38 @@+import { get } from "@vercel/edge-config";++export type BetaFeatures = "tokens" | "webhooks";+type BetaFeaturesRecord = Record<BetaFeatures, string[]>;++export const getFeatureFlags = async ({ teamId }: { teamId?: string }) => {+ const teamFeatures: Record<BetaFeatures, boolean> = {+ tokens: false,+ webhooks: false,+ };++ // Return all features as true if edge config is not available+ if (!process.env.EDGE_CONFIG) {+ return Object.fromEntries(+ Object.entries(teamFeatures).map(([key, _v]) => [key, true]),+ );+ } else if (!teamId) {+ return teamFeatures;+ }++ let betaFeatures: BetaFeaturesRecord | undefined = undefined;++ try {+ betaFeatures = await get("betaFeatures");+ } catch (e) {+ console.error(`Error getting beta features: ${e}`);+ }++ if (betaFeatures) {+ for (const [featureFlag, teamIds] of Object.entries(betaFeatures)) {+ if (teamIds.includes(teamId)) {+ teamFeatures[featureFlag as BetaFeatures] = true;+ }+ }+ }++ return teamFeatures;+};diff --git a/lib/files/put-file-server.ts b/lib/files/put-file-server.tsindex bd1030e4..76f7a194 100644--- a/lib/files/put-file-server.ts+++ b/lib/files/put-file-server.ts@@ -7,6 +7,7 @@ import { match } from "ts-pattern";import { newId } from "@/lib/id-helper";+import { SUPPORTED_DOCUMENT_MIME_TYPES } from "../constants";import { getS3Client } from "./aws-client";// `File` is a web API type and not available server-side, so we need to define our own type@@ -20,15 +21,19 @@ export const putFileServer = async ({file,teamId,docId,+ restricted = true,}: {file: File;teamId: string;docId?: string;+ restricted?: boolean;}) => {const NEXT_PUBLIC_UPLOAD_TRANSPORT = process.env.NEXT_PUBLIC_UPLOAD_TRANSPORT;const { type, data } = await match(NEXT_PUBLIC_UPLOAD_TRANSPORT)- .with("s3", async () => putFileInS3Server({ file, teamId, docId }))+ .with("s3", async () =>+ putFileInS3Server({ file, teamId, docId, restricted }),+ ).with("vercel", async () => putFileInVercelServer(file)).otherwise(() => {return {@@ -58,16 +63,19 @@ const putFileInS3Server = async ({file,teamId,docId,+ restricted = true,}: {file: File;teamId: string;docId?: string;+ restricted?: boolean;}) => {if (!docId) {docId = newId("doc");}if (+ restricted &&file.type !== "image/png" &&file.type !== "image/jpeg" &&file.type !== "application/pdf"@@ -75,6 +83,10 @@ const putFileInS3Server = async ({throw new Error("Only PNG, JPEG or PDF files are supported");}+ if (!restricted && !SUPPORTED_DOCUMENT_MIME_TYPES.includes(file.type)) {+ throw new Error("Unsupported file type");+ }+const client = getS3Client();// Get the basename and extension for the filediff --git a/lib/id-helper.ts b/lib/id-helper.tsindex 8a484893..ea0ea35c 100644--- a/lib/id-helper.ts+++ b/lib/id-helper.ts@@ -40,4 +40,8 @@ export const newId = new IdGenerator({page: "page",dataroom: "dr",preview: "preview",+ webhook: "wh",+ webhookEvent: "evt",+ webhookSecret: "whsec",+ token: "pmk",}).id;diff --git a/lib/middleware/incoming-webhooks.ts b/lib/middleware/incoming-webhooks.tsnew file mode 100644index 00000000..e82d788f--- /dev/null+++ b/lib/middleware/incoming-webhooks.ts@@ -0,0 +1,30 @@+import { NextRequest, NextResponse } from "next/server";++export default async function IncomingWebhookMiddleware(req: NextRequest) {+ const url = req.nextUrl.clone();+ const path = url.pathname;++ // Only handle /services/* paths+ if (path.startsWith("/services/")) {+ // Rewrite to /api/webhooks/services/*+ url.pathname = `/api/webhooks${path}`;++ return NextResponse.rewrite(url);+ }++ // Return 404 for all other paths+ url.pathname = "/404";+ return NextResponse.rewrite(url, { status: 404 });+}++export function isWebhookPath(host: string | null) {+ if (!process.env.NEXT_PUBLIC_WEBHOOK_BASE_HOST) {+ return false;+ }++ if (host === process.env.NEXT_PUBLIC_WEBHOOK_BASE_HOST) {+ return true;+ }++ return false;+}diff --git a/lib/webhooks/index.ts b/lib/webhooks/index.tsnew file mode 100644index 00000000..795acaa9--- /dev/null+++ b/lib/webhooks/index.ts@@ -0,0 +1,73 @@+// lib/webhooks.ts+import crypto from "crypto";++import { newId } from "../id-helper";++function generateBase62String(length: number): string {+ const chars =+ "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";+ const bytes = crypto.randomBytes(length);+ let result = "";++ for (let i = 0; i < length; i++) {+ result += chars[bytes[i] % chars.length];+ }++ return result;+}++function encodeTeamId(teamId: string): string {+ // Convert the teamId to a Buffer if it's not already+ const buffer = Buffer.from(teamId);+ // Convert to base62 string+ return buffer+ .toString("base64")+ .replace(/\+/g, "-")+ .replace(/\//g, "_")+ .replace(/=/g, "");+}++function decodeTeamId(encoded: string): string {+ // Add back the padding+ const padding = "=".repeat((4 - (encoded.length % 4)) % 4);+ const base64 = encoded.replace(/-/g, "+").replace(/_/g, "/") + padding;++ return Buffer.from(base64, "base64").toString();+}++export function generateWebhookId(teamId: string): string {+ // Format: T{encoded_team_id}/B{8 chars}/{24 chars}+ const encodedTeamId = encodeTeamId(teamId);+ const botPart = generateBase62String(8);+ const secretPart = generateBase62String(24);++ return `T${encodedTeamId}/B${botPart}/${secretPart}`;+}++export function extractTeamId(webhookId: string): string | null {+ try {+ const [teamPart] = webhookId.split("/");+ if (!teamPart || !teamPart.startsWith("T")) return null;++ const encodedTeamId = teamPart.slice(1); // Remove 'T' prefix+ return decodeTeamId(encodedTeamId);+ } catch {+ return null;+ }+}++export function isValidWebhookId(webhookId: string): boolean {+ // Validate format: T{encoded_team_id}/B{8}/{\24}+ const parts = webhookId.split("/");+ return (+ parts.length === 3 &&+ parts[0].startsWith("T") &&+ parts[1].startsWith("B") &&+ parts[1].length === 9 && // 'B' + 8 chars+ parts[2].length === 24+ );+}++export function generateWebhookSecret(): string {+ return newId("webhookSecret"); // whsec_+}diff --git a/middleware.ts b/middleware.tsindex bcdebcec..c1616b09 100644--- a/middleware.ts+++ b/middleware.ts@@ -4,6 +4,9 @@ import AppMiddleware from "@/lib/middleware/app";import DomainMiddleware from "@/lib/middleware/domain";import { BLOCKED_PATHNAMES } from "./lib/constants";+import IncomingWebhookMiddleware, {+ isWebhookPath,+} from "./lib/middleware/incoming-webhooks";import PostHogMiddleware from "./lib/middleware/posthog";function isAnalyticsPath(path: string) {@@ -38,6 +41,11 @@ export default async function middleware(req: NextRequest, ev: NextFetchEvent) {return PostHogMiddleware(req);}+ // Handle incoming webhooks+ if (isWebhookPath(host)) {+ return IncomingWebhookMiddleware(req);+ }+if ((process.env.NODE_ENV === "development" && host?.includes(".local")) ||(process.env.NODE_ENV !== "development" &&diff --git a/next.config.mjs b/next.config.mjsindex 7d4abf4e..42d4e441 100644--- a/next.config.mjs+++ b/next.config.mjs@@ -55,6 +55,30 @@ const nextConfig = {},],},+ {+ source: "/services/:path*",+ has: [+ {+ type: "host",+ value: process.env.NEXT_PUBLIC_WEBHOOK_BASE_HOST,+ },+ ],+ headers: [+ {+ key: "X-Robots-Tag",+ value: "noindex",+ },+ ],+ },+ {+ source: "/api/webhooks/services/:path*",+ headers: [+ {+ key: "X-Robots-Tag",+ value: "noindex",+ },+ ],+ },];},experimental: {diff --git a/package-lock.json b/package-lock.jsonindex e896aada..47aa8179 100644--- a/package-lock.json+++ b/package-lock.json@@ -60,6 +60,7 @@"@upstash/ratelimit": "^2.0.4","@upstash/redis": "^1.34.3","@vercel/blob": "^0.23.4",+ "@vercel/edge-config": "^1.4.0","@vercel/functions": "^1.5.0","ai": "2.2.37","autoprefixer": "^10.4.20",@@ -6907,6 +6908,30 @@"node": ">=16.14"}},+ "node_modules/@vercel/edge-config": {+ "version": "1.4.0",+ "resolved": "https://registry.npmjs.org/@vercel/edge-config/-/edge-config-1.4.0.tgz",+ "integrity": "sha512-69Wg5gw9DzwnyUmnjToSeLRm1nm8mCPgN0kflX8EHRHyqvzH80wPem5A8rI2LXPb2Y9tJNoqN3vXPcQhS2Wh5g==",+ "dependencies": {+ "@vercel/edge-config-fs": "0.1.0"+ },+ "engines": {+ "node": ">=14.6"+ },+ "peerDependencies": {+ "@opentelemetry/api": "^1.7.0"+ },+ "peerDependenciesMeta": {+ "@opentelemetry/api": {+ "optional": true+ }+ }+ },+ "node_modules/@vercel/edge-config-fs": {+ "version": "0.1.0",+ "resolved": "https://registry.npmjs.org/@vercel/edge-config-fs/-/edge-config-fs-0.1.0.tgz",+ "integrity": "sha512-NRIBwfcS0bUoUbRWlNGetqjvLSwgYH/BqKqDN7vK1g32p7dN96k0712COgaz6VFizAm9b0g6IG6hR6+hc0KCPg=="+ },"node_modules/@vercel/functions": {"version": "1.5.0","resolved": "https://registry.npmjs.org/@vercel/functions/-/functions-1.5.0.tgz",diff --git a/package.json b/package.jsonindex 03c8f138..15a2eaf7 100644--- a/package.json+++ b/package.json@@ -71,6 +71,7 @@"@upstash/ratelimit": "^2.0.4","@upstash/redis": "^1.34.3","@vercel/blob": "^0.23.4",+ "@vercel/edge-config": "^1.4.0","@vercel/functions": "^1.5.0","ai": "2.2.37","autoprefixer": "^10.4.20",diff --git a/pages/api/teams/[teamId]/documents/index.ts b/pages/api/teams/[teamId]/documents/index.tsindex f83305df..6e1da491 100644--- a/pages/api/teams/[teamId]/documents/index.ts+++ b/pages/api/teams/[teamId]/documents/index.ts@@ -6,6 +6,7 @@ import { DocumentStorageType, Prisma } from "@prisma/client";import { getServerSession } from "next-auth/next";import { parsePageId } from "notion-utils";+import { hashToken } from "@/lib/api/auth/token";import { errorhandler } from "@/lib/errorHandler";import notion from "@/lib/notion";import prisma from "@/lib/prisma";@@ -121,15 +122,42 @@ export default async function handle(}} else if (req.method === "POST") {// POST /api/teams/:teamId/documents- const session = await getServerSession(req, res, authOptions);- if (!session) {- res.status(401).end("Unauthorized");- return;- }const { teamId } = req.query as { teamId: string };- const userId = (session.user as CustomUser).id;+ // Check for API token first+ const authHeader = req.headers.authorization;+ let userId: string;++ if (authHeader?.startsWith("Bearer ")) {+ const token = authHeader.replace("Bearer ", "");+ const hashedToken = hashToken(token);++ // Look up token in database+ const restrictedToken = await prisma.restrictedToken.findUnique({+ where: { hashedKey: hashedToken },+ select: { userId: true, teamId: true },+ });++ // Check if token exists+ if (!restrictedToken) {+ return res.status(401).json({ error: "Unauthorized" });+ }++ // Check if token is for the correct team+ if (restrictedToken.teamId !== teamId) {+ return res.status(401).json({ error: "Unauthorized" });+ }++ userId = restrictedToken.userId;+ } else {+ // Fall back to session auth+ const session = await getServerSession(req, res, authOptions);+ if (!session) {+ return res.status(401).json({ error: "Unauthorized" });+ }+ userId = (session.user as CustomUser).id;+ }// Assuming data is an object with `name` and `description` propertiesconst {@@ -199,7 +227,7 @@ export default async function handle(contentType: contentType,type: type,storageType,- ownerId: (session.user as CustomUser).id,+ ownerId: userId,teamId: teamId,...(createLink && {links: {diff --git a/pages/api/teams/[teamId]/tokens/index.ts b/pages/api/teams/[teamId]/tokens/index.tsnew file mode 100644index 00000000..bd948bae--- /dev/null+++ b/pages/api/teams/[teamId]/tokens/index.ts@@ -0,0 +1,174 @@+import { NextApiRequest, NextApiResponse } from "next";++import { authOptions } from "@/pages/api/auth/[...nextauth]";+import { getServerSession } from "next-auth";++import { hashToken } from "@/lib/api/auth/token";+import { getFeatureFlags } from "@/lib/featureFlags";+import { newId } from "@/lib/id-helper";+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 };++ const features = await getFeatureFlags({ teamId });+ if (!features.tokens) {+ 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 { teamId } = req.query as { teamId: string };+ const userId = (session.user as CustomUser).id;++ // Check if user is in team+ const userTeam = await prisma.userTeam.findUnique({+ where: {+ userId_teamId: {+ userId,+ teamId,+ },+ },+ });++ if (!userTeam) {+ return res.status(403).json({ error: "Unauthorized" });+ }++ // Fetch tokens+ const tokens = await prisma.restrictedToken.findMany({+ where: {+ teamId,+ },+ select: {+ id: true,+ name: true,+ partialKey: true,+ createdAt: true,+ lastUsed: true,+ user: {+ select: {+ name: true,+ email: true,+ },+ },+ },+ orderBy: {+ createdAt: "desc",+ },+ });++ return res.status(200).json(tokens);+ } catch (error) {+ console.error(error);+ return res.status(500).json({ error: "Error fetching tokens" });+ }+ } else 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;+ const { name } = req.body;++ try {+ // Check if user is in team+ const { role } = await prisma.userTeam.findUniqueOrThrow({+ where: {+ userId_teamId: {+ userId,+ teamId,+ },+ },+ select: {+ role: true,+ },+ });++ // Only admins can create tokens+ if (role !== "ADMIN") {+ return res.status(403).json({ error: "Forbidden" });+ }++ // Generate token+ const token = newId("token"); // pmk_+ const hashedToken = hashToken(token);+ const partialKey = `${token.slice(0, 3)}...${token.slice(-4)}`;++ // Create token in database+ await prisma.restrictedToken.create({+ data: {+ name,+ hashedKey: hashedToken,+ partialKey,+ teamId,+ userId,+ },+ });++ // Return token only once+ return res.status(200).json({ token });+ } catch (error) {+ console.error(error);+ return res.status(500).json({ error: "Error creating token" });+ }+ } else 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 { tokenId } = 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 tokens+ if (role !== "ADMIN") {+ return res.status(403).json({ error: "Forbidden" });+ }++ // Delete the token+ await prisma.restrictedToken.delete({+ where: {+ id: tokenId,+ teamId, // Ensure token belongs to the team+ },+ });++ return res.status(200).json({ message: "Token deleted successfully" });+ } catch (error) {+ console.error(error);+ return res.status(500).json({ error: "Error deleting token" });+ }+ } else {+ res.setHeader("Allow", ["GET", "POST", "DELETE"]);+ return res.status(405).json({ error: "Method not allowed" });+ }+}diff --git a/pages/api/teams/[teamId]/webhooks/index.ts b/pages/api/teams/[teamId]/webhooks/index.tsnew file mode 100644index 00000000..7d06ad3d--- /dev/null+++ b/pages/api/teams/[teamId]/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 prisma from "@/lib/prisma";+import { CustomUser } from "@/lib/types";+import { generateWebhookId } from "@/lib/webhooks";++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.tsnew file mode 100644index 00000000..3c9cfcf3--- /dev/null+++ b/pages/api/webhooks/services/[...path]/index.ts@@ -0,0 +1,181 @@+import { NextApiRequest, NextApiResponse } from "next";++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 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+ supportsResponseStreaming: true,+ maxDuration: 60,+};++export default async function incomingWebhookHandler(+ req: NextApiRequest,+ res: NextApiResponse,+) {+ if (req.method !== "POST") {+ return res.status(405).json({ error: "Method not allowed" });+ }++ // Get the full webhook ID from the path+ const { path } = req.query;+ const webhookId = Array.isArray(path) ? path.join("/") : path;++ if (!webhookId || !isValidWebhookId(webhookId)) {+ return res.status(400).json({ error: "Invalid webhook format" });+ }++ // Check for API token+ const authHeader = req.headers.authorization;+ if (!authHeader?.startsWith("Bearer ")) {+ return res+ .status(401)+ .json({ error: "Missing or invalid authorization header" });+ }++ const token = authHeader.replace("Bearer ", "");+ const hashedToken = hashToken(token);++ // Look up token in database+ const restrictedToken = await prisma.restrictedToken.findUnique({+ where: { hashedKey: hashedToken },+ select: { teamId: true, rateLimit: true },+ });++ if (!restrictedToken) {+ return res.status(401).json({ error: "Invalid token" });+ }++ // Rate limit checks for API tokens+ const rateLimit = restrictedToken.rateLimit || 60; // Default rate limit of 60 requests per minute++ const { success, limit, reset, remaining } = await ratelimit(+ rateLimit,+ "1 m",+ ).limit(hashedToken);++ // Set rate limit headers+ res.setHeader("Retry-After", reset.toString());+ res.setHeader("X-RateLimit-Limit", limit.toString());+ res.setHeader("X-RateLimit-Remaining", remaining.toString());+ res.setHeader("X-RateLimit-Reset", reset.toString());++ if (!success) {+ return res.status(429).json({ error: "Too many requests" });+ }++ // Update last used timestamp for the token+ waitUntil(+ prisma.restrictedToken.update({+ where: {+ hashedKey: hashedToken,+ },+ data: {+ lastUsed: new Date(),+ },+ }),+ );++ const teamId = extractTeamId(webhookId);+ if (!teamId) {+ return res.status(400).json({ error: "Invalid team ID in webhook" });+ }++ if (restrictedToken.teamId !== teamId) {+ return res.status(401).json({ error: "Unauthorized" });+ }++ try {+ // 1. Find the webhook integration+ const incomingWebhook = await prisma.incomingWebhook.findUnique({+ where: {+ externalId: webhookId,+ teamId: teamId,+ },+ include: { team: true },+ });++ if (!incomingWebhook) {+ return res.status(404).json({ error: "Webhook not found" });+ }++ // 3. Validate request body+ const { fileUrl, name, contentType } = req.body;++ if (!fileUrl) {+ return res.status(400).json({ error: "File URL is required" });+ }++ // Check if the content type is supported+ const supportedContentType = getSupportedContentType(contentType);+ if (!supportedContentType) {+ return res.status(400).json({ error: "Unsupported content type" });+ }++ // 4. Fetch file from URL+ const response = await fetch(fileUrl);+ if (!response.ok) {+ return res.status(400).json({ error: "Failed to fetch file from URL" });+ }++ // 5. Convert to buffer+ const fileBuffer = Buffer.from(await response.arrayBuffer());++ console.log(+ "Uploading file to storage",+ incomingWebhook.teamId,+ name,+ contentType,+ );++ // Upload the file to storage+ const { type: storageType, data } = await putFileServer({+ file: {+ name: name,+ type: contentType,+ buffer: fileBuffer,+ },+ teamId: incomingWebhook.teamId,+ restricted: false, // allows all supported file types+ });++ if (!data || !storageType) {+ return res.status(500).json({ error: "Failed to save file to storage" });+ }++ // 6. Create document using our service+ const documentCreationResponse = await createDocument({+ documentData: {+ name: name,+ key: data,+ storageType: storageType,+ contentType: contentType,+ supportedFileType: supportedContentType,+ },+ teamId: incomingWebhook.teamId,+ numPages: 1,+ token: token,+ });++ if (!documentCreationResponse.ok) {+ return res.status(500).json({ error: "Failed to create document" });+ }++ const document = await documentCreationResponse.json();++ return res.status(200).json({+ message: "Document created successfully",+ documentId: document.id,+ });+ } catch (error) {+ console.error("Webhook error:", error);+ return res.status(500).json({ error: "Internal server error" });+ }+}diff --git a/pages/settings/tokens.tsx b/pages/settings/tokens.tsxnew file mode 100644index 00000000..c78db52a--- /dev/null+++ b/pages/settings/tokens.tsx@@ -0,0 +1,214 @@+import { useRouter } from "next/router";++import { useEffect, useState } from "react";++import { useTeam } from "@/context/team-context";+import { format } from "date-fns";+import { CircleHelpIcon } 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 { Input } from "@/components/ui/input";+import { Label } from "@/components/ui/label";+import { BadgeTooltip } from "@/components/ui/tooltip";++import { fetcher } from "@/lib/utils";++interface Token {+ id: string;+ name: string;+ partialKey: string;+ createdAt: string;+ user: {+ name: string;+ email: string;+ };+}++export default function TokenSettings() {+ const teamInfo = useTeam();+ const teamId = teamInfo?.currentTeam?.id;+ const router = useRouter();+ const [name, setName] = useState("");+ const [token, setToken] = useState<string | null>(null);+ const [isLoading, setIsLoading] = useState(false);++ // Replace the useEffect with useSWR for feature flags+ const { data: features } = useSWR<{ tokens: boolean }>(+ teamId ? `/api/feature-flags?teamId=${teamId}` : null,+ fetcher,+ );++ // Redirect if feature is not enabled+ useEffect(() => {+ if (features && !features.tokens) {+ router.push("/settings/general");+ toast.error("This feature is not available for your team");+ }+ }, [features, router]);++ const { data: tokens, mutate } = useSWR<Token[]>(+ teamId ? `/api/teams/${teamId}/tokens` : null,+ fetcher,+ );++ const generateToken = async () => {+ try {+ setIsLoading(true);+ const response = await fetch(`/api/teams/${teamId}/tokens`, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ name,+ }),+ });++ if (!response.ok) {+ throw new Error("Failed to generate token");+ }++ const data = await response.json();+ setToken(data.token);+ toast.success("API token generated successfully");++ // After successful token generation, refresh the tokens list+ mutate();+ } catch (error) {+ toast.error("Failed to generate token");+ } finally {+ setIsLoading(false);+ }+ };++ const deleteToken = async (tokenId: string) => {+ try {+ const response = await fetch(`/api/teams/${teamId}/tokens`, {+ method: "DELETE",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({ tokenId }),+ });++ if (!response.ok) {+ throw new Error("Failed to delete token");+ }++ // Refresh the tokens list+ mutate();+ toast.success("Token revoked successfully");+ } catch (error) {+ console.error(error);+ toast.error("Failed to revoke token");+ }+ };++ 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 className="rounded-lg border border-gray-200 bg-white">+ <div className="flex flex-col items-center justify-between gap-4 space-y-3 border-b border-gray-200 p-5 sm:flex-row sm:space-y-0 sm:p-10">+ <div className="flex max-w-screen-sm flex-col space-y-3">+ <div className="flex items-center gap-2">+ <h2 className="text-xl font-medium">API Tokens</h2>+ <BadgeTooltip content="Use these tokens to authenticate your API requests">+ <CircleHelpIcon className="h-4 w-4 text-gray-500" />+ </BadgeTooltip>+ </div>+ <p className="text-sm text-gray-500">+ Create API tokens to integrate Papermark with your applications.+ Keep your tokens secure and never share them publicly.+ </p>+ </div>+ </div>++ <div className="p-5 sm:p-10">+ <div className="flex flex-col space-y-4">+ <div>+ <Label htmlFor="token-name">Token Name</Label>+ <Input+ id="token-name"+ placeholder="Enter a name for your token"+ value={name}+ onChange={(e) => setName(e.target.value)}+ />+ </div>++ {token && (+ <div className="rounded-lg bg-gray-50 p-4">+ <Label>+ Your API Token (copy it now, it won't be shown again)+ </Label>+ <code className="mt-2 block break-all rounded bg-gray-100 p-2 font-mono text-sm">+ {token}+ </code>+ </div>+ )}++ <Button+ onClick={generateToken}+ disabled={!name || isLoading}+ className="w-fit"+ >+ {isLoading ? "Generating..." : "Generate Token"}+ </Button>++ {/* Tokens List */}+ <div className="mt-8">+ <h3 className="mb-4 text-lg font-medium">Existing Tokens</h3>+ <div className="rounded-lg border border-gray-200">+ {tokens?.length === 0 ? (+ <div className="p-4 text-center text-sm text-gray-500">+ No tokens generated yet+ </div>+ ) : (+ <div className="divide-y divide-gray-200">+ {tokens?.map((token) => (+ <div+ key={token.id}+ className="flex items-center justify-between p-4"+ >+ <div className="space-y-1">+ <p className="font-medium">{token.name}</p>+ <div className="flex items-center space-x-2 text-sm text-gray-500">+ <span className="font-mono">+ {token.partialKey}+ </span>+ <span>•</span>+ <span>Created by {token.user.name}</span>+ <span>•</span>+ <span>+ {format(+ new Date(token.createdAt),+ "MMM d, yyyy",+ )}+ </span>+ </div>+ </div>+ <Button+ variant="destructive"+ size="sm"+ onClick={() => deleteToken(token.id)}+ >+ Revoke+ </Button>+ </div>+ ))}+ </div>+ )}+ </div>+ </div>+ </div>+ </div>+ </div>+ </main>+ </AppLayout>+ );+}diff --git a/pages/settings/webhooks.tsx b/pages/settings/webhooks.tsxnew file mode 100644index 00000000..36955bde--- /dev/null+++ b/pages/settings/webhooks.tsx@@ -0,0 +1,222 @@+import { useRouter } from "next/router";++import { useEffect, useState } from "react";++import { useTeam } from "@/context/team-context";+import { format } from "date-fns";+import { CircleHelpIcon, CopyIcon } 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 { Input } from "@/components/ui/input";+import { Label } from "@/components/ui/label";+import { BadgeTooltip } from "@/components/ui/tooltip";++import { fetcher } from "@/lib/utils";++interface Webhook {+ id: string;+ name: string;+ webhookId: string;+ createdAt: string;+}++export default function WebhookSettings() {+ const teamInfo = useTeam();+ const teamId = teamInfo?.currentTeam?.id;+ const router = useRouter();+ const [name, setName] = useState("");+ const [webhookId, setWebhookId] = useState<string | null>(null);+ const [isLoading, setIsLoading] = useState(false);++ // Feature flag check+ const { data: features } = useSWR<{ webhooks: boolean }>(+ teamId ? `/api/feature-flags?teamId=${teamId}` : null,+ fetcher,+ );++ // Redirect if feature is not enabled+ useEffect(() => {+ if (features && !features.webhooks) {+ 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,+ fetcher,+ );++ const createWebhook = async () => {+ try {+ setIsLoading(true);+ const response = await fetch(`/api/teams/${teamId}/webhooks`, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ name,+ }),+ });++ if (!response.ok) {+ throw new Error("Failed to create webhook");+ }++ const data = await response.json();+ setWebhookId(data.webhookId);+ toast.success("Webhook created successfully");++ // Refresh the webhooks list+ mutate();+ } catch (error) {+ toast.error("Failed to create webhook");+ } finally {+ setIsLoading(false);+ }+ };++ const deleteWebhook = async (webhookId: string) => {+ try {+ const response = await fetch(`/api/teams/${teamId}/webhooks`, {+ method: "DELETE",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({ webhookId }),+ });++ if (!response.ok) {+ throw new Error("Failed to delete webhook");+ }++ mutate();+ toast.success("Webhook deleted successfully");+ } catch (error) {+ console.error(error);+ toast.error("Failed to delete 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 />++ <div className="rounded-lg border border-gray-200 bg-white">+ <div className="flex flex-col items-center justify-between gap-4 space-y-3 border-b border-gray-200 p-5 sm:flex-row sm:space-y-0 sm:p-10">+ <div className="flex max-w-screen-sm flex-col space-y-3">+ <div className="flex items-center gap-2">+ <h2 className="text-xl font-medium">Incoming Webhooks</h2>+ <BadgeTooltip content="Use webhooks to receive data from external services">+ <CircleHelpIcon className="h-4 w-4 text-gray-500" />+ </BadgeTooltip>+ </div>+ <p className="text-sm text-gray-500">+ Create incoming webhooks to receive data from external services+ and automatically create new documents in Papermark.+ </p>+ </div>+ </div>++ <div className="p-5 sm:p-10">+ <div className="flex flex-col space-y-4">+ <div>+ <Label htmlFor="webhook-name">Webhook Name</Label>+ <Input+ id="webhook-name"+ placeholder="Enter a name for your webhook"+ value={name}+ onChange={(e) => setName(e.target.value)}+ />+ </div>++ {webhookId && (+ <div className="rounded-lg bg-gray-50 p-4">+ <Label>Your Webhook URL (copy it now)</Label>+ <code className="mt-2 block break-all rounded bg-gray-100 p-2 font-mono text-sm">+ {`${process.env.NEXT_PUBLIC_WEBHOOK_BASE_URL}/services/${webhookId}`}+ </code>+ </div>+ )}++ <Button+ onClick={createWebhook}+ disabled={!name || isLoading}+ className="w-fit"+ >+ {isLoading ? "Creating..." : "Create Webhook"}+ </Button>++ {/* Webhooks List */}+ <div className="mt-8">+ <h3 className="mb-4 text-lg font-medium">Existing Webhooks</h3>+ <div className="rounded-lg border border-gray-200">+ {webhooks?.length === 0 ? (+ <div className="p-4 text-center text-sm text-gray-500">+ No webhooks created yet+ </div>+ ) : (+ <div className="divide-y divide-gray-200">+ {webhooks?.map((webhook) => (+ <div+ key={webhook.id}+ className="flex items-center justify-between p-4"+ >+ <div className="space-y-1">+ <p className="font-medium">{webhook.name}</p>+ <div className="flex items-center space-x-2 text-sm text-gray-500">+ <div className="flex items-center gap-2 rounded-md border border-gray-200 bg-gray-50 px-3 py-1.5 font-mono">+ <span className="max-w-[200px] overflow-x-auto whitespace-nowrap md:max-w-[400px]">+ {`${process.env.NEXT_PUBLIC_WEBHOOK_BASE_URL}/services/${webhook.webhookId}`}+ </span>+ <Button+ variant="ghost"+ size="icon"+ className="h-6 w-6"+ onClick={() => {+ navigator.clipboard.writeText(+ `${process.env.NEXT_PUBLIC_WEBHOOK_BASE_URL}/services/${webhook.webhookId}`,+ );+ toast.success(+ "Webhook URL copied to clipboard",+ );+ }}+ >+ <CopyIcon className="h-3 w-3" />+ </Button>+ </div>+ <span>•</span>+ <span>+ {format(+ new Date(webhook.createdAt),+ "MMM d, yyyy",+ )}+ </span>+ </div>+ </div>+ <Button+ variant="destructive"+ size="sm"+ onClick={() => deleteWebhook(webhook.id)}+ >+ Delete+ </Button>+ </div>+ ))}+ </div>+ )}+ </div>+ </div>+ </div>+ </div>+ </div>+ </main>+ </AppLayout>+ );+}diff --git a/prisma/migrations/20241107000000_add_tokens_and_webhooks/migration.sql b/prisma/migrations/20241107000000_add_tokens_and_webhooks/migration.sqlnew file mode 100644index 00000000..84dd0161--- /dev/null+++ b/prisma/migrations/20241107000000_add_tokens_and_webhooks/migration.sql@@ -0,0 +1,60 @@+-- CreateTable+CREATE TABLE "IncomingWebhook" (+ "id" TEXT NOT NULL,+ "externalId" TEXT NOT NULL,+ "name" TEXT NOT NULL,+ "secret" TEXT,+ "source" TEXT,+ "actions" TEXT,+ "consecutiveFailures" INTEGER NOT NULL DEFAULT 0,+ "lastFailedAt" TIMESTAMP(3),+ "disabledAt" TIMESTAMP(3),+ "teamId" TEXT NOT NULL,+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,+ "updatedAt" TIMESTAMP(3) NOT NULL,++ CONSTRAINT "IncomingWebhook_pkey" PRIMARY KEY ("id")+);++-- CreateTable+CREATE TABLE "RestrictedToken" (+ "id" TEXT NOT NULL,+ "name" TEXT NOT NULL,+ "hashedKey" TEXT NOT NULL,+ "partialKey" TEXT NOT NULL,+ "scopes" TEXT,+ "expires" TIMESTAMP(3),+ "lastUsed" TIMESTAMP(3),+ "rateLimit" INTEGER NOT NULL DEFAULT 60,+ "userId" TEXT NOT NULL,+ "teamId" TEXT NOT NULL,+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,+ "updatedAt" TIMESTAMP(3) NOT NULL,++ CONSTRAINT "RestrictedToken_pkey" PRIMARY KEY ("id")+);++-- CreateIndex+CREATE UNIQUE INDEX "IncomingWebhook_externalId_key" ON "IncomingWebhook"("externalId");++-- CreateIndex+CREATE INDEX "IncomingWebhook_teamId_idx" ON "IncomingWebhook"("teamId");++-- CreateIndex+CREATE UNIQUE INDEX "RestrictedToken_hashedKey_key" ON "RestrictedToken"("hashedKey");++-- CreateIndex+CREATE INDEX "RestrictedToken_userId_idx" ON "RestrictedToken"("userId");++-- CreateIndex+CREATE INDEX "RestrictedToken_teamId_idx" ON "RestrictedToken"("teamId");++-- AddForeignKey+ALTER TABLE "IncomingWebhook" ADD CONSTRAINT "IncomingWebhook_teamId_fkey" FOREIGN KEY ("teamId") REFERENCES "Team"("id") ON DELETE CASCADE ON UPDATE CASCADE;++-- AddForeignKey+ALTER TABLE "RestrictedToken" ADD CONSTRAINT "RestrictedToken_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;++-- AddForeignKey+ALTER TABLE "RestrictedToken" ADD CONSTRAINT "RestrictedToken_teamId_fkey" FOREIGN KEY ("teamId") REFERENCES "Team"("id") ON DELETE CASCADE ON UPDATE CASCADE;+diff --git a/prisma/schema.prisma b/prisma/schema.prismaindex b7f08c4c..00b1e240 100644--- a/prisma/schema.prisma+++ b/prisma/schema.prisma@@ -55,6 +55,8 @@ model User {subscriptionId String? @unique // Stripe subscription IDstartsAt DateTime? // Stripe subscription start dateendsAt DateTime? // Stripe subscription end date++ restrictedTokens RestrictedToken[]}model Team {@@ -72,8 +74,8 @@ model Team {viewerGroups ViewerGroup[]viewers Viewer[]- links Link[]- views View[]+ links Link[]+ views View[]plan String @default("free")stripeId String? @unique // Stripe customer ID@@ -85,6 +87,9 @@ model Team {limits Json? // Plan limits // {datarooms: 1, users: 1, domains: 1, customDomainOnPro: boolean, customDomainInDataroom: boolean}+ incomingWebhooks IncomingWebhook[]+ restrictedTokens RestrictedToken[]+createdAt DateTime @default(now())updatedAt DateTime @updatedAt}@@ -639,3 +644,45 @@ enum ItemType {DATAROOM_DOCUMENTDATAROOM_FOLDER}++model IncomingWebhook {+ id String @id @default(cuid())+ externalId String @unique+ name String+ secret String? // Webhook signing secret for verification+ source String? // Allowed source URL/domain+ actions String? // comma separated (Eg: "documents:write,documentVersions:write")+ consecutiveFailures Int @default(0)+ lastFailedAt DateTime?+ disabledAt DateTime?++ teamId String+ team Team @relation(fields: [teamId], references: [id], onDelete: Cascade)++ createdAt DateTime @default(now())+ updatedAt DateTime @updatedAt++ @@index([teamId])+}++model RestrictedToken {+ id String @id @default(cuid())+ name String+ hashedKey String @unique+ partialKey String+ scopes String? // comma separated (Eg: "documents:write,links:write")+ expires DateTime?+ lastUsed DateTime?+ rateLimit Int @default(60) // rate limit per minute++ userId String+ teamId String+ user User @relation(fields: [userId], references: [id], onDelete: Cascade)+ team Team @relation(fields: [teamId], references: [id], onDelete: Cascade)++ createdAt DateTime @default(now())+ updatedAt DateTime @updatedAt++ @@index([userId])+ @@index([teamId])+}