Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
feat(documents): support self-contained HTML files (behind htmlDocuments flag)
Marc Seitz1e269441ee53
diff --git a/app/api/views-dataroom/route.ts b/app/api/views-dataroom/route.tsindex f1eebd84..4d6d98fb 100644--- a/app/api/views-dataroom/route.ts+++ b/app/api/views-dataroom/route.ts@@ -17,6 +17,7 @@ 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 { getFeatureFlags } from "@/lib/featureFlags";import { getAdvancedExcelFileUrl } from "@/lib/files/advanced-excel-url";import { getFile } from "@/lib/files/get-file";import { signPageLinks } from "@/lib/files/sign-page-links";@@ -48,6 +49,7 @@ import {import { generateOTP } from "@/lib/utils/generate-otp";import { LOCALHOST_IP } from "@/lib/utils/geo";import { checkGlobalBlockList } from "@/lib/utils/global-block-list";+import { resolveHtmlContentForRender } from "@/lib/utils/html-document";import { validateEmail } from "@/lib/utils/validate-email";export async function POST(request: NextRequest) {@@ -1277,6 +1279,7 @@ export async function POST(request: NextRequest) {// otherwise, return file from document versionlet documentPages, documentVersion;let sheetData;+ let htmlContent: string | undefined;const INITIAL_PAGES_TO_LOAD = 10;if (hasPages) {@@ -1378,6 +1381,33 @@ export async function POST(request: NextRequest) {sheetData = data;}}++ if (documentVersion.type === "html") {+ const featureFlags = await getFeatureFlags({ teamId: link.teamId! });+ if (!featureFlags.htmlDocuments) {+ return NextResponse.json(+ { message: "This document is not available for viewing." },+ { status: 400 },+ );+ }++ try {+ const fileUrl = await getFile({+ data: documentVersion.file,+ type: documentVersion.storageType,+ });+ htmlContent = await resolveHtmlContentForRender({+ documentId: resolvedDocumentId,+ url: fileUrl,+ });+ } catch (error) {+ console.error("Failed to load HTML document for rendering:", error);+ return NextResponse.json(+ { message: "This document could not be loaded." },+ { status: 400 },+ );+ }+ }console.timeEnd("get-file");}@@ -1421,6 +1451,10 @@ export async function POST(request: NextRequest) {!useAdvancedExcelViewer? sheetData: undefined,+ htmlContent:+ documentVersion && documentVersion.type === "html"+ ? htmlContent+ : undefined,fileType: documentVersion? documentVersion.type: documentPagesdiff --git a/app/api/views/route.ts b/app/api/views/route.tsindex 27fd1607..3356c9ef 100644--- a/app/api/views/route.ts+++ b/app/api/views/route.ts@@ -43,6 +43,7 @@ import { isEmailMatched } from "@/lib/utils/email-domain";import { generateOTP } from "@/lib/utils/generate-otp";import { LOCALHOST_IP } from "@/lib/utils/geo";import { checkGlobalBlockList } from "@/lib/utils/global-block-list";+import { resolveHtmlContentForRender } from "@/lib/utils/html-document";import { validateEmail } from "@/lib/utils/validate-email";export async function POST(request: NextRequest) {@@ -781,6 +782,7 @@ export async function POST(request: NextRequest) {// otherwise, return file from document versionlet documentPages, documentVersion;let sheetData;+ let htmlContent: string | undefined;const INITIAL_PAGES_TO_LOAD = 10;// let documentPagesPromise, documentVersionPromise;if (hasPages) {@@ -884,6 +886,33 @@ export async function POST(request: NextRequest) {sheetData = data;}}++ if (documentVersion.type === "html") {+ const featureFlags = await getFeatureFlags({ teamId: link.teamId! });+ if (!featureFlags.htmlDocuments) {+ return NextResponse.json(+ { message: "This document is not available for viewing." },+ { status: 400 },+ );+ }++ try {+ const fileUrl = await getFile({+ data: documentVersion.file,+ type: documentVersion.storageType,+ });+ htmlContent = await resolveHtmlContentForRender({+ documentId,+ url: fileUrl,+ });+ } catch (error) {+ console.error("Failed to load HTML document for rendering:", error);+ return NextResponse.json(+ { message: "This document could not be loaded." },+ { status: 400 },+ );+ }+ }console.timeEnd("get-file");}@@ -954,6 +983,10 @@ export async function POST(request: NextRequest) {!useAdvancedExcelViewer? sheetData: undefined,+ htmlContent:+ documentVersion && documentVersion.type === "html"+ ? htmlContent+ : undefined,fileType: documentVersion? documentVersion.type: documentPagesdiff --git a/components/document-upload.tsx b/components/document-upload.tsxindex 9c14f177..c95bc118 100644--- a/components/document-upload.tsx+++ b/components/document-upload.tsx@@ -10,11 +10,14 @@ import { toast } from "sonner";import {FREE_PLAN_ACCEPTED_FILE_TYPES,FULL_PLAN_ACCEPTED_FILE_TYPES,+ HTML_ACCEPTED_FILE_TYPES,SUPPORTED_DOCUMENT_MIME_TYPES,} from "@/lib/constants";+import { useFeatureFlags } from "@/lib/hooks/use-feature-flags";import { usePlan } from "@/lib/swr/use-billing";import useLimits from "@/lib/swr/use-limits";import { bytesToSize } from "@/lib/utils";+import { isHtmlFile } from "@/lib/utils/get-content-type";import { fileIcon } from "@/lib/utils/get-file-icon";import {getFileSizeLimit,@@ -41,6 +44,16 @@ export default function DocumentUpload({theme === "light" || (theme === "system" && systemTheme === "light");const { isFree, isTrial } = usePlan();const { limits } = useLimits();+ const { isFeatureEnabled } = useFeatureFlags();+ const htmlDocumentsEnabled = isFeatureEnabled("htmlDocuments");++ const fullPlanAcceptedFileTypes = useMemo(+ () => ({+ ...FULL_PLAN_ACCEPTED_FILE_TYPES,+ ...(htmlDocumentsEnabled ? HTML_ACCEPTED_FILE_TYPES : {}),+ }),+ [htmlDocumentsEnabled],+ );const fileSizeLimits = useMemo(() =>@@ -63,7 +76,7 @@ export default function DocumentUpload({? { "application/pdf": [".pdf"] }: isFree && !isTrial? FREE_PLAN_ACCEPTED_FILE_TYPES- : FULL_PLAN_ACCEPTED_FILE_TYPES,+ : fullPlanAcceptedFileTypes,multiple: false,onDropAccepted: (acceptedFiles) => {if (acceptedFiles.length === 0) {@@ -185,7 +198,12 @@ export default function DocumentUpload({<div className="flex flex-col items-center text-foreground sm:flex-row sm:space-x-2"><div>{fileIcon({- fileType: currentFile.type,+ fileType: isHtmlFile({+ name: currentFile.name,+ contentType: currentFile.type,+ })+ ? "html"+ : currentFile.type,isLight,})}</div>@@ -211,7 +229,7 @@ export default function DocumentUpload({? `Only *.pdf`: isFree && !isTrial? `Only *.pdf, *.xls, *.xlsx, *.csv, *.tsv, *.ods, *.png, *.jpeg, *.jpg`- : `Only *.pdf, *.pptx, *.docx, *.xlsx, *.xls, *.xlsm, *.csv, *.tsv, *.ods, *.ppt, *.odp, *.doc, *.odt, *.rtf, *.txt, *.md, *.dwg, *.dxf, *.png, *.jpg, *.jpeg, *.mp4, *.mov, *.avi, *.webm, *.ogg, *.log`}+ : `Only *.pdf, *.pptx, *.docx, *.xlsx, *.xls, *.xlsm, *.csv, *.tsv, *.ods, *.ppt, *.odp, *.doc, *.odt, *.rtf, *.txt, *.md, *.dwg, *.dxf, *.png, *.jpg, *.jpeg, *.mp4, *.mov, *.avi, *.webm, *.ogg, *.log${htmlDocumentsEnabled ? ", *.html, *.htm" : ""}`}</p></div></div>diff --git a/components/documents/add-document-modal.tsx b/components/documents/add-document-modal.tsxindex 74cb8a59..25b42a94 100644--- a/components/documents/add-document-modal.tsx+++ b/components/documents/add-document-modal.tsx@@ -24,7 +24,10 @@ import { getNotionPageIdFromSlug } from "@/lib/notion/utils";import { usePlan } from "@/lib/swr/use-billing";import { useDataroom } from "@/lib/swr/use-dataroom";import useLimits from "@/lib/swr/use-limits";-import { getSupportedContentType } from "@/lib/utils/get-content-type";+import {+ getSupportedContentType,+ isHtmlFile,+} from "@/lib/utils/get-content-type";import { SetUnifiedPermissionsModal } from "@/components/datarooms/groups/set-unified-permissions-modal";import DocumentUpload from "@/components/document-upload";@@ -329,6 +332,11 @@ export function AddDocumentModal({contentType = "application/x-bak";}+ if (isHtmlFile({ name: currentFile.name, contentType })) {+ supportedFileType = "html";+ contentType = "text/html";+ }+if (!supportedFileType) {setUploading(false);toast.error(diff --git a/components/documents/preview-viewers/preview-viewer.tsx b/components/documents/preview-viewers/preview-viewer.tsxindex 85194d5a..f69cc426 100644--- a/components/documents/preview-viewers/preview-viewer.tsx+++ b/components/documents/preview-viewers/preview-viewer.tsx@@ -1,6 +1,7 @@import { useTeam } from "@/context/team-context";import { DocumentPreviewData } from "@/lib/types/document-preview";+import { HTML_DOCUMENT_IFRAME_SANDBOX } from "@/lib/utils/html-document";import { PreviewExcelViewer } from "./preview-excel-viewer";import { PreviewImageViewer } from "./preview-image-viewer";@@ -67,6 +68,19 @@ export function PreviewViewer({);}+ if (documentData.fileType === "html" && documentData.htmlContent) {+ return (+ <iframe+ srcDoc={documentData.htmlContent}+ title={documentData.documentName || "HTML document"}+ className="h-full w-full rounded-lg border-0 bg-white"+ sandbox={HTML_DOCUMENT_IFRAME_SANDBOX}+ referrerPolicy="no-referrer"+ allow=""+ />+ );+ }+// Notion documents (not fully supported yet)if (documentData.fileType === "notion") {return (diff --git a/components/upload-zone.tsx b/components/upload-zone.tsxindex 63f55eec..508f9be8 100644--- a/components/upload-zone.tsx+++ b/components/upload-zone.tsx@@ -14,6 +14,7 @@ import { useAnalytics } from "@/lib/analytics";import {FREE_PLAN_ACCEPTED_FILE_TYPES,FULL_PLAN_ACCEPTED_FILE_TYPES,+ HTML_ACCEPTED_FILE_TYPES,SUPPORTED_DOCUMENT_MIME_TYPES,} from "@/lib/constants";import { DocumentData, createDocument } from "@/lib/documents/create-document";@@ -29,12 +30,16 @@ import {createFolderInMainDocs,isSystemFile,} from "@/lib/folders/create-folder";+import { useFeatureFlags } from "@/lib/hooks/use-feature-flags";import { usePlan } from "@/lib/swr/use-billing";import useLimits from "@/lib/swr/use-limits";import { useTeamSettings } from "@/lib/swr/use-team-settings";import { CustomUser } from "@/lib/types";import { cn } from "@/lib/utils";-import { getSupportedContentType } from "@/lib/utils/get-content-type";+import {+ getSupportedContentType,+ isHtmlFile,+} from "@/lib/utils/get-content-type";import {getFileSizeLimit,getFileSizeLimits,@@ -282,6 +287,8 @@ export default function UploadZone({const { data: session } = useSession();const { limits, canAddDocuments, isPaused } = useLimits();const { registerUploadTriggers } = useUploadProgress();+ const { isFeatureEnabled } = useFeatureFlags();+ const htmlDocumentsEnabled = isFeatureEnabled("htmlDocuments");// Refs to the two hidden file inputs rendered inside this zone. Used to// open the OS picker without traversing the DOM by id, so callers@@ -335,10 +342,16 @@ export default function UploadZone({[limits, isFree, isTrial],);- const acceptableDropZoneFileTypes =- isFree && !isTrial- ? acceptableDropZoneMimeTypesWhenIsFreePlanAndNotTrial- : allAcceptableDropZoneMimeTypes;+ const acceptableDropZoneFileTypes = useMemo(+ () =>+ isFree && !isTrial+ ? acceptableDropZoneMimeTypesWhenIsFreePlanAndNotTrial+ : {+ ...allAcceptableDropZoneMimeTypes,+ ...(htmlDocumentsEnabled ? HTML_ACCEPTED_FILE_TYPES : {}),+ },+ [isFree, isTrial, htmlDocumentsEnabled],+ );// Helper function to get or create the dataroom folder in "All Documents"// Uses promise-lock pattern to prevent concurrent creation attempts@@ -975,6 +988,11 @@ export default function UploadZone({contentType = "application/x-bak";}+ if (isHtmlFile({ name: storageFileName, contentType })) {+ supportedFileType = "html";+ contentType = "text/html";+ }+const documentData: DocumentData = {key: storageKey,supportedFileType: supportedFileType,@@ -1869,7 +1887,7 @@ export default function UploadZone({<p className="mt-1 text-xs leading-5 text-muted-foreground">{isFree && !isTrial? `Only *.pdf, *.xls, *.xlsx, *.csv, *.tsv, *.ods, *.png, *.jpeg, *.jpg`- : `Only *.pdf, *.pptx, *.docx, *.xlsx, *.xls, *.csv, *.tsv, *.ods, *.ppt, *.odp, *.doc, *.odt, *.md, *.dwg, *.dxf, *.png, *.jpg, *.jpeg, *.mp4, *.mov, *.avi, *.webm, *.ogg, *.log`}+ : `Only *.pdf, *.pptx, *.docx, *.xlsx, *.xls, *.csv, *.tsv, *.ods, *.ppt, *.odp, *.doc, *.odt, *.md, *.dwg, *.dxf, *.png, *.jpg, *.jpeg, *.mp4, *.mov, *.avi, *.webm, *.ogg, *.log${htmlDocumentsEnabled ? ", *.html, *.htm" : ""}`}</p></div></div>diff --git a/components/view/dataroom/dataroom-document-view.tsx b/components/view/dataroom/dataroom-document-view.tsxindex cb87a175..6cd490cb 100644--- a/components/view/dataroom/dataroom-document-view.tsx+++ b/components/view/dataroom/dataroom-document-view.tsx@@ -56,6 +56,7 @@ export type DEFAULT_DATAROOM_DOCUMENT_VIEW_TYPE = {}[]| null;sheetData?: SheetData[] | null;+ htmlContent?: string | null;notionData?: {recordMap: ExtendedRecordMap | null;theme: NotionTheme | null | undefined;@@ -210,6 +211,7 @@ export default function DataroomDocumentView({pages,notionData,sheetData,+ htmlContent,fileType,isPreview,ipAddress,@@ -258,6 +260,7 @@ export default function DataroomDocumentView({pages,notionData,sheetData,+ htmlContent,fileType,isPreview,ipAddress,diff --git a/components/view/document-view.tsx b/components/view/document-view.tsxindex 5cd57f14..d01b2673 100644--- a/components/view/document-view.tsx+++ b/components/view/document-view.tsx@@ -49,6 +49,7 @@ export type DEFAULT_DOCUMENT_VIEW_TYPE = {}[]| null;sheetData?: SheetData[] | null;+ htmlContent?: string | null;fileType?: string;isPreview?: boolean;ipAddress?: string;@@ -183,6 +184,7 @@ export default function DocumentView({file,pages,sheetData,+ htmlContent,fileType,isPreview,ipAddress,@@ -223,6 +225,7 @@ export default function DocumentView({file,pages,sheetData,+ htmlContent,fileType,isPreview,ipAddress,diff --git a/components/view/view-data.tsx b/components/view/view-data.tsxindex a0a80c60..7941485c 100644--- a/components/view/view-data.tsx+++ b/components/view/view-data.tsx@@ -38,6 +38,7 @@ import LinkPreview from "./link-preview";import { TNavData } from "./nav";import AdvancedExcelViewer from "./viewer/advanced-excel-viewer";import DownloadOnlyViewer from "./viewer/download-only-viewer";+import HtmlViewer from "./viewer/html-viewer";import ImageViewer from "./viewer/image-viewer";import PagesHorizontalViewer from "./viewer/pages-horizontal-viewer";import PagesVerticalViewer from "./viewer/pages-vertical-viewer";@@ -203,6 +204,15 @@ export default function ViewData({documentName={document.name}navData={navData}/>+ ) : viewData.fileType === "html" && viewData.htmlContent ? (+ <HtmlViewer+ htmlContent={viewData.htmlContent}+ documentName={document.name}+ versionNumber={document.versions[0].versionNumber}+ screenshotProtectionEnabled={link.enableScreenshotProtection!}+ confidentialViewEnabled={!!link.enableConfidentialView}+ navData={navData}+ />) : viewData.fileType === "sheet" && viewData.sheetData ? (<ExcelViewerversionNumber={document.versions[0].versionNumber}diff --git a/components/view/viewer/html-viewer.tsx b/components/view/viewer/html-viewer.tsxnew file mode 100644index 00000000..99ca061d--- /dev/null+++ b/components/view/viewer/html-viewer.tsx@@ -0,0 +1,229 @@+import { useRouter } from "next/router";++import { useEffect, useRef, useState } from "react";++import { ConfidentialViewOverlay } from "@/ee/features/permissions/components/confidential-view/confidential-view-overlay";++import { useSafePageViewTracker } from "@/lib/tracking/safe-page-view-tracker";+import { getTrackingOptions } from "@/lib/tracking/tracking-config";+import { cn } from "@/lib/utils";+import { HTML_DOCUMENT_IFRAME_SANDBOX } from "@/lib/utils/html-document";++import LoadingSpinner from "@/components/ui/loading-spinner";++import { ScreenProtector } from "../ScreenProtection";+import Nav, { TNavData } from "../nav";+import { AwayPoster } from "./away-poster";++export default function HtmlViewer({+ htmlContent,+ documentName,+ versionNumber,+ screenshotProtectionEnabled,+ confidentialViewEnabled,+ navData,+}: {+ htmlContent: string;+ documentName?: string;+ versionNumber: number;+ screenshotProtectionEnabled: boolean;+ confidentialViewEnabled?: boolean;+ navData: TNavData;+}) {+ const router = useRouter();+ const startTimeRef = useRef(Date.now());+ const [iframeLoaded, setIframeLoaded] = useState<boolean>(false);+ const [isWindowFocused, setIsWindowFocused] = useState<boolean>(true);++ const trackingOptions = getTrackingOptions();+ const {+ trackPageViewSafely,+ resetTrackingState,+ startIntervalTracking,+ stopIntervalTracking,+ getActiveDuration,+ isInactive,+ updateActivity,+ } = useSafePageViewTracker({+ ...trackingOptions,+ externalStartTimeRef: startTimeRef,+ });++ const { linkId, documentId, viewId, isPreview, dataroomId } = navData;++ useEffect(() => {+ const removeQueryParams = (queries: string[]) => {+ const currentQuery = { ...router.query };+ const currentPath = router.asPath.split("?")[0];+ queries.forEach((query) => delete currentQuery[query]);++ router.replace(+ { pathname: currentPath, query: currentQuery },+ undefined,+ { shallow: true },+ );+ };++ if (router.query.token) {+ removeQueryParams(["token", "email", "domain", "slug", "linkId"]);+ }+ }, []);++ useEffect(() => {+ const trackingData = {+ linkId,+ documentId,+ viewId,+ pageNumber: 1,+ versionNumber,+ dataroomId,+ isPreview,+ };++ startIntervalTracking(trackingData);++ return () => {+ stopIntervalTracking();+ };+ }, [+ linkId,+ documentId,+ viewId,+ versionNumber,+ dataroomId,+ isPreview,+ startIntervalTracking,+ stopIntervalTracking,+ ]);++ useEffect(() => {+ const handleVisibilityChange = () => {+ const trackingData = {+ linkId,+ documentId,+ viewId,+ pageNumber: 1,+ versionNumber,+ dataroomId,+ isPreview,+ };++ if (document.visibilityState === "visible") {+ resetTrackingState();+ startIntervalTracking(trackingData);+ } else {+ stopIntervalTracking();+ trackPageViewSafely(+ { ...trackingData, duration: getActiveDuration() },+ true,+ );+ }+ };++ document.addEventListener("visibilitychange", handleVisibilityChange);+ return () => {+ document.removeEventListener("visibilitychange", handleVisibilityChange);+ };+ }, [+ linkId,+ documentId,+ viewId,+ versionNumber,+ dataroomId,+ isPreview,+ trackPageViewSafely,+ resetTrackingState,+ startIntervalTracking,+ stopIntervalTracking,+ getActiveDuration,+ ]);++ useEffect(() => {+ const handleBeforeUnload = () => {+ stopIntervalTracking();+ trackPageViewSafely(+ {+ linkId,+ documentId,+ viewId,+ duration: getActiveDuration(),+ pageNumber: 1,+ versionNumber,+ dataroomId,+ isPreview,+ },+ true,+ );+ };++ window.addEventListener("beforeunload", handleBeforeUnload);+ return () => {+ window.removeEventListener("beforeunload", handleBeforeUnload);+ };+ }, [+ linkId,+ documentId,+ viewId,+ versionNumber,+ dataroomId,+ isPreview,+ trackPageViewSafely,+ stopIntervalTracking,+ getActiveDuration,+ ]);++ useEffect(() => {+ if (!screenshotProtectionEnabled) return;++ const handleFocus = () => setIsWindowFocused(true);+ const handleBlur = () => setIsWindowFocused(false);++ window.addEventListener("focus", handleFocus);+ window.addEventListener("blur", handleBlur);++ return () => {+ window.removeEventListener("focus", handleFocus);+ window.removeEventListener("blur", handleBlur);+ };+ }, [screenshotProtectionEnabled]);++ return (+ <>+ <Nav pageNumber={1} numPages={1} navData={navData} />+ <div+ style={{ height: "calc(100dvh - 64px)" }}+ className={cn(+ "relative flex flex-col bg-gray-50 dark:bg-gray-900",+ !isWindowFocused &&+ screenshotProtectionEnabled &&+ "blur-xl transition-all duration-300",+ )}+ >+ {!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+ srcDoc={htmlContent}+ title={documentName || "HTML document"}+ onLoad={() => setIframeLoaded(true)}+ className="h-full w-full border-0 bg-white"+ sandbox={HTML_DOCUMENT_IFRAME_SANDBOX}+ referrerPolicy="no-referrer"+ allow=""+ />+ {screenshotProtectionEnabled && <ScreenProtector />}+ {confidentialViewEnabled ? <ConfidentialViewOverlay /> : null}+ </div>+ <AwayPoster+ isVisible={isInactive}+ inactivityThreshold={trackingOptions.inactivityThreshold}+ onDismiss={updateActivity}+ />+ </>+ );+}diff --git a/lib/api/documents/process-document.ts b/lib/api/documents/process-document.tsindex fb44dcee..abbae95d 100644--- a/lib/api/documents/process-document.ts+++ b/lib/api/documents/process-document.ts@@ -6,6 +6,7 @@ import { tasks } from "@trigger.dev/sdk";import { validateExternalDocumentUrl } from "@/lib/api/documents/validate-external-url";import { DocumentData } from "@/lib/documents/create-document";+import { getFeatureFlags } from "@/lib/featureFlags";import prisma from "@/lib/prisma";import { processVideo } from "@/lib/trigger/optimize-video-files";import { convertPdfToImageRoute } from "@/lib/trigger/pdf-to-image-route";@@ -50,6 +51,13 @@ export const processDocument = async ({// Get passed type property or alternatively, the file extension and save it as the typeconst type = supportedFileType || getExtension(name);+ if (type === "html") {+ const featureFlags = await getFeatureFlags({ teamId });+ if (!featureFlags.htmlDocuments) {+ throw new Error("HTML documents are not enabled for this team.");+ }+ }+// For notion/link documents, validate the external URL (Notion page must be// public; link URLs must be well-formed and not blocked). No-op otherwise.await validateExternalDocumentUrl({ type, key, teamId });diff --git a/lib/constants.ts b/lib/constants.tsindex e67372bd..80505088 100644--- a/lib/constants.ts+++ b/lib/constants.ts@@ -123,8 +123,14 @@ export const SUPPORTED_DOCUMENT_MIME_TYPES = ["application/vnd.google-earth.kmz", // .kmz"application/vnd.ms-outlook", // .msg"message/rfc822", // .eml+ "text/html", // .html, .htm];+// Merged into the dropzone accept map only when the `htmlDocuments` flag is on.+export const HTML_ACCEPTED_FILE_TYPES = {+ "text/html": [".html", ".htm"],+};+// Upload configurations for different plan types and contextsexport const FREE_PLAN_ACCEPTED_FILE_TYPES = {"application/pdf": [], // ".pdf"@@ -257,6 +263,7 @@ export const SUPPORTED_DOCUMENT_SIMPLE_TYPES = ["video","map","email",+ "html","other",] as const;diff --git a/lib/featureFlags/index.ts b/lib/featureFlags/index.tsindex 66f5499b..eabb8aa4 100644--- a/lib/featureFlags/index.ts+++ b/lib/featureFlags/index.ts@@ -21,6 +21,7 @@ export type BetaFeatures =| "redaction"| "requestList"| "logoOnAccessForm"+ | "htmlDocuments"| "hideFooterOnAccessForm";type BetaFeaturesRecord = Record<BetaFeatures, string[]>;@@ -47,6 +48,7 @@ export const getFeatureFlags = async ({ teamId }: { teamId?: string }) => {redaction: false,requestList: false,logoOnAccessForm: false,+ htmlDocuments: false,hideFooterOnAccessForm: false,};diff --git a/lib/types/document-preview.ts b/lib/types/document-preview.tsindex 6ea78a63..0e8ceaa2 100644--- a/lib/types/document-preview.ts+++ b/lib/types/document-preview.ts@@ -17,4 +17,5 @@ export interface DocumentPreviewData {}[];file?: string;sheetData?: any;+ htmlContent?: string;}diff --git a/lib/utils/get-content-type.ts b/lib/utils/get-content-type.tsindex dbda154c..c05b920e 100644--- a/lib/utils/get-content-type.ts+++ b/lib/utils/get-content-type.ts@@ -62,6 +62,8 @@ export function getSupportedContentType(contentType: string): string | null {case "application/vnd.ms-outlook":case "message/rfc822":return "email";+ case "text/html":+ return "html";case "image/tiff":case "image/x-ecw":case "application/x-bak":@@ -85,6 +87,20 @@ export function isMarkdownFile({return false;}+// Checks the extension too because browsers often upload `.html` with an empty+// or generic content type.+export function isHtmlFile({+ name,+ contentType,+}: {+ name?: string | null;+ contentType?: string | null;+}): boolean {+ if (contentType === "text/html") return true;+ if (name && /\.html?$/i.test(name)) return true;+ return false;+}+export function getExtensionFromContentType(contentType: string,): string | null {@@ -161,6 +177,8 @@ export function getExtensionFromContentType(return "msg";case "message/rfc822":return "eml";+ case "text/html":+ return "html";case "image/tiff":return "tiff";case "image/x-ecw":diff --git a/lib/utils/get-file-icon.tsx b/lib/utils/get-file-icon.tsxindex 7311b33f..7c08e8d4 100644--- a/lib/utils/get-file-icon.tsx+++ b/lib/utils/get-file-icon.tsx@@ -1,4 +1,4 @@-import { FileIcon, Link as LinkIcon, MailIcon } from "lucide-react";+import { FileCode, FileIcon, Link as LinkIcon, MailIcon } from "lucide-react";import CadIcon from "@/components/shared/icons/files/cad";import DocsIcon from "@/components/shared/icons/files/docs";@@ -73,6 +73,9 @@ export function fileIcon({case "application/vnd.ms-outlook":case "email":return <MailIcon className={className} />;+ case "text/html":+ case "html":+ return <FileCode className={className} />;default:return <FileIcon className={className} />;}diff --git a/lib/utils/html-document.ts b/lib/utils/html-document.tsnew file mode 100644index 00000000..38c371ec--- /dev/null+++ b/lib/utils/html-document.ts@@ -0,0 +1,150 @@+// Consumers return the document inline as JSON, so the cap has to stay below+// Vercel's 4.5 MB response limit with room for JSON escaping.+export const MAX_HTML_DOCUMENT_BYTES = 3 * 1024 * 1024;++export const HTML_DOCUMENT_FETCH_TIMEOUT_MS = 10_000;++// Must not include `allow-same-origin`: combined with `allow-scripts` the+// document could remove its own sandbox and reach Papermark's origin.+export const HTML_DOCUMENT_IFRAME_SANDBOX = "allow-scripts allow-popups";++export type HtmlDocumentRiskReport = {+ byteLength: number;+ hasInlineScript: boolean;+ hasInlineEventHandlers: boolean;+ hasForms: boolean;+ hasNestedIframes: boolean;+ hasMetaRefresh: boolean;+ externalResourceHosts: string[];+};++const EXTERNAL_URL_REGEX = /(?:src|href)\s*=\s*["']?(https?:\/\/[^"'\s>]+)/gi;+const INLINE_EVENT_HANDLER_REGEX = /<[^>]+\son[a-z]+\s*=/i;++export function scanHtmlDocument(html: string): HtmlDocumentRiskReport {+ const externalResourceHosts = new Set<string>();+ for (const match of html.matchAll(EXTERNAL_URL_REGEX)) {+ try {+ externalResourceHosts.add(new URL(match[1]).host);+ } catch {+ // Malformed URLs won't resolve when rendered either.+ }+ }++ return {+ byteLength: byteLength(html),+ hasInlineScript: /<script[\s>]/i.test(html),+ hasInlineEventHandlers: INLINE_EVENT_HANDLER_REGEX.test(html),+ hasForms: /<form[\s>]/i.test(html),+ hasNestedIframes: /<iframe[\s>]/i.test(html),+ hasMetaRefresh: /<meta[^>]+http-equiv\s*=\s*["']?refresh/i.test(html),+ externalResourceHosts: Array.from(externalResourceHosts),+ };+}++function byteLength(value: string): number {+ return new TextEncoder().encode(value).length;+}++// Releases the socket when we bail out before reading the body; a failing+// cancel must not replace the caller-facing error.+async function discardBody(response: Response): Promise<void> {+ try {+ await response.body?.cancel();+ } catch {}+}++export async function fetchHtmlDocumentForRender({+ url,+ maxBytes = MAX_HTML_DOCUMENT_BYTES,+ timeoutMs = HTML_DOCUMENT_FETCH_TIMEOUT_MS,+}: {+ url: string;+ maxBytes?: number;+ timeoutMs?: number;+}): Promise<string> {+ // The deadline covers the streamed body too, so a stalled storage backend+ // cannot hold the request open.+ const signal = AbortSignal.timeout(timeoutMs);++ try {+ const response = await fetch(url, { signal });++ if (!response.ok) {+ await discardBody(response);+ throw new Error(+ `Failed to fetch HTML document (status ${response.status})`,+ );+ }++ const declaredLength = Number(response.headers.get("content-length"));+ if (Number.isFinite(declaredLength) && declaredLength > maxBytes) {+ await discardBody(response);+ throw new Error("HTML document exceeds the maximum allowed size");+ }++ const body = response.body;+ if (!body) {+ const text = await response.text();+ if (byteLength(text) > maxBytes) {+ throw new Error("HTML document exceeds the maximum allowed size");+ }+ return text;+ }++ // Enforce the cap while streaming so an oversized response is never fully+ // buffered into memory.+ const reader = body.getReader();+ const decoder = new TextDecoder("utf-8");+ let received = 0;+ let text = "";++ while (true) {+ const { done, value } = await reader.read();+ if (done) break;+ if (!value) continue;++ received += value.byteLength;+ if (received > maxBytes) {+ await reader.cancel();+ throw new Error("HTML document exceeds the maximum allowed size");+ }+ text += decoder.decode(value, { stream: true });+ }+ text += decoder.decode();++ return text;+ } catch (error) {+ if (+ error instanceof Error &&+ (error.name === "TimeoutError" || error.name === "AbortError")+ ) {+ throw new Error(`Timed out fetching HTML document after ${timeoutMs}ms`);+ }+ throw error;+ }+}++export async function resolveHtmlContentForRender({+ documentId,+ url,+}: {+ documentId: string;+ url: string;+}): Promise<string> {+ const html = await fetchHtmlDocumentForRender({ url });+ const report = scanHtmlDocument(html);++ console.info("[htmlDocument] rendering document", {+ documentId,+ byteLength: report.byteLength,+ hasInlineScript: report.hasInlineScript,+ hasInlineEventHandlers: report.hasInlineEventHandlers,+ hasForms: report.hasForms,+ hasNestedIframes: report.hasNestedIframes,+ hasMetaRefresh: report.hasMetaRefresh,+ externalResourceHosts: report.externalResourceHosts,+ });++ return html;+}diff --git a/pages/api/teams/[teamId]/documents/[id]/preview-data.ts b/pages/api/teams/[teamId]/documents/[id]/preview-data.tsindex ac5f2ec6..35a7c917 100644--- a/pages/api/teams/[teamId]/documents/[id]/preview-data.ts+++ b/pages/api/teams/[teamId]/documents/[id]/preview-data.ts@@ -3,12 +3,14 @@ import { NextApiRequest, NextApiResponse } from "next";import { getServerSession } from "next-auth/next";import { enforceDocumentMemberScope } from "@/lib/api/rbac/guard";+import { getFeatureFlags } from "@/lib/featureFlags";import { getAdvancedExcelFileUrl } from "@/lib/files/advanced-excel-url";import { getFile } from "@/lib/files/get-file";import { signPageLinks } from "@/lib/files/sign-page-links";import prisma from "@/lib/prisma";import { CustomUser } from "@/lib/types";import { log } from "@/lib/utils";+import { resolveHtmlContentForRender } from "@/lib/utils/html-document";import { authOptions } from "../../../../auth/[...nextauth]";@@ -111,6 +113,7 @@ export default async function handle(pages: undefined as any,file: undefined as string | undefined,sheetData: undefined as any,+ htmlContent: undefined as string | undefined,};const INITIAL_PAGES_TO_LOAD = 10;@@ -154,6 +157,32 @@ export default async function handle(}// Non-advanced sheets: return 200 with advancedExcelEnabled=false so// PreviewViewer renders its inline fallback instead of showing an error.+ } else if (primaryVersion.type === "html") {+ const featureFlags = await getFeatureFlags({ teamId });+ if (!featureFlags.htmlDocuments) {+ return res.status(400).json({+ message: "HTML documents are not enabled for this team.",+ });+ }+ try {+ const fileUrl = await getFile({+ data: primaryVersion.file,+ type: primaryVersion.storageType,+ });+ returnData.htmlContent = await resolveHtmlContentForRender({+ documentId,+ url: fileUrl,+ });+ returnData.numPages = 1;+ } catch (error) {+ console.error("Failed to load HTML document preview:", error);+ return res.status(400).json({+ message:+ error instanceof Error && error.message+ ? error.message+ : "Preview not available for this document",+ });+ }} else if (primaryVersion.type === "notion") {// Notion documents - preview not supportedreturn res.status(400).json({diff --git a/pages/api/teams/[teamId]/documents/[id]/versions/index.ts b/pages/api/teams/[teamId]/documents/[id]/versions/index.tsindex 1a83c94f..fb5aaa68 100644--- a/pages/api/teams/[teamId]/documents/[id]/versions/index.ts+++ b/pages/api/teams/[teamId]/documents/[id]/versions/index.ts@@ -8,6 +8,7 @@ import { getServerSession } from "next-auth/next";import { hashToken } from "@/lib/api/auth/token";import { enforceDocumentMemberScope } from "@/lib/api/rbac/guard";+import { getFeatureFlags } from "@/lib/featureFlags";import prisma from "@/lib/prisma";import { processVideo } from "@/lib/trigger/optimize-video-files";import { convertPdfToImageRoute } from "@/lib/trigger/pdf-to-image-route";@@ -102,6 +103,15 @@ export default async function handle(return res.status(401).end("Unauthorized");}+ if (type === "html") {+ const featureFlags = await getFeatureFlags({ teamId });+ if (!featureFlags.htmlDocuments) {+ return res.status(403).json({+ error: "HTML documents are not enabled for this team.",+ });+ }+ }+// Check if team is pausedconst teamIsPaused = await isTeamPausedById(teamId);if (teamIsPaused) {