Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
feat: iframe embeddable custom links d0a9
Marc Seitz99a3b636a0e7
diff --git a/app/api/views-dataroom/route.ts b/app/api/views-dataroom/route.tsindex 7a33977d..8bdfc2d6 100644--- a/app/api/views-dataroom/route.ts+++ b/app/api/views-dataroom/route.ts@@ -16,6 +16,7 @@ import {} from "@/lib/auth/dataroom-auth";import { verifyDataroomSession } from "@/lib/auth/dataroom-auth";import { PreviewSession, verifyPreviewSession } from "@/lib/auth/preview-auth";+import { isEmbeddableUrl } from "@/lib/edge-config/embeddable-domains";import { sendOtpVerificationEmail } from "@/lib/emails/send-email-otp-verification";import { getFile } from "@/lib/files/get-file";import { newId } from "@/lib/id-helper";@@ -1068,6 +1069,11 @@ export async function POST(request: NextRequest) {}}+ const isLinkType = documentVersion?.type === "link";+ const isEmbeddable = isLinkType+ ? await isEmbeddableUrl(documentVersion?.file)+ : false;+const returnObject = {message: "View recorded",viewId: !isPreview && newView ? newView.id : undefined,@@ -1119,6 +1125,7 @@ export async function POST(request: NextRequest) {agentsEnabled: link.dataroom?.agentsEnabled ?? false,dataroomName: link.dataroom?.name,...(isTeamMember && { isTeamMember: true }),+ ...(isEmbeddable && { isEmbeddable: true }),};const response = NextResponse.json(returnObject, { status: 200 });diff --git a/app/api/views/route.ts b/app/api/views/route.tsindex dad410a5..ab5c1aa9 100644--- a/app/api/views/route.ts+++ b/app/api/views/route.ts@@ -10,6 +10,7 @@ import { getServerSession } from "next-auth";import { hashToken } from "@/lib/api/auth/token";import { verifyPreviewSession } from "@/lib/auth/preview-auth";import { PreviewSession } from "@/lib/auth/preview-auth";+import { isEmbeddableUrl } from "@/lib/edge-config/embeddable-domains";import { sendOtpVerificationEmail } from "@/lib/emails/send-email-otp-verification";import { getFeatureFlags } from "@/lib/featureFlags";import { getFile } from "@/lib/files/get-file";@@ -729,6 +730,11 @@ export async function POST(request: NextRequest) {const agentsEnabled =link.team?.agentsEnabled && link.document?.agentsEnabled;+ const isLinkType = documentVersion?.type === "link";+ const isEmbeddable = isLinkType+ ? await isEmbeddableUrl(documentVersion?.file)+ : false;+const returnObject = {message: "View recorded",viewId: !isPreview && newView ? newView.id : undefined,@@ -772,6 +778,7 @@ export async function POST(request: NextRequest) {verificationToken: hashedVerificationToken ?? undefined,...(isTeamMember && { isTeamMember: true }),...(agentsEnabled && { agentsEnabled: true }),+ ...(isEmbeddable && { isEmbeddable: true }),};return NextResponse.json(returnObject);diff --git a/components/view/dataroom/dataroom-document-view.tsx b/components/view/dataroom/dataroom-document-view.tsxindex 911a16ec..e7bea68f 100644--- a/components/view/dataroom/dataroom-document-view.tsx+++ b/components/view/dataroom/dataroom-document-view.tsx@@ -65,6 +65,7 @@ export type DEFAULT_DATAROOM_DOCUMENT_VIEW_TYPE = {conversationsEnabled?: boolean;isTeamMember?: boolean;agentsEnabled?: boolean;+ isEmbeddable?: boolean;dataroomName?: string;};@@ -198,6 +199,7 @@ export default function DataroomDocumentView({conversationsEnabled,isTeamMember,agentsEnabled,+ isEmbeddable,dataroomName,} = fetchData as DEFAULT_DATAROOM_DOCUMENT_VIEW_TYPE;analytics.identify(@@ -244,6 +246,7 @@ export default function DataroomDocumentView({conversationsEnabled,isTeamMember,agentsEnabled,+ isEmbeddable,dataroomName,}));setSubmitted(true);diff --git a/components/view/document-view.tsx b/components/view/document-view.tsxindex c7620ef5..58ccd323 100644--- a/components/view/document-view.tsx+++ b/components/view/document-view.tsx@@ -51,6 +51,7 @@ export type DEFAULT_DOCUMENT_VIEW_TYPE = {verificationToken?: string;isTeamMember?: boolean;agentsEnabled?: boolean;+ isEmbeddable?: boolean;viewerId?: string;};@@ -176,6 +177,7 @@ export default function DocumentView({ipAddress,verificationToken,agentsEnabled,+ isEmbeddable,isTeamMember,viewerId,} = fetchData as DEFAULT_DOCUMENT_VIEW_TYPE;@@ -215,6 +217,7 @@ export default function DocumentView({ipAddress,isTeamMember,agentsEnabled,+ isEmbeddable,viewerId,});setSubmitted(true);diff --git a/components/view/link-preview.tsx b/components/view/link-preview.tsxindex dba29282..c91b222b 100644--- a/components/view/link-preview.tsx+++ b/components/view/link-preview.tsx@@ -1,6 +1,6 @@import { useRouter } from "next/router";-import { useEffect, useMemo, useRef } from "react";+import { useEffect, useMemo, useRef, useState } from "react";import { ExternalLink } from "lucide-react";@@ -8,6 +8,7 @@ import { useSafePageViewTracker } from "@/lib/tracking/safe-page-view-tracker";import { getTrackingOptions } from "@/lib/tracking/tracking-config";import { Button } from "@/components/ui/button";+import LoadingSpinner from "@/components/ui/loading-spinner";import Nav, { TNavData } from "./nav";import { AwayPoster } from "./viewer/away-poster";@@ -17,6 +18,13 @@ interface LinkPreviewProps {linkName: string;navData: TNavData;versionNumber: number;+ /**+ * When true, the URL has been validated server-side against the+ * Edge-Config-backed allowlist and may be rendered directly inside a+ * sandboxed iframe. Trusting this flag is safe because it can only be set+ * by the views API after consulting the allowlist.+ */+ isEmbeddable?: boolean;}export default function LinkPreview({@@ -24,10 +32,12 @@ export default function LinkPreview({linkName,navData,versionNumber,+ isEmbeddable = false,}: LinkPreviewProps) {const router = useRouter();const startTimeRef = useRef(Date.now());const visibilityRef = useRef<boolean>(true);+ const [iframeLoaded, setIframeLoaded] = useState<boolean>(false);const domain = useMemo(() => {if (!linkUrl) return "";@@ -230,6 +240,75 @@ export default function LinkPreview({return;};+ if (isEmbeddable && linkUrl) {+ return (+ <>+ <Nav pageNumber={1} numPages={1} navData={navData} />+ <div+ style={{ height: "calc(100dvh - 64px)" }}+ className="relative flex flex-col bg-gray-50 dark:bg-gray-900"+ >+ {!iframeLoaded && (+ <div+ className="absolute inset-0 z-10 flex items-center justify-center bg-gray-50 dark:bg-gray-900"+ aria-hidden="true"+ >+ <LoadingSpinner className="h-10 w-10 text-gray-500 dark:text-gray-400" />+ </div>+ )}+ <iframe+ src={linkUrl}+ title={linkName || domain || "Embedded content"}+ onLoad={() => setIframeLoaded(true)}+ className="h-full w-full border-0"+ // Permissions Policy: deny everything not required for a passive+ // viewer. We intentionally do not grant camera, microphone,+ // geolocation, clipboard, payment, USB, MIDI, etc. — even+ // allowlisted hosts shouldn't be able to access these from+ // inside Papermark without an explicit opt-in.+ allow="fullscreen 'self'"+ allowFullScreen+ // Send no referrer so the embedded host cannot learn anything+ // about the Papermark viewer URL (link id, document id, query+ // params, etc.).+ referrerPolicy="no-referrer"+ // Sandbox the frame to the minimum capabilities required to+ // render an interactive embed:+ // - allow-scripts: required to actually run the embed.+ // - allow-same-origin: required so the embed can read its+ // own cookies / storage on the host's origin (without it,+ // XHR, fetch and storage all break).+ // - allow-forms: lets users submit forms (e.g. login on the+ // embedded host).+ // - allow-popups: a click on a link inside the embed may+ // open a new tab (e.g. external help links).+ // Notably omitted (each of these expand the blast radius):+ // - allow-top-navigation*: prevents the embed from+ // navigating Papermark's top-level window away.+ // - allow-popups-to-escape-sandbox: any popup the embed+ // opens inherits the sandbox restrictions instead of+ // becoming an unrestricted window.+ // - allow-modals: blocks alert/confirm/prompt and other+ // modal hijacks.+ // - allow-downloads: block drive-by downloads from the+ // embedded origin.+ // - allow-presentation, allow-pointer-lock,+ // allow-orientation-lock: not needed and easy to abuse.+ // - allow-storage-access-by-user-activation: keep the+ // embed's cookie scope strictly first-party.+ sandbox="allow-scripts allow-same-origin allow-forms allow-popups"+ loading="lazy"+ />+ </div>+ <AwayPoster+ isVisible={isInactive}+ inactivityThreshold={trackingOptions.inactivityThreshold}+ onDismiss={updateActivity}+ />+ </>+ );+ }+return (<><Nav pageNumber={1} numPages={1} navData={navData} />diff --git a/components/view/view-data.tsx b/components/view/view-data.tsxindex d186fc34..5a1f7b5c 100644--- a/components/view/view-data.tsx+++ b/components/view/view-data.tsx@@ -183,6 +183,7 @@ export default function ViewData({linkUrl={viewData.file || document.versions[0]?.file || ""}linkName={document.name}versionNumber={document.versions[0]?.versionNumber || 1}+ isEmbeddable={viewData.isEmbeddable ?? false}navData={navData}/>) : document.downloadOnly ? (diff --git a/lib/edge-config/embeddable-domains.ts b/lib/edge-config/embeddable-domains.tsnew file mode 100644index 00000000..0b9fa4b0--- /dev/null+++ b/lib/edge-config/embeddable-domains.ts@@ -0,0 +1,67 @@+import { get } from "@vercel/edge-config";++/**+ * Allowlist of hostnames stored in Edge Config under the `embeddableDomains`+ * key as an array of plain strings. The list is intentionally kept out of the+ * codebase so that hosts can be added or removed without a deploy.+ *+ * Each entry is matched against the URL hostname (case-insensitive). Entries+ * beginning with a dot are treated as suffix matches (e.g. `.example.com`+ * matches `app.example.com` but not `example.com`). All other entries+ * require an exact hostname match.+ */++const isNonEmptyString = (value: unknown): value is string =>+ typeof value === "string" && value.length > 0;++const matchesHost = (hostname: string, host: string): boolean => {+ const normalizedHostname = hostname.toLowerCase();+ const normalizedHost = host.toLowerCase();++ if (normalizedHost.startsWith(".")) {+ return normalizedHostname.endsWith(normalizedHost);+ }++ return normalizedHostname === normalizedHost;+};++/**+ * Reads the embeddable-domains allowlist from Edge Config. Returns an empty+ * array (i.e. nothing is embeddable) when Edge Config is not configured or+ * the key is missing/malformed.+ */+export const getEmbeddableDomains = async (): Promise<string[]> => {+ if (!process.env.EDGE_CONFIG) return [];++ try {+ const result = await get("embeddableDomains");+ if (!Array.isArray(result)) return [];+ return result.filter(isNonEmptyString);+ } catch {+ return [];+ }+};++/**+ * Returns true when the supplied URL is HTTPS and its hostname is on the+ * Edge-Config-backed allowlist.+ */+export const isEmbeddableUrl = async (+ url: string | null | undefined,+): Promise<boolean> => {+ if (!url) return false;++ let parsed: URL;+ try {+ parsed = new URL(url);+ } catch {+ return false;+ }++ if (parsed.protocol !== "https:") return false;++ const allowlist = await getEmbeddableDomains();+ if (allowlist.length === 0) return false;++ return allowlist.some((host) => matchesHost(parsed.hostname, host));+};