Skip to content

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

feat(embed): support custom-domain embeds so downloads work first-party

Marc Seitz0d6ba0df5910
diff --git a/app/api/views/route.ts b/app/api/views/route.ts
index 7e436fae..029cccb8 100644
--- a/app/api/views/route.ts
+++ b/app/api/views/route.ts
@@ -11,7 +11,10 @@ import {
collectFingerprintHeaders,
generateSessionFingerprint,
} from "@/lib/auth/dataroom-auth";
-import { createLinkSession } from "@/lib/auth/link-session";
+import {
+ createLinkSession,
+ getLinkSessionCookieName,
+} from "@/lib/auth/link-session";
import { verifyPreviewSession } from "@/lib/auth/preview-auth";
import { PreviewSession } from "@/lib/auth/preview-auth";
import { isEmbeddableUrl } from "@/lib/edge-config/embeddable-domains";
@@ -985,7 +988,7 @@ export async function POST(request: NextRequest) {
fingerprint,
);
- response.cookies.set(`pm_ls_${linkId}`, sessionToken, {
+ response.cookies.set(getLinkSessionCookieName(linkId), sessionToken, {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "lax",
diff --git a/components/links/embed-code-modal.tsx b/components/links/embed-code-modal.tsx
index 06fcc153..f59f6acd 100644
--- a/components/links/embed-code-modal.tsx
+++ b/components/links/embed-code-modal.tsx
@@ -3,6 +3,8 @@ import { useState } from "react";
import { Check, Copy } from "lucide-react";
import { toast } from "sonner";
+import { getEmbedUrl } from "@/lib/utils/embed";
+
import { Button } from "@/components/ui/button";
import {
Dialog,
@@ -16,6 +18,8 @@ interface EmbedCodeModalProps {
setIsOpen: (open: boolean) => void;
linkId: string;
linkName: string;
+ domain?: string | null;
+ slug?: string | null;
}
export default function EmbedCodeModal({
@@ -23,11 +27,13 @@ export default function EmbedCodeModal({
setIsOpen,
linkId,
linkName,
+ domain,
+ slug,
}: EmbedCodeModalProps) {
const [copied, setCopied] = useState(false);
const embedCode = `<iframe
- src="${process.env.NEXT_PUBLIC_BASE_URL}/view/${linkId}/embed"
+ src="${getEmbedUrl({ linkId, domain, slug })}"
style="width: 100%; height: 100%; border: none; border-radius: 8px;"
allow="fullscreen"
loading="lazy">
diff --git a/components/links/links-table.tsx b/components/links/links-table.tsx
index e7e210dd..23a83cb4 100644
--- a/components/links/links-table.tsx
+++ b/components/links/links-table.tsx
@@ -366,6 +366,8 @@ export default function LinksTable({
const [selectedEmbedLink, setSelectedEmbedLink] = useState<{
id: string;
name: string;
+ domain?: string | null;
+ slug?: string | null;
} | null>(null);
const [popoverOpen, setPopoverOpen] = useState<string | null>(null);
const hoverTimeout = useRef<NodeJS.Timeout | null>(null);
@@ -1096,6 +1098,10 @@ export default function LinksTable({
setSelectedEmbedLink({
id: link.id,
name: link.name || `Link #${link.id.slice(-5)}`,
+ domain: link.domainId
+ ? link.domainSlug
+ : null,
+ slug: link.domainId ? link.slug : null,
});
setEmbedModalOpen(true);
}}
@@ -1256,6 +1262,8 @@ export default function LinksTable({
setIsOpen={setEmbedModalOpen}
linkId={selectedEmbedLink.id}
linkName={selectedEmbedLink.name}
+ domain={selectedEmbedLink.domain}
+ slug={selectedEmbedLink.slug}
/>
)}
diff --git a/lib/auth/link-session-cookie.ts b/lib/auth/link-session-cookie.ts
new file mode 100644
index 00000000..ef3433e1
--- /dev/null
+++ b/lib/auth/link-session-cookie.ts
@@ -0,0 +1,3 @@
+export function getLinkSessionCookieName(linkId: string): string {
+ return `pm_ls_${linkId}`;
+}
diff --git a/lib/auth/link-session.ts b/lib/auth/link-session.ts
index 07cdbe18..b5b36bb1 100644
--- a/lib/auth/link-session.ts
+++ b/lib/auth/link-session.ts
@@ -15,6 +15,9 @@ import { redis } from "@/lib/redis";
const COOKIE_EXPIRATION_TIME = 23 * 60 * 60 * 1000; // 23 hours
+export { getLinkSessionCookieName } from "@/lib/auth/link-session-cookie";
+import { getLinkSessionCookieName } from "@/lib/auth/link-session-cookie";
+
export const LinkSessionSchema = z.object({
linkId: z.string(),
documentId: z.string().optional(),
@@ -179,7 +182,7 @@ export async function verifyLinkSession(
request: NextRequest,
linkId: string,
): Promise<LinkSession | null> {
- const sessionToken = cookies().get(`pm_ls_${linkId}`)?.value;
+ const sessionToken = cookies().get(getLinkSessionCookieName(linkId))?.value;
const fingerprint = generateSessionFingerprint(
collectFingerprintHeaders(request.headers),
);
@@ -192,7 +195,9 @@ export async function verifyLinkSessionInPagesRouter(
req: NextApiRequest,
linkId: string,
): Promise<LinkSession | null> {
- const sessionToken = parse(req.headers.cookie || "")[`pm_ls_${linkId}`];
+ const sessionToken = parse(req.headers.cookie || "")[
+ getLinkSessionCookieName(linkId)
+ ];
const fingerprint = getFingerprintFromPagesRequest(req);
const userAgent =
(Array.isArray(req.headers["user-agent"])
@@ -213,7 +218,7 @@ async function deleteLinkSession(
}
export async function revokeLinkSession(linkId: string): Promise<void> {
- const sessionToken = cookies().get(`pm_ls_${linkId}`)?.value;
+ const sessionToken = cookies().get(getLinkSessionCookieName(linkId))?.value;
if (sessionToken) {
const session = await redis.get(`link_session:${sessionToken}`);
if (session) {
diff --git a/lib/middleware/domain.ts b/lib/middleware/domain.ts
index c2434070..463844ad 100644
--- a/lib/middleware/domain.ts
+++ b/lib/middleware/domain.ts
@@ -34,11 +34,18 @@ export default async function DomainMiddleware(req: NextRequest) {
// Rewrite to the pages/view/domains/[domain]/[slug] route
url.pathname = `/view/domains/${host}${path}`;
- return NextResponse.rewrite(url, {
- headers: {
- "X-Robots-Tag": "noindex",
- "X-Powered-By":
- "Papermark - Secure Data Room Infrastructure for the modern web",
- },
- });
+ const headers: Record<string, string> = {
+ "X-Robots-Tag": "noindex",
+ "X-Powered-By":
+ "Papermark - Secure Data Room Infrastructure for the modern web",
+ };
+
+ // Allow custom-domain embeds to be framed from any host, matching the
+ // papermark.com `/view/:path*/embed` behavior. next.config `headers()` match
+ // the external path (`/{slug}/embed`), so the framing header is set here.
+ if (path.endsWith("/embed")) {
+ headers["Content-Security-Policy"] = "frame-ancestors *;";
+ }
+
+ return NextResponse.rewrite(url, { headers });
}
diff --git a/lib/utils/embed.ts b/lib/utils/embed.ts
new file mode 100644
index 00000000..b96d2df6
--- /dev/null
+++ b/lib/utils/embed.ts
@@ -0,0 +1,19 @@
+// Custom-domain embeds are served from the customer's domain so the iframe is
+// first-party relative to a host app on the same root domain, letting the
+// session cookie flow. Falls back to the default papermark URL otherwise.
+export function getEmbedUrl({
+ linkId,
+ domain,
+ slug,
+ baseUrl = process.env.NEXT_PUBLIC_BASE_URL,
+}: {
+ linkId: string;
+ domain?: string | null;
+ slug?: string | null;
+ baseUrl?: string;
+}): string {
+ if (domain && slug) {
+ return `https://${domain}/${slug}/embed`;
+ }
+ return `${baseUrl}/view/${linkId}/embed`;
+}
diff --git a/pages/view/domains/[domain]/[slug]/embed.tsx b/pages/view/domains/[domain]/[slug]/embed.tsx
new file mode 100644
index 00000000..93957a8c
--- /dev/null
+++ b/pages/view/domains/[domain]/[slug]/embed.tsx
@@ -0,0 +1,233 @@
+import { useRouter } from "next/router";
+
+import { useEffect, useState } from "react";
+
+import NotFound from "@/pages/404";
+import { Brand, DataroomBrand } from "@prisma/client";
+
+import { useAnalytics } from "@/lib/analytics";
+import { type ViewerI18nPageProps } from "@/lib/i18n/viewer-page-props";
+import { LinkWithDataroom, LinkWithDocument } from "@/lib/types";
+
+import LoadingSpinner from "@/components/ui/loading-spinner";
+import DataroomView from "@/components/view/dataroom/dataroom-view";
+import DocumentView from "@/components/view/document-view";
+import { ViewerI18nProvider } from "@/components/view/viewer-i18n-provider";
+
+// Reuse the same getStaticProps and getStaticPaths from the main domain view page
+export { getStaticProps, getStaticPaths } from "./index";
+
+type DocumentLinkData = {
+ linkType: "DOCUMENT_LINK";
+ link: LinkWithDocument;
+ brand: Brand | null;
+};
+
+type DataroomLinkData = {
+ linkType: "DATAROOM_LINK";
+ link: LinkWithDataroom;
+ brand: DataroomBrand | null;
+};
+
+type DomainEmbedPageProps = Partial<ViewerI18nPageProps> & {
+ frozen?: boolean;
+ error?: boolean;
+ linkData: DocumentLinkData | DataroomLinkData | { linkType: string };
+ notionData: {
+ rootNotionPageId: string | null;
+ recordMap: any;
+ theme: any;
+ };
+ showAccountCreationSlide?: boolean;
+ useAdvancedExcelViewer?: boolean;
+ useCustomAccessForm?: boolean;
+ logoOnAccessForm?: boolean;
+ textSelectionEnabled?: boolean;
+};
+
+function EmbedPageInner(props: DomainEmbedPageProps) {
+ const router = useRouter();
+ const [isEmbedded, setIsEmbedded] = useState<boolean | null>(null);
+ const analytics = useAnalytics();
+
+ useEffect(() => {
+ if (!router.isReady || !router.query.slug) return;
+
+ const isInIframe = window !== window.parent;
+ setIsEmbedded(isInIframe);
+
+ if (isInIframe) {
+ document.body.classList.add("embed-view");
+
+ const referrer = document.referrer;
+ const embedSource = referrer ? new URL(referrer).hostname : "direct";
+
+ analytics.capture("Embedded Link Loaded", {
+ domain: router.query.domain as string,
+ slug: router.query.slug as string,
+ embedSource,
+ url: referrer || "unknown",
+ userAgent: window.navigator.userAgent,
+ });
+
+ return () => document.body.classList.remove("embed-view");
+ }
+ }, [router.isReady, router.query.slug, router.query.domain]);
+
+ if (isEmbedded === null || router.isFallback) {
+ return (
+ <div className="flex h-screen items-center justify-center">
+ <LoadingSpinner className="h-20 w-20" />
+ </div>
+ );
+ }
+
+ if (!isEmbedded) {
+ return (
+ <NotFound message="This page can only be accessed when embedded in another website." />
+ );
+ }
+
+ if (props.frozen) {
+ return (
+ <NotFound message="This data room has been closed and is no longer available." />
+ );
+ }
+
+ if (props.error) {
+ return (
+ <NotFound message="Sorry, we had trouble loading this link. Please try again in a moment." />
+ );
+ }
+
+ const {
+ email: verifiedEmail,
+ d: disableEditEmail,
+ previewToken,
+ } = router.query as {
+ email: string;
+ d: string;
+ previewToken?: string;
+ };
+
+ const { linkType } = props.linkData;
+
+ if (linkType === "DOCUMENT_LINK") {
+ const { link, brand } = props.linkData as DocumentLinkData;
+ if (!link || router.isFallback) {
+ return (
+ <div className="flex h-screen items-center justify-center">
+ <LoadingSpinner className="h-20 w-20" />
+ </div>
+ );
+ }
+
+ const {
+ expiresAt,
+ emailProtected,
+ password: linkPassword,
+ enableAgreement,
+ isArchived,
+ } = link;
+
+ 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}
+ showAccountCreationSlide={props.showAccountCreationSlide}
+ useAdvancedExcelViewer={props.useAdvancedExcelViewer}
+ previewToken={previewToken}
+ disableEditEmail={!!disableEditEmail}
+ useCustomAccessForm={props.useCustomAccessForm}
+ logoOnAccessForm={props.logoOnAccessForm}
+ verifiedEmail={verifiedEmail}
+ textSelectionEnabled={props.textSelectionEnabled}
+ isEmbedded
+ />
+ </div>
+ );
+ }
+
+ if (linkType === "DATAROOM_LINK") {
+ const { link, brand } = props.linkData as DataroomLinkData;
+ if (!link || router.isFallback) {
+ return (
+ <div className="flex h-screen items-center justify-center">
+ <LoadingSpinner className="h-20 w-20" />
+ </div>
+ );
+ }
+
+ const {
+ expiresAt,
+ emailProtected,
+ password: linkPassword,
+ enableAgreement,
+ isArchived,
+ } = link;
+
+ 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}
+ previewToken={previewToken}
+ disableEditEmail={!!disableEditEmail}
+ useCustomAccessForm={props.useCustomAccessForm}
+ logoOnAccessForm={props.logoOnAccessForm}
+ verifiedEmail={verifiedEmail}
+ textSelectionEnabled={props.textSelectionEnabled}
+ isEmbedded
+ />
+ </div>
+ );
+ }
+
+ return (
+ <div className="flex h-screen items-center justify-center">
+ <LoadingSpinner className="h-20 w-20" />
+ </div>
+ );
+}
+
+export default function EmbedPage(props: DomainEmbedPageProps) {
+ const locale = props.i18n?.locale ?? "en";
+ const resources = props.i18n?.resources ?? {};
+ return (
+ <ViewerI18nProvider locale={locale} resources={resources}>
+ <EmbedPageInner {...props} />
+ </ViewerI18nProvider>
+ );
+}