Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
feat: update link permissions
Marc Seitz0c0c80ee429e
diff --git a/app/api/views-dataroom/route.ts b/app/api/views-dataroom/route.tsindex 4a3b3601..5d874048 100644--- a/app/api/views-dataroom/route.ts+++ b/app/api/views-dataroom/route.ts@@ -930,10 +930,48 @@ export async function POST(request: NextRequest) {!dataroomDocumentPermission?.canView &&!dataroomDocumentPermission?.canDownload) {- return NextResponse.json(- { message: "Unauthorized access." },- { status: 403 },- );+ // Fallback: viewer-uploaded docs aren't tied to the link's+ // permission group, so allow the original uploader through. Gated+ // on a verified session (or NextAuth team-member preview) to+ // prevent unverified callers from claiming an upload's viewerId.+ const allowUploadFallback = isEmailVerified || isTeamMember;+ const ownerViewerId = viewer?.id ?? dataroomSession?.viewerId;+ const viewerUpload =+ ownerViewerId || isTeamMember+ ? await prisma.documentUpload.findFirst({+ where: {+ linkId,+ dataroomDocumentId: dataroomDocument.id,+ ...(ownerViewerId && !isTeamMember+ ? { viewerId: ownerViewerId }+ : {}),+ },+ select: { id: true },+ })+ : null;++ if (!viewerUpload) {+ return NextResponse.json(+ { message: "Unauthorized access." },+ { status: 403 },+ );+ }++ if (!allowUploadFallback) {+ // Trigger inline OTP re-auth. Echoing the email back is safe+ // here — the caller supplied it on the access form.+ return NextResponse.json(+ {+ message: "Email verification required to access your upload.",+ requiresVerification: "viewer-upload",+ email: viewer?.email ?? null,+ },+ { status: 401 },+ );+ }++ // Per-link `allowDownload` still gates the download UI downstream.+ dataroomDocumentPermission = { canView: true, canDownload: true };}}diff --git a/app/api/views/pages/route.ts b/app/api/views/pages/route.tsindex 165091d2..02896182 100644--- a/app/api/views/pages/route.ts+++ b/app/api/views/pages/route.ts@@ -155,6 +155,7 @@ export async function POST(request: NextRequest) {dataroomId: true,linkId: true,viewedAt: true,+ viewerId: true,},}),prisma.documentVersion.findUnique({@@ -203,6 +204,21 @@ export async function POST(request: NextRequest) {{ status: 401 },);}++ // Bind the requested viewId to the caller's session. Cross-view+ // access (re-opening a doc within the same dataroom session creates+ // a new DOCUMENT_VIEW row) requires both viewerIds to be defined and+ // equal — anonymous views must match by viewId only.+ const sameViewer =+ !!session.viewerId &&+ !!view.viewerId &&+ session.viewerId === view.viewerId;+ if (session.viewId !== view.id && !sameViewer) {+ return NextResponse.json(+ { message: "Unauthorized access." },+ { status: 403 },+ );+ }}return await fetchAndReturnPages(documentVersionId, pageNumbers);diff --git a/components/datarooms/groups/group-permissions.tsx b/components/datarooms/groups/group-permissions.tsxindex e7bd9de0..622294e8 100644--- a/components/datarooms/groups/group-permissions.tsx+++ b/components/datarooms/groups/group-permissions.tsx@@ -52,6 +52,12 @@ import {TableRow,} from "@/components/ui/table";import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group";+import {+ Tooltip,+ TooltipContent,+ TooltipPortal,+ TooltipTrigger,+} from "@/components/ui/tooltip";const PermissionItemName = ({ item }: { item: FileOrFolder }) => {const { isFeatureEnabled } = useFeatureFlags();@@ -66,17 +72,29 @@ const PermissionItemName = ({ item }: { item: FileOrFolder }) => {const isRoot = item.id === VIRTUAL_ROOT_ID;return (- <div className="flex items-center text-foreground">+ <div className="flex min-w-0 items-center text-foreground">{isRoot ? (- <HomeIcon className="mr-2 h-5 w-5" />+ <HomeIcon className="mr-2 h-5 w-5 shrink-0" />) : item.itemType === ItemType.DATAROOM_FOLDER ? (- <Folder className="mr-2 h-5 w-5" />+ <Folder className="mr-2 h-5 w-5 shrink-0" />) : (- <File className="mr-2 h-5 w-5" />+ <File className="mr-2 h-5 w-5 shrink-0" />)}- <span className="truncate" style={HIERARCHICAL_DISPLAY_STYLE}>- {displayName}- </span>+ <Tooltip delayDuration={300}>+ <TooltipTrigger asChild>+ <span+ className="truncate"+ style={HIERARCHICAL_DISPLAY_STYLE}+ >+ {displayName}+ </span>+ </TooltipTrigger>+ <TooltipPortal>+ <TooltipContent className="max-w-sm break-words" side="top">+ {displayName}+ </TooltipContent>+ </TooltipPortal>+ </Tooltip></div>);};@@ -108,9 +126,9 @@ const createColumns = (extra: ColumnExtra): ColumnDef<FileOrFolder>[] => [accessorKey: "name",header: "Name",cell: ({ row }) => {- const isRoot = row.original.id === "__dataroom_root__";+ const isRoot = row.original.id === VIRTUAL_ROOT_ID;return (- <div className="flex items-center text-foreground">+ <div className="flex min-w-0 items-center text-foreground">{isRoot ? (<div className="h-6 w-6 shrink-0" />) : row.getCanExpand() ? (@@ -329,7 +347,7 @@ const buildTreeWithRoot = (return [{- id: "__dataroom_root__",+ id: VIRTUAL_ROOT_ID,name: dataroomName,subItems: allItems,permissions: rootPermissions,@@ -644,7 +662,7 @@ export default function ExpandableTable({},getRowCanExpand: (row) => {// Root folder is always expanded and cannot be collapsed- if (row.original.id === "__dataroom_root__") {+ if (row.original.id === VIRTUAL_ROOT_ID) {return true;}return (row.subRows?.length ?? 0) > 0;@@ -722,14 +740,19 @@ export default function ExpandableTable({isSaving && "pointer-events-none opacity-60",)}>- <Table>+ <Table className="table-fixed"><TableHeader>{table.getHeaderGroups().map((headerGroup) => (<TableRow key={headerGroup.id}>- {headerGroup.headers.map((header) => (+ {headerGroup.headers.map((header, index) => (<TableHeadkey={header.id}- className="py-2 first:w-12 last:text-right"+ className={cn(+ "py-2",+ index === 0+ ? "w-auto"+ : "w-[120px] whitespace-nowrap text-right",+ )}>{header.isPlaceholder? null@@ -745,7 +768,7 @@ export default function ExpandableTable({<TableBody>{table.getRowModel().rows?.length ? (table.getRowModel().rows.map((row) => {- const isRoot = row.original.id === "__dataroom_root__";+ const isRoot = row.original.id === VIRTUAL_ROOT_ID;return (<TableRowkey={row.id}@@ -764,12 +787,24 @@ export default function ExpandableTable({}: undefined}- className="py-2 last:flex last:justify-end"- >- {flexRender(- cell.column.columnDef.cell,- cell.getContext(),+ className={cn(+ "py-2",+ index === 0+ ? "max-w-0"+ : "w-[120px] whitespace-nowrap",)}+ >+ <div+ className={cn(+ "min-w-0",+ index !== 0 && "flex justify-end",+ )}+ >+ {flexRender(+ cell.column.columnDef.cell,+ cell.getContext(),+ )}+ </div></TableCell>))}</TableRow>diff --git a/components/view/dataroom/dataroom-document-view.tsx b/components/view/dataroom/dataroom-document-view.tsxindex e7bea68f..d7298284 100644--- a/components/view/dataroom/dataroom-document-view.tsx+++ b/components/view/dataroom/dataroom-document-view.tsx@@ -20,6 +20,7 @@ import AccessForm, {import EmailVerificationMessage from "../access-form/email-verification-form";import ViewData, { TViewDocumentData } from "../view-data";+import { DownloadOtpVerification } from "./download-otp-verification";type RowData = { [key: string]: any };type SheetData = {@@ -137,8 +138,16 @@ export default function DataroomDocumentView({const [code, setCode] = useState<string | null>(null);const [isInvalidCode, setIsInvalidCode] = useState<boolean>(false);+ // Set when the server requires inline OTP re-auth before granting access.+ const [uploadReauth, setUploadReauth] = useState<{+ email: string;+ } | null>(null);+const handleSubmission = async (): Promise<void> => {setIsLoading(true);+ // Captured up front because the inner `data` binding below shadows the+ // component-scope `data` (form state).+ const formEmail = data.email;const response = await fetch("/api/views-dataroom", {method: "POST",headers: {@@ -255,6 +264,22 @@ export default function DataroomDocumentView({}} else {const data = await response.json();++ // Server requires inline OTP re-auth. Skip the toast — the OTP+ // component renders its own explanation.+ if (+ response.status === 401 &&+ data.requiresVerification === "viewer-upload"+ ) {+ const reauthEmail =+ data.email ?? verifiedEmail ?? userEmail ?? formEmail ?? null;+ if (reauthEmail) {+ setUploadReauth({ email: reauthEmail });+ setIsLoading(false);+ return;+ }+ }+toast.error(data.message);if (data.resetVerification) {@@ -316,6 +341,39 @@ export default function DataroomDocumentView({);}+ // Inline OTP re-auth step. On success the session flips to verified and+ // `handleSubmission` retries cleanly.+ if (uploadReauth) {+ return (+ <div className="flex min-h-screen items-center justify-center bg-background px-4">+ <div className="w-full max-w-sm space-y-4 rounded-lg border bg-card p-6 shadow-sm">+ <div className="space-y-1">+ <h1 className="text-lg font-semibold">Verify it's you</h1>+ <p className="text-sm text-muted-foreground">+ This file was uploaded by you. To reopen it, confirm you control{" "}+ <strong>{uploadReauth.email}</strong>.+ </p>+ </div>+ <DownloadOtpVerification+ linkId={link.id}+ email={uploadReauth.email}+ sendOtpOnMount+ description={+ <p className="text-sm text-muted-foreground">+ We sent a 6-digit code to <strong>{uploadReauth.email}</strong>.+ Enter it below to access your uploaded file.+ </p>+ }+ onVerified={() => {+ setUploadReauth(null);+ void handleSubmission();+ }}+ />+ </div>+ </div>+ );+ }+// If link is not submitted and does not have email / password protection, show the access formif (!submitted && isProtected) {return (diff --git a/components/view/dataroom/download-otp-verification.tsx b/components/view/dataroom/download-otp-verification.tsxindex 6472d32e..b17cf5f6 100644--- a/components/view/dataroom/download-otp-verification.tsx+++ b/components/view/dataroom/download-otp-verification.tsx@@ -1,6 +1,6 @@"use client";-import { useCallback, useEffect, useRef, useState } from "react";+import { ReactNode, useCallback, useEffect, useRef, useState } from "react";import {InputOTP,@@ -21,6 +21,12 @@ export interface DownloadOtpVerificationProps {compact?: boolean;/** When true, send OTP email automatically on mount (e.g. when user just chose "Notify me" and clicked Start download). */sendOtpOnMount?: boolean;+ /**+ * Optional copy shown above the OTP input. Defaults to the+ * download-notification phrasing. Override for other re-auth flows+ * (e.g. viewer-upload access).+ */+ description?: ReactNode;}const RESEND_COOLDOWN_SECONDS = 60;@@ -33,6 +39,7 @@ export function DownloadOtpVerification({onCancel,compact = false,sendOtpOnMount = false,+ description,}: DownloadOtpVerificationProps) {const [code, setCode] = useState<string | null>(null);const [isLoading, setIsLoading] = useState(false);@@ -106,10 +113,12 @@ export function DownloadOtpVerification({return (<form onSubmit={verifyOtp} className="space-y-4">- <p className="text-sm text-muted-foreground">- We sent a 6-digit code to <strong>{email}</strong>. Enter it below to- verify and receive download notifications.- </p>+ {description ?? (+ <p className="text-sm text-muted-foreground">+ We sent a 6-digit code to <strong>{email}</strong>. Enter it below to+ verify and receive download notifications.+ </p>+ )}<InputOTPmaxLength={6}pattern={REGEXP_ONLY_DIGITS}diff --git a/lib/api/links/link-data.ts b/lib/api/links/link-data.tsindex 43d7892d..444a9160 100644--- a/lib/api/links/link-data.ts+++ b/lib/api/links/link-data.ts@@ -385,7 +385,19 @@ export async function fetchDataroomDocumentLinkData({hasAccess = groupPermissions.length > 0;}- // if it's a group/permission link, we need to check if the document is accessible+ // Fallback: viewer-uploaded docs aren't tied to the link's permission+ // group, so let getStaticProps render the page. The runtime view+ // endpoint enforces per-viewer ownership and OTP re-auth.+ if (!hasAccess) {+ const viewerUpload = await prisma.documentUpload.findFirst({+ where: { linkId, dataroomDocumentId },+ select: { id: true },+ });+ if (viewerUpload) {+ hasAccess = true;+ }+ }+if (!hasAccess) {throw new Error("Document not found in group");}diff --git a/lib/dataroom/permissions-sql.ts b/lib/dataroom/permissions-sql.tsindex b0db5c7d..ce99658f 100644--- a/lib/dataroom/permissions-sql.ts+++ b/lib/dataroom/permissions-sql.ts@@ -1,36 +1,51 @@import { ItemType, Prisma } from "@prisma/client";/**- * SQL builders for bulk-saving viewer-group permissions.+ * SQL builders for bulk-saving dataroom permissions.*- * Replaces the previous loop of per-row `prisma.viewerGroupAccessControls- * .upsert(...)` calls inside `prisma.$transaction(async (tx) => …)`, which- * needed thousands of round-trips on large datarooms and reliably timed out- * Prisma's interactive-transaction window for big "Save changes" payloads.+ * Replaces per-row `prisma.*.upsert(...)` loops inside+ * `prisma.$transaction(async (tx) => …)` blocks, which needed thousands of+ * round-trips on large datarooms and reliably timed out Prisma's interactive+ * transaction window for big "Save changes" payloads.*- * The handler combines three statements inside a single transaction:- * 1. `buildBulkUpsertPermissionsSql` — single `INSERT … ON CONFLICT DO- * UPDATE` for every entry in the user-supplied payload.- * 2. `buildFindAncestorFolderIdsSql` — single recursive-CTE walk of- * `DataroomFolder.parentId` returning the distinct ancestor folder ids- * of every item the payload is making visible.- * 3. `buildUpsertAncestorVisibilitySql` — single bulk upsert that forces- * `canView=true` on those ancestor folders while preserving any- * existing `canDownload`. This is the server-side safety net for- * callers (e.g. the post-upload modal in- * `set-unified-permissions-modal.tsx`) that submit only a single- * document and don't compute parent chains client-side.+ * Two consumers share these builders:+ * 1. **Viewer groups** (admin-side dataroom permissions UI) — writes to+ * `ViewerGroupAccessControls`. Append-only delta semantics: only rows+ * in the user's payload are upserted; nothing is deleted.+ * 2. **Link permission groups** (per-link permission overrides) — writes+ * to `PermissionGroupAccessControls`. Set-everything semantics: the+ * caller posts the complete desired state, so any DB row not in the+ * payload (or in the computed ancestor set) is deleted.+ *+ * Both tables share the columns we touch:+ * `id, groupId, itemId, itemType, canView, canDownload, createdAt, updatedAt`+ *+ * `PermissionGroupAccessControls` has an extra `canDownloadOriginal Boolean+ * @default(false)`. We intentionally never reference it in the SET clause+ * here so its existing value is preserved on update and the column default+ * fills in for INSERT — same shape as the previous Prisma client code path.** `id` values are generated client-side as cuids — same convention as the* rest of the schema's `@id @default(cuid())` columns — and passed in as- * normal bound parameters. We deliberately avoid `gen_random_uuid()::text`- * here so every row in `ViewerGroupAccessControls` keeps a consistent id- * format.+ * normal bound parameters.** All builders are pure functions over their inputs so we can assert their* shape in unit tests without spinning up Postgres.*/+/**+ * The two access-control tables we know how to bulk-write to. The literal+ * string is interpolated into the SQL with `Prisma.raw`, which is safe here+ * because the value is a closed union type — it cannot be supplied by user+ * input, only by callers in this codebase.+ */+export type AccessControlTable =+ | "ViewerGroupAccessControls"+ | "PermissionGroupAccessControls";++const tableRef = (table: AccessControlTable): Prisma.Sql =>+ Prisma.raw(`"${table}"`);+export type PermissionUpsertRow = {/** Pre-generated cuid (same format as `@id @default(cuid())`). */id: string;@@ -41,7 +56,7 @@ export type PermissionUpsertRow = {};export type AncestorUpsertRow = {- /** Pre-generated cuid for the new `ViewerGroupAccessControls` row. */+ /** Pre-generated cuid for the new access-control row. */id: string;folderId: string;};@@ -52,6 +67,7 @@ export type AncestorUpsertRow = {* Returns `null` when `rows` is empty so the caller can skip the round-trip.*/export function buildBulkUpsertPermissionsSql(+ table: AccessControlTable,groupId: string,rows: PermissionUpsertRow[],): Prisma.Sql | null {@@ -69,7 +85,7 @@ export function buildBulkUpsertPermissionsSql();return Prisma.sql`- INSERT INTO "ViewerGroupAccessControls" (+ INSERT INTO ${tableRef(table)} ("id","groupId","itemId",@@ -110,6 +126,9 @@ export function buildBulkUpsertPermissionsSql(* - Folder→parent walking starts from each visible folder *and* from each* visible document's `folderId`. Root-level documents have no folder, so* they're filtered out (correct: they have no ancestor to make visible).+ *+ * Independent of the access-control table — this only walks+ * `DataroomFolder` / `DataroomDocument` and is shared by both consumers.*/export function buildFindAncestorFolderIdsSql(dataroomId: string,@@ -173,6 +192,7 @@ export function buildFindAncestorFolderIdsSql(* ancestor is already visible — typical case in steady state.*/export function buildUpsertAncestorVisibilitySql(+ table: AccessControlTable,groupId: string,ancestors: AncestorUpsertRow[],): Prisma.Sql | null {@@ -188,7 +208,7 @@ export function buildUpsertAncestorVisibilitySql();return Prisma.sql`- INSERT INTO "ViewerGroupAccessControls" (+ INSERT INTO ${tableRef(table)} ("id","groupId","itemId",@@ -211,7 +231,35 @@ export function buildUpsertAncestorVisibilitySql(ON CONFLICT ("groupId", "itemId") DO UPDATE SET"canView" = TRUE,"updatedAt" = NOW()- WHERE "ViewerGroupAccessControls"."canView" = FALSE;+ WHERE ${tableRef(table)}."canView" = FALSE;+ `;+}++/**+ * Build a `DELETE` for rows in `table` belonging to `groupId` whose `itemId`+ * is *not* in `keepItemIds`. This is the link-permission "set the entire+ * permission state" semantic — anything no longer in the desired payload+ * (after ancestor expansion) is removed.+ *+ * Returns `null` when `keepItemIds` is empty so the caller can decide+ * whether to wipe everything for the group or skip the call entirely. Most+ * link saves should always include something (at minimum the toggled item+ * and its ancestors), so an empty array is unusual.+ */+export function buildDeletePermissionsNotInPayloadSql(+ table: AccessControlTable,+ groupId: string,+ keepItemIds: string[],+): Prisma.Sql | null {+ if (keepItemIds.length === 0) return null;++ // Dedupe so the bound parameter list stays compact for huge payloads.+ const uniqueIds = Array.from(new Set(keepItemIds));++ return Prisma.sql`+ DELETE FROM ${tableRef(table)}+ WHERE "groupId" = ${groupId}+ AND "itemId" NOT IN (${Prisma.join(uniqueIds)});`;}diff --git a/package-lock.json b/package-lock.jsonindex 33466629..69663782 100644--- a/package-lock.json+++ b/package-lock.json@@ -66,9 +66,9 @@"@tiptap/react": "^3.22.5","@tiptap/starter-kit": "^3.22.5","@tremor/react": "^3.18.7",- "@trigger.dev/python": "4.4.5",- "@trigger.dev/react-hooks": "4.4.5",- "@trigger.dev/sdk": "4.4.5",+ "@trigger.dev/python": "4.4.6",+ "@trigger.dev/react-hooks": "4.4.6",+ "@trigger.dev/sdk": "4.4.6","@tus/s3-store": "^1.9.1","@tus/server": "^1.10.2","@tus/utils": "^0.5.1",@@ -162,7 +162,7 @@"devDependencies": {"@react-email/ui": "^6.1.1","@tailwindcss/forms": "^0.5.11",- "@trigger.dev/build": "4.4.5",+ "@trigger.dev/build": "4.4.6","@trivago/prettier-plugin-sort-imports": "^6.0.2","@types/bcryptjs": "^2.4.6","@types/cookie": "^0.6.0",@@ -10365,13 +10365,13 @@}},"node_modules/@trigger.dev/build": {- "version": "4.4.5",- "resolved": "https://registry.npmjs.org/@trigger.dev/build/-/build-4.4.5.tgz",- "integrity": "sha512-45l8cv59JERkDrC5tADkKVDJriZjPtCtkAHVWvCZXRJMlm93Ao8deTHdtOf++TqdsqdG9Tk5cxhupY1COq4muA==",+ "version": "4.4.6",+ "resolved": "https://registry.npmjs.org/@trigger.dev/build/-/build-4.4.6.tgz",+ "integrity": "sha512-eHPPaeuFe9GZDndQzP4QUlxocyIJWYSx0FMx1GEiAnEVKwXWUqiW72DRFH7cr9v7IQnI9YbAWRuWvyMPHSVLwg==","license": "MIT","dependencies": {"@prisma/config": "^6.10.0",- "@trigger.dev/core": "4.4.5",+ "@trigger.dev/core": "4.4.6","mlly": "^1.7.1","pkg-types": "^1.1.3","resolve": "^1.22.8",@@ -10383,9 +10383,9 @@}},"node_modules/@trigger.dev/core": {- "version": "4.4.5",- "resolved": "https://registry.npmjs.org/@trigger.dev/core/-/core-4.4.5.tgz",- "integrity": "sha512-VI4AjX5ivbm+E8RMdP2kjuo/ph8cTCQTNkZSx6UknnAxyu2mihqPbcYWl2tqZCGbbX/HIlzhEtM2NM3a01Juxg==",+ "version": "4.4.6",+ "resolved": "https://registry.npmjs.org/@trigger.dev/core/-/core-4.4.6.tgz",+ "integrity": "sha512-oXAjxBNVMiKXUKj1EnHUlO2ULujc4Dy8ad+H/59DYZGY1barkGVzrQAQIpBZo/kDygu7dKGT+F5yBkbIkYjAUw==","license": "MIT","dependencies": {"@bugsnag/cuid": "^3.1.1",@@ -10614,29 +10614,29 @@}},"node_modules/@trigger.dev/python": {- "version": "4.4.5",- "resolved": "https://registry.npmjs.org/@trigger.dev/python/-/python-4.4.5.tgz",- "integrity": "sha512-SwwInXDB0OH9PztQaTPt84XFU2HbNmIdYwTOlsW60gLPEVNdYCZVPRJXyQMM163fVL8Rzr9ScKumLVQbNUd2AQ==",+ "version": "4.4.6",+ "resolved": "https://registry.npmjs.org/@trigger.dev/python/-/python-4.4.6.tgz",+ "integrity": "sha512-iYlg40+2jVXJaog4TqcM35kEks/ES53sGQJsfTpl/M0RusirY4POXVmPPaudJZE33SKVb2X8PuKLBWhejT1WqQ==","license": "MIT","dependencies": {- "@trigger.dev/core": "4.4.5",+ "@trigger.dev/core": "4.4.6","tinyexec": "^0.3.2"},"engines": {"node": ">=18.20.0"},"peerDependencies": {- "@trigger.dev/build": "^4.4.5",- "@trigger.dev/sdk": "^4.4.5"+ "@trigger.dev/build": "^4.4.6",+ "@trigger.dev/sdk": "^4.4.6"}},"node_modules/@trigger.dev/react-hooks": {- "version": "4.4.5",- "resolved": "https://registry.npmjs.org/@trigger.dev/react-hooks/-/react-hooks-4.4.5.tgz",- "integrity": "sha512-csY7tmfg2wNAt3MOLgJ5C94y9Cf0g0f3K8NN5etNiI/48wnKV8PgSrZpARSQczhBoB6pt/cwvB4kiLAG/aVQug==",+ "version": "4.4.6",+ "resolved": "https://registry.npmjs.org/@trigger.dev/react-hooks/-/react-hooks-4.4.6.tgz",+ "integrity": "sha512-Fr4nQIt3sAAPGTbBJfALHzMQUE0O4HPNVz4lRwIwCc3/HAfjPr8uza6e7iagDOWWs68PWtOOayDWQ5Nvbz6QOg==","license": "MIT","dependencies": {- "@trigger.dev/core": "^4.4.5",+ "@trigger.dev/core": "^4.4.6","swr": "^2.2.5"},"engines": {@@ -10648,14 +10648,14 @@}},"node_modules/@trigger.dev/sdk": {- "version": "4.4.5",- "resolved": "https://registry.npmjs.org/@trigger.dev/sdk/-/sdk-4.4.5.tgz",- "integrity": "sha512-iXjEWQQy+Dc7WDdjOtGLTlHIcVdcg00GUYL/hTr5FwMlY/Aswvfe0Snfn+7XECtls2tgZTPJ+rnTP4mo77o5eg==",+ "version": "4.4.6",+ "resolved": "https://registry.npmjs.org/@trigger.dev/sdk/-/sdk-4.4.6.tgz",+ "integrity": "sha512-FAC5/oES4dClLWlLGvnuNUlhfzWXDA6ResxB7B6/2UohSdxn3yWt9uOtjEL434JiN0xNUCiSAN8KTP1azpOgBg==","license": "MIT","dependencies": {"@opentelemetry/api": "1.9.0","@opentelemetry/semantic-conventions": "1.36.0",- "@trigger.dev/core": "4.4.5",+ "@trigger.dev/core": "4.4.6","chalk": "^5.2.0","cronstrue": "^2.21.0","debug": "^4.3.4",@@ -13110,6 +13110,8 @@},"node_modules/chalk": {"version": "5.6.2",+ "resolved": "https://registry.npmjs.org/chalk/-/chalk-5.6.2.tgz",+ "integrity": "sha512-7NzBL0rN6fMUW+f7A6Io4h40qQlG+xGmtMxfbnH/K7TAtt8JQWVQK+6g0UXKMeVJoyV5EkkNsErQ8pVD3bLHbA==","license": "MIT","engines": {"node": "^12.17.0 || ^14.13 || >=16.0.0"diff --git a/package.json b/package.jsonindex 880d7750..28ed37a4 100644--- a/package.json+++ b/package.json@@ -78,9 +78,9 @@"@tiptap/react": "^3.22.5","@tiptap/starter-kit": "^3.22.5","@tremor/react": "^3.18.7",- "@trigger.dev/python": "4.4.5",- "@trigger.dev/react-hooks": "4.4.5",- "@trigger.dev/sdk": "4.4.5",+ "@trigger.dev/python": "4.4.6",+ "@trigger.dev/react-hooks": "4.4.6",+ "@trigger.dev/sdk": "4.4.6","@tus/s3-store": "^1.9.1","@tus/server": "^1.10.2","@tus/utils": "^0.5.1",@@ -174,7 +174,7 @@"devDependencies": {"@react-email/ui": "^6.1.1","@tailwindcss/forms": "^0.5.11",- "@trigger.dev/build": "4.4.5",+ "@trigger.dev/build": "4.4.6","@trivago/prettier-plugin-sort-imports": "^6.0.2","@types/bcryptjs": "^2.4.6","@types/cookie": "^0.6.0",@@ -217,4 +217,4 @@"tar": "7.5.10","lodash": "4.18.1"}-}+}\ No newline at end of filediff --git a/pages/api/links/[id]/documents/[documentId].ts b/pages/api/links/[id]/documents/[documentId].tsdeleted file mode 100644index f29c646c..00000000--- a/pages/api/links/[id]/documents/[documentId].ts+++ /dev/null@@ -1,147 +0,0 @@-import { NextApiRequest, NextApiResponse } from "next";--import { DataroomBrand, LinkAudienceType } from "@prisma/client";--import { fetchDataroomDocumentLinkData } from "@/lib/api/links/link-data";-import { errorhandler } from "@/lib/errorHandler";-import prisma from "@/lib/prisma";-import { checkGlobalBlockList } from "@/lib/utils/global-block-list";--export default async function handle(- req: NextApiRequest,- res: NextApiResponse,-) {- if (req.method !== "GET") {- res.setHeader("Allow", ["GET"]);- return res.status(405).end(`Method ${req.method} Not Allowed`);- }-- const { id, documentId: dataroomDocumentId } = req.query as {- id: string;- documentId: string;- };-- try {- // First fetch the link and verify it's a dataroom link- const link = await prisma.link.findUnique({- where: { id, linkType: "DATAROOM_LINK" },- select: {- id: true,- expiresAt: true,- emailProtected: true,- emailAuthenticated: true,- allowDownload: true,- enableFeedback: true,- enableScreenshotProtection: true,- password: true,- isArchived: true,- deletedAt: true,- enableCustomMetatag: true,- metaTitle: true,- metaDescription: true,- metaImage: true,- metaFavicon: true,- welcomeMessage: true,- enableQuestion: true,- linkType: true,- feedback: {- select: {- id: true,- data: true,- },- },- enableAgreement: true,- agreement: true,- showBanner: true,- enableWatermark: true,- watermarkConfig: true,- groupId: true,- permissionGroupId: true,- audienceType: true,- dataroomId: true,- teamId: true,- team: {- select: {- plan: true,- globalBlockList: true,- },- },- customFields: {- select: {- id: true,- type: true,- identifier: true,- label: true,- placeholder: true,- required: true,- disabled: true,- orderIndex: true,- },- orderBy: {- orderIndex: "asc",- },- },- },- });-- if (!link) {- return res.status(404).json({ error: "Link not found" });- }-- if (link.deletedAt) {- return res.status(404).json({ error: "Link has been deleted" });- }-- if (link.isArchived) {- return res.status(404).json({ error: "Link is archived" });- }-- const { email } = req.query as { email?: string };- const globalBlockCheck = checkGlobalBlockList(- email,- link.team?.globalBlockList,- );- if (globalBlockCheck.error) {- return res.status(400).json({ message: globalBlockCheck.error });- }- if (globalBlockCheck.isBlocked) {- return res.status(403).json({ message: "Access denied" });- }-- let brand: Partial<DataroomBrand> | null = null;- let linkData: any;-- const data = await fetchDataroomDocumentLinkData({- linkId: id,- teamId: link.teamId!,- dataroomDocumentId: dataroomDocumentId,- permissionGroupId: link.permissionGroupId || undefined,- ...(link.audienceType === LinkAudienceType.GROUP &&- link.groupId && {- groupId: link.groupId,- }),- });-- linkData = data.linkData;- brand = data.brand;-- const teamPlan = link.team?.plan || "free";- const linkType = link.linkType;-- const returnLink = {- ...link,- dataroomDocument: linkData.dataroom?.documents[0],- ...(teamPlan === "free" && {- customFields: [], // reset custom fields for free plan- enableAgreement: false,- enableWatermark: false,- permissionGroupId: null,- }),- };-- return res.status(200).json({ linkType, link: returnLink, brand });- } catch (error) {- console.error("Error fetching document:", error);- errorhandler(error, res);- }-}diff --git a/pages/api/links/[id]/documents/[documentId]/annotations.ts b/pages/api/links/[id]/documents/[documentId]/annotations.tsindex 7c9b8d57..c952637c 100644--- a/pages/api/links/[id]/documents/[documentId]/annotations.ts+++ b/pages/api/links/[id]/documents/[documentId]/annotations.ts@@ -1,5 +1,9 @@import { NextApiRequest, NextApiResponse } from "next";+import {+ getDataroomSessionByLinkIdInPagesRouter,+ verifyDataroomSessionInPagesRouter,+} from "@/lib/auth/dataroom-auth";import { errorhandler } from "@/lib/errorHandler";import { getFeatureFlags } from "@/lib/featureFlags";import prisma from "@/lib/prisma";@@ -30,6 +34,7 @@ export default async function handle(select: {id: true,viewedAt: true,+ viewerId: true,link: {select: {id: true,@@ -56,6 +61,36 @@ export default async function handle(return res.status(403).json({ error: "Access denied" });}+ // Bind the requested viewId to the caller's session. Dataroom links+ // are verified against (linkId, dataroomId); document-only links only+ // enforce when a dataroom-session cookie is present (not all+ // document-link views set one).+ if (view.link.linkType === "DATAROOM_LINK" && view.link.dataroomId) {+ const session = await verifyDataroomSessionInPagesRouter(+ req,+ linkId,+ view.link.dataroomId,+ );+ if (!session) {+ return res.status(401).json({ error: "Unauthorized" });+ }+ const sameViewer =+ !!session.viewerId &&+ !!view.viewerId &&+ session.viewerId === view.viewerId;+ if (session.viewId !== view.id && !sameViewer) {+ return res.status(403).json({ error: "Access denied" });+ }+ } else {+ const session = await getDataroomSessionByLinkIdInPagesRouter(+ req,+ linkId,+ );+ if (session && session.viewId !== view.id) {+ return res.status(403).json({ error: "Access denied" });+ }+ }+// Check if annotations feature is enabled for this teamconst featureFlags = await getFeatureFlags({teamId: view.link.teamId || undefined,diff --git a/pages/api/links/download/dataroom-document.ts b/pages/api/links/download/dataroom-document.tsindex bfc656ed..93b9a795 100644--- a/pages/api/links/download/dataroom-document.ts+++ b/pages/api/links/download/dataroom-document.ts@@ -168,17 +168,47 @@ export default async function handle(});}- const permittedDocumentIds = groupPermissions- .filter(- (permission) => permission.itemType === ItemType.DATAROOM_DOCUMENT,- )- .map((permission) => permission.itemId);+ const permittedDocumentIds = new Set(+ groupPermissions+ .filter(+ (permission) =>+ permission.itemType === ItemType.DATAROOM_DOCUMENT,+ )+ .map((permission) => permission.itemId as string),+ );++ // Fallback: viewer-uploaded docs aren't tied to the link's+ // permission group. Allow the original uploader through, scoped to+ // the current viewer's id.+ const candidateDocIds = downloadDocuments+ .filter((doc) => !permittedDocumentIds.has(doc.id))+ .map((doc) => doc.id);++ if (candidateDocIds.length > 0 && view.viewerId) {+ const viewerUploads = await prisma.documentUpload.findMany({+ where: {+ linkId,+ viewerId: view.viewerId,+ dataroomDocumentId: { in: candidateDocIds },+ },+ select: { dataroomDocumentId: true },+ });+ for (const upload of viewerUploads) {+ if (upload.dataroomDocumentId) {+ permittedDocumentIds.add(upload.dataroomDocumentId);+ }+ }+ }downloadDocuments = downloadDocuments.filter((doc) =>- permittedDocumentIds.includes(doc.id),+ permittedDocumentIds.has(doc.id),);}+ if (downloadDocuments.length === 0) {+ return res.status(403).json({ error: "Error downloading" });+ }+//creates new view for documentawait prisma.view.create({data: {diff --git a/pages/api/teams/[teamId]/datarooms/[id]/groups/[groupId]/permissions.ts b/pages/api/teams/[teamId]/datarooms/[id]/groups/[groupId]/permissions.tsindex 92836f4c..b6e47078 100644--- a/pages/api/teams/[teamId]/datarooms/[id]/groups/[groupId]/permissions.ts+++ b/pages/api/teams/[teamId]/datarooms/[id]/groups/[groupId]/permissions.ts@@ -96,7 +96,11 @@ export default async function handler(}),);- const bulkUpsertSql = buildBulkUpsertPermissionsSql(groupId, upsertRows);+ const bulkUpsertSql = buildBulkUpsertPermissionsSql(+ "ViewerGroupAccessControls",+ groupId,+ upsertRows,+ );const { visibleDocumentIds, visibleFolderIds } =extractVisibleItemIds(permissions);@@ -128,6 +132,7 @@ export default async function handler(}));const ancestorUpsertSql = buildUpsertAncestorVisibilitySql(+ "ViewerGroupAccessControls",groupId,ancestors,);diff --git a/pages/api/teams/[teamId]/datarooms/[id]/permission-groups/[permissionGroupId].ts b/pages/api/teams/[teamId]/datarooms/[id]/permission-groups/[permissionGroupId].tsindex 595a3676..fbc41d9e 100644--- a/pages/api/teams/[teamId]/datarooms/[id]/permission-groups/[permissionGroupId].ts+++ b/pages/api/teams/[teamId]/datarooms/[id]/permission-groups/[permissionGroupId].ts@@ -2,14 +2,32 @@ import { NextApiRequest, NextApiResponse } from "next";import { authOptions } from "@/pages/api/auth/[...nextauth]";import { ItemType } from "@prisma/client";+import cuid from "cuid";import { getServerSession } from "next-auth/next";import { z } from "zod";import { revalidateLinksForPermissionGroup } from "@/lib/api/links/revalidate";+import {+ buildBulkUpsertPermissionsSql,+ buildDeletePermissionsNotInPayloadSql,+ buildFindAncestorFolderIdsSql,+ buildUpsertAncestorVisibilitySql,+ extractVisibleItemIds,+ type AncestorUpsertRow,+ type PermissionUpsertRow,+} from "@/lib/dataroom/permissions-sql";import { errorhandler } from "@/lib/errorHandler";import prisma from "@/lib/prisma";import { CustomUser } from "@/lib/types";+// PUT can save thousands of permission rows in a single payload (think+// "select all" on a large dataroom). With the bulk-SQL path below this is+// now ~3-4 round-trips total, but we still bump the platform timeout to be+// safe — same as the neighbouring `groups/[groupId]/permissions.ts`.+export const config = {+ maxDuration: 300,+};+// Zod schema for validating permissionsconst itemPermissionSchema = z.object({view: z.boolean(),@@ -24,121 +42,6 @@ const patchPermissionGroupSchema = z.object({description: z.string().optional(),});-// Helper function to get parent folder IDs for a given document in a dataroom-async function getParentFolderIds(- dataroomId: string,- documentId: string,-): Promise<string[]> {- // Get the dataroom document to find which folder it's in- const dataroomDocument = await prisma.dataroomDocument.findUnique({- where: { id: documentId },- select: { folderId: true },- });-- if (!dataroomDocument?.folderId) {- return []; // Document is at root level- }-- // Get the folder and walk up the hierarchy- const parentFolders: string[] = [];- let currentFolderId: string | null = dataroomDocument.folderId;-- while (currentFolderId) {- parentFolders.push(currentFolderId);-- const folder: { parentId: string | null } | null =- await prisma.dataroomFolder.findUnique({- where: { id: currentFolderId },- select: { parentId: true },- });-- currentFolderId = folder?.parentId || null;- }-- return parentFolders;-}--// Helper function to ensure parent folders are visible when child documents are made visible-async function ensureParentFoldersVisible(- dataroomId: string,- groupId: string,- permissions: Record<- string,- { itemType: ItemType; view: boolean; download: boolean }- >,-): Promise<void> {- const foldersToMakeVisible = new Set<string>();-- // Find all documents that are being made visible- const visibleDocuments = Object.entries(permissions)- .filter(- ([_, perm]) => perm.itemType === ItemType.DATAROOM_DOCUMENT && perm.view,- )- .map(([itemId, _]) => itemId);-- // Get parent folder IDs for all visible documents- for (const documentId of visibleDocuments) {- const parentFolders = await getParentFolderIds(dataroomId, documentId);- parentFolders.forEach((folderId) => foldersToMakeVisible.add(folderId));- }-- // Also handle folders that are being made visible - ensure their parent folders are visible too- const visibleFolders = Object.entries(permissions)- .filter(- ([_, perm]) => perm.itemType === ItemType.DATAROOM_FOLDER && perm.view,- )- .map(([itemId, _]) => itemId);-- for (const folderId of visibleFolders) {- let currentFolderId: string | null = folderId;-- while (currentFolderId) {- const folder: { parentId: string | null } | null =- await prisma.dataroomFolder.findUnique({- where: { id: currentFolderId },- select: { parentId: true },- });-- if (folder?.parentId) {- foldersToMakeVisible.add(folder.parentId);- currentFolderId = folder.parentId;- } else {- break;- }- }- }-- // Update or create permissions for parent folders to make them visible- if (foldersToMakeVisible.size > 0) {- const foldersToUpdate = Array.from(foldersToMakeVisible);-- await prisma.$transaction(async (tx) => {- for (const folderId of foldersToUpdate) {- await tx.permissionGroupAccessControls.upsert({- where: {- groupId_itemId: {- groupId: groupId,- itemId: folderId,- },- },- create: {- groupId: groupId,- itemId: folderId,- itemType: ItemType.DATAROOM_FOLDER,- canView: true,- canDownload: false,- canDownloadOriginal: false,- },- update: {- canView: true, // Always ensure parent folders are visible- // Don't change canDownload - preserve existing setting- },- });- }- });- }-}-export default async function handle(req: NextApiRequest,res: NextApiResponse,@@ -359,7 +262,6 @@ export default async function handle(return res.status(400).json({ error: "Permissions are required" });}- // Validate schema structureconst validationResult = permissionsSchema.safeParse(permissions);if (!validationResult.success) {return res.status(400).json({@@ -370,129 +272,100 @@ export default async function handle(const validatedPermissions = validationResult.data;- const updatedPermissionGroup = await prisma.$transaction(async (tx) => {- // Get existing permissions for comparison- const existingPermissions =- await tx.permissionGroupAccessControls.findMany({- where: {- groupId: permissionGroupId,- },- });+ // Build the bulk-SQL plan. The link-permission UI posts the+ // *complete* desired state (it merges existing rows with pending+ // changes before calling us), so we treat the payload as+ // authoritative: anything in DB but not in (payload ∪ ancestor+ // expansion) is removed.+ const upsertRows: PermissionUpsertRow[] = Object.entries(+ validatedPermissions,+ ).map(([itemId, perm]) => ({+ id: cuid(),+ itemId,+ itemType: perm.itemType,+ canView: perm.view,+ canDownload: perm.download,+ }));++ const bulkUpsertSql = buildBulkUpsertPermissionsSql(+ "PermissionGroupAccessControls",+ permissionGroupId,+ upsertRows,+ );- // Create maps for efficient lookup- const existingMap = new Map(- existingPermissions.map((p) => [`${p.itemId}-${p.itemType}`, p]),- );+ const { visibleDocumentIds, visibleFolderIds } =+ extractVisibleItemIds(validatedPermissions);- // Categorize permissions into updates vs creates- const toUpdate: Array<{- itemId: string;- itemType: ItemType;- canView: boolean;- canDownload: boolean;- canDownloadOriginal: boolean;- }> = [];-- const toCreate: Array<{- groupId: string;- itemId: string;- itemType: ItemType;- canView: boolean;- canDownload: boolean;- canDownloadOriginal: boolean;- }> = [];-- // Categorize permissions into updates vs creates- Object.entries(validatedPermissions).forEach(([itemId, permission]) => {- const key = `${itemId}-${permission.itemType}`;- const existing = existingMap.get(key);-- const permissionData = {- itemId,- itemType: permission.itemType,- canView: permission.view,- canDownload: permission.download,- canDownloadOriginal: false,- };-- if (existing) {- // Check if anything actually changed- if (- existing.canView !== permission.view ||- existing.canDownload !== permission.download- ) {- toUpdate.push(permissionData);- }- } else {- toCreate.push({- groupId: permissionGroupId,- ...permissionData,- });- }- });+ const findAncestorsSql = buildFindAncestorFolderIdsSql(+ dataroomId,+ visibleDocumentIds,+ visibleFolderIds,+ );- // Perform updates- if (toUpdate.length > 0) {- await Promise.all(- toUpdate.map((item) =>- tx.permissionGroupAccessControls.updateMany({- where: {- groupId: permissionGroupId,- itemId: item.itemId,- itemType: item.itemType,- },- data: {- canView: item.canView,- canDownload: item.canDownload,- canDownloadOriginal: item.canDownloadOriginal,- },- }),- ),- );+ await prisma.$transaction(async (tx) => {+ if (bulkUpsertSql) {+ await tx.$executeRaw(bulkUpsertSql);}- // Perform creates- if (toCreate.length > 0) {- await tx.permissionGroupAccessControls.createMany({- data: toCreate,- });+ // Server-side safety net for the "visible item ⇒ visible+ // ancestors" invariant. Defence-in-depth: the client already+ // includes ancestors in its payload via `collectChangesForItem`,+ // but a buggy/old client or external API caller might not.+ const ancestorIds = new Set<string>();+ if (findAncestorsSql) {+ const ancestorRows = await tx.$queryRaw<{ folder_id: string }[]>(+ findAncestorsSql,+ );+ for (const r of ancestorRows) ancestorIds.add(r.folder_id);++ if (ancestorRows.length > 0) {+ const ancestors: AncestorUpsertRow[] = ancestorRows.map((r) => ({+ id: cuid(),+ folderId: r.folder_id,+ }));++ const ancestorUpsertSql = buildUpsertAncestorVisibilitySql(+ "PermissionGroupAccessControls",+ permissionGroupId,+ ancestors,+ );+ if (ancestorUpsertSql) {+ await tx.$executeRaw(ancestorUpsertSql);+ }+ }}- // Remove permissions that are no longer in the new set- const newItemKeys = new Set(- Object.entries(validatedPermissions).map(- ([itemId, permission]) => `${itemId}-${permission.itemType}`,- ),- );-- const toDelete = existingPermissions.filter(- (p) => !newItemKeys.has(`${p.itemId}-${p.itemType}`),- );-- if (toDelete.length > 0) {+ // Set-everything semantic: drop any DB row whose itemId is no+ // longer in the desired state. We keep both the explicit payload+ // ids *and* the ancestor folder ids so the visibility safety net+ // we just upserted isn't immediately deleted again.+ const keepItemIds = [+ ...Object.keys(validatedPermissions),+ ...ancestorIds,+ ];++ if (keepItemIds.length > 0) {+ const deleteSql = buildDeletePermissionsNotInPayloadSql(+ "PermissionGroupAccessControls",+ permissionGroupId,+ keepItemIds,+ );+ if (deleteSql) {+ await tx.$executeRaw(deleteSql);+ }+ } else {+ // Empty payload + no ancestors → user is clearing all+ // permissions. Delete every row for this group.await tx.permissionGroupAccessControls.deleteMany({- where: {- id: {- in: toDelete.map((p) => p.id),- },- },+ where: { groupId: permissionGroupId },});}-- return permissionGroup;});- // After saving permissions, ensure parent folders are visible for any items that were made visible- await ensureParentFoldersVisible(- dataroomId,- permissionGroupId,- validatedPermissions,- );-// Revalidate ISR pages so viewers see the updated file listawait revalidateLinksForPermissionGroup(permissionGroupId);- return res.status(200).json({ permissionGroup: updatedPermissionGroup });+ return res.status(200).json({ permissionGroup });} catch (error) {return errorhandler(error, res);}diff --git a/pages/api/teams/[teamId]/datarooms/[id]/permission-groups/index.ts b/pages/api/teams/[teamId]/datarooms/[id]/permission-groups/index.tsindex 6210f454..d51c429a 100644--- a/pages/api/teams/[teamId]/datarooms/[id]/permission-groups/index.ts+++ b/pages/api/teams/[teamId]/datarooms/[id]/permission-groups/index.ts@@ -1,18 +1,43 @@import { NextApiRequest, NextApiResponse } from "next";import { ItemType } from "@prisma/client";+import cuid from "cuid";import { getServerSession } from "next-auth/next";+import { z } from "zod";import {revalidateLinkById,revalidateLinksForPermissionGroup,} from "@/lib/api/links/revalidate";+import {+ buildFindAncestorFolderIdsSql,+ buildUpsertAncestorVisibilitySql,+ extractVisibleItemIds,+ type AncestorUpsertRow,+} from "@/lib/dataroom/permissions-sql";import { errorhandler } from "@/lib/errorHandler";import prisma from "@/lib/prisma";import { CustomUser } from "@/lib/types";import { authOptions } from "../../../../../auth/[...nextauth]";+// Same payload-size considerations as the PUT route — bump the timeout so+// large datarooms saving full permission state at create time don't trip+// the platform default.+export const config = {+ maxDuration: 300,+};++// Mirrors the schema used by the PUT handler in+// `[permissionGroupId].ts` so the same validation rules apply to creates.+const itemPermissionSchema = z.object({+ view: z.boolean(),+ download: z.boolean(),+ itemType: z.nativeEnum(ItemType),+});++const permissionsSchema = z.record(z.string(), itemPermissionSchema);+export default async function handle(req: NextApiRequest,res: NextApiResponse,@@ -171,6 +196,44 @@ export default async function handle(return res.status(404).json({ error: "Dataroom not found" });}+ // Validate permissions payload using Zod before any DB work so+ // malformed bodies fail closed and never reach raw-SQL builders or+ // the interactive transaction below.+ if (!permissions) {+ return res.status(400).json({ error: "Permissions are required" });+ }++ const validationResult = permissionsSchema.safeParse(permissions);+ if (!validationResult.success) {+ return res.status(400).json({+ error: "Invalid permissions format",+ details: validationResult.error.issues,+ });+ }++ const typedPermissions = validationResult.data;++ // Compute the recursive-CTE ancestor walk *before* opening the+ // transaction so the interactive transaction stays as short as+ // possible. The CTE only reads `DataroomFolder` / `DataroomDocument`+ // — both immutable from this caller's perspective — so doing it+ // outside the tx is safe.+ const { visibleDocumentIds, visibleFolderIds } =+ extractVisibleItemIds(typedPermissions);+ const findAncestorsSql = buildFindAncestorFolderIdsSql(+ dataroomId,+ visibleDocumentIds,+ visibleFolderIds,+ );++ let ancestorFolderIds: string[] = [];+ if (findAncestorsSql) {+ const ancestorRows = await prisma.$queryRaw<{ folder_id: string }[]>(+ findAncestorsSql,+ );+ ancestorFolderIds = ancestorRows.map((r) => r.folder_id);+ }+// Create permission group and access controls in a transactionconst result = await prisma.$transaction(async (tx) => {// Create the permission group@@ -184,22 +247,15 @@ export default async function handle(});// Prepare access control data for batch insert- const accessControlData = Object.entries(permissions).map(- ([itemId, permission]) => {- const perm = permission as {- view: boolean;- download: boolean;- itemType: ItemType;- };- return {- groupId: permissionGroup.id,- itemId: itemId,- itemType: perm.itemType,- canView: perm.view,- canDownload: perm.download,- canDownloadOriginal: false,- };- },+ const accessControlData = Object.entries(typedPermissions).map(+ ([itemId, perm]) => ({+ groupId: permissionGroup.id,+ itemId: itemId,+ itemType: perm.itemType,+ canView: perm.view,+ canDownload: perm.download,+ canDownloadOriginal: false,+ }),);// Create all access controls in a single batch operation@@ -207,6 +263,29 @@ export default async function handle(data: accessControlData,});+ // Server-side safety net for "visible item ⇒ visible ancestors".+ // Defence-in-depth: with the shared `permissions-tree` helpers the+ // client already includes ancestors, but a buggy/old client or an+ // external API caller might not. We force `canView=true` on those+ // ancestor folders without touching `canDownload` so we don't+ // clobber any ancestor's existing download grant.+ if (ancestorFolderIds.length > 0) {+ const ancestors: AncestorUpsertRow[] = ancestorFolderIds.map(+ (folderId) => ({+ id: cuid(),+ folderId,+ }),+ );+ const ancestorUpsertSql = buildUpsertAncestorVisibilitySql(+ "PermissionGroupAccessControls",+ permissionGroup.id,+ ancestors,+ );+ if (ancestorUpsertSql) {+ await tx.$executeRaw(ancestorUpsertSql);+ }+ }+// Fetch the created access controls for return dataconst accessControls = await tx.permissionGroupAccessControls.findMany({where: {