Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
feat: add embeddable link
Marc Seitzcd40dd93b5c1
diff --git a/app/api/csp-report/route.ts b/app/api/csp-report/route.tsnew file mode 100644index 00000000..adddee66--- /dev/null+++ b/app/api/csp-report/route.ts@@ -0,0 +1,16 @@+import { NextResponse } from "next/server";++export async function POST(request: Request) {+ const report = await request.json();++ // Log the report or send to your logging service+ // console.log("CSP Violation:", report);++ // You could send this to your logging service+ // await fetch('your-logging-service', {+ // method: 'POST',+ // body: JSON.stringify(report)+ // })++ return NextResponse.json({ success: true });+}diff --git a/components/links/embed-code-modal.tsx b/components/links/embed-code-modal.tsxnew file mode 100644index 00000000..06fcc153--- /dev/null+++ b/components/links/embed-code-modal.tsx@@ -0,0 +1,77 @@+import { useState } from "react";++import { Check, Copy } from "lucide-react";+import { toast } from "sonner";++import { Button } from "@/components/ui/button";+import {+ Dialog,+ DialogContent,+ DialogHeader,+ DialogTitle,+} from "@/components/ui/dialog";++interface EmbedCodeModalProps {+ isOpen: boolean;+ setIsOpen: (open: boolean) => void;+ linkId: string;+ linkName: string;+}++export default function EmbedCodeModal({+ isOpen,+ setIsOpen,+ linkId,+ linkName,+}: EmbedCodeModalProps) {+ const [copied, setCopied] = useState(false);++ const embedCode = `<iframe+ src="${process.env.NEXT_PUBLIC_BASE_URL}/view/${linkId}/embed"+ style="width: 100%; height: 100%; border: none; border-radius: 8px;"+ allow="fullscreen"+ loading="lazy">+</iframe>`;++ const copyToClipboard = () => {+ navigator.clipboard.writeText(embedCode);+ toast.success("Embed code copied to clipboard");+ setCopied(true);+ setTimeout(() => setCopied(false), 2000);+ };++ return (+ <Dialog open={isOpen} onOpenChange={setIsOpen}>+ <DialogContent className="sm:max-w-xl">+ <DialogHeader>+ <DialogTitle className="font-normal">+ Embed Code for <span className="font-bold">{linkName}</span>+ </DialogTitle>+ </DialogHeader>+ <div className="space-y-4">+ <div className="relative">+ <pre className="max-h-[200px] overflow-x-auto whitespace-pre-wrap break-all rounded-lg bg-secondary p-4 font-mono text-sm text-secondary-foreground">+ <code className="block w-full pr-8">{embedCode}</code>+ </pre>+ <Button+ size="sm"+ variant="ghost"+ className="absolute right-2 top-2"+ onClick={copyToClipboard}+ >+ {copied ? (+ <Check className="h-4 w-4" />+ ) : (+ <Copy className="h-4 w-4" />+ )}+ </Button>+ </div>+ <p className="text-sm text-muted-foreground">+ Copy and paste this code into your website to embed the document+ link.+ </p>+ </div>+ </DialogContent>+ </Dialog>+ );+}diff --git a/components/links/links-table.tsx b/components/links/links-table.tsxindex 55ab92de..27bd137a 100644--- a/components/links/links-table.tsx+++ b/components/links/links-table.tsx@@ -4,9 +4,18 @@ import { useState } from "react";import { useTeam } from "@/context/team-context";import { DocumentVersion } from "@prisma/client";-import { BoxesIcon, EyeIcon, LinkIcon, Settings2Icon } from "lucide-react";+import {+ ArchiveIcon,+ BoxesIcon,+ Code2Icon,+ CopyIcon,+ CopyPlusIcon,+ EyeIcon,+ LinkIcon,+ Settings2Icon,+} from "lucide-react";import { toast } from "sonner";-import { mutate } from "swr";+import useSWR, { mutate } from "swr";import { UpgradePlanModal } from "@/components/billing/upgrade-plan-modal";import { Button } from "@/components/ui/button";@@ -36,13 +45,14 @@ import {import { usePlan } from "@/lib/swr/use-billing";import useLimits from "@/lib/swr/use-limits";import { LinkWithViews, WatermarkConfig } from "@/lib/types";-import { cn, copyToClipboard, nFormatter, timeAgo } from "@/lib/utils";+import { cn, copyToClipboard, fetcher, nFormatter, timeAgo } from "@/lib/utils";import ProcessStatusBar from "../documents/process-status-bar";import BarChart from "../shared/icons/bar-chart";import ChevronDown from "../shared/icons/chevron-down";import MoreHorizontal from "../shared/icons/more-horizontal";import { ButtonTooltip } from "../ui/tooltip";+import EmbedCodeModal from "./embed-code-modal";import LinkSheet, {DEFAULT_LINK_PROPS,type DEFAULT_LINK_TYPE,@@ -63,12 +73,25 @@ export default function LinksTable({const teamInfo = useTeam();const { canAddLinks } = useLimits();+ const { data: features } = useSWR<{+ embedding: boolean;+ }>(+ teamInfo?.currentTeam?.id+ ? `/api/feature-flags?teamId=${teamInfo.currentTeam.id}`+ : null,+ fetcher,+ );const [isLoading, setIsLoading] = useState<boolean>(false);const [isLinkSheetVisible, setIsLinkSheetVisible] = useState<boolean>(false);const [selectedLink, setSelectedLink] = useState<DEFAULT_LINK_TYPE>(DEFAULT_LINK_PROPS(`${targetType}_LINK`),);+ const [embedModalOpen, setEmbedModalOpen] = useState(false);+ const [selectedEmbedLink, setSelectedEmbedLink] = useState<{+ id: string;+ name: string;+ } | null>(null);const handleCopyToClipboard = (linkString: string) => {copyToClipboard(`${linkString}`, "Link copied to clipboard.");@@ -409,14 +432,32 @@ export default function LinksTable({<DropdownMenuItemonClick={() => handleEditLink(link)}>+ <Settings2Icon className="mr-2 h-4 w-4" />Edit Link</DropdownMenuItem><DropdownMenuItemdisabled={!canAddLinks}onClick={() => handleDuplicateLink(link)}>+ <CopyPlusIcon className="mr-2 h-4 w-4" />Duplicate Link</DropdownMenuItem>+ {features?.embedding ? (+ <DropdownMenuItem+ onClick={() => {+ setSelectedEmbedLink({+ id: link.id,+ name:+ link.name ||+ `Link #${link.id.slice(-5)}`,+ });+ setEmbedModalOpen(true);+ }}+ >+ <Code2Icon className="mr-2 h-4 w-4" />+ Get Embed Code+ </DropdownMenuItem>+ ) : null}<DropdownMenuItemclassName="text-destructive focus:bg-destructive focus:text-destructive-foreground"onClick={() =>@@ -427,6 +468,7 @@ export default function LinksTable({)}>+ <ArchiveIcon className="mr-2 h-4 w-4" />Archive</DropdownMenuItem></DropdownMenuContent>@@ -473,6 +515,15 @@ export default function LinksTable({existingLinks={links}/>+ {selectedEmbedLink && (+ <EmbedCodeModal+ isOpen={embedModalOpen}+ setIsOpen={setEmbedModalOpen}+ linkId={selectedEmbedLink.id}+ linkName={selectedEmbedLink.name}+ />+ )}+{archivedLinksCount > 0 && (<Collapsible asChild><>diff --git a/components/view/dataroom/dataroom-view.tsx b/components/view/dataroom/dataroom-view.tsxindex e8799fae..ea2c3aef 100644--- a/components/view/dataroom/dataroom-view.tsx+++ b/components/view/dataroom/dataroom-view.tsx@@ -91,6 +91,7 @@ export default function DataroomView({previewToken,disableEditEmail,useCustomAccessForm,+ isEmbedded,}: {link: LinkWithDataroom;userEmail: string | null | undefined;@@ -103,6 +104,7 @@ export default function DataroomView({previewToken?: string;disableEditEmail?: boolean;useCustomAccessForm?: boolean;+ isEmbedded?: boolean;}) {const {linkType,@@ -201,6 +203,7 @@ export default function DataroomView({linkType: linkType,viewerId: viewId,viewerEmail: data.email ?? verifiedEmail ?? userEmail,+ isEmbedded,});// set the verification token to the cookiediff --git a/components/view/document-view.tsx b/components/view/document-view.tsxindex 7e96a85a..e1993e9a 100644--- a/components/view/document-view.tsx+++ b/components/view/document-view.tsx@@ -61,6 +61,7 @@ export default function DocumentView({previewToken,disableEditEmail,useCustomAccessForm,+ isEmbedded,}: {link: LinkWithDocument;userEmail: string | null | undefined;@@ -80,6 +81,7 @@ export default function DocumentView({previewToken?: string;disableEditEmail?: boolean;useCustomAccessForm?: boolean;+ isEmbedded?: boolean;}) {const {document,@@ -161,6 +163,7 @@ export default function DocumentView({linkType: "DOCUMENT_LINK",viewerId: viewId,viewerEmail: data.email ?? verifiedEmail ?? userEmail,+ isEmbedded,});// set the verification token to the cookiediff --git a/lib/featureFlags/index.ts b/lib/featureFlags/index.tsindex d08f2248..df9506cd 100644--- a/lib/featureFlags/index.ts+++ b/lib/featureFlags/index.ts@@ -1,6 +1,10 @@import { get } from "@vercel/edge-config";-export type BetaFeatures = "tokens" | "webhooks" | "roomChangeNotifications";+export type BetaFeatures =+ | "tokens"+ | "webhooks"+ | "roomChangeNotifications"+ | "embedding";type BetaFeaturesRecord = Record<BetaFeatures, string[]>;export const getFeatureFlags = async ({ teamId }: { teamId?: string }) => {@@ -8,6 +12,7 @@ export const getFeatureFlags = async ({ teamId }: { teamId?: string }) => {tokens: false,webhooks: false,roomChangeNotifications: false,+ embedding: false,};// Return all features as true if edge config is not availablediff --git a/next.config.mjs b/next.config.mjsindex 5625d216..059b58eb 100644--- a/next.config.mjs+++ b/next.config.mjs@@ -28,8 +28,11 @@ const nextConfig = {];},async headers() {+ const isDev = process.env.NODE_ENV === "development";+return [{+ // Default headers for all routessource: "/:path*",headers: [{@@ -44,6 +47,27 @@ const nextConfig = {key: "X-Frame-Options",value: "SAMEORIGIN",},+ {+ key: "Report-To",+ value: JSON.stringify({+ group: "csp-endpoint",+ max_age: 10886400,+ endpoints: [{ url: "/api/csp-report" }],+ }),+ },+ {+ key: "Content-Security-Policy-Report-Only",+ value:+ `default-src 'self' https: ${isDev ? "http:" : ""}; ` ++ `script-src 'self' 'unsafe-inline' 'unsafe-eval' https: ${isDev ? "http:" : ""}; ` ++ `style-src 'self' 'unsafe-inline' https: ${isDev ? "http:" : ""}; ` ++ `img-src 'self' data: blob: https: ${isDev ? "http:" : ""}; ` ++ `font-src 'self' data: https: ${isDev ? "http:" : ""}; ` ++ `frame-ancestors 'none'; ` ++ `connect-src 'self' https: ${isDev ? "http: ws: wss:" : ""}; ` + // Add WebSocket for hot reload+ `${isDev ? "" : "upgrade-insecure-requests;"} ` ++ "report-to csp-endpoint;",+ },],},{@@ -55,6 +79,28 @@ const nextConfig = {},],},+ {+ // Embed routes - allow iframe embedding+ source: "/view/:path*/embed",+ headers: [+ {+ key: "Content-Security-Policy",+ value:+ `default-src 'self' https: ${isDev ? "http:" : ""}; ` ++ `script-src 'self' 'unsafe-inline' 'unsafe-eval' https: ${isDev ? "http:" : ""}; ` ++ `style-src 'self' 'unsafe-inline' https: ${isDev ? "http:" : ""}; ` ++ `img-src 'self' data: blob: https: ${isDev ? "http:" : ""}; ` ++ `font-src 'self' data: https: ${isDev ? "http:" : ""}; ` ++ "frame-ancestors *; " + // This allows iframe embedding+ `connect-src 'self' https: ${isDev ? "http: ws: wss:" : ""}; ` + // Add WebSocket for hot reload+ `${isDev ? "" : "upgrade-insecure-requests;"}`,+ },+ {+ key: "X-Robots-Tag",+ value: "noindex",+ },+ ],+ },{source: "/services/:path*",has: [diff --git a/pages/view/[linkId]/embed.tsx b/pages/view/[linkId]/embed.tsxnew file mode 100644index 00000000..c2cc6710--- /dev/null+++ b/pages/view/[linkId]/embed.tsx@@ -0,0 +1,180 @@+import { useRouter } from "next/router";++import { useEffect, useState } from "react";++import NotFound from "@/pages/404";++import LoadingSpinner from "@/components/ui/loading-spinner";+import DataroomView from "@/components/view/dataroom/dataroom-view";+import DocumentView from "@/components/view/document-view";++import { useAnalytics } from "@/lib/analytics";++import { ViewPageProps } from "./index";++// Reuse the same getStaticProps and getStaticPaths from the main view page+export { getStaticProps, getStaticPaths } from "./index";++export default function EmbedPage(props: ViewPageProps) {+ const router = useRouter();+ const [isEmbedded, setIsEmbedded] = useState<boolean | null>(null);+ const analytics = useAnalytics();++ useEffect(() => {+ // Only run when router is ready and linkId is present+ if (!router.isReady || !router.query.linkId) return;++ // Check if the page is embedded in an iframe+ const isInIframe = window !== window.parent;+ setIsEmbedded(isInIframe);++ if (isInIframe) {+ document.body.classList.add("embed-view");++ // Track embed view with referrer information+ const referrer = document.referrer;+ const embedSource = referrer ? new URL(referrer).hostname : "direct";++ analytics.capture("Embedded Link Loaded", {+ linkId: router.query.linkId as string,+ embedSource,+ url: referrer || "unknown",+ userAgent: window.navigator.userAgent,+ });++ return () => document.body.classList.remove("embed-view");+ }+ }, [router.isReady, router.query.linkId]);++ // Show loading state while checking+ if (isEmbedded === null || router.isFallback) {+ return (+ <div className="flex h-screen items-center justify-center">+ <LoadingSpinner className="h-20 w-20" />+ </div>+ );+ }++ // Block direct access+ if (!isEmbedded) {+ return (+ <NotFound message="This page can only be accessed when embedded in another website." />+ );+ }++ const {+ email: verifiedEmail,+ d: disableEditEmail,+ previewToken,+ } = router.query as {+ email: string;+ d: string;+ previewToken?: string;+ };+ const { linkType, link, brand } = props.linkData;++ // Render the document view for DOCUMENT_LINK+ if (linkType === "DOCUMENT_LINK") {+ if (!props.linkData || router.isFallback) {+ return (+ <div className="flex h-screen items-center justify-center">+ <LoadingSpinner className="h-20 w-20" />+ </div>+ );+ }++ const {+ expiresAt,+ emailProtected,+ emailAuthenticated,+ password: linkPassword,+ enableAgreement,+ isArchived,+ } = link;++ // If the link is expired, show a 404 page+ if (expiresAt && new Date(expiresAt) < new Date()) {+ return (+ <NotFound message="Sorry, the link you're looking for is expired." />+ );+ }++ if (isArchived) {+ return (+ <NotFound message="Sorry, the link you're looking for is archived." />+ );+ }++ return (+ <div className="h-screen w-full overflow-hidden">+ <DocumentView+ link={link}+ userEmail={verifiedEmail}+ userId={null}+ isProtected={!!(emailProtected || linkPassword || enableAgreement)}+ notionData={props.notionData}+ brand={brand}+ showPoweredByBanner={props.showPoweredByBanner}+ showAccountCreationSlide={props.showAccountCreationSlide}+ useAdvancedExcelViewer={props.useAdvancedExcelViewer}+ previewToken={previewToken}+ disableEditEmail={!!disableEditEmail}+ useCustomAccessForm={props.useCustomAccessForm}+ verifiedEmail={verifiedEmail}+ isEmbedded+ />+ </div>+ );+ }++ // Render the dataroom view for DATAROOM_LINK+ if (linkType === "DATAROOM_LINK") {+ if (!link || router.isFallback) {+ return (+ <div className="flex h-screen items-center justify-center">+ <LoadingSpinner className="h-20 w-20" />+ </div>+ );+ }++ const {+ expiresAt,+ emailProtected,+ emailAuthenticated,+ password: linkPassword,+ enableAgreement,+ isArchived,+ } = link;++ // If the link is expired, show a 404 page+ if (expiresAt && new Date(expiresAt) < new Date()) {+ return (+ <NotFound message="Sorry, the link you're looking for is expired." />+ );+ }++ if (isArchived) {+ return (+ <NotFound message="Sorry, the link you're looking for is archived." />+ );+ }++ return (+ <div className="h-screen w-full overflow-hidden">+ <DataroomView+ link={link}+ userEmail={verifiedEmail}+ userId={null}+ isProtected={!!(emailProtected || linkPassword || enableAgreement)}+ brand={brand}+ useAdvancedExcelViewer={props.useAdvancedExcelViewer}+ previewToken={previewToken}+ disableEditEmail={!!disableEditEmail}+ useCustomAccessForm={props.useCustomAccessForm}+ verifiedEmail={verifiedEmail}+ isEmbedded+ />+ </div>+ );+ }+}diff --git a/pages/view/[linkId]/index.tsx b/pages/view/[linkId]/index.tsxindex 7b210d49..7412588d 100644--- a/pages/view/[linkId]/index.tsx+++ b/pages/view/[linkId]/index.tsx@@ -35,6 +35,27 @@ type DataroomLinkData = {brand: DataroomBrand | null;};+export interface ViewPageProps {+ linkData: DocumentLinkData | DataroomLinkData;+ notionData: {+ rootNotionPageId: string | null;+ recordMap: ExtendedRecordMap | null;+ theme: NotionTheme | null;+ };+ meta: {+ enableCustomMetatag: boolean;+ metaTitle: string | null;+ metaDescription: string | null;+ metaImage: string | null;+ metaUrl: string | null;+ metaFavicon: string | null;+ };+ showPoweredByBanner: boolean;+ showAccountCreationSlide: boolean;+ useAdvancedExcelViewer: boolean;+ useCustomAccessForm: boolean;+}+export const getStaticProps = async (context: GetStaticPropsContext) => {const { linkId } = context.params as { linkId: string };@@ -190,26 +211,7 @@ export default function ViewPage({showAccountCreationSlide,useAdvancedExcelViewer,useCustomAccessForm,-}: {- linkData: DocumentLinkData | DataroomLinkData;- notionData: {- rootNotionPageId: string | null;- recordMap: ExtendedRecordMap | null;- theme: NotionTheme | null;- };- meta: {- enableCustomMetatag: boolean;- metaTitle: string | null;- metaDescription: string | null;- metaImage: string | null;- metaUrl: string | null;- metaFavicon: string | null;- };- showPoweredByBanner: boolean;- showAccountCreationSlide: boolean;- useAdvancedExcelViewer: boolean;- useCustomAccessForm: boolean;-}) {+}: ViewPageProps) {const router = useRouter();const { data: session, status } = useSession();const [storedToken, setStoredToken] = useState<string | undefined>(undefined);