Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
feat: add link indicator and additional validation
Marc Seitz6a622514b24e
diff --git a/components/documents/link-document-indicator.tsx b/components/documents/link-document-indicator.tsxnew file mode 100644index 00000000..51e9de7f--- /dev/null+++ b/components/documents/link-document-indicator.tsx@@ -0,0 +1,213 @@+import { useState } from "react";++import { useTeam } from "@/context/team-context";+import { DocumentVersion } from "@prisma/client";+import { Edit, ExternalLink, LinkIcon } from "lucide-react";+import { toast } from "sonner";++import { Button } from "@/components/ui/button";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+ DialogTrigger,+} from "@/components/ui/dialog";+import { Input } from "@/components/ui/input";+import { Label } from "@/components/ui/label";+import LoadingSpinner from "@/components/ui/loading-spinner";+import { ButtonTooltip } from "@/components/ui/tooltip";++interface LinkDocumentIndicatorProps {+ documentId: string;+ primaryVersion: DocumentVersion;+ onUrlUpdate?: () => void;+}++export default function LinkDocumentIndicator({+ documentId,+ primaryVersion,+ onUrlUpdate,+}: LinkDocumentIndicatorProps) {+ const teamInfo = useTeam();+ const [isMainDialogOpen, setIsMainDialogOpen] = useState(false);+ const [isUrlDialogOpen, setIsUrlDialogOpen] = useState(false);+ const [newUrl, setNewUrl] = useState("");+ const [isUpdating, setIsUpdating] = useState(false);++ const currentUrl = primaryVersion.file;++ const updateLinkUrl = async () => {+ if (!teamInfo?.currentTeam?.id || !newUrl.trim()) return;++ setIsUpdating(true);+ try {+ const response = await fetch(+ `/api/teams/${teamInfo.currentTeam.id}/documents/${documentId}/update-link-url`,+ {+ method: "PATCH",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({ linkUrl: newUrl.trim() }),+ },+ );++ const data = await response.json();++ if (response.ok) {+ toast.success("Link URL updated successfully");+ setIsUrlDialogOpen(false);+ setNewUrl("");+ // Trigger parent component update if provided+ if (onUrlUpdate) {+ onUrlUpdate();+ }+ } else {+ toast.error(data.message || "Failed to update URL");+ }+ } catch (error) {+ console.error("Error updating URL:", error);+ toast.error("Failed to update URL");+ } finally {+ setIsUpdating(false);+ }+ };++ const openLinkInNewTab = () => {+ if (currentUrl) {+ window.open(currentUrl, "_blank");+ }+ };++ const getDisplayUrl = () => {+ try {+ const urlObj = new URL(currentUrl);+ return urlObj.hostname + (urlObj.pathname !== "/" ? urlObj.pathname : "");+ } catch {+ return currentUrl;+ }+ };++ // Only render for link documents+ if (primaryVersion.type !== "link") {+ return null;+ }++ return (+ <>+ {/* Compact Icon Trigger */}+ <Dialog open={isMainDialogOpen} onOpenChange={setIsMainDialogOpen}>+ <ButtonTooltip content="View link details">+ <DialogTrigger asChild>+ <Button+ variant="outline"+ size="default"+ className="h-8 w-8 p-0 lg:h-9 lg:w-9"+ >+ <LinkIcon className="h-4 w-4" />+ </Button>+ </DialogTrigger>+ </ButtonTooltip>++ {/* Main Status Dialog */}+ <DialogContent className="sm:max-w-lg">+ <DialogHeader>+ <DialogTitle>Link Details</DialogTitle>+ <DialogDescription>+ View and manage your external link.+ </DialogDescription>+ </DialogHeader>++ <div className="space-y-4 py-4">+ {/* URL Display */}+ <div className="rounded-lg border p-3">+ <div className="mb-1 text-sm font-medium text-muted-foreground">+ Current URL+ </div>+ <div className="break-all font-mono text-sm">{currentUrl}</div>+ </div>++ {/* Action Buttons */}+ <div className="flex gap-2">+ <Button+ variant="outline"+ size="sm"+ onClick={openLinkInNewTab}+ className="flex-1"+ >+ <ExternalLink className="mr-2 h-4 w-4" />+ Open Link+ </Button>++ <Button+ variant="outline"+ size="sm"+ onClick={() => {+ setNewUrl(currentUrl || "");+ setIsUrlDialogOpen(true);+ }}+ className="flex-1"+ >+ <Edit className="mr-2 h-4 w-4" />+ Edit URL+ </Button>+ </div>+ </div>+ </DialogContent>+ </Dialog>++ {/* URL Edit Dialog */}+ <Dialog open={isUrlDialogOpen} onOpenChange={setIsUrlDialogOpen}>+ <DialogContent className="sm:max-w-md">+ <DialogHeader>+ <DialogTitle>Update Link URL</DialogTitle>+ <DialogDescription>+ Change the URL for this link document.+ </DialogDescription>+ </DialogHeader>+ <div className="grid gap-4 py-4">+ <div className="grid gap-2">+ <Label htmlFor="link-url">Link URL</Label>+ <Input+ id="link-url"+ value={newUrl}+ onChange={(e) => setNewUrl(e.target.value)}+ placeholder="https://example.com/your-link"+ className="w-full"+ />+ <p className="text-xs text-muted-foreground">+ URL must use HTTPS protocol.+ </p>+ </div>+ </div>+ <DialogFooter>+ <Button+ variant="outline"+ onClick={() => setIsUrlDialogOpen(false)}+ disabled={isUpdating}+ >+ Cancel+ </Button>+ <Button+ onClick={updateLinkUrl}+ disabled={isUpdating || !newUrl.trim()}+ >+ {isUpdating ? (+ <>+ <LoadingSpinner className="mr-2 h-4 w-4" />+ Updating...+ </>+ ) : (+ "Update URL"+ )}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ </>+ );+}+diff --git a/lib/zod/url-validation.ts b/lib/zod/url-validation.tsindex fd41303b..d4f6ad4e 100644--- a/lib/zod/url-validation.ts+++ b/lib/zod/url-validation.ts@@ -388,6 +388,23 @@ export const documentUploadSchema = z},);+// Link URL update validation schema+export const linkUrlUpdateSchema = z+ .string()+ .url("Invalid URL format")+ .refine((url) => url.startsWith("https://"), {+ message: "Link URL must use HTTPS",+ })+ .refine(+ (url) => {+ // Security validation including SSRF protection+ return validateUrlSecurity(url);+ },+ {+ message: "URL contains invalid characters or targets internal resources",+ },+ );+// Webhook file URL validator - only allows trusted external sources for webhooksexport const webhookFileUrlSchema = z.string()diff --git a/pages/api/teams/[teamId]/documents/[id]/update-link-url.ts b/pages/api/teams/[teamId]/documents/[id]/update-link-url.tsnew file mode 100644index 00000000..ce12c6d8--- /dev/null+++ b/pages/api/teams/[teamId]/documents/[id]/update-link-url.ts@@ -0,0 +1,119 @@+import { NextApiRequest, NextApiResponse } from "next";++import { authOptions } from "@/pages/api/auth/[...nextauth]";+import { get } from "@vercel/edge-config";+import { getServerSession } from "next-auth/next";++import prisma from "@/lib/prisma";+import { CustomUser } from "@/lib/types";+import { log } from "@/lib/utils";+import { linkUrlUpdateSchema } from "@/lib/zod/url-validation";++export default async function handle(+ req: NextApiRequest,+ res: NextApiResponse,+) {+ if (req.method !== "PATCH") {+ return res.status(405).json({ message: "Method not allowed" });+ }++ const session = await getServerSession(req, res, authOptions);+ if (!session) {+ return res.status(401).json({ message: "Unauthorized" });+ }++ const userId = (session.user as CustomUser).id;+ const { teamId, id: documentId } = req.query as {+ teamId: string;+ id: string;+ };+ const { linkUrl } = req.body as { linkUrl: string };++ const validationResult = await linkUrlUpdateSchema.safeParseAsync(linkUrl);+ if (!validationResult.success) {+ return res.status(400).json({ message: validationResult.error.message });+ }++ const validatedUrl = validationResult.data;++ try {+ const teamAccess = await prisma.userTeam.findUnique({+ where: {+ userId_teamId: {+ userId: userId,+ teamId: teamId,+ },+ },+ });+ if (!teamAccess) {+ return res.status(401).json({ message: "Unauthorized" });+ }++ // Check if document exists+ const document = await prisma.document.findUnique({+ where: {+ id: documentId,+ teamId: teamId,+ },+ select: {+ id: true,+ file: true,+ type: true,+ versions: { select: { id: true, file: true, type: true } },+ },+ });++ if (!document) {+ return res.status(404).json({ message: "Document not found" });+ }++ if (document.type !== "link") {+ return res+ .status(400)+ .json({ message: "Document is not a link document" });+ }++ // Check if URL contains blocked keywords+ const keywords = await get("keywords");+ if (Array.isArray(keywords) && keywords.length > 0) {+ const matchedKeyword = keywords.find(+ (keyword) =>+ typeof keyword === "string" && validatedUrl.includes(keyword),+ );++ if (matchedKeyword) {+ log({+ message: `Link URL update blocked: ${matchedKeyword} \n\n \`Metadata: {teamId: ${teamId}, documentId: ${documentId}, url: ${validatedUrl}}\``,+ type: "error",+ mention: true,+ });+ return res.status(400).json({+ message: "This URL is not allowed",+ matchedKeyword: matchedKeyword,+ });+ }+ }++ // Update document version+ await prisma.document.update({+ where: {+ id: documentId,+ teamId: teamId,+ },+ data: {+ file: validatedUrl.toString(),+ versions: {+ update: {+ where: { id: document.versions[0].id },+ data: { file: validatedUrl.toString() },+ },+ },+ },+ });++ return res.status(200).json({ message: "Link URL updated successfully" });+ } catch (error) {+ console.error("Error updating Link URL:", error);+ return res.status(500).json({ message: "Internal server error" });+ }+}diff --git a/pages/api/teams/[teamId]/documents/index.ts b/pages/api/teams/[teamId]/documents/index.tsindex 232b7f5c..01a0744c 100644--- a/pages/api/teams/[teamId]/documents/index.ts+++ b/pages/api/teams/[teamId]/documents/index.ts@@ -3,6 +3,7 @@ import { NextApiRequest, NextApiResponse } from "next";import { isTeamPausedById } from "@/ee/features/billing/cancellation/lib/is-team-paused";import { authOptions } from "@/pages/api/auth/[...nextauth]";import { Prisma } from "@prisma/client";+import { get } from "@vercel/edge-config";import { getServerSession } from "next-auth/next";import { hashToken } from "@/lib/api/auth/token";@@ -347,6 +348,29 @@ export default async function handle(});}+ // Check if URL contains blocked keywords (for link type documents)+ if (fileType === "link") {+ const keywords = await get("keywords");+ if (Array.isArray(keywords) && keywords.length > 0) {+ const matchedKeyword = keywords.find(+ (keyword) =>+ typeof keyword === "string" && fileUrl.includes(keyword),+ );++ if (matchedKeyword) {+ log({+ message: `Link document creation blocked: ${matchedKeyword} \n\n \`Metadata: {teamId: ${teamId}, url: ${fileUrl}}\``,+ type: "error",+ mention: true,+ });+ return res.status(400).json({+ error: "This URL is not allowed",+ matchedKeyword: matchedKeyword,+ });+ }+ }+ }+// For link documents, storageType is optional but processDocument requires it// Use VERCEL_BLOB as a placeholder (not actually used for links)const finalStorageType =diff --git a/pages/documents/[id]/index.tsx b/pages/documents/[id]/index.tsxindex 154c7133..5586e2d1 100644--- a/pages/documents/[id]/index.tsx+++ b/pages/documents/[id]/index.tsx@@ -16,6 +16,7 @@ import DocumentHeader from "@/components/documents/document-header";import { DocumentPreviewButton } from "@/components/documents/document-preview-button";// Import placeholder componentsimport DocumentStatsPlaceholder from "@/components/documents/document-stats-placeholder";+import LinkDocumentIndicator from "@/components/documents/link-document-indicator";import NotionAccessibilityIndicator from "@/components/documents/notion-accessibility-indicator";import VideoStatsPlaceholder from "@/components/documents/video-stats-placeholder";import AppLayout from "@/components/layouts/app";@@ -159,6 +160,12 @@ export default function DocumentPage() {primaryVersion={primaryVersion}onUrlUpdate={mutateDocument}/>,+ <LinkDocumentIndicator+ key={"link-status"}+ documentId={prismaDocument.id}+ primaryVersion={primaryVersion}+ onUrlUpdate={mutateDocument}+ />,<>{featureFlags?.annotations && (<AnnotationSheet