Skip to content

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

feat: add document signing

Marc Seitz3d8c44d3d2df
diff --git a/.gitignore b/.gitignore
index e70a0b49..8973adf7 100644
--- a/.gitignore
+++ b/.gitignore
@@ -70,4 +70,6 @@ changelog
.docs
# Local sync workflow dry-run output
-_public/
\ No newline at end of file
+_public/
+
+.opencode
\ No newline at end of file
diff --git a/app/api/views-dataroom/route.ts b/app/api/views-dataroom/route.ts
index 5d874048..271ec9bd 100644
--- a/app/api/views-dataroom/route.ts
+++ b/app/api/views-dataroom/route.ts
@@ -2,12 +2,12 @@ import { NextRequest, NextResponse } from "next/server";
import { reportDeniedAccessAttempt } from "@/ee/features/access-notifications";
import { getTeamStorageConfigById } from "@/ee/features/storage/config";
-import { authOptions } from "@/lib/auth/auth-options";
import { ItemType, LinkAudienceType, LinkType } from "@prisma/client";
import { ipAddress, waitUntil } from "@vercel/functions";
import { getServerSession } from "next-auth";
import { hashToken } from "@/lib/api/auth/token";
+import { authOptions } from "@/lib/auth/auth-options";
import {
DataroomSession,
collectFingerprintHeaders,
@@ -27,6 +27,15 @@ import {
import prisma from "@/lib/prisma";
import { ratelimit } from "@/lib/redis";
import { parseSheet } from "@/lib/sheet";
+import {
+ getSignedAgreementAccessCookieName,
+ parseSignedAgreementAccessToken,
+} from "@/lib/signing/access-token";
+import {
+ ensureAgreementResponseForAccess,
+ normalizeSignerEmail,
+ normalizeSignerName,
+} from "@/lib/signing/agreements";
import { recordLinkView } from "@/lib/tracking/record-link-view";
import { CustomUser, WatermarkConfigSchema } from "@/lib/types";
import { checkPassword, decryptEncrpytedPassword, log } from "@/lib/utils";
@@ -71,10 +80,17 @@ export async function POST(request: NextRequest) {
startPage?: number;
};
- const { email, password, name, hasConfirmedAgreement } = data as {
+ const {
+ email,
+ password,
+ name,
+ agreementResponseId,
+ hasConfirmedAgreement,
+ } = data as {
email: string;
password: string;
name?: string;
+ agreementResponseId?: string;
hasConfirmedAgreement?: boolean;
};
@@ -124,6 +140,14 @@ export async function POST(request: NextRequest) {
denyList: true,
enableAgreement: true,
agreementId: true,
+ agreement: {
+ select: {
+ id: true,
+ signingProvider: true,
+ contentType: true,
+ requireName: true,
+ },
+ },
enableWatermark: true,
watermarkConfig: true,
groupId: true,
@@ -258,18 +282,59 @@ export async function POST(request: NextRequest) {
link.dataroomId!,
);
-
// If we have a dataroom session, use its verified status
if (dataroomSession) {
isEmailVerified = dataroomSession.verified;
}
}
+ let effectiveEmail = normalizeSignerEmail(email);
+ let effectiveName = normalizeSignerName(name);
+
+ const signedAccessCookieValue =
+ link.enableAgreement && link.agreement
+ ? request.cookies.get(getSignedAgreementAccessCookieName(linkId))?.value
+ : undefined;
+ const signedAccessPayload = parseSignedAgreementAccessToken(
+ signedAccessCookieValue,
+ );
+ const cookieAgreementResponseId =
+ link.enableAgreement &&
+ link.agreement &&
+ signedAccessPayload &&
+ signedAccessPayload.linkId === linkId &&
+ signedAccessPayload.agreementId === link.agreement.id
+ ? signedAccessPayload.agreementResponseId
+ : null;
+
+ let verifiedAgreementResponse: Awaited<
+ ReturnType<typeof ensureAgreementResponseForAccess>
+ > | null = null;
+
// If there is no session, then we need to check if the link is protected and enforce the checks
if (!dataroomSession && !isPreview) {
+ if (cookieAgreementResponseId && link.enableAgreement && link.agreement) {
+ try {
+ verifiedAgreementResponse = await ensureAgreementResponseForAccess({
+ agreement: link.agreement,
+ linkId,
+ agreementResponseId: cookieAgreementResponseId,
+ skipSignerIdentityCheck: true,
+ });
+ effectiveEmail =
+ normalizeSignerEmail(verifiedAgreementResponse.signerEmail) ??
+ effectiveEmail;
+ effectiveName =
+ normalizeSignerName(verifiedAgreementResponse.signerName) ??
+ effectiveName;
+ } catch {
+ // Continue with the submitted identity; the agreement gate below will fail closed if needed.
+ }
+ }
+
// Check if email is required for visiting the link
if (link.emailProtected) {
- if (!email || email.trim() === "") {
+ if (!effectiveEmail || effectiveEmail.trim() === "") {
return NextResponse.json(
{ message: "Email is required." },
{ status: 400 },
@@ -277,7 +342,7 @@ export async function POST(request: NextRequest) {
}
// validate email
- if (!validateEmail(email)) {
+ if (!validateEmail(effectiveEmail)) {
return NextResponse.json(
{ message: "Invalid email address." },
{ status: 400 },
@@ -311,17 +376,60 @@ export async function POST(request: NextRequest) {
}
}
- // Check if agreement is required for visiting the link
- if (link.enableAgreement && !hasConfirmedAgreement) {
+ // Fail closed when an agreement is required but not configured, to avoid silently granting access.
+ if (link.enableAgreement && !link.agreement) {
return NextResponse.json(
- { message: "Agreement to NDA is required." },
- { status: 400 },
+ { message: "Agreement is required but not configured." },
+ { status: 500 },
);
}
+ if (
+ link.enableAgreement &&
+ link.agreement &&
+ !verifiedAgreementResponse
+ ) {
+ const resolvedAgreementResponseId =
+ agreementResponseId ?? cookieAgreementResponseId ?? undefined;
+
+ const hasCookieIdentityProof =
+ !!cookieAgreementResponseId &&
+ (!agreementResponseId ||
+ agreementResponseId === cookieAgreementResponseId);
+
+ try {
+ verifiedAgreementResponse = await ensureAgreementResponseForAccess({
+ agreement: link.agreement,
+ linkId,
+ agreementResponseId: resolvedAgreementResponseId,
+ hasConfirmedAgreement,
+ signerEmail: effectiveEmail,
+ signerName: effectiveName,
+ requireSignerEmail: link.emailProtected,
+ skipSignerIdentityCheck: hasCookieIdentityProof,
+ });
+ effectiveEmail =
+ normalizeSignerEmail(verifiedAgreementResponse.signerEmail) ??
+ effectiveEmail;
+ effectiveName =
+ normalizeSignerName(verifiedAgreementResponse.signerName) ??
+ effectiveName;
+ } catch (error) {
+ return NextResponse.json(
+ {
+ message:
+ error instanceof Error
+ ? error.message
+ : "Agreement signing is required.",
+ },
+ { status: 400 },
+ );
+ }
+ }
+
// Check global block list first - this overrides all other access controls
const globalBlockCheck = checkGlobalBlockList(
- email,
+ effectiveEmail ?? undefined,
link.team?.globalBlockList,
);
if (globalBlockCheck.error) {
@@ -331,7 +439,9 @@ export async function POST(request: NextRequest) {
);
}
if (globalBlockCheck.isBlocked) {
- waitUntil(reportDeniedAccessAttempt(link, email, "global"));
+ waitUntil(
+ reportDeniedAccessAttempt(link, effectiveEmail ?? "", "global"),
+ );
return NextResponse.json({ message: "Access denied" }, { status: 403 });
}
@@ -348,12 +458,14 @@ export async function POST(request: NextRequest) {
if (combinedAllowList.length > 0) {
// Determine if the email or its domain is allowed
const isAllowed = combinedAllowList.some((allowed) =>
- isEmailMatched(email, allowed),
+ isEmailMatched(effectiveEmail ?? "", allowed),
);
// Deny access if the email is not allowed
if (!isAllowed) {
- waitUntil(reportDeniedAccessAttempt(link, email, "allow"));
+ waitUntil(
+ reportDeniedAccessAttempt(link, effectiveEmail ?? "", "allow"),
+ );
return NextResponse.json(
{ message: "Unauthorized access" },
@@ -366,12 +478,14 @@ export async function POST(request: NextRequest) {
if (link.denyList && link.denyList.length > 0) {
// Determine if the email or its domain is denied
const isDenied = link.denyList.some((denied) =>
- isEmailMatched(email, denied),
+ isEmailMatched(effectiveEmail ?? "", denied),
);
// Deny access if the email is denied
if (isDenied) {
- waitUntil(reportDeniedAccessAttempt(link, email, "deny"));
+ waitUntil(
+ reportDeniedAccessAttempt(link, effectiveEmail ?? "", "deny"),
+ );
return NextResponse.json(
{ message: "Unauthorized access" },
@@ -404,18 +518,20 @@ export async function POST(request: NextRequest) {
} else {
// Check individual membership
const isMember = group.members.some(
- (member) => member.viewer.email === email,
+ (member) => member.viewer.email === effectiveEmail,
);
// Extract domain from email
- const emailDomain = extractEmailDomain(email);
+ const emailDomain = extractEmailDomain(effectiveEmail ?? "");
// Check domain access
const hasDomainAccess = emailDomain
? group.domains.some((domain) => domain === emailDomain)
: false;
if (!isMember && !hasDomainAccess) {
- waitUntil(reportDeniedAccessAttempt(link, email, "allow"));
+ waitUntil(
+ reportDeniedAccessAttempt(link, effectiveEmail ?? "", "allow"),
+ );
return NextResponse.json(
{ message: "Unauthorized access" },
{ status: 403 },
@@ -432,7 +548,7 @@ export async function POST(request: NextRequest) {
// Rate limit per email/link combination (1 per 30 seconds) to prevent OTP flooding
const { success: emailLimitSuccess } = await ratelimit(1, "30 s").limit(
- `send-otp:${linkId}:${email}`,
+ `send-otp:${linkId}:${effectiveEmail}`,
);
if (!emailLimitSuccess) {
return NextResponse.json(
@@ -457,7 +573,7 @@ export async function POST(request: NextRequest) {
await prisma.verificationToken.deleteMany({
where: {
- identifier: `otp:${linkId}:${email}`,
+ identifier: `otp:${linkId}:${effectiveEmail}`,
},
});
@@ -468,12 +584,19 @@ export async function POST(request: NextRequest) {
await prisma.verificationToken.create({
data: {
token: otpCode,
- identifier: `otp:${linkId}:${email}`,
+ identifier: `otp:${linkId}:${effectiveEmail}`,
expires: expiresAt,
},
});
- waitUntil(sendOtpVerificationEmail(email, otpCode, true, link.teamId!));
+ waitUntil(
+ sendOtpVerificationEmail(
+ effectiveEmail ?? "",
+ otpCode,
+ true,
+ link.teamId!,
+ ),
+ );
return NextResponse.json(
{
type: "email-verification",
@@ -499,7 +622,7 @@ export async function POST(request: NextRequest) {
const verification = await prisma.verificationToken.findUnique({
where: {
token: code,
- identifier: `otp:${linkId}:${email}`,
+ identifier: `otp:${linkId}:${effectiveEmail}`,
},
});
@@ -544,7 +667,7 @@ export async function POST(request: NextRequest) {
await prisma.verificationToken.create({
data: {
token: hashedVerificationToken,
- identifier: `link-verification:${linkId}:${link.teamId}:${email}`,
+ identifier: `link-verification:${linkId}:${link.teamId}:${effectiveEmail}`,
expires: tokenExpiresAt,
},
});
@@ -568,7 +691,7 @@ export async function POST(request: NextRequest) {
const verification = await prisma.verificationToken.findUnique({
where: {
token: token,
- identifier: `link-verification:${linkId}:${link.teamId}:${email}`,
+ identifier: `link-verification:${linkId}:${link.teamId}:${effectiveEmail}`,
},
});
@@ -601,20 +724,47 @@ export async function POST(request: NextRequest) {
isEmailVerified = true;
}
+ }
+ if (
+ !verifiedAgreementResponse &&
+ cookieAgreementResponseId &&
+ link.enableAgreement &&
+ link.agreement
+ ) {
+ try {
+ verifiedAgreementResponse = await ensureAgreementResponseForAccess({
+ agreement: link.agreement,
+ linkId,
+ agreementResponseId: cookieAgreementResponseId,
+ skipSignerIdentityCheck: true,
+ });
+ effectiveEmail =
+ normalizeSignerEmail(verifiedAgreementResponse.signerEmail) ??
+ effectiveEmail;
+ effectiveName =
+ normalizeSignerName(verifiedAgreementResponse.signerName) ??
+ effectiveName;
+ } catch {
+ // Existing dataroom sessions still grant access; ignore stale signed identity cookies.
+ }
}
+ const hasSignedAgreementIdentity = !!normalizeSignerEmail(
+ verifiedAgreementResponse?.signerEmail,
+ );
+
let viewer: { id: string; email: string; verified: boolean } | null = null;
if (!isPreview) {
if (!dataroomSession) {
- if (email) {
+ if (effectiveEmail) {
// find or create a viewer
console.time("find-viewer");
viewer = await prisma.viewer.findUnique({
where: {
teamId_email: {
teamId: link.teamId!,
- email: email,
+ email: effectiveEmail,
},
},
select: { id: true, email: true, verified: true },
@@ -625,7 +775,7 @@ export async function POST(request: NextRequest) {
console.time("create-viewer");
viewer = await prisma.viewer.create({
data: {
- email: email,
+ email: effectiveEmail,
verified: isEmailVerified,
teamId: link.teamId!,
},
@@ -641,6 +791,33 @@ export async function POST(request: NextRequest) {
select: { id: true, email: true, verified: true },
});
}
+
+ if (
+ hasSignedAgreementIdentity &&
+ effectiveEmail &&
+ (!viewer || viewer.email.toLowerCase() !== effectiveEmail)
+ ) {
+ viewer = await prisma.viewer.findUnique({
+ where: {
+ teamId_email: {
+ teamId: link.teamId!,
+ email: effectiveEmail,
+ },
+ },
+ select: { id: true, email: true, verified: true },
+ });
+
+ if (!viewer) {
+ viewer = await prisma.viewer.create({
+ data: {
+ email: effectiveEmail,
+ verified: isEmailVerified,
+ teamId: link.teamId!,
+ },
+ select: { id: true, email: true, verified: true },
+ });
+ }
+ }
}
if (viewer && !viewer.verified && isEmailVerified) {
@@ -651,26 +828,41 @@ export async function POST(request: NextRequest) {
// Update the viewer object to reflect the new verified status
viewer.verified = isEmailVerified;
}
+
+ if (dataroomSession?.viewId && hasSignedAgreementIdentity && viewer) {
+ await prisma.view.updateMany({
+ where: {
+ id: dataroomSession.viewId,
+ linkId,
+ dataroomId: link.dataroomId,
+ viewType: "DATAROOM_VIEW",
+ },
+ data: {
+ viewerEmail: viewer.email,
+ viewerName: effectiveName ?? undefined,
+ viewerId: viewer.id,
+ verified: viewer.verified || isEmailVerified,
+ },
+ });
+ }
}
+ const shouldRefreshDataroomSession = Boolean(
+ dataroomSession &&
+ hasSignedAgreementIdentity &&
+ viewer &&
+ dataroomSession.viewerId !== viewer.id,
+ );
+
// Common fields for the view object shared between DATAROOM_VIEW and DOCUMENT_VIEW
const viewFields = {
linkId: linkId,
- viewerEmail: viewer?.email ?? email,
- viewerName: name,
+ viewerEmail: viewer?.email ?? effectiveEmail,
+ viewerName: effectiveName,
verified: isEmailVerified,
dataroomId: link.dataroomId,
viewerId: viewer?.id ?? undefined,
teamId: link.teamId,
- ...(link.enableAgreement &&
- link.agreementId &&
- hasConfirmedAgreement && {
- agreementResponse: {
- create: {
- agreementId: link.agreementId,
- },
- },
- }),
...(link.audienceType === LinkAudienceType.GROUP &&
link.groupId && {
groupId: link.groupId,
@@ -705,6 +897,17 @@ export async function POST(request: NextRequest) {
data: { ...viewFields, viewType: "DATAROOM_VIEW" },
select: { id: true },
});
+
+ if (verifiedAgreementResponse) {
+ await prisma.agreementResponse.update({
+ where: {
+ id: verifiedAgreementResponse.id,
+ },
+ data: {
+ viewId: newDataroomView.id,
+ },
+ });
+ }
console.timeEnd("create-view");
}
}
@@ -733,7 +936,7 @@ export async function POST(request: NextRequest) {
teamId: link.teamId!,
dataroomId: link.dataroomId!,
linkId,
- viewerEmail: verifiedEmail ?? email,
+ viewerEmail: effectiveEmail ?? verifiedEmail ?? undefined,
viewerId: viewer?.id,
teamIsPaused: isPaused,
});
@@ -796,15 +999,21 @@ export async function POST(request: NextRequest) {
const response = NextResponse.json(returnObject, { status: 200 });
- // Create a dataroom session token if a dataroom session doesn't exist yet
- if (!dataroomSession && !isPreview) {
+ // Create or refresh the dataroom session token when the signed identity is canonical.
+ if ((!dataroomSession || shouldRefreshDataroomSession) && !isPreview) {
+ const sessionViewId = newDataroomView?.id ?? dataroomSession?.viewId;
+
+ if (!sessionViewId) {
+ return response;
+ }
+
const fingerprint = generateSessionFingerprint(
collectFingerprintHeaders(request.headers),
);
const newDataroomSession = await createDataroomSession(
link.dataroomId!,
linkId,
- newDataroomView?.id!,
+ sessionViewId,
ipAddress(request) ?? LOCALHOST_IP,
isEmailVerified,
viewer?.id,
@@ -988,6 +1197,17 @@ export async function POST(request: NextRequest) {
select: { id: true },
});
+ if (verifiedAgreementResponse) {
+ await prisma.agreementResponse.update({
+ where: {
+ id: verifiedAgreementResponse.id,
+ },
+ data: {
+ viewId: dataroomView.id,
+ },
+ });
+ }
+
waitUntil(
// Record link view in Tinybird
recordLinkView({
@@ -1025,7 +1245,7 @@ export async function POST(request: NextRequest) {
documentId: resolvedDocumentId,
dataroomId: link.dataroomId!,
linkId,
- viewerEmail: verifiedEmail ?? email,
+ viewerEmail: effectiveEmail ?? verifiedEmail ?? undefined,
viewerId: viewer?.id,
teamIsPaused: isPaused,
});
@@ -1061,10 +1281,16 @@ export async function POST(request: NextRequest) {
// Sign URLs for pages around the requested start page (or page 1 by default).
// Remaining page URLs are fetched on-demand by the client via /api/views/pages.
- const centerIndex = Math.max(0, (startPage ?? 1) - 1);
+ const centerIndex = Math.min(
+ Math.max(0, (startPage ?? 1) - 1),
+ Math.max(0, documentPages.length - 1),
+ );
const halfWindow = Math.floor(INITIAL_PAGES_TO_LOAD / 2);
const signStart = Math.max(0, centerIndex - halfWindow);
- const signEnd = Math.min(documentPages.length, signStart + INITIAL_PAGES_TO_LOAD);
+ const signEnd = Math.min(
+ documentPages.length,
+ signStart + INITIAL_PAGES_TO_LOAD,
+ );
documentPages = await Promise.all(
documentPages.map(async (page, index) => {
@@ -1188,7 +1414,7 @@ export async function POST(request: NextRequest) {
watermarkConfig: link.enableWatermark
? link.watermarkConfig
: undefined,
- viewerEmail: viewer?.email ?? email ?? verifiedEmail ?? null,
+ viewerEmail: viewer?.email ?? effectiveEmail ?? verifiedEmail ?? null,
ipAddress:
link.enableWatermark &&
link.watermarkConfig &&
@@ -1214,15 +1440,21 @@ export async function POST(request: NextRequest) {
const response = NextResponse.json(returnObject, { status: 200 });
- // Create a dataroom session token if a dataroom session doesn't exist yet
- if (!dataroomSession && !isPreview) {
+ // Create or refresh the dataroom session token when the signed identity is canonical.
+ if ((!dataroomSession || shouldRefreshDataroomSession) && !isPreview) {
+ const sessionViewId = dataroomView?.id ?? dataroomSession?.viewId;
+
+ if (!sessionViewId) {
+ return response;
+ }
+
const fingerprint = generateSessionFingerprint(
collectFingerprintHeaders(request.headers),
);
const newDataroomSession = await createDataroomSession(
link.dataroomId!,
linkId,
- dataroomView?.id!,
+ sessionViewId,
ipAddress(request) ?? LOCALHOST_IP,
isEmailVerified,
viewer?.id,
diff --git a/app/api/views/route.ts b/app/api/views/route.ts
index b843caef..7e436fae 100644
--- a/app/api/views/route.ts
+++ b/app/api/views/route.ts
@@ -2,12 +2,11 @@ import { NextRequest, NextResponse } from "next/server";
import { reportDeniedAccessAttempt } from "@/ee/features/access-notifications";
import { getTeamStorageConfigById } from "@/ee/features/storage/config";
-// Import authOptions directly from the source
-import { authOptions } from "@/lib/auth/auth-options";
import { ipAddress, waitUntil } from "@vercel/functions";
import { getServerSession } from "next-auth";
import { hashToken } from "@/lib/api/auth/token";
+import { authOptions } from "@/lib/auth/auth-options";
import {
collectFingerprintHeaders,
generateSessionFingerprint,
@@ -24,6 +23,15 @@ import { notifyDocumentView } from "@/lib/integrations/slack/events";
import prisma from "@/lib/prisma";
import { ratelimit } from "@/lib/redis";
import { parseSheet } from "@/lib/sheet";
+import {
+ getSignedAgreementAccessCookieName,
+ parseSignedAgreementAccessToken,
+} from "@/lib/signing/access-token";
+import {
+ ensureAgreementResponseForAccess,
+ normalizeSignerEmail,
+ normalizeSignerName,
+} from "@/lib/signing/agreements";
import { recordLinkView } from "@/lib/tracking/record-link-view";
import { CustomUser, WatermarkConfigSchema } from "@/lib/types";
import { checkPassword, decryptEncrpytedPassword, log } from "@/lib/utils";
@@ -57,10 +65,17 @@ export async function POST(request: NextRequest) {
startPage?: number;
};
- const { email, password, name, hasConfirmedAgreement } = data as {
+ const {
+ email,
+ password,
+ name,
+ agreementResponseId,
+ hasConfirmedAgreement,
+ } = data as {
email: string;
password: string;
name?: string;
+ agreementResponseId?: string;
hasConfirmedAgreement?: boolean;
};
@@ -107,6 +122,14 @@ export async function POST(request: NextRequest) {
denyList: true,
enableAgreement: true,
agreementId: true,
+ agreement: {
+ select: {
+ id: true,
+ signingProvider: true,
+ contentType: true,
+ requireName: true,
+ },
+ },
enableWatermark: true,
watermarkConfig: true,
teamId: true,
@@ -226,10 +249,52 @@ export async function POST(request: NextRequest) {
}
}
+ let effectiveEmail = normalizeSignerEmail(email);
+ let effectiveName = normalizeSignerName(name);
+
+ const signedAccessCookieValue =
+ link.enableAgreement && link.agreement
+ ? request.cookies.get(getSignedAgreementAccessCookieName(linkId))?.value
+ : undefined;
+ const signedAccessPayload = parseSignedAgreementAccessToken(
+ signedAccessCookieValue,
+ );
+ const cookieAgreementResponseId =
+ link.enableAgreement &&
+ link.agreement &&
+ signedAccessPayload &&
+ signedAccessPayload.linkId === linkId &&
+ signedAccessPayload.agreementId === link.agreement.id
+ ? signedAccessPayload.agreementResponseId
+ : null;
+
+ let verifiedAgreementResponse: Awaited<
+ ReturnType<typeof ensureAgreementResponseForAccess>
+ > | null = null;
+
if (!isTeamMember) {
+ if (cookieAgreementResponseId && link.enableAgreement && link.agreement) {
+ try {
+ verifiedAgreementResponse = await ensureAgreementResponseForAccess({
+ agreement: link.agreement,
+ linkId,
+ agreementResponseId: cookieAgreementResponseId,
+ skipSignerIdentityCheck: true,
+ });
+ effectiveEmail =
+ normalizeSignerEmail(verifiedAgreementResponse.signerEmail) ??
+ effectiveEmail;
+ effectiveName =
+ normalizeSignerName(verifiedAgreementResponse.signerName) ??
+ effectiveName;
+ } catch {
+ // Continue with the submitted identity; the agreement gate below will fail closed if needed.
+ }
+ }
+
// Check if email is required for visiting the link
if (link.emailProtected) {
- if (!email || email.trim() === "") {
+ if (!effectiveEmail || effectiveEmail.trim() === "") {
return NextResponse.json(
{ message: "Email is required." },
{ status: 400 },
@@ -237,7 +302,7 @@ export async function POST(request: NextRequest) {
}
// validate email
- if (!validateEmail(email)) {
+ if (!validateEmail(effectiveEmail)) {
return NextResponse.json(
{ message: "Invalid email address." },
{ status: 400 },
@@ -271,17 +336,59 @@ export async function POST(request: NextRequest) {
}
}
- // Check if agreement is required for visiting the link
- if (link.enableAgreement && !hasConfirmedAgreement) {
+ if (link.enableAgreement && !link.agreement) {
return NextResponse.json(
- { message: "Agreement to NDA is required." },
- { status: 400 },
+ { message: "Agreement is required but not configured." },
+ { status: 500 },
);
}
+ if (
+ link.enableAgreement &&
+ link.agreement &&
+ !verifiedAgreementResponse
+ ) {
+ const resolvedAgreementResponseId =
+ agreementResponseId ?? cookieAgreementResponseId ?? undefined;
+
+ const hasCookieIdentityProof =
+ !!cookieAgreementResponseId &&
+ (!agreementResponseId ||
+ agreementResponseId === cookieAgreementResponseId);
+
+ try {
+ verifiedAgreementResponse = await ensureAgreementResponseForAccess({
+ agreement: link.agreement,
+ linkId,
+ agreementResponseId: resolvedAgreementResponseId,
+ hasConfirmedAgreement,
+ signerEmail: effectiveEmail,
+ signerName: effectiveName,
+ requireSignerEmail: link.emailProtected,
+ skipSignerIdentityCheck: hasCookieIdentityProof,
+ });
+ effectiveEmail =
+ normalizeSignerEmail(verifiedAgreementResponse.signerEmail) ??
+ effectiveEmail;
+ effectiveName =
+ normalizeSignerName(verifiedAgreementResponse.signerName) ??
+ effectiveName;
+ } catch (error) {
+ return NextResponse.json(
+ {
+ message:
+ error instanceof Error
+ ? error.message
+ : "Agreement signing is required.",
+ },
+ { status: 400 },
+ );
+ }
+ }
+
// Check global block list first - this overrides all other access controls
const globalBlockCheck = checkGlobalBlockList(
- email,
+ effectiveEmail ?? undefined,
link.team?.globalBlockList,
);
if (globalBlockCheck.error) {
@@ -291,7 +398,9 @@ export async function POST(request: NextRequest) {
);
}
if (globalBlockCheck.isBlocked) {
- waitUntil(reportDeniedAccessAttempt(link, email, "global"));
+ waitUntil(
+ reportDeniedAccessAttempt(link, effectiveEmail ?? "", "global"),
+ );
return NextResponse.json({ message: "Access denied" }, { status: 403 });
}
@@ -308,12 +417,14 @@ export async function POST(request: NextRequest) {
if (combinedAllowList.length > 0) {
// Determine if the email or its domain is allowed
const isAllowed = combinedAllowList.some((allowed) =>
- isEmailMatched(email, allowed),
+ isEmailMatched(effectiveEmail ?? "", allowed),
);
// Deny access if the email is not allowed
if (!isAllowed) {
- waitUntil(reportDeniedAccessAttempt(link, email, "allow"));
+ waitUntil(
+ reportDeniedAccessAttempt(link, effectiveEmail ?? "", "allow"),
+ );
return NextResponse.json(
{ message: "Unauthorized access" },
@@ -326,12 +437,14 @@ export async function POST(request: NextRequest) {
if (link.denyList && link.denyList.length > 0) {
// Determine if the email or its domain is denied
const isDenied = link.denyList.some((denied) =>
- isEmailMatched(email, denied),
+ isEmailMatched(effectiveEmail ?? "", denied),
);
// Deny access if the email is denied
if (isDenied) {
- waitUntil(reportDeniedAccessAttempt(link, email, "deny"));
+ waitUntil(
+ reportDeniedAccessAttempt(link, effectiveEmail ?? "", "deny"),
+ );
return NextResponse.json(
{ message: "Unauthorized access" },
@@ -348,7 +461,7 @@ export async function POST(request: NextRequest) {
// Rate limit per email/link combination (1 per 30 seconds) to prevent OTP flooding
const { success: emailLimitSuccess } = await ratelimit(1, "30 s").limit(
- `send-otp:${linkId}:${email}`,
+ `send-otp:${linkId}:${effectiveEmail}`,
);
if (!emailLimitSuccess) {
return NextResponse.json(
@@ -373,7 +486,7 @@ export async function POST(request: NextRequest) {
await prisma.verificationToken.deleteMany({
where: {
- identifier: `otp:${linkId}:${email}`,
+ identifier: `otp:${linkId}:${effectiveEmail}`,
},
});
@@ -384,13 +497,18 @@ export async function POST(request: NextRequest) {
await prisma.verificationToken.create({
data: {
token: otpCode,
- identifier: `otp:${linkId}:${email}`,
+ identifier: `otp:${linkId}:${effectiveEmail}`,
expires: expiresAt,
},
});
waitUntil(
- sendOtpVerificationEmail(email, otpCode, false, link.teamId!),
+ sendOtpVerificationEmail(
+ effectiveEmail ?? "",
+ otpCode,
+ false,
+ link.teamId!,
+ ),
);
return NextResponse.json({
type: "email-verification",
@@ -414,7 +532,7 @@ export async function POST(request: NextRequest) {
const verification = await prisma.verificationToken.findUnique({
where: {
token: code,
- identifier: `otp:${linkId}:${email}`,
+ identifier: `otp:${linkId}:${effectiveEmail}`,
},
});
@@ -459,7 +577,7 @@ export async function POST(request: NextRequest) {
await prisma.verificationToken.create({
data: {
token: hashedVerificationToken,
- identifier: `link-verification:${linkId}:${link.teamId}:${email}`,
+ identifier: `link-verification:${linkId}:${link.teamId}:${effectiveEmail}`,
expires: tokenExpiresAt,
},
});
@@ -483,7 +601,7 @@ export async function POST(request: NextRequest) {
const verification = await prisma.verificationToken.findUnique({
where: {
token: token,
- identifier: `link-verification:${linkId}:${link.teamId}:${email}`,
+ identifier: `link-verification:${linkId}:${link.teamId}:${effectiveEmail}`,
},
});
@@ -518,6 +636,30 @@ export async function POST(request: NextRequest) {
}
}
+ if (
+ !verifiedAgreementResponse &&
+ cookieAgreementResponseId &&
+ link.enableAgreement &&
+ link.agreement
+ ) {
+ try {
+ verifiedAgreementResponse = await ensureAgreementResponseForAccess({
+ agreement: link.agreement,
+ linkId,
+ agreementResponseId: cookieAgreementResponseId,
+ skipSignerIdentityCheck: true,
+ });
+ effectiveEmail =
+ normalizeSignerEmail(verifiedAgreementResponse.signerEmail) ??
+ effectiveEmail;
+ effectiveName =
+ normalizeSignerName(verifiedAgreementResponse.signerName) ??
+ effectiveName;
+ } catch {
+ // Existing link sessions still grant access; ignore stale signed identity cookies.
+ }
+ }
+
// Check if there's a valid preview session
let previewSession: PreviewSession | null = null;
if (!isPreview && previewToken) {
@@ -549,14 +691,14 @@ export async function POST(request: NextRequest) {
try {
let viewer: { id: string; verified: boolean } | null = null;
- if (email && !isPreview) {
+ if (effectiveEmail && !isPreview) {
// find or create a viewer
console.time("find-viewer");
viewer = await prisma.viewer.findUnique({
where: {
teamId_email: {
teamId: link.teamId!,
- email: email,
+ email: effectiveEmail,
},
},
select: { id: true, verified: true },
@@ -567,7 +709,7 @@ export async function POST(request: NextRequest) {
console.time("create-viewer");
viewer = await prisma.viewer.create({
data: {
- email: email,
+ email: effectiveEmail,
verified: isEmailVerified,
teamId: link.teamId!,
},
@@ -588,21 +730,12 @@ export async function POST(request: NextRequest) {
newView = await prisma.view.create({
data: {
linkId: linkId,
- viewerEmail: email,
- viewerName: name,
+ viewerEmail: effectiveEmail,
+ viewerName: effectiveName,
documentId: documentId,
teamId: link.teamId!,
viewerId: viewer?.id ?? undefined,
verified: isEmailVerified,
- ...(link.enableAgreement &&
- link.agreementId &&
- hasConfirmedAgreement && {
- agreementResponse: {
- create: {
- agreementId: link.agreementId,
- },
- },
- }),
...(customFields &&
link.customFields.length > 0 && {
customFieldResponse: {
@@ -618,6 +751,17 @@ export async function POST(request: NextRequest) {
},
select: { id: true },
});
+
+ if (verifiedAgreementResponse) {
+ await prisma.agreementResponse.update({
+ where: {
+ id: verifiedAgreementResponse.id,
+ },
+ data: {
+ viewId: newView.id,
+ },
+ });
+ }
console.timeEnd("create-view");
}
@@ -754,7 +898,7 @@ export async function POST(request: NextRequest) {
teamId: link.teamId!,
documentId,
linkId,
- viewerEmail: email ?? undefined,
+ viewerEmail: effectiveEmail ?? undefined,
viewerId: viewer?.id ?? undefined,
teamIsPaused: isPaused,
}).catch((error) => {
@@ -831,7 +975,7 @@ export async function POST(request: NextRequest) {
linkId,
"DOCUMENT_LINK",
newView.id,
- email ?? "",
+ effectiveEmail ?? "",
ipAddressValue,
userAgent,
isEmailVerified,
diff --git a/app/api/webhooks/signing/route.ts b/app/api/webhooks/signing/route.ts
new file mode 100644
index 00000000..fa7f1d8c
--- /dev/null
+++ b/app/api/webhooks/signing/route.ts
@@ -0,0 +1,112 @@
+import { NextRequest, NextResponse } from "next/server";
+
+import { waitUntil } from "@vercel/functions";
+import { z } from "zod";
+
+import {
+ SIGNING_STATUS_SCHEMA,
+ findAgreementResponseByExternalId,
+ getAgreementResponseSignedState,
+ syncAgreementResponseWithSigningDocument,
+ verifySigningWebhookSecret,
+} from "@/lib/signing/agreements";
+import { mirrorSignedAgreementToStorage } from "@/lib/signing/mirror";
+
+export const runtime = "nodejs";
+export const dynamic = "force-dynamic";
+
+const signingWebhookSchema = z.object({
+ event: z.string(),
+ payload: z.object({
+ id: z.number().int().positive(),
+ externalId: z.string().nullable().optional(),
+ }),
+});
+
+const SIGNING_EVENTS = new Set(["DOCUMENT_SIGNED", "DOCUMENT_COMPLETED"]);
+
+// POST /api/webhooks/signing – receive Documenso signing webhooks
+export async function POST(req: NextRequest) {
+ const secretHeader = req.headers.get("x-documenso-secret");
+ const { ok, configured } = verifySigningWebhookSecret(secretHeader);
+
+ // Distinguish a missing-secret misconfiguration (503 so Documenso keeps retrying) from a forged call (401 immediately).
+ if (!configured) {
+ return NextResponse.json(
+ { message: "Signing webhook is not configured." },
+ { status: 503 },
+ );
+ }
+
+ if (!ok) {
+ return NextResponse.json({ message: "Unauthorized" }, { status: 401 });
+ }
+
+ try {
+ const body = await req.json().catch(() => null);
+ const parseResult = signingWebhookSchema.safeParse(body);
+
+ if (!parseResult.success) {
+ // 400 (not 200) so Documenso surfaces schema drift and we can detect upstream payload changes.
+ return NextResponse.json(
+ { message: "Invalid webhook payload." },
+ { status: 400 },
+ );
+ }
+
+ const {
+ event,
+ payload: { externalId, id: documentId },
+ } = parseResult.data;
+
+ if (!SIGNING_EVENTS.has(event) || !externalId) {
+ return NextResponse.json({ ok: true });
+ }
+
+ const agreementResponse =
+ await findAgreementResponseByExternalId(externalId);
+
+ if (!agreementResponse) {
+ return NextResponse.json({ ok: true });
+ }
+
+ // Idempotency: skip the write if already in a terminal signed state, but only short-circuit for SIGNED events since DOCUMENT_COMPLETED may still upgrade a prior DOCUMENT_SIGNED row.
+ const nextStatus =
+ event === "DOCUMENT_COMPLETED"
+ ? SIGNING_STATUS_SCHEMA.enum.COMPLETED
+ : SIGNING_STATUS_SCHEMA.enum.SIGNED;
+
+ if (
+ nextStatus === SIGNING_STATUS_SCHEMA.enum.SIGNED &&
+ getAgreementResponseSignedState(agreementResponse.signingStatus)
+ ) {
+ return NextResponse.json({ ok: true });
+ }
+
+ await syncAgreementResponseWithSigningDocument({
+ agreementResponseId: agreementResponse.id,
+ documentId,
+ signingStatus: nextStatus,
+ });
+
+ waitUntil(
+ mirrorSignedAgreementToStorage({
+ agreementResponseId: agreementResponse.id,
+ }).catch((error) => {
+ console.error(
+ "[signing] background mirror of signed agreement failed",
+ error,
+ );
+ }),
+ );
+
+ return NextResponse.json({ ok: true });
+ } catch (error) {
+ console.error("[signing] webhook handler failed", error);
+ // Never echo the internal error message — Documenso retry logs could leak SDK/database details.
+ return NextResponse.json(
+ { message: "Internal Server Error" },
+ { status: 500 },
+ );
+ }
+}
diff --git a/components/agreements/agreement-card.tsx b/components/agreements/agreement-card.tsx
index 66c38a3a..a1e949a2 100644
--- a/components/agreements/agreement-card.tsx
+++ b/components/agreements/agreement-card.tsx
@@ -1,10 +1,29 @@
-import { useState } from "react";
+import { memo, useState } from "react";
import { useTeam } from "@/context/team-context";
-import { DownloadIcon, FileTextIcon, MoreVertical, TrashIcon } from "lucide-react";
+import {
+ ChevronDownIcon,
+ DownloadIcon,
+ FileSignatureIcon,
+ FileTextIcon,
+ Link2Icon,
+ MoreVertical,
+ PencilIcon,
+ ServerIcon,
+ TrashIcon,
+} from "lucide-react";
import { toast } from "sonner";
+import {
+ buildTeamSignedAgreementDownloadUrl,
+ downloadSignedAgreement,
+} from "@/lib/signing/download";
+import {
+ AgreementResponseSummary,
+ useAgreementResponses,
+} from "@/lib/swr/use-agreement-responses";
import { AgreementWithLinksCount } from "@/lib/swr/use-agreements";
+import { cn, timeAgo } from "@/lib/utils";
import {
AlertDialog,
@@ -23,27 +42,52 @@ import {
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
+import { Skeleton } from "@/components/ui/skeleton";
+import { TimestampTooltip } from "@/components/ui/timestamp-tooltip";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipPortal,
+ TooltipProvider,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
interface AgreementCardProps {
agreement: AgreementWithLinksCount;
onDelete: (id: string) => void;
+ onEdit: (agreement: AgreementWithLinksCount) => void;
}
-export default function AgreementCard({
+function AgreementCard({
agreement,
onDelete,
+ onEdit,
}: AgreementCardProps) {
const teamInfo = useTeam();
+ const teamId = teamInfo?.currentTeam?.id;
const [showDeleteDialog, setShowDeleteDialog] = useState(false);
+ const [isExpanded, setIsExpanded] = useState(false);
+
+ const isSigningAgreement =
+ agreement.signingProvider === "DOCUMENSO" ||
+ agreement.contentType === "SIGNING";
+ const hasSignedResponses = (agreement._count?.responses ?? 0) > 0;
+ const disableEdit = isSigningAgreement && hasSignedResponses;
+ const disabledEditReason =
+ "Signing agreements cannot be edited after signatures have been collected";
+
+ const {
+ responses,
+ loading: responsesLoading,
+ error: responsesError,
+ } = useAgreementResponses(isExpanded && isSigningAgreement ? agreement.id : null);
const handleDelete = async () => {
+ if (!teamId) return;
toast.promise(
- fetch(
- `/api/teams/${teamInfo?.currentTeam?.id}/agreements/${agreement.id}`,
- {
- method: "PUT",
- },
- ).then(async (response) => {
+ fetch(`/api/teams/${teamId}/agreements/${agreement.id}`, {
+ method: "PUT",
+ }).then(async (response) => {
if (!response.ok) {
throw new Error("Failed to delete agreement");
}
@@ -58,9 +102,10 @@ export default function AgreementCard({
};
const handleDownload = async () => {
+ if (!teamId) return;
toast.promise(
fetch(
- `/api/teams/${teamInfo?.currentTeam?.id}/agreements/${agreement.id}/download`,
+ `/api/teams/${teamId}/agreements/${agreement.id}/download`,
{
method: "POST",
},
@@ -68,13 +113,13 @@ export default function AgreementCard({
if (!response.ok) {
throw new Error("Failed to download agreement");
}
-
- // Get the filename from the Content-Disposition header or use default
+
const contentDisposition = response.headers.get("Content-Disposition");
const filenameMatch = contentDisposition?.match(/filename="([^"]+)"/);
- const filename = filenameMatch ? filenameMatch[1] : `${agreement.name}.txt`;
-
- // Create a blob and download
+ const filename = filenameMatch
+ ? filenameMatch[1]
+ : `${agreement.name}.txt`;
+
const blob = await response.blob();
const url = window.URL.createObjectURL(blob);
const link = document.createElement("a");
@@ -82,8 +127,7 @@ export default function AgreementCard({
link.download = filename;
document.body.appendChild(link);
link.click();
-
- // Cleanup
+
setTimeout(() => {
window.URL.revokeObjectURL(url);
document.body.removeChild(link);
@@ -97,48 +141,159 @@ export default function AgreementCard({
);
};
+ const handleDownloadResponse = async (response: AgreementResponseSummary) => {
+ if (!teamId) return;
+
+ const url = buildTeamSignedAgreementDownloadUrl({
+ teamId,
+ agreementId: agreement.id,
+ responseId: response.id,
+ });
+
+ const safeName = agreement.name
+ .replace(/[^a-z0-9\-_]/gi, "_")
+ .toLowerCase()
+ .substring(0, 50);
+
+ await toast.promise(
+ downloadSignedAgreement({
+ url,
+ fallbackFilename: `${safeName || "agreement"}_signed.pdf`,
+ }),
+ {
+ loading: "Preparing signed NDA...",
+ success: "Signed NDA downloaded",
+ error: (error: unknown) =>
+ error instanceof Error
+ ? error.message
+ : "Failed to download the signed NDA.",
+ },
+ );
+ };
+
return (
<>
- <div className="flex items-center justify-between rounded-lg border p-4">
- <div className="flex items-center space-x-4">
- <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-muted">
- <FileTextIcon className="h-5 w-5" />
+ <div className="rounded-lg border">
+ <div className="flex items-center justify-between p-4">
+ <div className="flex items-center space-x-4">
+ <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-muted">
+ {isSigningAgreement ? (
+ <FileSignatureIcon className="h-5 w-5" />
+ ) : (
+ <FileTextIcon className="h-5 w-5" />
+ )}
+ </div>
+ <div>
+ <h3 className="font-medium">{agreement.name}</h3>
+ <p className="text-sm text-muted-foreground">
+ Last updated{" "}
+ {new Date(agreement.updatedAt).toLocaleDateString()}
+ </p>
+ </div>
</div>
- <div>
- <h3 className="font-medium">{agreement.name}</h3>
- <p className="text-sm text-muted-foreground">
- Last updated {new Date(agreement.updatedAt).toLocaleDateString()}
- </p>
+
+ <div className="flex items-center gap-x-2">
+ <div className="text-sm text-muted-foreground">
+ {agreement._count?.links || 0}{" "}
+ {agreement._count?.links === 1 ? "link" : "links"}
+ </div>
+ {isSigningAgreement ? (
+ <Button
+ variant="ghost"
+ size="sm"
+ className="hidden h-8 gap-x-1 px-2 text-xs text-muted-foreground sm:flex"
+ onClick={() => setIsExpanded((prev) => !prev)}
+ aria-expanded={isExpanded}
+ >
+ {isExpanded ? "Hide signed" : "Show signed"}
+ <ChevronDownIcon
+ className={cn(
+ "h-4 w-4 transition-transform",
+ isExpanded && "rotate-180",
+ )}
+ />
+ </Button>
+ ) : null}
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button variant="ghost" className="h-8 w-8 p-0">
+ <span className="sr-only">Open menu</span>
+ <MoreVertical className="h-4 w-4" />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <TooltipProvider delayDuration={0}>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <DropdownMenuItem
+ aria-disabled={disableEdit}
+ className={cn(
+ disableEdit &&
+ "cursor-not-allowed opacity-50 focus:bg-transparent focus:text-muted-foreground",
+ )}
+ onSelect={(event) => {
+ if (disableEdit) {
+ event.preventDefault();
+ return;
+ }
+
+ onEdit(agreement);
+ }}
+ >
+ <PencilIcon className="mr-2 h-4 w-4" />
+ Edit agreement
+ </DropdownMenuItem>
+ </TooltipTrigger>
+ {disableEdit ? (
+ <TooltipPortal>
+ <TooltipContent
+ side="left"
+ sideOffset={8}
+ className="max-w-64 text-center text-xs"
+ >
+ {disabledEditReason}
+ </TooltipContent>
+ </TooltipPortal>
+ ) : null}
+ </Tooltip>
+ </TooltipProvider>
+ {isSigningAgreement ? (
+ <DropdownMenuItem
+ onClick={() => setIsExpanded((prev) => !prev)}
+ className="sm:hidden"
+ >
+ <FileSignatureIcon className="mr-2 h-4 w-4" />
+ {isExpanded ? "Hide signed NDAs" : "Show signed NDAs"}
+ </DropdownMenuItem>
+ ) : null}
+ {!isSigningAgreement ? (
+ <DropdownMenuItem onClick={handleDownload}>
+ <DownloadIcon className="mr-2 h-4 w-4" />
+ Download agreement
+ </DropdownMenuItem>
+ ) : null}
+ <DropdownMenuItem
+ className="text-destructive focus:bg-destructive focus:text-destructive-foreground"
+ onClick={() => setShowDeleteDialog(true)}
+ >
+ <TrashIcon className="mr-2 h-4 w-4" />
+ Delete agreement
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
</div>
</div>
- <div className="flex items-center gap-x-2">
- <div className="text-sm text-muted-foreground">
- {agreement._count?.links || 0}{" "}
- {agreement._count?.links === 1 ? "link" : "links"}
+ {isExpanded && isSigningAgreement ? (
+ <div className="border-t bg-muted/20 px-4 py-3">
+ <AgreementResponsesSection
+ loading={responsesLoading}
+ error={!!responsesError}
+ responses={responses}
+ onDownload={handleDownloadResponse}
+ />
</div>
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <Button variant="ghost" className="h-8 w-8 p-0">
- <span className="sr-only">Open menu</span>
- <MoreVertical className="h-4 w-4" />
- </Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end">
- <DropdownMenuItem onClick={handleDownload}>
- <DownloadIcon className="mr-2 h-4 w-4" />
- Download agreement
- </DropdownMenuItem>
- <DropdownMenuItem
- className="text-destructive focus:bg-destructive focus:text-destructive-foreground"
- onClick={() => setShowDeleteDialog(true)}
- >
- <TrashIcon className="mr-2 h-4 w-4" />
- Delete agreement
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
- </div>
+ ) : null}
</div>
<AlertDialog open={showDeleteDialog} onOpenChange={setShowDeleteDialog}>
@@ -171,3 +326,161 @@ export default function AgreementCard({
</>
);
}
+
+export default memo(AgreementCard);
+
+function AgreementResponsesSection({
+ loading,
+ error,
+ responses,
+ onDownload,
+}: {
+ loading: boolean;
+ error: boolean;
+ responses: AgreementResponseSummary[];
+ onDownload: (response: AgreementResponseSummary) => void | Promise<void>;
+}) {
+ if (loading) {
+ return (
+ <div className="space-y-2">
+ <Skeleton className="h-12 w-full" />
+ <Skeleton className="h-12 w-full" />
+ </div>
+ );
+ }
+
+ if (error) {
+ return (
+ <p className="py-2 text-sm text-destructive">
+ Failed to load signed NDAs. Try again later.
+ </p>
+ );
+ }
+
+ if (responses.length === 0) {
+ return (
+ <p className="py-2 text-sm text-muted-foreground">
+ No signed NDAs yet. Once a visitor completes the embedded signing flow,
+ their signed copy will appear here.
+ </p>
+ );
+ }
+
+ return (
+ <ul className="divide-y divide-border">
+ <li className="flex items-center gap-3 py-2 text-xs font-medium uppercase tracking-wide text-muted-foreground">
+ <span className="flex-1">Signer</span>
+ <span className="hidden flex-1 md:block">Source</span>
+ <span className="hidden w-24 md:block">Signed</span>
+ <span className="w-10" />
+ </li>
+ {responses.map((response) => {
+ const signedAt =
+ response.signedAt ||
+ response.completedAt ||
+ response.createdAt;
+ const signerLabel =
+ response.view?.viewerName ||
+ response.view?.viewerEmail ||
+ response.signerName ||
+ response.signerEmail ||
+ "Signed before opening link";
+ const signerSubLabel =
+ response.view?.viewerName && response.view?.viewerEmail
+ ? response.view.viewerEmail
+ : !response.view && response.signerName && response.signerEmail
+ ? response.signerEmail
+ : null;
+ const linkSourceId =
+ response.view?.link?.id ||
+ response.view?.linkId ||
+ response.link?.id ||
+ response.linkId ||
+ null;
+ const linkSourceName =
+ response.view?.link?.name || response.link?.name || null;
+ const linkLabel =
+ linkSourceName ||
+ (linkSourceId ? `Link #${linkSourceId.slice(-5)}` : "Unknown link");
+ const documentLabel = response.view?.document?.name;
+ const dataroomLabel = response.view?.dataroom?.name;
+ const isOrphanResponse = !response.view;
+
+ return (
+ <li
+ key={response.id}
+ className="flex flex-col gap-2 py-3 md:flex-row md:items-center md:gap-3"
+ >
+ <div className="flex flex-1 items-center gap-2 min-w-0">
+ <div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-emerald-500/10 text-emerald-600">
+ <FileSignatureIcon className="h-4 w-4" />
+ </div>
+ <div className="min-w-0 flex-1">
+ <p className="truncate text-sm font-medium text-foreground">
+ {signerLabel}
+ </p>
+ {signerSubLabel ? (
+ <p className="truncate text-xs text-muted-foreground">
+ {signerSubLabel}
+ </p>
+ ) : isOrphanResponse ? (
+ <p className="truncate text-xs text-muted-foreground">
+ Signed but did not continue into the link
+ </p>
+ ) : null}
+ </div>
+ </div>
+
+ <div className="min-w-0 flex-1 text-xs text-muted-foreground md:text-sm">
+ <div className="flex items-center gap-1 truncate">
+ <Link2Icon className="h-3.5 w-3.5 shrink-0" />
+ <span className="truncate">{linkLabel}</span>
+ </div>
+ {dataroomLabel ? (
+ <div className="mt-0.5 flex items-center gap-1 truncate">
+ <ServerIcon className="h-3.5 w-3.5 shrink-0 text-[#fb7a00]" />
+ <span className="truncate">{dataroomLabel}</span>
+ </div>
+ ) : documentLabel ? (
+ <div className="mt-0.5 flex items-center gap-1 truncate">
+ <FileTextIcon className="h-3.5 w-3.5 shrink-0" />
+ <span className="truncate">{documentLabel}</span>
+ </div>
+ ) : null}
+ </div>
+
+ <div className="text-xs text-muted-foreground md:w-24">
+ {signedAt ? (
+ <TimestampTooltip
+ timestamp={new Date(signedAt)}
+ rows={["local", "utc", "unix"]}
+ >
+ <time
+ className="select-none"
+ dateTime={new Date(signedAt).toISOString()}
+ >
+ {timeAgo(new Date(signedAt))}
+ </time>
+ </TimestampTooltip>
+ ) : (
+ "—"
+ )}
+ </div>
+
+ <div className="flex justify-end md:w-10">
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={() => onDownload(response)}
+ title="Download signed NDA"
+ >
+ <DownloadIcon className="h-4 w-4" />
+ <span className="sr-only">Download signed NDA</span>
+ </Button>
+ </div>
+ </li>
+ );
+ })}
+ </ul>
+ );
+}
diff --git a/components/agreements/signing-template-authoring.tsx b/components/agreements/signing-template-authoring.tsx
new file mode 100644
index 00000000..d1770c48
--- /dev/null
+++ b/components/agreements/signing-template-authoring.tsx
@@ -0,0 +1,144 @@
+import dynamic from "next/dynamic";
+
+import { useEffect, useRef } from "react";
+
+import LoadingSpinner from "@/components/ui/loading-spinner";
+
+const authoringCssVars = {
+ background: "hsl(0 0% 100%)",
+ foreground: "hsl(224 71.4% 4.1%)",
+ muted: "hsl(220 14.3% 95.9%)",
+ mutedForeground: "hsl(220 8.9% 46.1%)",
+ popover: "hsl(0 0% 100%)",
+ popoverForeground: "hsl(224 71.4% 4.1%)",
+ card: "hsl(0 0% 100%)",
+ cardBorder: "hsl(220 13% 91%)",
+ cardBorderTint: "hsl(216 12.2% 83.9%)",
+ cardForeground: "hsl(224 71.4% 4.1%)",
+ fieldCard: "hsl(220 14.3% 95.9%)",
+ fieldCardBorder: "hsl(220 13% 91%)",
+ fieldCardForeground: "hsl(224 71.4% 4.1%)",
+ widget: "hsl(0 0% 100%)",
+ widgetForeground: "hsl(224 71.4% 4.1%)",
+ border: "hsl(220 13% 91%)",
+ input: "hsl(216 12.2% 83.9%)",
+ primary: "hsl(220.9 39.3% 11%)",
+ primaryForeground: "hsl(210 20% 98%)",
+ secondary: "hsl(220 14.3% 95.9%)",
+ secondaryForeground: "hsl(220.9 39.3% 11%)",
+ accent: "hsl(220 14.3% 95.9%)",
+ accentForeground: "hsl(220.9 39.3% 11%)",
+ destructive: "hsl(0 84.2% 60.2%)",
+ destructiveForeground: "hsl(210 20% 98%)",
+ ring: "hsl(217.9 10.6% 64.9%)",
+ warning: "hsl(38 92% 50%)",
+ envelopeEditorBackground: "hsl(220 14.3% 95.9%)",
+ radius: "0.5rem",
+};
+
+const authoringCss = `
+ .embed--Root,
+ .embed--DocumentContainer,
+ .embed--DocumentWidget,
+ .embed--DocumentWidgetContainer,
+ .embed--DocumentViewer {
+ border-radius: 0.5rem;
+ }
+
+ .embed--DocumentWidget,
+ .embed--DocumentWidgetContainer,
+ .embed--DocumentWidgetHeader,
+ .embed--DocumentWidgetContent,
+ .embed--DocumentWidgetFooter {
+ box-shadow: none;
+ }
+
+ .embed--DocumentContainer {
+ gap: 1rem;
+ }
+`;
+
+const authoringFeatures = {
+ general: {
+ allowConfigureEnvelopeTitle: false,
+ allowUploadAndRecipientStep: false,
+ allowAddFieldsStep: true,
+ allowPreviewStep: false,
+ minimizeLeftSidebar: true,
+ },
+ settings: null,
+ actions: {
+ allowAttachments: false,
+ },
+ envelopeItems: {
+ allowConfigureTitle: false,
+ allowConfigureOrder: false,
+ allowUpload: false,
+ allowDelete: false,
+ allowReplace: false,
+ },
+ recipients: null,
+};
+
+const INITIAL_EMBED_EVENT_GUARD_MS = 3000;
+
+const EmbedUpdateEnvelope = dynamic(
+ () =>
+ import("@documenso/embed-react").then((mod) => mod.EmbedUpdateEnvelopeV2),
+ {
+ ssr: false,
+ loading: () => (
+ <div className="flex h-full items-center justify-center">
+ <LoadingSpinner className="h-10 w-10" />
+ </div>
+ ),
+ },
+);
+
+export default function SigningTemplateAuthoring({
+ host,
+ presignToken,
+ externalId,
+ envelopeId,
+ onEnvelopeSaved,
+}: {
+ host: string;
+ presignToken: string;
+ externalId?: string | null;
+ envelopeId: string;
+ onEnvelopeSaved: (envelopeId: string) => void;
+}) {
+ const canHandleEnvelopeUpdatedRef = useRef(false);
+
+ useEffect(() => {
+ const timer = window.setTimeout(() => {
+ canHandleEnvelopeUpdatedRef.current = true;
+ }, INITIAL_EMBED_EVENT_GUARD_MS);
+
+ return () => window.clearTimeout(timer);
+ }, []);
+
+ return (
+ <div className="h-full min-h-[600px] w-full overflow-hidden rounded-lg border bg-background">
+ <EmbedUpdateEnvelope
+ className="h-full w-full"
+ host={host}
+ presignToken={presignToken}
+ externalId={externalId ?? undefined}
+ envelopeId={envelopeId}
+ darkModeDisabled
+ cssVars={authoringCssVars}
+ css={authoringCss}
+ features={authoringFeatures}
+ onEnvelopeUpdated={(data) => {
+ // Ignore the initial Documenso update event fired during editor init; only later events are real saves.
+ if (!canHandleEnvelopeUpdatedRef.current) {
+ return;
+ }
+
+ onEnvelopeSaved(String(data.envelopeId));
+ }}
+ />
+ </div>
+ );
+}
diff --git a/components/document-upload.tsx b/components/document-upload.tsx
index f45a5e1c..18f95ec2 100644
--- a/components/document-upload.tsx
+++ b/components/document-upload.tsx
@@ -25,9 +25,15 @@ import { getPagesCount } from "@/lib/utils/get-page-number-count";
export default function DocumentUpload({
currentFile,
setCurrentFile,
+ pdfOnly = false,
+ maxSizeBytes,
+ maxSizeErrorMessage,
}: {
currentFile: File | null;
setCurrentFile: React.Dispatch<React.SetStateAction<File | null>>;
+ pdfOnly?: boolean;
+ maxSizeBytes?: number;
+ maxSizeErrorMessage?: string;
}) {
const router = useRouter();
const { theme, systemTheme } = useTheme();
@@ -36,7 +42,6 @@ export default function DocumentUpload({
const { isFree, isTrial } = usePlan();
const { limits } = useLimits();
- // Get file size limits
const fileSizeLimits = useMemo(
() =>
getFileSizeLimits({
@@ -47,9 +52,16 @@ export default function DocumentUpload({
[limits, isFree, isTrial],
);
+ // When an explicit byte limit is provided (e.g. NDA signing template), use it instead of the plan limit.
+ const maxSizeMB =
+ typeof maxSizeBytes === "number"
+ ? Math.floor(maxSizeBytes / (1024 * 1024))
+ : undefined;
+
const { getRootProps, getInputProps } = useDropzone({
- accept:
- isFree && !isTrial
+ accept: pdfOnly
+ ? { "application/pdf": [".pdf"] }
+ : isFree && !isTrial
? FREE_PLAN_ACCEPTED_FILE_TYPES
: FULL_PLAN_ACCEPTED_FILE_TYPES,
multiple: false,
@@ -60,11 +72,14 @@ export default function DocumentUpload({
const file = acceptedFiles[0];
const fileType = file.type;
const fileSizeLimitMB = getFileSizeLimit(fileType, fileSizeLimits); // in MB
- const fileSizeLimit = fileSizeLimitMB * 1024 * 1024; // in bytes
+ const limitMB = maxSizeMB ?? fileSizeLimitMB; // displayed limit
+ const fileSizeLimit = maxSizeBytes ?? fileSizeLimitMB * 1024 * 1024; // in bytes
if (file.size > fileSizeLimit) {
- const message = `File size too big for ${fileType} (max. ${fileSizeLimitMB} MB)`;
- if (isFree && !isTrial) {
+ const message =
+ maxSizeErrorMessage ||
+ `File size too big for ${fileType} (max. ${limitMB} MB)`;
+ if (!maxSizeErrorMessage && isFree && !isTrial) {
toast.error(message, {
description: "Upgrade to a paid plan to increase the limit",
action: {
@@ -105,9 +120,10 @@ export default function DocumentUpload({
const { errors, file } = fileRejections[0];
let message;
if (errors[0].code === "file-too-large") {
- const fileSizeLimitMB = getFileSizeLimit(file.type, fileSizeLimits);
- message = `File size too big (max. ${fileSizeLimitMB} MB)`;
- if (isFree && !isTrial) {
+ const limitMB = maxSizeMB ?? getFileSizeLimit(file.type, fileSizeLimits);
+ message =
+ maxSizeErrorMessage || `File size too big (max. ${limitMB} MB)`;
+ if (!maxSizeErrorMessage && isFree && !isTrial) {
toast.error(message, {
description: "Upgrade to a paid plan to increase the limit",
action: {
@@ -137,6 +153,7 @@ export default function DocumentUpload({
}
toast.error(message);
},
+ maxSize: maxSizeBytes,
});
const imageBlobUrl = useMemo(
@@ -190,9 +207,11 @@ export default function DocumentUpload({
<p className="text-xs leading-5 text-gray-500">
{currentFile
? "Replace file?"
- : 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, *.dwg, *.dxf, *.png, *.jpg, *.jpeg, *.mp4, *.mov, *.avi, *.webm, *.ogg, *.log`}
+ : pdfOnly
+ ? `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, *.dwg, *.dxf, *.png, *.jpg, *.jpeg, *.mp4, *.mov, *.avi, *.webm, *.ogg, *.log`}
</p>
</div>
</div>
diff --git a/components/links/link-sheet/agreement-panel/index.tsx b/components/links/link-sheet/agreement-panel/index.tsx
index 23f47599..3fc91ae1 100644
--- a/components/links/link-sheet/agreement-panel/index.tsx
+++ b/components/links/link-sheet/agreement-panel/index.tsx
@@ -2,11 +2,15 @@ import {
Dispatch,
FormEvent,
SetStateAction,
+ useCallback,
useEffect,
+ useRef,
useState,
} from "react";
import { useTeam } from "@/context/team-context";
+import { Agreement } from "@prisma/client";
+import { useRealtimeRun } from "@trigger.dev/react-hooks";
import { toast } from "sonner";
import { mutate } from "swr";
import { z } from "zod";
@@ -16,12 +20,20 @@ import {
createAgreementDocument,
} from "@/lib/documents/create-document";
import { putFile } from "@/lib/files/put-file";
+import {
+ MAX_SIGNING_TEMPLATE_PDF_BYTES,
+ SIGNING_TEMPLATE_PDF_CONTENT_TYPE,
+ getSigningTemplateTooLargeMessage,
+} from "@/lib/signing/template-upload";
import { getSupportedContentType } from "@/lib/utils/get-content-type";
+import SigningTemplateAuthoring from "@/components/agreements/signing-template-authoring";
import DocumentUpload from "@/components/document-upload";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
+import LoadingSpinner from "@/components/ui/loading-spinner";
+import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { ScrollArea } from "@/components/ui/scroll-area";
import {
Sheet,
@@ -32,11 +44,9 @@ import {
SheetTitle,
} from "@/components/ui/sheet";
import { Textarea } from "@/components/ui/textarea";
-import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import LinkItem from "../link-item";
-// Add the validation schema
const agreementUrlSchema = z
.string()
.min(1, "URL is required")
@@ -45,154 +55,578 @@ const agreementUrlSchema = z
message: "URL must start with https://",
});
+const SIGNING_RECIPIENT_COUNT = 1;
+// Safety net: give up if realtime never reaches a terminal state so the UI never spins forever.
+const SIGNING_SETUP_TIMEOUT_MS = 2 * 60 * 1000;
+
+const SIGNING_SETUP_FAILURE_STATUSES = new Set([
+ "FAILED",
+ "CRASHED",
+ "CANCELED",
+ "SYSTEM_FAILURE",
+ "TIMED_OUT",
+ "EXPIRED",
+]);
+
+const initialData = {
+ name: "",
+ link: "",
+ textContent: "",
+ contentType: "SIGNING",
+ requireName: true,
+};
+
+type AgreementFormState = typeof initialData;
+
+type SigningSetupResponse = {
+ presignToken: string;
+ expiresAt: string;
+ externalId: string | null;
+ envelopeId: string;
+ host: string;
+};
+
+type SigningSetupRunResponse = {
+ runId: string;
+ publicAccessToken: string;
+};
+
+type PendingSigningRun = {
+ runId: string;
+ accessToken: string;
+ agreement: Agreement;
+ createdNow: boolean;
+};
+
+const isSigningAgreementRecord = (
+ agreement: Pick<Agreement, "contentType" | "signingProvider">,
+) =>
+ agreement.contentType === "SIGNING" ||
+ agreement.signingProvider === "DOCUMENSO";
+
export default function AgreementSheet({
defaultData,
+ editAgreement,
isOpen,
setIsOpen,
isOnlyView = false,
+ startSigningAuthoring = false,
onClose,
+ onSaved,
}: {
- defaultData?: { name: string; link: string; requireName: boolean; contentType?: string; textContent?: string } | null;
+ defaultData?: {
+ name: string;
+ link: string;
+ requireName: boolean;
+ contentType?: string;
+ textContent?: string;
+ } | null;
+ editAgreement?: Agreement | null;
isOpen: boolean;
setIsOpen: Dispatch<SetStateAction<boolean>>;
isOnlyView?: boolean;
+ startSigningAuthoring?: boolean;
onClose?: () => void;
+ onSaved?: (agreement: Agreement) => void;
}) {
const teamInfo = useTeam();
const teamId = teamInfo?.currentTeam?.id;
- const [data, setData] = useState({
- name: "",
- link: "",
- textContent: "",
- contentType: "LINK",
- requireName: true
- });
- const [isLoading, setIsLoading] = useState<boolean>(false);
+ const isEditing = !!editAgreement;
+ const [data, setData] = useState<AgreementFormState>(initialData);
+ const [isLoading, setIsLoading] = useState(false);
const [currentFile, setCurrentFile] = useState<File | null>(null);
-
- // Add validation state
- const [urlError, setUrlError] = useState<string>("");
- const [isUrlValid, setIsUrlValid] = useState<boolean>(true);
+ const [signingFile, setSigningFile] = useState<File | null>(null);
+ const [urlError, setUrlError] = useState("");
+ const [isUrlValid, setIsUrlValid] = useState(true);
+ const [createdAgreement, setCreatedAgreement] = useState<Agreement | null>(
+ null,
+ );
+ const [pendingSigningAgreement, setPendingSigningAgreement] =
+ useState<Agreement | null>(null);
+ const [signingSetup, setSigningSetup] = useState<SigningSetupResponse | null>(
+ null,
+ );
+ const [isSyncingTemplate, setIsSyncingTemplate] = useState(false);
+ const [isLoadingSigningAuthoring, setIsLoadingSigningAuthoring] =
+ useState(false);
+ const [signingRun, setSigningRun] = useState<PendingSigningRun | null>(null);
+ const autoStartedSigningAuthoringRef = useRef<string | null>(null);
+ // Tracks the run id we've already finalized so the realtime effect and the
+ // watchdog timeout can never resolve the same run twice.
+ const signingRunFinalizedRef = useRef<string | null>(null);
useEffect(() => {
- if (defaultData) {
+ if (editAgreement) {
+ const contentType = editAgreement.contentType || "SIGNING";
+ setData({
+ name: editAgreement.name || "",
+ link: contentType === "LINK" ? editAgreement.content || "" : "",
+ textContent: contentType === "TEXT" ? editAgreement.content || "" : "",
+ contentType,
+ requireName: editAgreement.requireName ?? true,
+ });
+ } else if (defaultData) {
setData({
- name: defaultData?.name || "",
- link: defaultData?.link || "",
- textContent: defaultData?.textContent || "",
- contentType: defaultData?.contentType || "LINK",
- requireName: defaultData?.requireName || true,
+ name: defaultData.name || "",
+ link: defaultData.link || "",
+ textContent: defaultData.textContent || "",
+ contentType: defaultData.contentType || "SIGNING",
+ requireName: defaultData.requireName ?? true,
});
}
- }, [defaultData]);
+ }, [defaultData, editAgreement]);
+
+ const resetState = () => {
+ setData(initialData);
+ setCurrentFile(null);
+ setSigningFile(null);
+ setIsLoading(false);
+ setUrlError("");
+ setIsUrlValid(true);
+ setCreatedAgreement(null);
+ setPendingSigningAgreement(null);
+ setSigningSetup(null);
+ setIsSyncingTemplate(false);
+ setIsLoadingSigningAuthoring(false);
+ setSigningRun(null);
+ autoStartedSigningAuthoringRef.current = null;
+ signingRunFinalizedRef.current = null;
+ };
const handleClose = (open: boolean) => {
setIsOpen(open);
- setData({
- name: "",
- link: "",
- textContent: "",
- contentType: "LINK",
- requireName: true
+
+ if (!open) {
+ resetState();
+ onClose?.();
+ }
+ };
+
+ const validateUrl = (url: string) => {
+ if (!url.trim()) {
+ setUrlError("");
+ setIsUrlValid(true);
+ return;
+ }
+
+ try {
+ agreementUrlSchema.parse(url);
+ setUrlError("");
+ setIsUrlValid(true);
+ } catch (error) {
+ if (error instanceof z.ZodError) {
+ setUrlError(error.errors[0]?.message || "Invalid URL");
+ setIsUrlValid(false);
+ }
+ }
+ };
+
+ const startSigningTemplateSetup = async ({
+ agreementId,
+ file,
+ }: {
+ agreementId: string;
+ file: File;
+ }): Promise<SigningSetupRunResponse> => {
+ if (!teamId) {
+ throw new Error("Team context is missing.");
+ }
+
+ if (file.size > MAX_SIGNING_TEMPLATE_PDF_BYTES) {
+ throw new Error(getSigningTemplateTooLargeMessage());
+ }
+
+ const { type, data, fileSize } = await putFile({
+ file,
+ teamId,
});
- setCurrentFile(null);
- setIsLoading(false);
- if (onClose) {
- onClose();
+
+ if (!type || !data || !fileSize) {
+ throw new Error("Failed to upload the agreement template.");
+ }
+
+ const response = await fetch(
+ `/api/teams/${teamId}/agreements/${agreementId}/signing/setup`,
+ {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ "X-Signer-Count": String(SIGNING_RECIPIENT_COUNT),
+ },
+ body: JSON.stringify({
+ fileName: file.name,
+ contentType: SIGNING_TEMPLATE_PDF_CONTENT_TYPE,
+ file: {
+ data,
+ storageType: type,
+ fileSize,
+ },
+ }),
+ },
+ );
+
+ if (!response.ok) {
+ const errorText = await response.text().catch(() => "");
+ throw new Error(errorText || "Failed to upload the agreement template.");
+ }
+
+ const { runId, publicAccessToken } =
+ (await response.json()) as SigningSetupRunResponse;
+
+ if (!runId || !publicAccessToken) {
+ throw new Error("Failed to start the signing template authoring flow.");
}
+
+ return { runId, publicAccessToken };
};
- const handleBrowserUpload = async () => {
- // event.preventDefault();
- // event.stopPropagation();
- if (isOnlyView) {
- handleClose(false);
- toast.error("Cannot upload file in view mode!");
+ // One-shot finalize once the run reports COMPLETED — the presign token must be minted server-side, not polled.
+ const fetchSigningSetupResult = useCallback(
+ async ({
+ agreementId,
+ runId,
+ }: {
+ agreementId: string;
+ runId: string;
+ }): Promise<SigningSetupResponse> => {
+ if (!teamId) {
+ throw new Error("Team context is missing.");
+ }
+
+ const statusResponse = await fetch(
+ `/api/teams/${teamId}/agreements/${agreementId}/signing/setup-status?runId=${encodeURIComponent(
+ runId,
+ )}`,
+ );
+
+ if (!statusResponse.ok) {
+ const errorText = await statusResponse.text().catch(() => "");
+ throw new Error(
+ errorText || "Failed to start the signing template authoring flow.",
+ );
+ }
+
+ return (await statusResponse.json()) as SigningSetupResponse;
+ },
+ [teamId],
+ );
+
+ // Best-effort rollback: a SIGNING agreement without a template/envelope is
+ // unusable, so soft-delete the row we just created if template setup fails.
+ const rollbackAgreement = useCallback(
+ async (agreementId: string) => {
+ if (!teamId) {
+ return;
+ }
+
+ try {
+ await fetch(`/api/teams/${teamId}/agreements/${agreementId}`, {
+ method: "PUT",
+ });
+ } catch (error) {
+ console.error(
+ "Failed to roll back agreement after template setup error.",
+ error,
+ );
+ }
+ },
+ [teamId],
+ );
+
+ const { run: signingSetupRun, error: signingSetupRunError } = useRealtimeRun(
+ signingRun?.runId,
+ {
+ accessToken: signingRun?.accessToken,
+ enabled: !!signingRun,
+ },
+ );
+
+ const failSigningRun = useCallback(
+ async (run: PendingSigningRun, message: string) => {
+ if (signingRunFinalizedRef.current === run.runId) {
+ return;
+ }
+ signingRunFinalizedRef.current = run.runId;
+
+ if (run.createdNow) {
+ // Roll back the row we just created so we never persist a SIGNING
+ // agreement without a template.
+ await rollbackAgreement(run.agreement.id);
+ mutate(`/api/teams/${teamId}/agreements`);
+ }
+
+ setSigningRun(null);
+ setPendingSigningAgreement(null);
+ toast.error(message);
+ },
+ [rollbackAgreement, teamId],
+ );
+
+ // Drive signing template setup from Trigger.dev Realtime instead of polling:
+ // react to the run's terminal state as it streams in.
+ useEffect(() => {
+ if (!signingRun || signingRunFinalizedRef.current === signingRun.runId) {
return;
}
- // Check if the file is chosen
- if (!currentFile) {
- toast.error("Please select a file to upload.");
- return; // prevent form from submitting
+
+ if (signingSetupRunError) {
+ void failSigningRun(
+ signingRun,
+ signingSetupRunError.message ||
+ "Failed to start the signing template authoring flow.",
+ );
+ return;
}
- try {
- setIsLoading(true);
+ const status = signingSetupRun?.status;
+
+ if (status && SIGNING_SETUP_FAILURE_STATUSES.has(status)) {
+ void failSigningRun(
+ signingRun,
+ "Failed to start the signing template authoring flow.",
+ );
+ return;
+ }
+
+ if (status === "COMPLETED") {
+ const run = signingRun;
+ // Claim the run before the async finalize so re-renders (e.g. metadata
+ // updates) can't kick off a second finalize.
+ signingRunFinalizedRef.current = run.runId;
+
+ void (async () => {
+ try {
+ const setup = await fetchSigningSetupResult({
+ agreementId: run.agreement.id,
+ runId: run.runId,
+ });
+ setCreatedAgreement(run.agreement);
+ setSigningSetup(setup);
+ setSigningRun(null);
+ setPendingSigningAgreement(null);
+ } catch (error) {
+ console.error(error);
+ // Release the guard so the shared failure handler can run.
+ signingRunFinalizedRef.current = null;
+ await failSigningRun(
+ run,
+ error instanceof Error
+ ? error.message
+ : "Failed to start the signing template authoring flow.",
+ );
+ }
+ })();
+ }
+ }, [
+ signingRun,
+ signingSetupRun?.status,
+ signingSetupRunError,
+ failSigningRun,
+ fetchSigningSetupResult,
+ ]);
+
+ // Watchdog: never leave the UI spinning if realtime stalls (e.g. the run is
+ // stuck QUEUED or the subscription drops without a terminal state).
+ useEffect(() => {
+ if (!signingRun) {
+ return;
+ }
+
+ const run = signingRun;
+ const timeoutId = setTimeout(() => {
+ void failSigningRun(
+ run,
+ "Signing template setup is taking longer than expected. Please try again.",
+ );
+ }, SIGNING_SETUP_TIMEOUT_MS);
- const contentType = currentFile.type;
- const supportedFileType = getSupportedContentType(contentType);
+ return () => clearTimeout(timeoutId);
+ }, [signingRun, failSigningRun]);
+
+ const openExistingSigningTemplate = useCallback(
+ async (agreement: Agreement) => {
+ if (!teamId) {
+ toast.error("Team context is not ready yet. Please try again.");
+ return;
+ }
+
+ if (!isSigningAgreementRecord(agreement)) {
+ toast.error("Only embedded signing agreements can edit fields.");
+ return;
+ }
- if (
- !supportedFileType ||
- (supportedFileType !== "pdf" && supportedFileType !== "docs")
- ) {
+ if (!agreement.signingEnvelopeId) {
toast.error(
- "Unsupported file format. Please upload a PDF or Word file.",
+ "This signing agreement is missing its template. Please create a new signing agreement.",
);
return;
}
- const { type, data, numPages, fileSize } = await putFile({
- file: currentFile,
- teamId: teamId!,
- });
+ setIsLoadingSigningAuthoring(true);
- const documentData: DocumentData = {
- name: currentFile.name,
- key: data!,
- storageType: type!,
- contentType: contentType,
- supportedFileType: supportedFileType,
- fileSize: fileSize,
- };
- // create a document in the database
- const response = await createAgreementDocument({
- documentData,
- teamId: teamId!,
- numPages,
- });
+ try {
+ const response = await fetch(
+ `/api/teams/${teamId}/agreements/${agreement.id}/signing/presign`,
+ {
+ method: "POST",
+ },
+ );
+
+ if (!response.ok) {
+ const errorPayload = (await response
+ .clone()
+ .json()
+ .catch(() => null)) as { error?: string; message?: string } | null;
+ const errorText = await response.text().catch(() => "");
+ throw new Error(
+ errorPayload?.error ||
+ errorPayload?.message ||
+ errorText ||
+ "Failed to open the signing editor.",
+ );
+ }
+
+ const setup = (await response.json()) as SigningSetupResponse;
+
+ if (!setup.envelopeId) {
+ throw new Error(
+ "This signing agreement is missing its template. Please create a new signing agreement.",
+ );
+ }
- if (response) {
- const document = await response.json();
- const linkId = document.links[0].id;
- setData((prevData) => ({
- ...prevData,
- link: "https://www.papermark.com/view/" + linkId,
- }));
+ setCreatedAgreement(agreement);
+ setSigningSetup(setup);
+ } catch (error) {
+ console.error(error);
+ toast.error(
+ error instanceof Error
+ ? error.message
+ : "Failed to open the signing editor.",
+ );
+ } finally {
+ setIsLoadingSigningAuthoring(false);
}
- } catch (error) {
- console.error("An error occurred while uploading the file: ", error);
- } finally {
- setCurrentFile(null);
- setIsLoading(false);
+ },
+ [teamId],
+ );
+
+ useEffect(() => {
+ if (!isOpen || !startSigningAuthoring || !editAgreement || !teamId) {
+ return;
}
- };
- // Add URL validation function
- const validateUrl = (url: string) => {
- if (!url.trim()) {
- setUrlError("");
- setIsUrlValid(true);
+ if (!isSigningAgreementRecord(editAgreement)) {
return;
}
- try {
- agreementUrlSchema.parse(url);
- setUrlError("");
- setIsUrlValid(true);
- } catch (error) {
- if (error instanceof z.ZodError) {
- const firstError = error.errors[0];
- setUrlError(firstError?.message || "Invalid URL");
- setIsUrlValid(false);
- }
+ if (autoStartedSigningAuthoringRef.current === editAgreement.id) {
+ return;
}
- };
- // Modify handleSubmit to include validation
- const handleSubmit = async (e: FormEvent<HTMLFormElement>) => {
- e.preventDefault();
- e.stopPropagation();
+ autoStartedSigningAuthoringRef.current = editAgreement.id;
+ void openExistingSigningTemplate(editAgreement);
+ }, [
+ editAgreement,
+ isOpen,
+ openExistingSigningTemplate,
+ startSigningAuthoring,
+ teamId,
+ ]);
+
+ const uploadBrowserFile = useCallback(
+ async (file: File) => {
+ if (isOnlyView) {
+ setIsOpen(false);
+ toast.error("Cannot upload file in view mode!");
+ return;
+ }
+
+ if (!teamId) {
+ toast.error("Team context is not ready yet. Please try again.");
+ return;
+ }
+
+ try {
+ setIsLoading(true);
+
+ const contentType = file.type;
+ const supportedFileType = getSupportedContentType(contentType);
+
+ if (
+ !supportedFileType ||
+ (supportedFileType !== "pdf" && supportedFileType !== "docs")
+ ) {
+ toast.error(
+ "Unsupported file format. Please upload a PDF or Word file.",
+ );
+ return;
+ }
+
+ const { type, data, numPages, fileSize } = await putFile({
+ file,
+ teamId,
+ });
+
+ const documentData: DocumentData = {
+ name: file.name,
+ key: data!,
+ storageType: type!,
+ contentType,
+ supportedFileType,
+ fileSize,
+ };
+
+ const response = await createAgreementDocument({
+ documentData,
+ teamId,
+ numPages,
+ });
+
+ if (response) {
+ const document = await response.json();
+ const linkId = document.links[0].id;
+ setData((prevData) => ({
+ ...prevData,
+ link: `https://www.papermark.com/view/${linkId}`,
+ }));
+ }
+ } catch (error) {
+ console.error("An error occurred while uploading the file: ", error);
+ } finally {
+ setCurrentFile(null);
+ setIsLoading(false);
+ }
+ },
+ [isOnlyView, setIsOpen, teamId],
+ );
+
+ // Trigger uploads from the file-picker event via a setter wrapper (not an effect on `currentFile`) to avoid re-runs on unrelated dependency changes.
+ // Side effects stay out of the state updater (StrictMode may invoke it twice); functional updates are passed through unchanged.
+ const contentTypeRef = useRef(data.contentType);
+ contentTypeRef.current = data.contentType;
+
+ const setCurrentFileForLinkUpload = useCallback<
+ Dispatch<SetStateAction<File | null>>
+ >(
+ (value) => {
+ if (typeof value === "function") {
+ setCurrentFile(value);
+ return;
+ }
+
+ setCurrentFile(value);
+
+ if (value && contentTypeRef.current === "LINK") {
+ // Fire-and-forget so the picker stays responsive; errors surface via toast in `uploadBrowserFile`.
+ void uploadBrowserFile(value);
+ }
+ },
+ [uploadBrowserFile],
+ );
+
+ const handleSubmit = async (event: FormEvent<HTMLFormElement>) => {
+ event.preventDefault();
+ event.stopPropagation();
if (isOnlyView) {
handleClose(false);
@@ -200,22 +634,40 @@ export default function AgreementSheet({
return;
}
- // Validate based on content type
+ if (!teamId) {
+ toast.error("Missing team context");
+ return;
+ }
+
if (data.contentType === "LINK") {
- // Validate URL
try {
agreementUrlSchema.parse(data.link);
} catch (error) {
if (error instanceof z.ZodError) {
- const firstError = error.errors[0];
- toast.error(firstError?.message || "Please enter a valid URL");
+ toast.error(error.errors[0]?.message || "Please enter a valid URL");
return;
}
}
- } else if (data.contentType === "TEXT") {
- // Validate text content
- if (!data.textContent.trim()) {
- toast.error("Please enter agreement text content");
+ }
+
+ if (data.contentType === "TEXT" && !data.textContent.trim()) {
+ toast.error("Please enter agreement text content");
+ return;
+ }
+
+ if (!isEditing && data.contentType === "SIGNING") {
+ if (!signingFile) {
+ toast.error("Upload the PDF you want signers to sign.");
+ return;
+ }
+
+ if (signingFile.type !== SIGNING_TEMPLATE_PDF_CONTENT_TYPE) {
+ toast.error("Signing templates currently support PDF files only.");
+ return;
+ }
+
+ if (signingFile.size > MAX_SIGNING_TEMPLATE_PDF_BYTES) {
+ toast.error(getSigningTemplateTooLargeMessage());
return;
}
}
@@ -223,228 +675,506 @@ export default function AgreementSheet({
setIsLoading(true);
try {
- const submitData = {
- name: data.name,
- contentType: data.contentType,
- content: data.contentType === "LINK" ? data.link : data.textContent,
- requireName: data.requireName,
- };
-
- const response = await fetch(`/api/teams/${teamId}/agreements`, {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- },
- body: JSON.stringify(submitData),
- });
+ if (isEditing && editAgreement) {
+ const updateBody: {
+ name: string;
+ requireName: boolean;
+ content?: string;
+ } = {
+ name: data.name,
+ requireName: data.requireName,
+ };
- if (!response.ok) {
- toast.error("Error creating agreement");
+ if (data.contentType === "LINK") {
+ updateBody.content = data.link;
+ } else if (data.contentType === "TEXT") {
+ updateBody.content = data.textContent;
+ }
+
+ const response = await fetch(
+ `/api/teams/${teamId}/agreements/${editAgreement.id}`,
+ {
+ method: "PATCH",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify(updateBody),
+ },
+ );
+
+ if (!response.ok) {
+ const result = await response.json().catch(() => null);
+ toast.error(result?.error || "Error updating agreement");
+ return;
+ }
+
+ const updated = (await response.json()) as Agreement;
+ mutate(`/api/teams/${teamId}/agreements`);
+ onSaved?.(updated);
+ toast.success("Agreement updated");
+ handleClose(false);
return;
}
- mutate(`/api/teams/${teamId}/agreements`);
+ let agreement = pendingSigningAgreement;
+ let createdNow = false;
+
+ if (!agreement) {
+ const submitData = {
+ name: data.name,
+ contentType: data.contentType,
+ content:
+ data.contentType === "LINK"
+ ? data.link
+ : data.contentType === "TEXT"
+ ? data.textContent
+ : undefined,
+ requireName: data.requireName,
+ };
+
+ const response = await fetch(`/api/teams/${teamId}/agreements`, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify(submitData),
+ });
+
+ if (!response.ok) {
+ const result = await response.json().catch(() => null);
+ toast.error(result?.error || "Error creating agreement");
+ return;
+ }
+
+ agreement = (await response.json()) as Agreement;
+ createdNow = true;
+ mutate(`/api/teams/${teamId}/agreements`);
+ }
+
+ if (data.contentType === "SIGNING" && signingFile) {
+ setPendingSigningAgreement(agreement);
+ signingRunFinalizedRef.current = null;
+
+ try {
+ const { runId, publicAccessToken } = await startSigningTemplateSetup({
+ agreementId: agreement.id,
+ file: signingFile,
+ });
+ // Hand off to the realtime subscription, which finalizes the setup
+ // (or rolls back) once the run reaches a terminal state.
+ setSigningRun({
+ runId,
+ accessToken: publicAccessToken,
+ agreement,
+ createdNow,
+ });
+ } catch (error) {
+ console.error(error);
+ // Failed before the run started: roll back so we never persist a templateless SIGNING agreement, and clear pendingSigningAgreement so the next attempt creates a fresh row.
+ if (createdNow) {
+ await rollbackAgreement(agreement.id);
+ mutate(`/api/teams/${teamId}/agreements`);
+ }
+ setPendingSigningAgreement(null);
+ toast.error(
+ error instanceof Error
+ ? error.message
+ : "Failed to start the signing template authoring flow.",
+ );
+ }
+ return;
+ }
+
+ onSaved?.(agreement);
+ toast.success("Agreement created");
+ handleClose(false);
} catch (error) {
console.error(error);
toast.error("An error occurred. Please try again.");
} finally {
setIsLoading(false);
- setIsOpen(false);
- setData({
- name: "",
- link: "",
- textContent: "",
- contentType: "LINK",
- requireName: true
- });
}
};
- useEffect(() => {
- if (currentFile) {
- handleBrowserUpload();
+ const handleEnvelopeSaved = async (envelopeId: string) => {
+ if (!teamId || !createdAgreement) {
+ toast.error("Missing agreement context for signing sync.");
+ return;
+ }
+
+ setIsSyncingTemplate(true);
+
+ try {
+ const response = await fetch(
+ `/api/teams/${teamId}/agreements/${createdAgreement.id}/signing/sync`,
+ {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({ envelopeId }),
+ },
+ );
+
+ if (!response.ok) {
+ throw new Error(await response.text());
+ }
+
+ const updatedAgreement = (await response.json()) as Agreement;
+
+ mutate(`/api/teams/${teamId}/agreements`);
+ onSaved?.(updatedAgreement);
+ toast.success("Agreement template saved.");
+ handleClose(false);
+ } catch (error) {
+ console.error(error);
+ toast.error("Failed to sync the agreement with the signing provider.");
+ } finally {
+ setIsSyncingTemplate(false);
}
- }, [currentFile]);
+ };
+
+ const showSigningAuthoring = !!createdAgreement && !!signingSetup;
+ const showSigningAuthoringLoader =
+ startSigningAuthoring &&
+ isEditing &&
+ isLoadingSigningAuthoring &&
+ !showSigningAuthoring;
+ const showSigningSetupLoader = !!signingRun && !showSigningAuthoring;
+ const signingSetupStatusText =
+ (signingSetupRun?.metadata as { status?: { text?: string } } | undefined)
+ ?.status?.text ?? "Preparing signing template...";
return (
<Sheet open={isOpen} onOpenChange={handleClose}>
- <SheetContent className="flex h-full w-[85%] flex-col justify-between bg-background px-4 text-foreground sm:w-[500px] md:px-5">
+ <SheetContent
+ className={`flex h-full flex-col justify-between bg-background px-4 text-foreground md:px-5 ${
+ showSigningAuthoring || showSigningAuthoringLoader
+ ? "w-[96vw] sm:max-w-5xl"
+ : "w-[85%] sm:w-[500px]"
+ }`}
+ >
<SheetHeader className="text-start">
<SheetTitle>
- {isOnlyView ? "View Agreement" : "Create a new agreement"}
+ {showSigningAuthoring
+ ? isEditing
+ ? "Edit signing fields"
+ : "Place signing fields"
+ : isOnlyView
+ ? "View Agreement"
+ : isEditing
+ ? "Edit agreement"
+ : "Create a new agreement"}
</SheetTitle>
<SheetDescription>
- {isOnlyView
- ? "View the details of this agreement."
- : "An agreement is a special document that visitors must accept before accessing your link. You can create a new agreement here."}
+ {showSigningAuthoring
+ ? isEditing
+ ? 'Adjust the signing fields on the PDF, then click "Update Template" in the editor to save.'
+ : 'Drag the signature, name, and date fields onto the PDF, then click "Update Template" in the editor to finish.'
+ : isOnlyView
+ ? "View the details of this agreement."
+ : isEditing
+ ? "Update the display name, requirements, and content of this agreement."
+ : "Create an agreement that visitors must complete before they can access your link."}
</SheetDescription>
</SheetHeader>
- <ScrollArea className="flex-1">
- <form className="flex grow flex-col" onSubmit={handleSubmit}>
- <div className="flex-grow space-y-6">
- <div className="w-full space-y-2">
- <Label htmlFor="name">Display name</Label>
- <Input
- className="flex w-full rounded-md border-0 bg-background py-1.5 text-foreground shadow-sm ring-1 ring-inset ring-input placeholder:text-muted-foreground focus:ring-2 focus:ring-inset focus:ring-gray-400 sm:text-sm sm:leading-6"
- id="name"
- type="text"
- name="name"
- required
- autoComplete="off"
- data-1p-ignore
- placeholder="Standard NDA"
- value={data.name || ""}
- onChange={(e) =>
- setData({
- ...data,
- name: e.target.value,
- })
- }
- disabled={isOnlyView}
- />
- </div>
-
- <div>
- <LinkItem
- title="Require viewer's name"
- enabled={data.requireName}
- action={() =>
- setData({ ...data, requireName: !data.requireName })
- }
- isAllowed={!isOnlyView}
- />
- </div>
-
- <div className="space-y-4">
- {/* Content Type Selection */}
+ {showSigningAuthoringLoader ? (
+ <div className="flex min-h-0 flex-1 flex-col items-center justify-center gap-3 pt-4 text-sm text-muted-foreground">
+ <LoadingSpinner className="h-8 w-8" />
+ <p>Opening signing editor...</p>
+ </div>
+ ) : showSigningAuthoring ? (
+ <div className="flex min-h-0 flex-1 flex-col pt-4">
+ <SigningTemplateAuthoring
+ host={signingSetup.host}
+ presignToken={signingSetup.presignToken}
+ externalId={signingSetup.externalId}
+ envelopeId={signingSetup.envelopeId}
+ onEnvelopeSaved={handleEnvelopeSaved}
+ />
+ </div>
+ ) : showSigningSetupLoader ? (
+ <div className="flex min-h-0 flex-1 flex-col items-center justify-center gap-3 pt-4 text-sm text-muted-foreground">
+ <LoadingSpinner className="h-8 w-8" />
+ <p>{signingSetupStatusText}</p>
+ </div>
+ ) : (
+ <ScrollArea className="flex-1">
+ <form className="flex grow flex-col" onSubmit={handleSubmit}>
+ <div className="flex-grow space-y-6 pt-2">
<div className="w-full space-y-2">
- <Label>Agreement Content Type</Label>
- <RadioGroup
- value={data.contentType}
- onValueChange={(value) => setData({...data, contentType: value})}
+ <Label htmlFor="name">Display name</Label>
+ <Input
+ className="flex w-full rounded-md border-0 bg-background py-1.5 text-foreground shadow-sm ring-1 ring-inset ring-input placeholder:text-muted-foreground focus:ring-2 focus:ring-inset focus:ring-gray-400 sm:text-sm sm:leading-6"
+ id="name"
+ type="text"
+ name="name"
+ required
+ autoComplete="off"
+ data-1p-ignore
+ placeholder="Standard NDA"
+ value={data.name}
+ onChange={(event) =>
+ setData((prev) => ({
+ ...prev,
+ name: event.target.value,
+ }))
+ }
disabled={isOnlyView}
- className="flex flex-col space-y-2"
- >
- <div className="flex items-center space-x-2">
- <RadioGroupItem value="LINK" id="link-type" />
- <Label htmlFor="link-type">Link to agreement document</Label>
- </div>
- <div className="flex items-center space-x-2">
- <RadioGroupItem value="TEXT" id="text-type" />
- <Label htmlFor="text-type">Text content</Label>
- </div>
- </RadioGroup>
+ />
</div>
- {/* Link Content */}
- {data.contentType === "LINK" && (
+ <div>
+ <LinkItem
+ title="Require viewer's name"
+ enabled={data.requireName}
+ action={() =>
+ setData((prev) => ({
+ ...prev,
+ requireName: !prev.requireName,
+ }))
+ }
+ isAllowed={!isOnlyView}
+ />
+ </div>
+
+ <div className="space-y-4">
<div className="w-full space-y-2">
- <Label htmlFor="link">Link to an agreement</Label>
- <Input
- className={`flex w-full rounded-md border-0 bg-background py-1.5 text-foreground shadow-sm ring-1 ring-inset placeholder:text-muted-foreground focus:ring-2 focus:ring-inset sm:text-sm sm:leading-6 ${
- !isUrlValid
- ? "ring-red-500 focus:ring-red-500"
- : "ring-input focus:ring-gray-400"
- }`}
- id="link"
- type="text"
- name="link"
- required={data.contentType === "LINK"}
- autoComplete="off"
- data-1p-ignore
- placeholder="https://www.papermark.com/nda"
- value={data.link || ""}
- onChange={(e) => {
- const newValue = e.target.value;
- setData({
- ...data,
- link: newValue,
- });
- validateUrl(newValue);
- }}
- onBlur={(e) => {
- validateUrl(e.target.value);
- }}
- disabled={isOnlyView}
- />
- {urlError && (
- <p className="mt-1 text-sm text-red-500">{urlError}</p>
- )}
-
- {!isOnlyView && (
- <div className="space-y-12">
- <div className="space-y-2 pb-6">
- <Label>Or upload an agreement</Label>
- <div className="grid grid-cols-1 gap-x-6 gap-y-8 sm:grid-cols-6">
- <DocumentUpload
- currentFile={currentFile}
- setCurrentFile={setCurrentFile}
- />
- </div>
- </div>
+ <Label>Agreement Type</Label>
+ <RadioGroup
+ value={data.contentType}
+ onValueChange={(value) =>
+ setData((prev) => ({
+ ...prev,
+ contentType: value,
+ }))
+ }
+ disabled={isOnlyView || isEditing}
+ className="flex flex-col space-y-2"
+ >
+ <div className="flex items-center space-x-2">
+ <RadioGroupItem value="SIGNING" id="signing-type" />
+ <Label htmlFor="signing-type">
+ Embedded signature flow
+ </Label>
+ </div>
+ <div className="flex items-center space-x-2">
+ <RadioGroupItem value="LINK" id="link-type" />
+ <Label htmlFor="link-type">Legacy link document</Label>
+ </div>
+ <div className="flex items-center space-x-2">
+ <RadioGroupItem value="TEXT" id="text-type" />
+ <Label htmlFor="text-type">Legacy text content</Label>
</div>
- )}
+ </RadioGroup>
+ {isEditing ? (
+ <p className="text-xs text-muted-foreground">
+ The agreement type cannot be changed after creation.
+ </p>
+ ) : null}
</div>
- )}
- {/* Text Content */}
- {data.contentType === "TEXT" && (
- <div className="w-full space-y-2">
- <Label htmlFor="textContent">Agreement Text</Label>
- <Textarea
- className="flex w-full rounded-md border-0 bg-background py-1.5 text-foreground shadow-sm ring-1 ring-inset ring-input placeholder:text-muted-foreground focus:ring-2 focus:ring-inset focus:ring-gray-400 sm:text-sm sm:leading-6"
- id="textContent"
- name="textContent"
- required={data.contentType === "TEXT"}
- placeholder="By accessing this document, you agree to maintain confidentiality of all information contained herein and not to share, copy, or distribute any content without prior written consent..."
- value={data.textContent || ""}
- onChange={(e) =>
- setData({
- ...data,
- textContent: e.target.value,
- })
- }
- disabled={isOnlyView}
- rows={6}
- maxLength={1500}
- />
- <div className="flex justify-between text-xs">
- <p className="text-muted-foreground">
- This text will be displayed to users as a compliance agreement before they can access the content.
+ {data.contentType === "SIGNING" && !isEditing ? (
+ <div className="space-y-2">
+ <Label>Upload the agreement PDF</Label>
+ <DocumentUpload
+ currentFile={signingFile}
+ setCurrentFile={setSigningFile}
+ pdfOnly
+ maxSizeBytes={MAX_SIGNING_TEMPLATE_PDF_BYTES}
+ maxSizeErrorMessage={getSigningTemplateTooLargeMessage()}
+ />
+ <p className="text-xs text-muted-foreground">
+ PDF only, max 30 MB. After upload you place the
+ viewer&apos;s signature, name, and date fields directly
+ on the document.
</p>
- <p className={`${data.textContent.length > 1400 ? 'text-orange-500' : 'text-muted-foreground'} ${data.textContent.length >= 1500 ? 'text-red-500 font-semibold' : ''}`}>
- {data.textContent.length}/1500
+ </div>
+ ) : null}
+
+ {data.contentType === "SIGNING" && isEditing ? (
+ <div className="space-y-3 rounded-md border border-dashed border-border bg-muted/30 p-3 text-xs text-muted-foreground">
+ <p>
+ The signed PDF and field placement are managed in the
+ signing template. Reopen the signing editor to adjust
+ the viewer&apos;s signature, name, and date fields.
</p>
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ loading={isLoadingSigningAuthoring}
+ disabled={
+ isLoadingSigningAuthoring ||
+ !editAgreement?.signingEnvelopeId
+ }
+ onClick={() => {
+ if (editAgreement) {
+ void openExistingSigningTemplate(editAgreement);
+ }
+ }}
+ >
+ Edit signing fields
+ </Button>
+ {!editAgreement?.signingEnvelopeId ? (
+ <p>
+ This agreement is missing its signing template. Create
+ a new signing agreement to replace the document.
+ </p>
+ ) : null}
</div>
- </div>
- )}
+ ) : null}
+
+ {data.contentType === "LINK" ? (
+ <div className="w-full space-y-2">
+ <Label htmlFor="link">Link to an agreement</Label>
+ <Input
+ className={`flex w-full rounded-md border-0 bg-background py-1.5 text-foreground shadow-sm ring-1 ring-inset placeholder:text-muted-foreground focus:ring-2 focus:ring-inset sm:text-sm sm:leading-6 ${
+ !isUrlValid
+ ? "ring-red-500 focus:ring-red-500"
+ : "ring-input focus:ring-gray-400"
+ }`}
+ id="link"
+ type="text"
+ name="link"
+ required
+ autoComplete="off"
+ data-1p-ignore
+ placeholder="https://www.papermark.com/nda"
+ value={data.link}
+ onChange={(event) => {
+ const newValue = event.target.value;
+ setData((prev) => ({
+ ...prev,
+ link: newValue,
+ }));
+ validateUrl(newValue);
+ }}
+ onBlur={(event) => validateUrl(event.target.value)}
+ disabled={isOnlyView}
+ />
+ {urlError ? (
+ <p className="mt-1 text-sm text-red-500">{urlError}</p>
+ ) : null}
+
+ {!isOnlyView ? (
+ <div className="space-y-12">
+ <div className="space-y-2 pb-6">
+ <Label>Or upload an agreement</Label>
+ <div className="grid grid-cols-1 gap-x-6 gap-y-8 sm:grid-cols-6">
+ <DocumentUpload
+ currentFile={currentFile}
+ setCurrentFile={setCurrentFileForLinkUpload}
+ />
+ </div>
+ </div>
+ </div>
+ ) : null}
+ </div>
+ ) : null}
+
+ {data.contentType === "TEXT" ? (
+ <div className="w-full space-y-2">
+ <Label htmlFor="textContent">Agreement Text</Label>
+ <Textarea
+ className="flex w-full rounded-md border-0 bg-background py-1.5 text-foreground shadow-sm ring-1 ring-inset ring-input placeholder:text-muted-foreground focus:ring-2 focus:ring-inset focus:ring-gray-400 sm:text-sm sm:leading-6"
+ id="textContent"
+ name="textContent"
+ required
+ placeholder="By accessing this document, you agree to maintain confidentiality of all information contained herein and not to share, copy, or distribute any content without prior written consent..."
+ value={data.textContent}
+ onChange={(event) =>
+ setData((prev) => ({
+ ...prev,
+ textContent: event.target.value,
+ }))
+ }
+ disabled={isOnlyView}
+ rows={6}
+ maxLength={1500}
+ />
+ <div className="flex justify-between text-xs">
+ <p className="text-muted-foreground">
+ This text will be displayed to users as a compliance
+ agreement before they can access the content.
+ </p>
+ <p
+ className={`${
+ data.textContent.length > 1400
+ ? "text-orange-500"
+ : "text-muted-foreground"
+ } ${
+ data.textContent.length >= 1500
+ ? "font-semibold text-red-500"
+ : ""
+ }`}
+ >
+ {data.textContent.length}/1500
+ </p>
+ </div>
+ </div>
+ ) : null}
+ </div>
</div>
+
+ <SheetFooter
+ className={`flex-shrink-0 ${isOnlyView ? "mt-6" : ""}`}
+ >
+ <div className="flex items-center">
+ {isOnlyView ? (
+ <Button type="button" onClick={() => handleClose(false)}>
+ Close
+ </Button>
+ ) : (
+ <Button
+ type="submit"
+ loading={isLoading}
+ disabled={
+ isLoadingSigningAuthoring ||
+ (data.contentType === "LINK" &&
+ !isUrlValid &&
+ data.link.trim() !== "") ||
+ (data.contentType === "TEXT" &&
+ !data.textContent.trim()) ||
+ (!isEditing &&
+ data.contentType === "SIGNING" &&
+ !signingFile) ||
+ !data.name.trim()
+ }
+ >
+ {isEditing
+ ? "Save changes"
+ : data.contentType === "SIGNING"
+ ? "Continue to field placement"
+ : "Create Agreement"}
+ </Button>
+ )}
+ </div>
+ </SheetFooter>
+ </form>
+ </ScrollArea>
+ )}
+
+ {showSigningAuthoring ? (
+ <SheetFooter className="mt-4 flex-shrink-0">
+ <div className="flex items-center gap-2">
+ <Button
+ type="button"
+ variant="outline"
+ onClick={() => handleClose(false)}
+ disabled={isSyncingTemplate}
+ >
+ Cancel
+ </Button>
+ {isSyncingTemplate ? (
+ <Button type="button" disabled loading>
+ Saving template...
+ </Button>
+ ) : null}
</div>
- <SheetFooter
- className={`flex-shrink-0 ${isOnlyView ? "mt-6" : ""}`}
- >
- <div className="flex items-center">
- {isOnlyView ? (
- <Button type="button" onClick={() => handleClose(false)}>
- Close
- </Button>
- ) : (
- <Button
- type="submit"
- loading={isLoading}
- disabled={
- (data.contentType === "LINK" && !isUrlValid && data.link.trim() !== "") ||
- (data.contentType === "TEXT" && !data.textContent.trim())
- }
- >
- Create Agreement
- </Button>
- )}
- </div>
- </SheetFooter>
- </form>
- </ScrollArea>
+ </SheetFooter>
+ ) : null}
</SheetContent>
</Sheet>
);
diff --git a/components/links/link-sheet/agreement-section.tsx b/components/links/link-sheet/agreement-section.tsx
index dca3335d..02ec01dc 100644
--- a/components/links/link-sheet/agreement-section.tsx
+++ b/components/links/link-sheet/agreement-section.tsx
@@ -1,11 +1,13 @@
import { useEffect, useMemo, useState } from "react";
-import { Agreement, LinkPreset } from "@prisma/client";
+import { Agreement } from "@prisma/client";
+import { PlusIcon } from "lucide-react";
import { motion } from "motion/react";
import { FADE_IN_ANIMATION_SETTINGS } from "@/lib/constants";
import { useAgreements } from "@/lib/swr/use-agreements";
+import { Button } from "@/components/ui/button";
import {
Select,
SelectContent,
@@ -13,12 +15,34 @@ import {
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipPortal,
+ TooltipProvider,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
import { DEFAULT_LINK_TYPE } from ".";
import AgreementSheet from "./agreement-panel";
import LinkItem from "./link-item";
import { LinkUpgradeOptions } from "./link-options";
+const isSigningAgreement = (
+ agreement: Pick<Agreement, "contentType" | "signingProvider">,
+) =>
+ agreement.contentType === "SIGNING" ||
+ agreement.signingProvider === "DOCUMENSO";
+
+type AgreementWithSignedResponseCount = Agreement & {
+ _count?: {
+ responses?: number;
+ };
+};
+
+const agreementHasSignatures = (agreement: AgreementWithSignedResponseCount) =>
+ (agreement._count?.responses ?? 0) > 0;
+
export default function AgreementSection({
data,
setData,
@@ -40,6 +64,9 @@ export default function AgreementSection({
const [enabled, setEnabled] = useState<boolean>(false);
const [isAgreementSheetVisible, setIsAgreementSheetVisible] =
useState<boolean>(false);
+ const [editAgreement, setEditAgreement] = useState<Agreement | null>(null);
+ const [startSigningAuthoring, setStartSigningAuthoring] = useState(false);
+ const [isAgreementSelectOpen, setIsAgreementSelectOpen] = useState(false);
const filteredAgreements = useMemo(
() =>
@@ -66,13 +93,33 @@ export default function AgreementSection({
};
const handleAgreementChange = (value: string) => {
- if (value === "add_agreement") {
- // Open the agreement sheet
- setIsAgreementSheetVisible(true);
+ setData({ ...data, agreementId: value });
+ };
+
+ const handleAgreementSaved = (agreement: Agreement) => {
+ setData((prev) => ({ ...prev, agreementId: agreement.id }));
+ };
+
+ const handleAddAgreement = () => {
+ setEditAgreement(null);
+ setStartSigningAuthoring(false);
+ setIsAgreementSheetVisible(true);
+ };
+
+ const handleEditSigningAgreement = (agreement: Agreement) => {
+ if (!isSigningAgreement(agreement)) {
return;
}
- setData({ ...data, agreementId: value });
+ setEditAgreement(agreement);
+ setStartSigningAuthoring(true);
+ setIsAgreementSelectOpen(false);
+ setIsAgreementSheetVisible(true);
+ };
+
+ const handleAgreementSheetClose = () => {
+ setEditAgreement(null);
+ setStartSigningAuthoring(false);
};
return (
@@ -100,35 +147,137 @@ export default function AgreementSection({
className="relative mt-4 space-y-3"
{...FADE_IN_ANIMATION_SETTINGS}
>
- <div className="flex w-full flex-col items-start gap-6 overflow-x-visible pb-4 pt-0">
- <div className="w-full space-y-2">
+ <div className="flex w-full flex-col items-start gap-3 overflow-x-visible pb-4 pt-0">
+ <div className="flex w-full flex-wrap items-center gap-2">
<Select
+ open={isAgreementSelectOpen}
+ onOpenChange={setIsAgreementSelectOpen}
+ value={agreementId ?? ""}
onValueChange={handleAgreementChange}
- defaultValue={agreementId ?? ""}
>
- <SelectTrigger className="focus:ring-offset-3 flex w-full rounded-md border-0 bg-background py-1.5 text-foreground shadow-sm ring-1 ring-inset ring-input placeholder:text-muted-foreground focus:ring-2 focus:ring-gray-400 sm:text-sm sm:leading-6">
+ <SelectTrigger className="focus:ring-offset-3 flex min-w-[220px] flex-1 rounded-md border-0 bg-background py-1.5 text-foreground shadow-sm ring-1 ring-inset ring-input placeholder:text-muted-foreground focus:ring-2 focus:ring-gray-400 sm:text-sm sm:leading-6">
<SelectValue placeholder="Select an agreement" />
</SelectTrigger>
<SelectContent>
- {filteredAgreements &&
- filteredAgreements.map(({ id, name }) => (
- <SelectItem key={id} value={id}>
- {name}
- </SelectItem>
- ))}
- <SelectItem key="add_agreement" value="add_agreement">
- Add new agreement
- </SelectItem>
+ {filteredAgreements && filteredAgreements.length > 0 ? (
+ filteredAgreements.map((agreement) => {
+ const canEditFields = isSigningAgreement(agreement);
+ const hasSignatures = agreementHasSignatures(agreement);
+ const isSelected = agreement.id === agreementId;
+ const disabledEditReason =
+ "Signing fields cannot be edited after signatures have been collected";
+ const editVisibilityClass = isSelected
+ ? hasSignatures
+ ? "opacity-50"
+ : "opacity-100"
+ : hasSignatures
+ ? "opacity-0 group-focus/agreement:opacity-50 group-hover/agreement:opacity-50"
+ : "opacity-0 group-focus/agreement:opacity-100 group-hover/agreement:opacity-100";
+
+ return (
+ <SelectItem
+ key={agreement.id}
+ value={agreement.id}
+ className="group/agreement pr-16"
+ trailingContent={
+ canEditFields ? (
+ <TooltipProvider delayDuration={0}>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span
+ role="button"
+ tabIndex={hasSignatures ? -1 : 0}
+ aria-disabled={hasSignatures}
+ aria-label={`Edit signing fields for ${agreement.name}`}
+ className={`absolute right-7 top-1/2 z-10 flex h-6 -translate-y-1/2 items-center rounded-md border border-border bg-background px-2 text-xs font-medium text-muted-foreground shadow-sm transition-opacity ${
+ hasSignatures
+ ? "cursor-not-allowed"
+ : "cursor-pointer hover:border-foreground/20 hover:text-foreground"
+ } ${editVisibilityClass}`}
+ onPointerDown={(event) => {
+ event.preventDefault();
+ event.stopPropagation();
+
+ if (hasSignatures) {
+ return;
+ }
+
+ handleEditSigningAgreement(agreement);
+ }}
+ onKeyDown={(event) => {
+ if (
+ event.key !== "Enter" &&
+ event.key !== " "
+ ) {
+ return;
+ }
+
+ event.preventDefault();
+ event.stopPropagation();
+
+ if (hasSignatures) {
+ return;
+ }
+
+ handleEditSigningAgreement(agreement);
+ }}
+ >
+ Edit
+ </span>
+ </TooltipTrigger>
+ {hasSignatures ? (
+ <TooltipPortal>
+ <TooltipContent
+ side="left"
+ sideOffset={8}
+ className="max-w-64 text-center text-xs"
+ >
+ {disabledEditReason}
+ </TooltipContent>
+ </TooltipPortal>
+ ) : null}
+ </Tooltip>
+ </TooltipProvider>
+ ) : null
+ }
+ >
+ {agreement.name}
+ </SelectItem>
+ );
+ })
+ ) : (
+ <div className="px-2 py-1.5 text-sm text-muted-foreground">
+ No agreements yet
+ </div>
+ )}
</SelectContent>
</Select>
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ className="h-9 shrink-0"
+ onClick={(e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ handleAddAgreement();
+ }}
+ >
+ <PlusIcon className="mr-2 h-4 w-4" />
+ Add agreement
+ </Button>
</div>
</div>
</motion.div>
)}
<AgreementSheet
+ editAgreement={editAgreement}
isOpen={isAgreementSheetVisible}
setIsOpen={setIsAgreementSheetVisible}
+ startSigningAuthoring={startSigningAuthoring}
+ onClose={handleAgreementSheetClose}
+ onSaved={handleAgreementSaved}
/>
</div>
);
diff --git a/components/ui/select.tsx b/components/ui/select.tsx
index 4a8f3bba..577f6c04 100644
--- a/components/ui/select.tsx
+++ b/components/ui/select.tsx
@@ -113,10 +113,16 @@ const SelectLabel = React.forwardRef<
));
SelectLabel.displayName = SelectPrimitive.Label.displayName;
+type SelectItemProps = React.ComponentPropsWithoutRef<
+ typeof SelectPrimitive.Item
+> & {
+ trailingContent?: React.ReactNode;
+};
+
const SelectItem = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Item>,
- React.ComponentPropsWithoutRef<typeof SelectPrimitive.Item>
->(({ className, children, ...props }, ref) => (
+ SelectItemProps
+>(({ className, children, trailingContent, ...props }, ref) => (
<SelectPrimitive.Item
ref={ref}
className={cn(
@@ -131,6 +137,7 @@ const SelectItem = React.forwardRef<
</SelectPrimitive.ItemIndicator>
</span>
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
+ {trailingContent}
</SelectPrimitive.Item>
));
SelectItem.displayName = SelectPrimitive.Item.displayName;
diff --git a/components/view/access-form/agreement-section.tsx b/components/view/access-form/agreement-section.tsx
index 0fb08b5a..a9ffa1d2 100644
--- a/components/view/access-form/agreement-section.tsx
+++ b/components/view/access-form/agreement-section.tsx
@@ -1,40 +1,765 @@
-import { Dispatch, SetStateAction } from "react";
+import dynamic from "next/dynamic";
+
+import {
+ type CSSProperties,
+ Dispatch,
+ SetStateAction,
+ useCallback,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+} from "react";
import { Brand, DataroomBrand } from "@prisma/client";
+import {
+ CheckCircle2,
+ DownloadIcon,
+ FileSignatureIcon,
+ PenLineIcon,
+} from "lucide-react";
+import { toast } from "sonner";
+import useSWRImmutable from "swr/immutable";
+
+import {
+ type StoredAgreementResponse,
+ getAgreementResponseStorageKey,
+ parseStoredAgreementResponse,
+} from "@/lib/signing/agreement-storage";
+import {
+ downloadSignedAgreement,
+ getErrorMessageFromResponse,
+} from "@/lib/signing/download";
+import { fetcher } from "@/lib/utils";
+import { validateEmail } from "@/lib/utils/validate-email";
+import { localStorage } from "@/lib/webstorage";
+import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
+import {
+ Sheet,
+ SheetContent,
+ SheetDescription,
+ SheetHeader,
+ SheetTitle,
+} from "@/components/ui/sheet";
import { DEFAULT_ACCESS_FORM_TYPE } from ".";
import { useAccessFormTheme } from "./access-form-theme";
+const getEmbedSurfaceColor = (value?: string) => {
+ return value && value !== "transparent" ? value : "rgb(255 255 255)";
+};
+
+// Injected into the Documenso iframe to hide its sidebar and use only the bottom widget; kept at module scope for a stable string identity.
+const SIGNING_EMBED_CSS = `
+ /* Never render the signing sidebar — the hovering bottom widget is the
+ only signing surface we want the visitor to use. */
+ .embed--DocumentWidgetContainer {
+ display: none !important;
+ }
+
+ /* Force the fixed bottom widget to show even at the desktop breakpoint
+ where Documenso would otherwise hide it in favour of the sidebar. The
+ widget wrapper is the \`lg:hidden\` direct child of the document viewer;
+ this pairs with the sidebar rule above so a wider surface still keeps a
+ signing control. */
+ .embed--DocumentViewer > .lg\\:hidden {
+ display: block !important;
+ }
+
+ /* Let the document reclaim the full width the sidebar used to occupy. */
+ .embed--DocumentContainer {
+ padding-left: 0;
+ padding-right: 0;
+ }
+
+ .embed--Root,
+ .embed--DocumentContainer,
+ .embed--DocumentViewer {
+ border-radius: 0.5rem;
+ }
+
+ /* Flatten Documenso's heavy default shadows so the header and the
+ completed/waiting states sit cleanly inside the Papermark sheet. */
+ .embed--DocumentWidgetHeader,
+ .embed--DocumentCompleted,
+ .embed--WaitingForTurn {
+ box-shadow: none;
+ }
+ `;
+
+const EmbedDirectTemplate = dynamic(
+ () => import("@documenso/embed-react").then((mod) => mod.EmbedDirectTemplate),
+ {
+ ssr: false,
+ },
+);
+
+type AgreementSigningSession = {
+ agreementResponseId: string;
+ externalId: string;
+ token: string;
+ host: string;
+};
+
+type AgreementSigningSessionResult =
+ | (AgreementSigningSession & { alreadySigned?: false })
+ | {
+ alreadySigned: true;
+ agreementResponseId: string;
+ signingStatus: string;
+ };
+
+type SignedAgreementStatus = {
+ signed?: boolean;
+ agreementResponseId?: string;
+ signingStatus?: string;
+ signerEmail?: string | null;
+ signerName?: string | null;
+};
+
+type CompletedSigningResult = {
+ id: string;
+ signingStatus: string;
+};
+
+const normalizeSignedEmail = (email?: string | null) => {
+ if (typeof email !== "string") {
+ return null;
+ }
+
+ const trimmed = email.trim().toLowerCase();
+ return trimmed.length > 0 ? trimmed : null;
+};
+
+const normalizeSignedName = (name?: string | null) => {
+ if (typeof name !== "string") {
+ return null;
+ }
+
+ const trimmed = name.trim();
+ return trimmed.length > 0 ? trimmed : null;
+};
+
+const persistSignedAgreementResponse = ({
+ linkId,
+ agreementId,
+ agreementResponseId,
+ signingStatus,
+}: {
+ linkId: string;
+ agreementId: string;
+ agreementResponseId: string;
+ signingStatus: string;
+}) => {
+ const payload: StoredAgreementResponse = {
+ agreementResponseId,
+ signingStatus,
+ };
+
+ localStorage.setItem(
+ getAgreementResponseStorageKey(linkId, agreementId),
+ JSON.stringify(payload),
+ );
+};
+
export default function AgreementSection({
data,
setData,
+ agreementId,
agreementContent,
agreementName,
agreementContentType,
+ signingProvider,
brand,
+ linkId,
+ requireEmail,
+ requireName,
useCustomAccessForm,
}: {
data: DEFAULT_ACCESS_FORM_TYPE;
setData: Dispatch<SetStateAction<DEFAULT_ACCESS_FORM_TYPE>>;
+ agreementId?: string;
agreementContent: string;
agreementName: string;
agreementContentType?: string;
+ signingProvider?: string;
brand?: Partial<Brand> | Partial<DataroomBrand> | null;
+ linkId?: string;
+ requireEmail?: boolean;
+ requireName?: boolean;
useCustomAccessForm?: boolean;
}) {
const theme = useAccessFormTheme();
const isChecked = !!data.hasConfirmedAgreement;
+ const visitorEmail = typeof data.email === "string" ? data.email.trim() : "";
+ const visitorName = typeof data.name === "string" ? data.name.trim() : "";
+ const currentSigningIdentity = `${visitorEmail}\n${visitorName}`;
+ const [isSheetOpen, setIsSheetOpen] = useState(false);
+ const [isPreparingSession, setIsPreparingSession] = useState(false);
+ const [isCompletingSession, setIsCompletingSession] = useState(false);
+ const [isDownloadingSigned, setIsDownloadingSigned] = useState(false);
+ const [session, setSession] = useState<AgreementSigningSession | null>(null);
+ const currentSigningIdentityRef = useRef(currentSigningIdentity);
+ const sessionIdentityRef = useRef<string | null>(null);
+ // Holds the in-flight session-creation request so a pre-warm (hover/focus)
+ // and a subsequent click both await the same POST instead of firing two.
+ const sessionPromiseRef =
+ useRef<Promise<AgreementSigningSession | null> | null>(null);
+ const sessionPromiseIdentityRef = useRef<string | null>(null);
+ // Pre-warm fires at most once per mount; reset on failure so a click retries.
+ const hasPrewarmedSessionRef = useRef(false);
const handleCheckChange = (checked: boolean) => {
setData((prevData) => ({ ...prevData, hasConfirmedAgreement: checked }));
};
+
const toggleAgreement = () => {
handleCheckChange(!isChecked);
};
+ const isSigningAgreement =
+ signingProvider === "DOCUMENSO" || agreementContentType === "SIGNING";
const isTextContent = agreementContentType === "TEXT";
+ const hasRequiredSigningIdentity =
+ (!requireName || visitorName.length > 0) &&
+ (!requireEmail || validateEmail(visitorEmail));
+ const hasCurrentSigningSession =
+ !!session && sessionIdentityRef.current === currentSigningIdentity;
+ const signingIdentityPrompt =
+ requireName && requireEmail
+ ? "Enter your name and email address before opening signing."
+ : requireName
+ ? "Enter your name before opening signing."
+ : "Enter a valid email address before opening signing.";
+
+ useEffect(() => {
+ currentSigningIdentityRef.current = currentSigningIdentity;
+ hasPrewarmedSessionRef.current = false;
+ }, [currentSigningIdentity]);
+
+ // The stored response id is only a hint the status API honors with a matching session-proof cookie, so it's safe to fold into the cache key.
+ const storedAgreementResponseId = useMemo(() => {
+ if (!isSigningAgreement || !linkId || !agreementId) {
+ return null;
+ }
+
+ return (
+ parseStoredAgreementResponse(
+ localStorage.getItem(
+ getAgreementResponseStorageKey(linkId, agreementId),
+ ),
+ )?.agreementResponseId ?? null
+ );
+ }, [isSigningAgreement, linkId, agreementId]);
+
+ // Only hydrate while unconfirmed (null key disables the request); useSWRImmutable since signed status is effectively one-shot.
+ const signedStatusKey = useMemo(() => {
+ if (
+ !isSigningAgreement ||
+ !agreementId ||
+ !linkId ||
+ data.hasConfirmedAgreement
+ ) {
+ return null;
+ }
+
+ const params = new URLSearchParams({ linkId, agreementId });
+ if (storedAgreementResponseId) {
+ params.set("agreementResponseId", storedAgreementResponseId);
+ }
+
+ return `/api/agreements/signing/status?${params.toString()}`;
+ }, [
+ isSigningAgreement,
+ agreementId,
+ linkId,
+ data.hasConfirmedAgreement,
+ storedAgreementResponseId,
+ ]);
+
+ // Best-effort hydration; failures are ignored so the visitor can still sign.
+ const { data: signedStatus } = useSWRImmutable<SignedAgreementStatus>(
+ signedStatusKey,
+ fetcher,
+ );
+
+ useEffect(() => {
+ if (
+ !linkId ||
+ !agreementId ||
+ data.hasConfirmedAgreement ||
+ !signedStatus?.signed ||
+ !signedStatus.agreementResponseId ||
+ !signedStatus.signingStatus
+ ) {
+ return;
+ }
+
+ const { agreementResponseId, signingStatus } = signedStatus;
+ const signerEmail = normalizeSignedEmail(signedStatus.signerEmail);
+ const signerName = normalizeSignedName(signedStatus.signerName);
+
+ setData((prevData) => ({
+ ...prevData,
+ hasConfirmedAgreement: true,
+ agreementResponseId,
+ agreementStatus: signingStatus,
+ email: signerEmail ?? prevData.email,
+ name: signerName ?? prevData.name,
+ }));
+
+ persistSignedAgreementResponse({
+ linkId,
+ agreementId,
+ agreementResponseId,
+ signingStatus,
+ });
+ }, [signedStatus, agreementId, linkId, data.hasConfirmedAgreement, setData]);
+
+ const signedAgreementHref = data.agreementResponseId
+ ? `/api/agreements/signing/${data.agreementResponseId}/download`
+ : null;
+
+ // The embed re-initializes when these change identity, so we depend only on
+ // the primitive theme tokens that actually feed into the CSS variables.
+ const signingEmbedCssVars = useMemo(
+ () => ({
+ background: getEmbedSurfaceColor(theme.backgroundColor),
+ foreground: theme.textColor,
+ muted: getEmbedSurfaceColor(theme.panelBgColor),
+ mutedForeground: theme.subtleTextColor,
+ popover: getEmbedSurfaceColor(theme.panelBgColor),
+ popoverForeground: theme.textColor,
+ card: getEmbedSurfaceColor(theme.panelBgColor),
+ cardBorder: theme.controlBorderColor,
+ cardBorderTint: theme.controlBorderStrongColor,
+ cardForeground: theme.textColor,
+ fieldCard: getEmbedSurfaceColor(theme.controlBgColor),
+ fieldCardBorder: theme.controlBorderColor,
+ fieldCardForeground: theme.textColor,
+ widget: getEmbedSurfaceColor(theme.panelBgColor),
+ widgetForeground: theme.textColor,
+ border: theme.controlBorderColor,
+ input: theme.controlBorderStrongColor,
+ primary: theme.ctaBgColor,
+ primaryForeground: theme.ctaTextColor,
+ secondary: getEmbedSurfaceColor(theme.controlBgColor),
+ secondaryForeground: theme.textColor,
+ accent: getEmbedSurfaceColor(theme.panelHoverBgColor),
+ accentForeground: theme.textColor,
+ destructive: "hsl(0 84.2% 60.2%)",
+ destructiveForeground: "hsl(210 20% 98%)",
+ ring: theme.controlBorderStrongColor,
+ warning: "hsl(38 92% 50%)",
+ radius: "0.5rem",
+ }),
+ [
+ theme.backgroundColor,
+ theme.controlBgColor,
+ theme.controlBorderColor,
+ theme.controlBorderStrongColor,
+ theme.ctaBgColor,
+ theme.ctaTextColor,
+ theme.panelBgColor,
+ theme.panelHoverBgColor,
+ theme.subtleTextColor,
+ theme.textColor,
+ ],
+ );
+
+ const openSignedAgreement = async () => {
+ if (!signedAgreementHref || isDownloadingSigned) {
+ return;
+ }
+
+ setIsDownloadingSigned(true);
+
+ try {
+ await downloadSignedAgreement({ url: signedAgreementHref });
+ } catch (error) {
+ toast.error(
+ error instanceof Error
+ ? error.message
+ : "Failed to download the signed copy.",
+ );
+ } finally {
+ setIsDownloadingSigned(false);
+ }
+ };
+
+ // Create or reuse the signing session; returns null when already-signed or unconfigured, and concurrent callers share one in-flight promise.
+ const ensureSigningSession =
+ useCallback(async (): Promise<AgreementSigningSession | null> => {
+ const requestSigningIdentity = currentSigningIdentity;
+
+ if (session && sessionIdentityRef.current === requestSigningIdentity) {
+ return session;
+ }
+ if (
+ sessionPromiseRef.current &&
+ sessionPromiseIdentityRef.current === requestSigningIdentity
+ ) {
+ return sessionPromiseRef.current;
+ }
+ if (!agreementId || !linkId) {
+ return null;
+ }
+
+ const createSession =
+ async (): Promise<AgreementSigningSession | null> => {
+ const stored = parseStoredAgreementResponse(
+ localStorage.getItem(
+ getAgreementResponseStorageKey(linkId, agreementId),
+ ),
+ );
+
+ const response = await fetch("/api/agreements/signing/session", {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({
+ agreementId,
+ linkId,
+ email: visitorEmail.length > 0 ? visitorEmail : null,
+ name: visitorName.length > 0 ? visitorName : null,
+ agreementResponseId:
+ data.agreementResponseId ?? stored?.agreementResponseId ?? null,
+ }),
+ });
+
+ if (!response.ok) {
+ throw new Error(
+ await getErrorMessageFromResponse(
+ response,
+ "Failed to start the agreement signing session.",
+ ),
+ );
+ }
+
+ const result =
+ (await response.json()) as AgreementSigningSessionResult;
+
+ if (result.alreadySigned) {
+ if (currentSigningIdentityRef.current === requestSigningIdentity) {
+ setData((prevData) => ({
+ ...prevData,
+ hasConfirmedAgreement: true,
+ agreementResponseId: result.agreementResponseId,
+ agreementStatus: result.signingStatus,
+ }));
+
+ persistSignedAgreementResponse({
+ linkId,
+ agreementId,
+ agreementResponseId: result.agreementResponseId,
+ signingStatus: result.signingStatus,
+ });
+ }
+ return null;
+ }
+
+ if (currentSigningIdentityRef.current !== requestSigningIdentity) {
+ return null;
+ }
+
+ sessionIdentityRef.current = requestSigningIdentity;
+ setSession(result);
+ setData((prevData) => ({
+ ...prevData,
+ agreementResponseId: result.agreementResponseId,
+ agreementStatus: "PENDING",
+ }));
+ return result;
+ };
+
+ const pending = createSession();
+ sessionPromiseRef.current = pending;
+ sessionPromiseIdentityRef.current = requestSigningIdentity;
+
+ try {
+ return await pending;
+ } finally {
+ if (sessionPromiseRef.current === pending) {
+ sessionPromiseRef.current = null;
+ sessionPromiseIdentityRef.current = null;
+ }
+ }
+ }, [
+ agreementId,
+ currentSigningIdentity,
+ linkId,
+ session,
+ visitorEmail,
+ visitorName,
+ data.agreementResponseId,
+ setData,
+ ]);
+
+ // Pre-warm on hover/focus so the iframe is ready on click; fires once per mount and resets its guard on failure so the click can retry.
+ const handlePrewarmSigningSession = useCallback(() => {
+ if (
+ hasPrewarmedSessionRef.current ||
+ !isSigningAgreement ||
+ !agreementId ||
+ !linkId ||
+ isChecked ||
+ !hasRequiredSigningIdentity ||
+ hasCurrentSigningSession ||
+ sessionPromiseRef.current
+ ) {
+ return;
+ }
+
+ hasPrewarmedSessionRef.current = true;
+
+ void ensureSigningSession().catch(() => {
+ hasPrewarmedSessionRef.current = false;
+ });
+ }, [
+ isSigningAgreement,
+ agreementId,
+ linkId,
+ isChecked,
+ hasRequiredSigningIdentity,
+ hasCurrentSigningSession,
+ ensureSigningSession,
+ ]);
+
+ const handleOpenSigningSheet = async () => {
+ if (!hasRequiredSigningIdentity) {
+ toast.error(signingIdentityPrompt);
+ return;
+ }
+
+ if (!agreementId || !linkId) {
+ toast.error(
+ "Agreement signing is not configured correctly for this link.",
+ );
+ return;
+ }
+
+ if (isChecked && signedAgreementHref) {
+ openSignedAgreement();
+ return;
+ }
+
+ if (hasCurrentSigningSession) {
+ setIsSheetOpen(true);
+ return;
+ }
+
+ setIsPreparingSession(true);
+
+ try {
+ const preparedSession = await ensureSigningSession();
+
+ if (preparedSession) {
+ setIsSheetOpen(true);
+ }
+ } catch (error) {
+ toast.error(
+ error instanceof Error
+ ? error.message
+ : "Failed to start the agreement signing session.",
+ );
+ } finally {
+ setIsPreparingSession(false);
+ }
+ };
+
+ const handleDocumentCompleted = async ({
+ documentId,
+ recipientId,
+ }: {
+ documentId: number;
+ recipientId: number;
+ }) => {
+ if (!session) {
+ toast.error("Agreement signing session is missing.");
+ return;
+ }
+
+ setIsCompletingSession(true);
+
+ try {
+ const response = await fetch("/api/agreements/signing/complete", {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({
+ agreementResponseId: session.agreementResponseId,
+ documentId,
+ recipientId,
+ }),
+ });
+
+ if (!response.ok) {
+ throw new Error(
+ await getErrorMessageFromResponse(
+ response,
+ "Failed to confirm the signed agreement.",
+ ),
+ );
+ }
+
+ const result = (await response.json()) as CompletedSigningResult;
+
+ setData((prevData) => ({
+ ...prevData,
+ hasConfirmedAgreement: true,
+ agreementResponseId: result.id,
+ agreementStatus: result.signingStatus,
+ }));
+
+ if (linkId && agreementId) {
+ persistSignedAgreementResponse({
+ linkId,
+ agreementId,
+ agreementResponseId: result.id,
+ signingStatus: result.signingStatus,
+ });
+ }
+
+ setIsSheetOpen(false);
+ toast.success("Agreement signed successfully.");
+ } catch (error) {
+ toast.error(
+ error instanceof Error
+ ? error.message
+ : "Failed to confirm the signed agreement.",
+ );
+ } finally {
+ setIsCompletingSession(false);
+ }
+ };
+
+ if (isSigningAgreement) {
+ const isLoading = isPreparingSession || isCompletingSession;
+
+ return (
+ <>
+ <div className="pt-2">
+ <div
+ className="flex items-center gap-3 rounded-md border px-3 py-2 transition-colors"
+ style={{
+ borderColor: isChecked
+ ? theme.controlBorderStrongColor
+ : theme.controlBorderColor,
+ backgroundColor: theme.controlBgColor,
+ }}
+ >
+ <div
+ className="flex h-8 w-8 shrink-0 items-center justify-center rounded-md"
+ style={{
+ backgroundColor: theme.panelBgColor,
+ color: theme.textColor,
+ }}
+ aria-hidden="true"
+ >
+ {isChecked ? (
+ <CheckCircle2 className="h-5 w-5" />
+ ) : (
+ <FileSignatureIcon className="h-5 w-5" />
+ )}
+ </div>
+
+ <p
+ className="min-w-0 flex-1 truncate text-sm font-medium leading-5"
+ style={{ color: theme.textColor }}
+ >
+ {agreementName}
+ </p>
+
+ {isChecked ? (
+ signedAgreementHref ? (
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={openSignedAgreement}
+ loading={isDownloadingSigned}
+ className="shrink-0 border bg-transparent hover:opacity-90"
+ style={
+ {
+ backgroundColor: "transparent",
+ borderColor: theme.controlBorderStrongColor,
+ color: theme.textColor,
+ } as CSSProperties
+ }
+ >
+ {!isDownloadingSigned ? (
+ <DownloadIcon className="!h-4 !w-4" />
+ ) : null}
+ {isDownloadingSigned ? "Preparing…" : "Download"}
+ </Button>
+ ) : null
+ ) : (
+ <Button
+ type="button"
+ size="sm"
+ onClick={handleOpenSigningSheet}
+ onMouseEnter={handlePrewarmSigningSession}
+ onFocus={handlePrewarmSigningSession}
+ loading={isLoading}
+ disabled={!hasRequiredSigningIdentity}
+ className="shrink-0 hover:opacity-90"
+ style={{
+ backgroundColor: theme.ctaBgColor,
+ color: theme.ctaTextColor,
+ }}
+ >
+ {!isLoading ? <PenLineIcon className="!h-4 !w-4" /> : null}
+ Open signing
+ </Button>
+ )}
+ </div>
+ </div>
+
+ <Sheet open={isSheetOpen} onOpenChange={setIsSheetOpen}>
+ {/* Width capped at max-w-3xl on purpose: without the white-label flag we can't hide Documenso's sidebar via CSS, so staying below its 768px breakpoint makes the embed render sidebar-less. Don't widen or the sidebar reappears. */}
+ <SheetContent className="w-[96vw] bg-background px-0 sm:max-w-3xl">
+ <SheetHeader className="px-6 pt-6 text-start">
+ <SheetTitle>Sign {agreementName}</SheetTitle>
+ <SheetDescription>
+ Complete the embedded signing flow to continue into the
+ protected Papermark link.
+ </SheetDescription>
+ </SheetHeader>
+
+ <div className="h-[calc(100%-96px)] px-4 pb-4 pt-2 sm:px-6">
+ {session ? (
+ <div className="h-full overflow-hidden rounded-lg border">
+ <EmbedDirectTemplate
+ className="h-full w-full"
+ host={session.host}
+ token={session.token}
+ externalId={session.externalId}
+ darkModeDisabled
+ cssVars={signingEmbedCssVars}
+ css={SIGNING_EMBED_CSS}
+ email={data.email ?? undefined}
+ lockEmail={!!data.email}
+ name={data.name ?? undefined}
+ lockName={!!data.name}
+ onDocumentCompleted={handleDocumentCompleted}
+ onDocumentError={(error) => toast.error(error)}
+ />
+ </div>
+ ) : (
+ <div className="flex h-full items-center justify-center text-sm text-muted-foreground">
+ Preparing signing flow...
+ </div>
+ )}
+ </div>
+ </SheetContent>
+ </Sheet>
+ </>
+ );
+ }
return (
<div className="relative flex items-start space-x-2 pt-5">
@@ -73,7 +798,7 @@ export default function AgreementSection({
target="_blank"
rel="noreferrer noopener"
className="underline hover:text-gray-200"
- onClick={(e) => e.stopPropagation()}
+ onClick={(event) => event.stopPropagation()}
style={{ color: theme.textColor }}
>
{agreementName}
diff --git a/components/view/access-form/email-section.tsx b/components/view/access-form/email-section.tsx
index aa284e0b..a03f964c 100644
--- a/components/view/access-form/email-section.tsx
+++ b/components/view/access-form/email-section.tsx
@@ -1,10 +1,10 @@
import {
+ type CSSProperties,
Dispatch,
SetStateAction,
useEffect,
useRef,
useState,
- type CSSProperties,
} from "react";
import { Brand, DataroomBrand } from "@prisma/client";
@@ -37,15 +37,19 @@ export default function EmailSection({
const [isDirty, setIsDirty] = useState(false);
useEffect(() => {
+ if (disableEditEmail) {
+ return;
+ }
+
// Load email from localStorage when the component mounts
const storedEmail = window.localStorage.getItem("papermark.email");
if (storedEmail) {
setData((prevData) => ({
...prevData,
- email: storedEmail.toLowerCase(),
+ email: prevData.email ?? storedEmail.toLowerCase(),
}));
}
- }, [setData]);
+ }, [disableEditEmail, setData]);
const handleInvalid = (e: React.InvalidEvent<HTMLInputElement>) => {
e.preventDefault(); // Prevent default browser validation popup
@@ -120,15 +124,15 @@ export default function EmailSection({
"notranslate flex w-full cursor-text rounded-md border-0 bg-black py-1.5 text-gray-500 shadow-sm ring-1 ring-inset ring-gray-600 placeholder:text-[var(--access-placeholder)] focus:ring-2 focus:ring-inset focus:ring-[var(--access-input-focus)] sm:text-sm sm:leading-6",
emailError && isDirty && "ring-red-500",
)}
- style={{
- backgroundColor: theme.controlBgColor,
- borderColor: theme.controlBorderColor,
- "--access-placeholder": theme.controlPlaceholderColor,
- "--access-input-focus": theme.controlBorderStrongColor,
- color: disableEditEmail
- ? theme.subtleTextColor
- : theme.textColor,
- } as CSSProperties}
+ style={
+ {
+ backgroundColor: theme.controlBgColor,
+ borderColor: theme.controlBorderColor,
+ "--access-placeholder": theme.controlPlaceholderColor,
+ "--access-input-focus": theme.controlBorderStrongColor,
+ color: disableEditEmail ? theme.subtleTextColor : theme.textColor,
+ } as CSSProperties
+ }
value={email || ""}
placeholder="Enter email"
onChange={handleEmailChange}
diff --git a/components/view/access-form/index.tsx b/components/view/access-form/index.tsx
index 7adb13c7..6a7cbe1b 100644
--- a/components/view/access-form/index.tsx
+++ b/components/view/access-form/index.tsx
@@ -1,15 +1,15 @@
-import { useEffect, useState } from "react";
+import { useEffect, useMemo, useState } from "react";
import { Brand, CustomField, DataroomBrand } from "@prisma/client";
import { ArrowUpRightIcon } from "lucide-react";
import { Button } from "@/components/ui/button";
-import AgreementSection from "./agreement-section";
import {
AccessFormThemeProvider,
createAccessFormTheme,
} from "./access-form-theme";
+import AgreementSection from "./agreement-section";
import CustomFieldsSection from "./custom-fields-section";
import EmailSection from "./email-section";
import NameSection from "./name-section";
@@ -18,12 +18,15 @@ import PasswordSection from "./password-section";
export const DEFAULT_ACCESS_FORM_DATA = {
email: null,
password: null,
+ agreementResponseId: null,
};
export type DEFAULT_ACCESS_FORM_TYPE = {
email: string | null;
password: string | null;
hasConfirmedAgreement?: boolean;
+ agreementResponseId?: string | null;
+ agreementStatus?: string | null;
name?: string | null;
customFields?: { [key: string]: string };
};
@@ -37,9 +40,11 @@ export default function AccessForm({
requireEmail,
requirePassword,
requireAgreement,
+ agreementId,
agreementName,
agreementContent,
agreementContentType,
+ signingProvider,
requireName,
isLoading,
linkId,
@@ -57,9 +62,11 @@ export default function AccessForm({
requireEmail: boolean;
requirePassword: boolean;
requireAgreement?: boolean;
+ agreementId?: string;
agreementName?: string;
agreementContent?: string;
agreementContentType?: string;
+ signingProvider?: string;
requireName?: boolean;
isLoading: boolean;
linkId?: string;
@@ -70,7 +77,19 @@ export default function AccessForm({
linkWelcomeMessage?: string | null;
}) {
const [isEmailValid, setIsEmailValid] = useState(true);
- const accessFormTheme = createAccessFormTheme(brand?.accentColor);
+ // Memoize the palette: expensive to compute and a new identity re-renders every theme consumer.
+ const accessFormTheme = useMemo(
+ () => createAccessFormTheme(brand?.accentColor),
+ [brand?.accentColor],
+ );
+
+ const isSigningAgreement =
+ signingProvider === "DOCUMENSO" || agreementContentType === "SIGNING";
+ const isAgreementLocked = Boolean(
+ requireAgreement && isSigningAgreement && data.hasConfirmedAgreement,
+ );
+ const lockEmailField = Boolean(disableEditEmail) || isAgreementLocked;
+ const lockNameField = isAgreementLocked;
useEffect(() => {
const userEmail = email;
@@ -126,123 +145,135 @@ export default function AccessForm({
color: accessFormTheme.textColor,
}}
>
- {/* Light Navbar */}
- {logoOnAccessForm && brand && brand.logo && (
- <nav
- className="w-full"
- style={{
- backgroundColor: brand.brandColor ? brand.brandColor : "black",
- }}
- >
- <div className="flex h-16 items-center justify-start px-2 sm:px-6 lg:px-8">
- <img
- src={brand.logo as string}
- alt="Brand Logo"
- className="h-16 w-auto object-contain"
- />
- </div>
- </nav>
- )}
-
- <div className="flex flex-1 flex-col px-6 pb-12 pt-8 lg:px-8">
- <div className="sm:mx-auto sm:w-full sm:max-w-md">
- <h1
- className="mt-10 text-2xl font-bold leading-9 tracking-tight text-white"
- style={{ color: accessFormTheme.textColor }}
+ {/* Light Navbar */}
+ {logoOnAccessForm && brand && brand.logo && (
+ <nav
+ className="w-full"
+ style={{
+ backgroundColor: brand.brandColor ? brand.brandColor : "black",
+ }}
>
- {linkWelcomeMessage ||
- (brand && "welcomeMessage" in brand && brand.welcomeMessage) ||
- "Your action is requested to continue"}
- </h1>
- </div>
-
- <div className="mt-10 sm:mx-auto sm:w-full sm:max-w-md">
- <form className="space-y-4" onSubmit={onSubmitHandler} translate="no">
- {requireAgreement && agreementContent && requireName ? (
- <NameSection {...{ data, setData, brand }} />
- ) : null}
- {requireEmail ? (
- <EmailSection
- {...{ data, setData, brand }}
- disableEditEmail={disableEditEmail}
- useCustomAccessForm={useCustomAccessForm}
- onValidationChange={setIsEmailValid}
- />
- ) : null}
- {requirePassword ? (
- <PasswordSection {...{ data, setData, brand }} />
- ) : null}
- {customFields?.length ? (
- <CustomFieldsSection
- fields={customFields}
- data={data.customFields || {}}
- setData={updateCustomFields}
- brand={brand}
- />
- ) : null}
- {requireAgreement && agreementContent && agreementName ? (
- <AgreementSection
- {...{ data, setData, brand }}
- agreementContent={agreementContent}
- agreementName={agreementName}
- agreementContentType={agreementContentType}
- useCustomAccessForm={useCustomAccessForm}
+ <div className="flex h-16 items-center justify-start px-2 sm:px-6 lg:px-8">
+ <img
+ src={brand.logo as string}
+ alt="Brand Logo"
+ className="h-16 w-auto object-contain"
/>
- ) : null}
-
- <div className="flex justify-center pt-5">
- <Button
- type="submit"
- disabled={!isFormValid()}
- className="w-1/3 min-w-fit bg-white text-gray-950 hover:bg-white/90"
- loading={isLoading}
- style={{
- backgroundColor: accessFormTheme.ctaBgColor,
- color: accessFormTheme.ctaTextColor,
- }}
- >
- Continue
- </Button>
</div>
- </form>
- </div>
- </div>
- {!useCustomAccessForm ? (
- <div className="flex flex-col items-center gap-0.5">
- <p
- className="text-center text-sm tracking-tight"
- style={{ color: accessFormTheme.subtleTextColor }}
- >
- This document is securely shared with you using{" "}
- <a
- href="https://www.papermark.com"
- target="_blank"
- rel="noopener noreferrer"
- className="font-medium"
- style={{ color: accessFormTheme.mutedTextColor }}
+ </nav>
+ )}
+
+ <div className="flex flex-1 flex-col px-6 pb-12 pt-8 lg:px-8">
+ <div className="sm:mx-auto sm:w-full sm:max-w-md">
+ <h1
+ className="mt-10 text-2xl font-bold leading-9 tracking-tight text-white"
+ style={{ color: accessFormTheme.textColor }}
>
- Papermark
- </a>
- .
- </p>
- <p
- className="text-center text-sm tracking-tight"
- style={{ color: accessFormTheme.subtleTextColor }}
- >
- See how we protect your data in our{" "}
- <a
- href="https://www.papermark.com/privacy"
- target="_blank"
- rel="noopener noreferrer"
- className="inline-flex items-center gap-0.5"
- style={{ color: accessFormTheme.mutedTextColor }}
+ {linkWelcomeMessage ||
+ (brand && "welcomeMessage" in brand && brand.welcomeMessage) ||
+ "Your action is requested to continue"}
+ </h1>
+ </div>
+
+ <div className="mt-10 sm:mx-auto sm:w-full sm:max-w-md">
+ <form
+ className="space-y-4"
+ onSubmit={onSubmitHandler}
+ translate="no"
>
- <span>Privacy Policy</span>
- <ArrowUpRightIcon className="h-3 w-3" />
- </a>
- </p>
+ {requireAgreement && agreementContent && requireName ? (
+ <NameSection
+ {...{ data, setData, brand }}
+ disableEditName={lockNameField}
+ />
+ ) : null}
+ {requireEmail ? (
+ <EmailSection
+ {...{ data, setData, brand }}
+ disableEditEmail={lockEmailField}
+ useCustomAccessForm={useCustomAccessForm}
+ onValidationChange={setIsEmailValid}
+ />
+ ) : null}
+ {requirePassword ? (
+ <PasswordSection {...{ data, setData, brand }} />
+ ) : null}
+ {customFields?.length ? (
+ <CustomFieldsSection
+ fields={customFields}
+ data={data.customFields || {}}
+ setData={updateCustomFields}
+ brand={brand}
+ />
+ ) : null}
+ {requireAgreement && agreementContent && agreementName ? (
+ <AgreementSection
+ {...{ data, setData, brand }}
+ agreementId={agreementId}
+ agreementContent={agreementContent}
+ agreementName={agreementName}
+ agreementContentType={agreementContentType}
+ signingProvider={signingProvider}
+ linkId={linkId}
+ requireEmail={requireEmail}
+ requireName={requireName}
+ useCustomAccessForm={useCustomAccessForm}
+ />
+ ) : null}
+
+ <div className="flex justify-center pt-5">
+ <Button
+ type="submit"
+ disabled={!isFormValid()}
+ className="w-1/3 min-w-fit bg-white text-gray-950 hover:bg-white/90"
+ loading={isLoading}
+ style={{
+ backgroundColor: accessFormTheme.ctaBgColor,
+ color: accessFormTheme.ctaTextColor,
+ }}
+ >
+ Continue
+ </Button>
+ </div>
+ </form>
+ </div>
</div>
- ) : null}
+ {!useCustomAccessForm ? (
+ <div className="flex flex-col items-center gap-0.5">
+ <p
+ className="text-center text-sm tracking-tight"
+ style={{ color: accessFormTheme.subtleTextColor }}
+ >
+ This document is securely shared with you using{" "}
+ <a
+ href="https://www.papermark.com"
+ target="_blank"
+ rel="noopener noreferrer"
+ className="font-medium"
+ style={{ color: accessFormTheme.mutedTextColor }}
+ >
+ Papermark
+ </a>
+ .
+ </p>
+ <p
+ className="text-center text-sm tracking-tight"
+ style={{ color: accessFormTheme.subtleTextColor }}
+ >
+ See how we protect your data in our{" "}
+ <a
+ href={`${process.env.NEXT_PUBLIC_MARKETING_URL}/privacy`}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="inline-flex items-center gap-0.5"
+ style={{ color: accessFormTheme.mutedTextColor }}
+ >
+ <span>Privacy Policy</span>
+ <ArrowUpRightIcon className="h-3 w-3" />
+ </a>
+ </p>
+ </div>
+ ) : null}
</div>
</AccessFormThemeProvider>
);
diff --git a/components/view/access-form/name-section.tsx b/components/view/access-form/name-section.tsx
index 07351aeb..0f84688b 100644
--- a/components/view/access-form/name-section.tsx
+++ b/components/view/access-form/name-section.tsx
@@ -10,16 +10,20 @@ export default function NameSection({
data,
setData,
brand,
+ disableEditName,
}: {
data: DEFAULT_ACCESS_FORM_TYPE;
setData: Dispatch<SetStateAction<DEFAULT_ACCESS_FORM_TYPE>>;
brand?: Partial<Brand> | Partial<DataroomBrand> | null;
+ disableEditName?: boolean;
}) {
const { name } = data;
const theme = useAccessFormTheme();
useEffect(() => {
- // Load name from localStorage when the component mounts
+ if (disableEditName) {
+ return;
+ }
const storedName = window.localStorage.getItem("papermark.name");
if (storedName) {
setData((prevData) => ({
@@ -27,13 +31,11 @@ export default function NameSection({
name: storedName,
}));
}
- }, [setData]);
+ }, [setData, disableEditName]);
const handleNameChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const newName = e.target.value;
- // Store the new email in localStorage
window.localStorage.setItem("papermark.name", newName);
- // Update the state
setData({ ...data, name: newName });
};
@@ -54,17 +56,18 @@ export default function NameSection({
autoComplete="off"
autoFocus
translate="no"
- className="notranslate flex w-full cursor-text rounded-md border-0 bg-black py-1.5 text-white shadow-sm ring-1 ring-inset ring-gray-600 placeholder:text-[var(--access-placeholder)] focus:ring-2 focus:ring-inset focus:ring-[var(--access-input-focus)] sm:text-sm sm:leading-6"
+ className="notranslate flex w-full cursor-text rounded-md border-0 bg-black py-1.5 text-white shadow-sm ring-1 ring-inset ring-gray-600 placeholder:text-[var(--access-placeholder)] focus:ring-2 focus:ring-inset focus:ring-[var(--access-input-focus)] disabled:cursor-not-allowed disabled:opacity-90 sm:text-sm sm:leading-6"
style={{
backgroundColor: theme.controlBgColor,
borderColor: theme.controlBorderColor,
"--access-placeholder": theme.controlPlaceholderColor,
"--access-input-focus": theme.controlBorderStrongColor,
- color: theme.textColor,
+ color: disableEditName ? theme.subtleTextColor : theme.textColor,
} as CSSProperties}
value={name || ""}
placeholder="Enter your full name"
onChange={handleNameChange}
+ disabled={disableEditName}
aria-invalid="true"
data-1p-ignore
/>
diff --git a/components/view/dataroom/dataroom-document-view.tsx b/components/view/dataroom/dataroom-document-view.tsx
index d7298284..48c3c5bc 100644
--- a/components/view/dataroom/dataroom-document-view.tsx
+++ b/components/view/dataroom/dataroom-document-view.tsx
@@ -385,11 +385,14 @@ export default function DataroomDocumentView({
requireEmail={emailProtected}
requirePassword={!!linkPassword}
requireAgreement={enableAgreement!}
+ agreementId={link.agreement?.id}
agreementName={link.agreement?.name}
agreementContent={link.agreement?.content}
agreementContentType={link.agreement?.contentType}
+ signingProvider={link.agreement?.signingProvider}
requireName={link.agreement?.requireName}
isLoading={isLoading}
+ linkId={link.id}
disableEditEmail={disableEditEmail}
useCustomAccessForm={useCustomAccessForm}
brand={brand}
diff --git a/components/view/dataroom/dataroom-view.tsx b/components/view/dataroom/dataroom-view.tsx
index 03b1b030..b69af236 100644
--- a/components/view/dataroom/dataroom-view.tsx
+++ b/components/view/dataroom/dataroom-view.tsx
@@ -2,11 +2,11 @@ import { useRouter } from "next/router";
import React, { useEffect, useRef, useState } from "react";
+import { PendingUploadsProvider } from "@/context/pending-uploads-context";
import { DataroomBrand } from "@prisma/client";
import Cookies from "js-cookie";
import { toast } from "sonner";
-import { PendingUploadsProvider } from "@/context/pending-uploads-context";
import { useAnalytics } from "@/lib/analytics";
import { SUPPORTED_DOCUMENT_SIMPLE_TYPES } from "@/lib/constants";
import { useDisablePrint } from "@/lib/hooks/use-disable-print";
@@ -279,11 +279,14 @@ export default function DataroomView({
requireEmail={emailProtected}
requirePassword={!!linkPassword}
requireAgreement={enableAgreement!}
+ agreementId={link.agreement?.id}
agreementName={link.agreement?.name}
agreementContent={link.agreement?.content}
agreementContentType={link.agreement?.contentType}
+ signingProvider={link.agreement?.signingProvider}
requireName={link.agreement?.requireName}
isLoading={isLoading}
+ linkId={link.id}
disableEditEmail={disableEditEmail}
useCustomAccessForm={useCustomAccessForm}
brand={brand}
diff --git a/components/view/document-view.tsx b/components/view/document-view.tsx
index 58ccd323..930b4883 100644
--- a/components/view/document-view.tsx
+++ b/components/view/document-view.tsx
@@ -285,12 +285,15 @@ export default function DocumentView({
requireEmail={emailProtected}
requirePassword={!!linkPassword}
requireAgreement={enableAgreement!}
+ agreementId={link.agreement?.id}
agreementName={link.agreement?.name}
agreementContent={link.agreement?.content}
agreementContentType={link.agreement?.contentType}
+ signingProvider={link.agreement?.signingProvider}
requireName={link.agreement?.requireName}
isLoading={isLoading}
brand={brand}
+ linkId={link.id}
disableEditEmail={disableEditEmail}
useCustomAccessForm={useCustomAccessForm}
customFields={link.customFields}
diff --git a/components/visitors/dataroom-visitors-table.tsx b/components/visitors/dataroom-visitors-table.tsx
index ef92be68..2570be7e 100644
--- a/components/visitors/dataroom-visitors-table.tsx
+++ b/components/visitors/dataroom-visitors-table.tsx
@@ -9,10 +9,17 @@ import {
BadgeInfoIcon,
Download,
DownloadCloudIcon,
+ DownloadIcon,
FileBadgeIcon,
+ FileSignatureIcon,
MailOpenIcon,
} from "lucide-react";
+import { toast } from "sonner";
+import {
+ buildTeamSignedAgreementDownloadUrl,
+ downloadSignedAgreement,
+} from "@/lib/signing/download";
import { usePlan } from "@/lib/swr/use-billing";
import { useDataroom } from "@/lib/swr/use-dataroom";
import { useDataroomVisits } from "@/lib/swr/use-dataroom";
@@ -43,6 +50,32 @@ import DataroomVisitorCustomFields from "./dataroom-visitor-custom-fields";
import { DataroomVisitorUserAgent } from "./dataroom-visitor-useragent";
import { VisitorAvatar } from "./visitor-avatar";
+type AgreementResponseSummary = {
+ id: string;
+ agreementId: string;
+ signingStatus: string;
+ agreement: {
+ name: string;
+ contentType: string;
+ signingProvider: string;
+ };
+};
+
+const isSignedAgreementResponse = (
+ response: AgreementResponseSummary | null | undefined,
+) => {
+ if (!response) return false;
+ const isSigningAgreement =
+ response.agreement.signingProvider === "DOCUMENSO" ||
+ response.agreement.contentType === "SIGNING";
+
+ return (
+ isSigningAgreement &&
+ (response.signingStatus === "SIGNED" ||
+ response.signingStatus === "COMPLETED")
+ );
+};
+
export default function DataroomVisitorsTable({
dataroomId,
groupId,
@@ -69,6 +102,44 @@ export default function DataroomVisitorsTable({
setExportModalOpen(true);
};
+ const handleDownloadSignedAgreement = async ({
+ agreementId,
+ responseId,
+ agreementName,
+ }: {
+ agreementId: string;
+ responseId: string;
+ agreementName: string;
+ }) => {
+ if (!teamId) return;
+
+ const url = buildTeamSignedAgreementDownloadUrl({
+ teamId,
+ agreementId,
+ responseId,
+ });
+
+ const safeName = agreementName
+ .replace(/[^a-z0-9\-_]/gi, "_")
+ .toLowerCase()
+ .substring(0, 50);
+
+ await toast.promise(
+ downloadSignedAgreement({
+ url,
+ fallbackFilename: `${safeName || "agreement"}_signed.pdf`,
+ }),
+ {
+ loading: "Preparing signed NDA...",
+ success: "Signed NDA downloaded",
+ error: (error: unknown) =>
+ error instanceof Error
+ ? error.message
+ : "Failed to download the signed NDA.",
+ },
+ );
+ };
+
const handleOpenChange = (viewId: string, open: boolean) => {
setExpandedViewIds((prev) => {
const next = new Set(prev);
@@ -186,10 +257,22 @@ export default function DataroomVisitorsTable({
)}
{view.agreementResponse && (
<BadgeTooltip
- content={`Agreed to ${view.agreementResponse.agreement.name}`}
+ content={
+ isSignedAgreementResponse(
+ view.agreementResponse,
+ )
+ ? `Signed ${view.agreementResponse.agreement.name}`
+ : `Agreed to ${view.agreementResponse.agreement.name}`
+ }
key={`agreement-${view.id}`}
>
- <FileBadgeIcon className="h-4 w-4 text-emerald-500 hover:text-emerald-600" />
+ {isSignedAgreementResponse(
+ view.agreementResponse,
+ ) ? (
+ <FileSignatureIcon className="h-4 w-4 text-emerald-500 hover:text-emerald-600" />
+ ) : (
+ <FileBadgeIcon className="h-4 w-4 text-emerald-500 hover:text-emerald-600" />
+ )}
</BadgeTooltip>
)}
</>
@@ -307,6 +390,76 @@ export default function DataroomVisitorsTable({
</TableRow>
) : null}
+ {isSignedAgreementResponse(view.agreementResponse) ? (
+ <TableRow
+ key={`signed-nda-${view.id}`}
+ className="[&>td]:py-3"
+ >
+ <TableCell>
+ <div className="flex items-center gap-x-4 overflow-visible">
+ <FileSignatureIcon className="h-5 w-5 text-emerald-500" />
+ <span>
+ Signed {view.agreementResponse.agreement.name}
+ </span>
+ <Button
+ variant="ghost"
+ size="icon"
+ className="h-6 w-6"
+ onClick={() =>
+ handleDownloadSignedAgreement({
+ agreementId:
+ view.agreementResponse.agreementId,
+ responseId: view.agreementResponse.id,
+ agreementName:
+ view.agreementResponse.agreement.name,
+ })
+ }
+ >
+ <DownloadIcon className="h-4 w-4" />
+ <span className="sr-only">
+ Download signed NDA
+ </span>
+ </Button>
+ </div>
+ </TableCell>
+ <TableCell />
+ <TableCell />
+ <TableCell>
+ {view.agreementResponse.signedAt ||
+ view.agreementResponse.completedAt ? (
+ <TimestampTooltip
+ timestamp={new Date(
+ view.agreementResponse.signedAt ||
+ view.agreementResponse.completedAt,
+ )}
+ side="right"
+ rows={["local", "utc", "unix"]}
+ >
+ <time
+ className="select-none truncate text-sm text-muted-foreground"
+ dateTime={new Date(
+ view.agreementResponse.signedAt ||
+ view.agreementResponse.completedAt,
+ ).toISOString()}
+ >
+ {timeAgo(
+ new Date(
+ view.agreementResponse.signedAt ||
+ view.agreementResponse.completedAt,
+ ),
+ )}
+ </time>
+ </TimestampTooltip>
+ ) : (
+ <span className="text-sm text-muted-foreground">
+ Signed
+ </span>
+ )}
+ </TableCell>
+ <TableCell />
+ </TableRow>
+ ) : null}
+
<DataroomViewStats
viewId={view.id}
dataroomId={dataroomId}
diff --git a/components/visitors/visitors-table.tsx b/components/visitors/visitors-table.tsx
index d692b506..5a4808c3 100644
--- a/components/visitors/visitors-table.tsx
+++ b/components/visitors/visitors-table.tsx
@@ -12,8 +12,10 @@ import {
BadgeCheckIcon,
BadgeInfoIcon,
DownloadCloudIcon,
+ DownloadIcon,
FileBadgeIcon,
FileDigitIcon,
+ FileSignatureIcon,
MoreHorizontalIcon,
ServerIcon,
ThumbsDownIcon,
@@ -24,6 +26,10 @@ import { mutate } from "swr";
import { usePlan } from "@/lib/swr/use-billing";
import { useDocumentVisits } from "@/lib/swr/use-document";
+import {
+ buildTeamSignedAgreementDownloadUrl,
+ downloadSignedAgreement,
+} from "@/lib/signing/download";
import { durationFormat, timeAgo } from "@/lib/utils";
import ChevronDown from "@/components/shared/icons/chevron-down";
@@ -66,6 +72,32 @@ import VisitorUserAgent from "./visitor-useragent";
import VisitorUserAgentPlaceholder from "./visitor-useragent-placeholder";
import VisitorVideoChart from "./visitor-video-chart";
+type AgreementResponseSummary = {
+ id: string;
+ agreementId: string;
+ signingStatus: string;
+ agreement: {
+ name: string;
+ contentType: string;
+ signingProvider: string;
+ };
+};
+
+const isSignedAgreementResponse = (
+ response: AgreementResponseSummary | null | undefined,
+) => {
+ if (!response) return false;
+ const isSigningAgreement =
+ response.agreement.signingProvider === "DOCUMENSO" ||
+ response.agreement.contentType === "SIGNING";
+
+ return (
+ isSigningAgreement &&
+ (response.signingStatus === "SIGNED" ||
+ response.signingStatus === "COMPLETED")
+ );
+};
+
export default function VisitorsTable({
primaryVersion,
isVideo = false,
@@ -93,6 +125,44 @@ export default function VisitorsTable({
setCurrentPage(1);
};
+ const handleDownloadSignedAgreement = async ({
+ teamId,
+ agreementId,
+ responseId,
+ agreementName,
+ }: {
+ teamId: string;
+ agreementId: string;
+ responseId: string;
+ agreementName: string;
+ }) => {
+ const url = buildTeamSignedAgreementDownloadUrl({
+ teamId,
+ agreementId,
+ responseId,
+ });
+
+ const safeName = agreementName
+ .replace(/[^a-z0-9\-_]/gi, "_")
+ .toLowerCase()
+ .substring(0, 50);
+
+ await toast.promise(
+ downloadSignedAgreement({
+ url,
+ fallbackFilename: `${safeName || "agreement"}_signed.pdf`,
+ }),
+ {
+ loading: "Preparing signed NDA...",
+ success: "Signed NDA downloaded",
+ error: (error: unknown) =>
+ error instanceof Error
+ ? error.message
+ : "Failed to download the signed NDA.",
+ },
+ );
+ };
+
const handleArchiveView = async (
viewId: string,
targetId: string,
@@ -364,10 +434,22 @@ export default function VisitorsTable({
)}
{view.agreementResponse && (
<BadgeTooltip
- content={`Agreed to ${view.agreementResponse.agreement.name}`}
+ content={
+ isSignedAgreementResponse(
+ view.agreementResponse,
+ )
+ ? `Signed ${view.agreementResponse.agreement.name}`
+ : `Agreed to ${view.agreementResponse.agreement.name}`
+ }
key={`agreement-${view.id}`}
>
- <FileBadgeIcon className="h-4 w-4 text-emerald-500 hover:text-emerald-600" />
+ {isSignedAgreementResponse(
+ view.agreementResponse,
+ ) ? (
+ <FileSignatureIcon className="h-4 w-4 text-emerald-500 hover:text-emerald-600" />
+ ) : (
+ <FileBadgeIcon className="h-4 w-4 text-emerald-500 hover:text-emerald-600" />
+ )}
</BadgeTooltip>
)}
{view.downloadedAt && (
@@ -519,6 +601,77 @@ export default function VisitorsTable({
</div>
</div>
+ {isSignedAgreementResponse(
+ view.agreementResponse,
+ ) && teamId ? (
+ <div className="pb-0.5 pl-0.5 md:pb-1 md:pl-1">
+ <div className="flex items-center justify-between gap-2 px-1">
+ <div className="flex min-w-0 items-center gap-x-1.5">
+ <FileSignatureIcon className="size-4 shrink-0 text-emerald-500" />
+ <span className="truncate">
+ Signed{" "}
+ {
+ view.agreementResponse!.agreement
+ .name
+ }
+ </span>
+ {view.agreementResponse!.signedAt ||
+ view.agreementResponse!.completedAt ? (
+ <TimestampTooltip
+ timestamp={new Date(
+ view.agreementResponse!.signedAt ||
+ view.agreementResponse!
+ .completedAt!,
+ )}
+ side="right"
+ rows={["local", "utc", "unix"]}
+ >
+ <time
+ className="select-none text-xs text-muted-foreground"
+ dateTime={new Date(
+ view.agreementResponse!
+ .signedAt ||
+ view.agreementResponse!
+ .completedAt!,
+ ).toISOString()}
+ >
+ {timeAgo(
+ new Date(
+ view.agreementResponse!
+ .signedAt ||
+ view.agreementResponse!
+ .completedAt!,
+ ),
+ )}
+ </time>
+ </TimestampTooltip>
+ ) : null}
+ </div>
+ <Button
+ variant="outline"
+ size="sm"
+ className="h-7 gap-1 px-2 text-xs"
+ onClick={() =>
+ handleDownloadSignedAgreement({
+ teamId,
+ agreementId:
+ view.agreementResponse!
+ .agreementId,
+ responseId:
+ view.agreementResponse!.id,
+ agreementName:
+ view.agreementResponse!.agreement
+ .name,
+ })
+ }
+ >
+ <DownloadIcon className="size-3.5" />
+ <span>Download signed NDA</span>
+ </Button>
+ </div>
+ </div>
+ ) : null}
+
{isVideo ? (
<VisitorVideoChart
documentId={view.documentId!}
diff --git a/lib/api/links/link-data.ts b/lib/api/links/link-data.ts
index 2febf058..37a487e1 100644
--- a/lib/api/links/link-data.ts
+++ b/lib/api/links/link-data.ts
@@ -1,3 +1,5 @@
+import { resolvePublicLinkMeta } from "@/ee/features/branding/lib/resolve-public-link-meta";
+import type { ResolvedPublicLinkMeta } from "@/ee/features/branding/lib/resolve-public-link-meta";
import {
Brand,
DataroomBrand,
@@ -10,10 +12,8 @@ import {
} from "@prisma/client";
import { getFeatureFlags } from "@/lib/featureFlags";
-import prisma from "@/lib/prisma";
import { resolveDataroomIndexEnabledForViewer } from "@/lib/featureFlags/dataroom-index-viewer";
-import { resolvePublicLinkMeta } from "@/ee/features/branding/lib/resolve-public-link-meta";
-import type { ResolvedPublicLinkMeta } from "@/ee/features/branding/lib/resolve-public-link-meta";
+import prisma from "@/lib/prisma";
import { sortItemsByIndexAndName } from "@/lib/utils/sort-items-by-index-name";
// ============================================================================
@@ -781,7 +781,6 @@ async function processLinkData(
}
}
- // Only include agreement if enabled (no need to expose it otherwise)
const sanitizedAgreement =
link.enableAgreement && link.agreement
? {
@@ -789,6 +788,7 @@ async function processLinkData(
name: link.agreement.name,
content: link.agreement.content,
contentType: link.agreement.contentType,
+ signingProvider: link.agreement.signingProvider,
requireName: link.agreement.requireName,
}
: null;
@@ -907,11 +907,10 @@ async function processLinkData(
let dataroomIndexEnabledForViewer: boolean | undefined;
if (linkType === "DATAROOM_LINK" && link.teamId) {
- dataroomIndexEnabledForViewer =
- await resolveDataroomIndexEnabledForViewer({
- teamId: link.teamId,
- teamPlan,
- });
+ dataroomIndexEnabledForViewer = await resolveDataroomIndexEnabledForViewer({
+ teamId: link.teamId,
+ teamPlan,
+ });
}
// Serialize to convert Date objects to strings (required for Next.js getStaticProps)
diff --git a/lib/errorHandler.ts b/lib/errorHandler.ts
index 443f8993..46129af5 100644
--- a/lib/errorHandler.ts
+++ b/lib/errorHandler.ts
@@ -1,12 +1,27 @@
import { NextApiResponse } from "next";
+function sanitizeError(err: unknown) {
+ if (!(err instanceof Error)) {
+ return { name: typeof err, message: String(err) };
+ }
+
+ const anyErr = err as Error & { code?: unknown; requestId?: unknown };
+ return {
+ name: err.name,
+ message: err.message,
+ code: anyErr.code,
+ requestId: anyErr.requestId ?? null,
+ stack: err.stack ? err.stack.split("\n")[0] : undefined,
+ };
+}
+
export function errorhandler(err: unknown, res: NextApiResponse) {
if (err instanceof TeamError || err instanceof DocumentError) {
return res.status(err.statusCode).end(err.message);
} else {
+ console.error("[errorhandler] unhandled error", sanitizeError(err));
return res.status(500).json({
message: "Internal Server Error",
- error: (err as Error).message,
});
}
}
diff --git a/lib/signing/access-token.ts b/lib/signing/access-token.ts
new file mode 100644
index 00000000..abaec28f
--- /dev/null
+++ b/lib/signing/access-token.ts
@@ -0,0 +1,183 @@
+import crypto from "crypto";
+
+import { TeamError } from "@/lib/errorHandler";
+
+// Long-lived HMAC cookie binding the browser to (linkId, agreementId, agreementResponseId) so signed state survives refresh without email lookups (which would enable enumeration).
+
+const TOKEN_TTL_MS = 90 * 24 * 60 * 60 * 1000; // 90 days
+
+export const SIGNED_ACCESS_COOKIE_PREFIX = "pm_sas_";
+// Path-scope to "/" so the cookie reaches the views/status/download routes; the HMAC binding plus HttpOnly + SameSite=Lax + Secure carry the security.
+export const SIGNED_ACCESS_COOKIE_PATH = "/";
+
+interface AccessTokenPayload {
+ agreementResponseId: string;
+ linkId: string;
+ agreementId: string;
+ exp: number;
+}
+
+const getTokenSecret = (): string => {
+ const secret = process.env.NEXTAUTH_SECRET;
+ if (!secret) {
+ throw new TeamError(
+ "Signing access token cannot be issued: NEXTAUTH_SECRET is not set.",
+ );
+ }
+ return secret;
+};
+
+const sign = (payloadB64: string, secret: string): string =>
+ crypto.createHmac("sha256", secret).update(payloadB64).digest("base64url");
+
+export const getSignedAgreementAccessCookieName = (linkId: string): string =>
+ `${SIGNED_ACCESS_COOKIE_PREFIX}${linkId}`;
+
+export const mintSignedAgreementAccessToken = ({
+ agreementResponseId,
+ linkId,
+ agreementId,
+}: {
+ agreementResponseId: string;
+ linkId: string;
+ agreementId: string;
+}): { token: string; expiresAt: number; maxAgeSeconds: number } => {
+ const secret = getTokenSecret();
+ const expiresAt = Date.now() + TOKEN_TTL_MS;
+
+ const payload: AccessTokenPayload = {
+ agreementResponseId,
+ linkId,
+ agreementId,
+ exp: expiresAt,
+ };
+
+ const payloadB64 = Buffer.from(JSON.stringify(payload)).toString("base64url");
+ const signature = sign(payloadB64, secret);
+
+ return {
+ token: `${payloadB64}.${signature}`,
+ expiresAt,
+ maxAgeSeconds: Math.floor(TOKEN_TTL_MS / 1000),
+ };
+};
+
+export const parseSignedAgreementAccessToken = (
+ token: string | undefined | null,
+): AccessTokenPayload | null => {
+ if (!token || typeof token !== "string") {
+ return null;
+ }
+
+ const parts = token.split(".");
+ if (parts.length !== 2) {
+ return null;
+ }
+
+ const [payloadB64, signature] = parts;
+ if (!payloadB64 || !signature) {
+ return null;
+ }
+
+ let secret: string;
+ try {
+ secret = getTokenSecret();
+ } catch {
+ return null;
+ }
+
+ const expectedSignature = sign(payloadB64, secret);
+ const signatureBuffer = Buffer.from(signature);
+ const expectedBuffer = Buffer.from(expectedSignature);
+
+ if (signatureBuffer.length !== expectedBuffer.length) {
+ return null;
+ }
+
+ if (!crypto.timingSafeEqual(signatureBuffer, expectedBuffer)) {
+ return null;
+ }
+
+ let payload: AccessTokenPayload;
+ try {
+ const parsed = JSON.parse(
+ Buffer.from(payloadB64, "base64url").toString("utf8"),
+ ) as AccessTokenPayload | null;
+ if (!parsed || typeof parsed !== "object") {
+ return null;
+ }
+ payload = parsed;
+ } catch {
+ return null;
+ }
+
+ if (
+ typeof payload.agreementResponseId !== "string" ||
+ typeof payload.linkId !== "string" ||
+ typeof payload.agreementId !== "string" ||
+ typeof payload.exp !== "number"
+ ) {
+ return null;
+ }
+
+ if (payload.exp < Date.now()) {
+ return null;
+ }
+
+ return payload;
+};
+
+export const verifySignedAgreementAccessToken = (
+ token: string | undefined | null,
+ expected: {
+ linkId: string;
+ agreementId: string;
+ agreementResponseId?: string;
+ },
+): boolean => {
+ const payload = parseSignedAgreementAccessToken(token);
+ if (!payload) {
+ return false;
+ }
+
+ if (payload.linkId !== expected.linkId) {
+ return false;
+ }
+
+ if (payload.agreementId !== expected.agreementId) {
+ return false;
+ }
+
+ if (
+ expected.agreementResponseId &&
+ payload.agreementResponseId !== expected.agreementResponseId
+ ) {
+ return false;
+ }
+
+ return true;
+};
+
+export const buildSignedAgreementAccessCookie = ({
+ linkId,
+ token,
+ maxAgeSeconds,
+ secure,
+}: {
+ linkId: string;
+ token: string;
+ maxAgeSeconds: number;
+ secure: boolean;
+}): string => {
+ const parts = [
+ `${getSignedAgreementAccessCookieName(linkId)}=${token}`,
+ `Path=${SIGNED_ACCESS_COOKIE_PATH}`,
+ `Max-Age=${maxAgeSeconds}`,
+ "HttpOnly",
+ "SameSite=Lax",
+ ];
+ if (secure) {
+ parts.push("Secure");
+ }
+ return parts.join("; ");
+};
diff --git a/lib/signing/agreement-storage.ts b/lib/signing/agreement-storage.ts
new file mode 100644
index 00000000..0d34e4df
--- /dev/null
+++ b/lib/signing/agreement-storage.ts
@@ -0,0 +1,31 @@
+export type StoredAgreementResponse = {
+ agreementResponseId: string;
+ signingStatus: string;
+};
+
+export const getAgreementResponseStorageKey = (
+ linkId: string,
+ agreementId: string,
+): string => `papermark.agreement.${linkId}.${agreementId}`;
+
+export const parseStoredAgreementResponse = (
+ raw: string | null,
+): StoredAgreementResponse | null => {
+ if (!raw) {
+ return null;
+ }
+
+ try {
+ const parsed = JSON.parse(raw) as StoredAgreementResponse | null;
+ if (
+ !parsed ||
+ typeof parsed.agreementResponseId !== "string" ||
+ typeof parsed.signingStatus !== "string"
+ ) {
+ return null;
+ }
+ return parsed;
+ } catch {
+ return null;
+ }
+};
diff --git a/lib/signing/agreements.ts b/lib/signing/agreements.ts
new file mode 100644
index 00000000..4e957b9c
--- /dev/null
+++ b/lib/signing/agreements.ts
@@ -0,0 +1,1070 @@
+import { Prisma } from "@prisma/client";
+import { waitUntil } from "@vercel/functions";
+import crypto from "crypto";
+import { z } from "zod";
+
+import { TeamError } from "@/lib/errorHandler";
+import prisma from "@/lib/prisma";
+
+import {
+ getSigningClient,
+ getSigningHost,
+ getSigningWebhookSecret,
+} from "./client";
+import { getEnvelope } from "./envelopes";
+
+export const SIGNING_PROVIDER_SCHEMA = z.enum(["LEGACY", "DOCUMENSO"]);
+export const SIGNING_STATUS_SCHEMA = z.enum([
+ "PENDING",
+ "SIGNED",
+ "COMPLETED",
+ "FAILED",
+]);
+
+export type SigningProvider = z.infer<typeof SIGNING_PROVIDER_SCHEMA>;
+export type SigningStatus = z.infer<typeof SIGNING_STATUS_SCHEMA>;
+
+const SIGNING_TEMPLATE_ID_SCHEMA = z.coerce.number().int().positive();
+
+export const buildAgreementSigningExternalId = (
+ teamId: string,
+ agreementId: string,
+) => {
+ return `papermark:team:${teamId}:agreement:${agreementId}`;
+};
+
+export const buildAgreementResponseSigningExternalId = (
+ teamId: string,
+ agreementResponseId: string,
+) => {
+ return `papermark:team:${teamId}:agreement-response:${agreementResponseId}`;
+};
+
+export const isSigningAgreement = ({
+ signingProvider,
+ contentType,
+}: {
+ signingProvider?: string | null;
+ contentType?: string | null;
+}) => {
+ const provider = SIGNING_PROVIDER_SCHEMA.safeParse(signingProvider);
+
+ return (
+ (provider.success && provider.data === "DOCUMENSO") ||
+ contentType === "SIGNING"
+ );
+};
+
+export const getAgreementResponseSignedState = (
+ signingStatus?: string | null,
+) => {
+ const parsedStatus = SIGNING_STATUS_SCHEMA.safeParse(signingStatus);
+
+ if (!parsedStatus.success) {
+ return false;
+ }
+
+ return parsedStatus.data === "SIGNED" || parsedStatus.data === "COMPLETED";
+};
+
+export const normalizeSignerEmail = (email?: string | null) => {
+ if (typeof email !== "string") {
+ return null;
+ }
+
+ const trimmed = email.trim().toLowerCase();
+ return trimmed.length > 0 ? trimmed : null;
+};
+
+export const normalizeSignerName = (name?: string | null) => {
+ if (typeof name !== "string") {
+ return null;
+ }
+
+ const trimmed = name.trim();
+ return trimmed.length > 0 ? trimmed : null;
+};
+
+const assertAgreementResponseSignerIdentity = ({
+ agreementResponse,
+ signerEmail,
+ signerName,
+ requireSignerEmail,
+ requireSignerName,
+}: {
+ agreementResponse: {
+ signerEmail: string | null;
+ signerName: string | null;
+ };
+ signerEmail?: string | null;
+ signerName?: string | null;
+ requireSignerEmail?: boolean;
+ requireSignerName?: boolean;
+}) => {
+ const submittedEmail = normalizeSignerEmail(signerEmail);
+ const storedEmail = normalizeSignerEmail(agreementResponse.signerEmail);
+
+ if (requireSignerEmail && !submittedEmail) {
+ throw new TeamError(
+ "Agreement signing could not be verified for this link.",
+ );
+ }
+
+ if (storedEmail) {
+ if (!submittedEmail || submittedEmail !== storedEmail) {
+ throw new TeamError(
+ "Agreement signing could not be verified for this link.",
+ );
+ }
+ }
+
+ const submittedName = normalizeSignerName(signerName);
+ const storedName = normalizeSignerName(agreementResponse.signerName);
+
+ if (requireSignerName && !submittedName) {
+ throw new TeamError(
+ "Agreement signing could not be verified for this link.",
+ );
+ }
+
+ if (storedName && submittedName && submittedName !== storedName) {
+ throw new TeamError(
+ "Agreement signing could not be verified for this link.",
+ );
+ }
+};
+
+export const verifySigningWebhookSecret = (
+ secret?: string | null,
+): { ok: boolean; configured: boolean } => {
+ const expectedSecret = getSigningWebhookSecret();
+
+ if (!expectedSecret) {
+ return { ok: false, configured: false };
+ }
+
+ if (!secret || secret.length !== expectedSecret.length) {
+ return { ok: false, configured: true };
+ }
+
+ const ok = crypto.timingSafeEqual(
+ Buffer.from(secret),
+ Buffer.from(expectedSecret),
+ );
+
+ return { ok, configured: true };
+};
+
+export const SIGNING_TEMPLATE_VIEWER_RECIPIENT_NAME = "Viewer";
+
+export const buildSigningTemplateViewerRecipient = () => ({
+ email: "" as const,
+ name: SIGNING_TEMPLATE_VIEWER_RECIPIENT_NAME,
+ role: "SIGNER" as const,
+ signingOrder: 1,
+});
+
+type SigningTemplateRecipient = {
+ id: number;
+ email?: string | null;
+ name?: string | null;
+ role?: string | null;
+ signingOrder?: number | null;
+};
+
+const isSigningTemplateViewerRecipient = (
+ recipient: SigningTemplateRecipient,
+) =>
+ recipient.name === SIGNING_TEMPLATE_VIEWER_RECIPIENT_NAME &&
+ recipient.role === "SIGNER";
+
+const findSigningTemplateViewerRecipient = <
+ T extends SigningTemplateRecipient,
+>(
+ recipients: T[],
+) =>
+ recipients.find(isSigningTemplateViewerRecipient) ??
+ recipients.find((recipient) => recipient.role === "SIGNER") ??
+ recipients[0];
+
+const recipientNeedsViewerNormalization = (
+ recipient: SigningTemplateRecipient,
+) =>
+ recipient.email !== "" ||
+ recipient.name !== SIGNING_TEMPLATE_VIEWER_RECIPIENT_NAME ||
+ recipient.role !== "SIGNER" ||
+ recipient.signingOrder !== 1;
+
+/** Reset the template recipient to the anonymous "Viewer" placeholder by its id (not a replacement) so existing fields stay attached. */
+export const ensureSigningTemplateViewerRecipient = async ({
+ envelopeId,
+}: {
+ envelopeId: string;
+}) => {
+ const signingClient = getSigningClient();
+ const envelope = await getEnvelope(envelopeId);
+
+ if (envelope.type !== "TEMPLATE") {
+ throw new TeamError(
+ "Signing envelopes must be templates before recipient setup can be checked.",
+ );
+ }
+
+ const recipient = findSigningTemplateViewerRecipient(envelope.recipients);
+
+ if (!recipient) {
+ await signingClient.envelopes.recipients.createMany({
+ envelopeId,
+ data: [buildSigningTemplateViewerRecipient()],
+ });
+ return getEnvelope(envelopeId);
+ }
+
+ if (recipientNeedsViewerNormalization(recipient)) {
+ await signingClient.envelopes.recipients.updateMany({
+ envelopeId,
+ data: [
+ {
+ id: recipient.id,
+ ...buildSigningTemplateViewerRecipient(),
+ },
+ ],
+ });
+ return getEnvelope(envelopeId);
+ }
+
+ return envelope;
+};
+
+/** Create a Documenso template and seed the placeholder "Viewer" signer via the envelope side (email "" = Unknown enum); the direct link is minted later by `/signing/sync`. */
+export const createSigningTemplateEnvelope = async ({
+ title,
+ externalId,
+ file,
+ folderId,
+}: {
+ title: string;
+ externalId: string;
+ file: {
+ fileName: string;
+ content: Uint8Array;
+ };
+ folderId?: string | null;
+}) => {
+ const signingClient = getSigningClient();
+
+ const template = await signingClient.templates.create({
+ payload: {
+ title,
+ externalId,
+ folderId: folderId || undefined,
+ meta: {
+ subject: title,
+ distributionMethod: "NONE",
+ emailSettings: {
+ recipientSigningRequest: false,
+ recipientRemoved: false,
+ recipientSigned: false,
+ documentPending: false,
+ documentCompleted: false,
+ documentDeleted: false,
+ ownerDocumentCompleted: false,
+ ownerRecipientExpired: false,
+ ownerDocumentCreated: false,
+ },
+ },
+ },
+ file: {
+ fileName: file.fileName,
+ content: file.content,
+ },
+ });
+
+ await signingClient.envelopes.recipients.createMany({
+ envelopeId: template.envelopeId,
+ data: [buildSigningTemplateViewerRecipient()],
+ });
+
+ return template;
+};
+
+const parseNumericTemplateId = (signingTemplateId: string) => {
+ const parsed = SIGNING_TEMPLATE_ID_SCHEMA.safeParse(signingTemplateId);
+ if (!parsed.success) {
+ throw new TeamError(
+ "The signing template id is invalid; please re-upload the agreement.",
+ );
+ }
+ return parsed.data;
+};
+
+/** Idempotently ensure a template's direct link exists (re-enable or mint), keyed by the numeric `templateId` read from our DB since it isn't on the V2 envelope. */
+export const ensureSigningTemplateDirectLink = async ({
+ signingTemplateId,
+}: {
+ signingTemplateId: string;
+}) => {
+ const numericTemplateId = parseNumericTemplateId(signingTemplateId);
+ const signingClient = getSigningClient();
+ const template = await signingClient.templates.get({
+ templateId: numericTemplateId,
+ });
+
+ if (template.directLink?.enabled && template.directLink.token) {
+ return { template, directLink: template.directLink };
+ }
+
+ if (template.directLink?.token) {
+ const directLink = await signingClient.templates.directLink.toggle({
+ templateId: numericTemplateId,
+ enabled: true,
+ });
+ return { template, directLink };
+ }
+
+ const signerRecipient = findSigningTemplateViewerRecipient(
+ template.recipients,
+ );
+ if (!signerRecipient) {
+ throw new TeamError(
+ "The signing template must include at least one recipient before a direct link can be created.",
+ );
+ }
+
+ try {
+ const directLink = await signingClient.templates.directLink.create({
+ templateId: numericTemplateId,
+ directRecipientId: signerRecipient.id,
+ });
+ return { template, directLink };
+ } catch (error) {
+ console.error(
+ "[signing] templates.directLink.create failed",
+ {
+ templateId: numericTemplateId,
+ directRecipientId: signerRecipient.id,
+ },
+ error,
+ );
+ throw error;
+ }
+};
+
+/** Delete (not just toggle off) the direct link so the V2 field editor doesn't fail on "direct template exists"; `/signing/sync` recreates it after save. */
+export const deleteSigningTemplateDirectLink = async ({
+ signingTemplateId,
+}: {
+ signingTemplateId: string;
+}) => {
+ const numericTemplateId = parseNumericTemplateId(signingTemplateId);
+ const signingClient = getSigningClient();
+ const template = await signingClient.templates.get({
+ templateId: numericTemplateId,
+ });
+
+ if (!template.directLink) {
+ return { template, directLink: template.directLink ?? null };
+ }
+
+ const directLink = await signingClient.templates.directLink.delete({
+ templateId: numericTemplateId,
+ });
+
+ return { template, directLink };
+};
+
+const DEFAULT_SIGNING_FOLDER_NAME = "Papermark";
+
+const buildTeamSigningFolderTag = (teamId: string) =>
+ `papermark:team:${teamId}`;
+
+export const buildTeamSigningFolderName = ({
+ name,
+ id,
+}: {
+ name?: string | null;
+ id: string;
+}) => {
+ const trimmedName = name?.trim();
+ const tag = buildTeamSigningFolderTag(id);
+ const prefix =
+ trimmedName && trimmedName.length > 0
+ ? trimmedName
+ : DEFAULT_SIGNING_FOLDER_NAME;
+
+ return `${prefix} [${tag}]`;
+};
+
+const folderHasTeamTag = (folderName: string, teamId: string) =>
+ folderName.includes(`[${buildTeamSigningFolderTag(teamId)}]`);
+
+const findTeamSigningFolderId = async ({
+ teamId,
+ type,
+}: {
+ teamId: string;
+ type: "TEMPLATE" | "DOCUMENT";
+}) => {
+ const signingClient = getSigningClient();
+ const tag = buildTeamSigningFolderTag(teamId);
+
+ let currentPage = 1;
+ let totalPages = 1;
+
+ while (currentPage <= totalPages) {
+ const folders = await signingClient.folders.find({
+ query: tag,
+ type,
+ page: currentPage,
+ perPage: 100,
+ });
+
+ const match = folders.data.find((folder) =>
+ folderHasTeamTag(folder.name, teamId),
+ );
+
+ if (match) {
+ return match.id;
+ }
+
+ totalPages = folders.totalPages;
+ currentPage += 1;
+ }
+
+ return null;
+};
+
+const ensureTeamSigningFolderByType = async ({
+ team,
+ type,
+}: {
+ team: { id: string; name?: string | null };
+ type: "TEMPLATE" | "DOCUMENT";
+}) => {
+ const existingFolderId = await findTeamSigningFolderId({
+ teamId: team.id,
+ type,
+ });
+
+ if (existingFolderId) {
+ return existingFolderId;
+ }
+
+ const signingClient = getSigningClient();
+ const folder = await signingClient.folders.create({
+ name: buildTeamSigningFolderName({ name: team.name, id: team.id }),
+ type,
+ });
+
+ return folder.id;
+};
+
+type TeamSigningFolders = {
+ templateFolderId: string;
+ documentFolderId: string;
+};
+
+const TEAM_SIGNING_FOLDER_CACHE_TTL_MS = 5 * 60 * 1000;
+
+const teamSigningFolderCache = new Map<
+ string,
+ { folders: TeamSigningFolders; expiresAt: number }
+>();
+
+export const ensureTeamSigningFolders = async (
+ teamId: string,
+): Promise<TeamSigningFolders> => {
+ const cached = teamSigningFolderCache.get(teamId);
+
+ if (cached && cached.expiresAt > Date.now()) {
+ return cached.folders;
+ }
+
+ const team = await prisma.team.findUnique({
+ where: {
+ id: teamId,
+ },
+ select: {
+ id: true,
+ name: true,
+ },
+ });
+
+ if (!team) {
+ throw new TeamError("Team not found while preparing signing folders.");
+ }
+
+ const [templateFolderId, documentFolderId] = await Promise.all([
+ ensureTeamSigningFolderByType({ team, type: "TEMPLATE" }),
+ ensureTeamSigningFolderByType({ team, type: "DOCUMENT" }),
+ ]);
+
+ const folders: TeamSigningFolders = {
+ templateFolderId,
+ documentFolderId,
+ };
+
+ teamSigningFolderCache.set(teamId, {
+ folders,
+ expiresAt: Date.now() + TEAM_SIGNING_FOLDER_CACHE_TTL_MS,
+ });
+
+ return folders;
+};
+
+/** Resolve an agreement's direct-link token, keyed by the numeric `templateId` from our DB (the envelope only carries it for DOCUMENT envelopes). */
+export const getAgreementSigningToken = async ({
+ signingTemplateId,
+}: {
+ signingTemplateId: string;
+}) => {
+ const { template, directLink } = await ensureSigningTemplateDirectLink({
+ signingTemplateId,
+ });
+
+ return {
+ token: directLink.token,
+ templateId: String(template.id),
+ directLinkId: directLink.id,
+ };
+};
+
+export type SigningDocumentSession = {
+ documentId: number;
+ envelopeId: string;
+ recipientId: number;
+ token: string;
+};
+
+/** Mint a per-visitor document via `templates.use` (EmbedSignDocument) so fields render inline; `distributionMethod: "NONE"` sends no email and `externalId` ties it back to the AgreementResponse. */
+export const createSigningDocumentFromTemplate = async ({
+ signingTemplateId,
+ externalId,
+ signerEmail,
+ signerName,
+}: {
+ signingTemplateId: string;
+ externalId: string;
+ signerEmail?: string | null;
+ signerName?: string | null;
+}): Promise<SigningDocumentSession> => {
+ const numericTemplateId = parseNumericTemplateId(signingTemplateId);
+ const signingClient = getSigningClient();
+
+ // Fields are drawn against the single "Viewer" recipient seeded at setup
+ // time; `templates.use` maps this visitor onto that placeholder by its id.
+ const template = await signingClient.templates.get({
+ templateId: numericTemplateId,
+ });
+
+ const viewerRecipient = findSigningTemplateViewerRecipient(
+ template.recipients,
+ );
+ if (!viewerRecipient) {
+ throw new TeamError(
+ "The signing template has no recipient to assign the signer to.",
+ );
+ }
+
+ const document = await signingClient.templates.use({
+ templateId: numericTemplateId,
+ externalId,
+ distributeDocument: true,
+ recipients: [
+ {
+ id: viewerRecipient.id,
+ email: normalizeSignerEmail(signerEmail) ?? "",
+ name: normalizeSignerName(signerName) ?? undefined,
+ },
+ ],
+ override: {
+ distributionMethod: "NONE",
+ },
+ });
+
+ const recipient =
+ document.recipients.find((item) => item.token) ?? document.recipients[0];
+
+ if (!recipient?.token) {
+ throw new TeamError(
+ "Documenso did not return a signing token for the created document.",
+ );
+ }
+
+ return {
+ documentId: document.id,
+ envelopeId: document.envelopeId,
+ recipientId: recipient.id,
+ token: recipient.token,
+ };
+};
+
+/** Re-fetch the token for an existing per-visitor document so re-opening reuses it instead of spawning a new one; returns null when it's no longer signable. */
+export const getReusableSigningDocumentSession = async ({
+ documentId,
+}: {
+ documentId: number;
+}): Promise<SigningDocumentSession | null> => {
+ const signingClient = getSigningClient();
+
+ try {
+ const document = await signingClient.documents.get({ documentId });
+
+ if (document.status === "COMPLETED" || document.status === "REJECTED") {
+ return null;
+ }
+
+ const recipient =
+ document.recipients.find((item) => item.token) ?? document.recipients[0];
+
+ if (!recipient?.token) {
+ return null;
+ }
+
+ return {
+ documentId,
+ envelopeId: recipient.envelopeId,
+ recipientId: recipient.id,
+ token: recipient.token,
+ };
+ } catch (error) {
+ console.error("[signing] failed to reuse signing document", {
+ documentId,
+ error,
+ });
+ return null;
+ }
+};
+
+/** Resolve a signable document session: reuse the response's pending document when possible, otherwise create one from the template. */
+export const ensureSigningDocumentSession = async ({
+ signingTemplateId,
+ externalId,
+ existingDocumentId,
+ signerEmail,
+ signerName,
+}: {
+ signingTemplateId: string;
+ externalId: string;
+ existingDocumentId?: number | null;
+ signerEmail?: string | null;
+ signerName?: string | null;
+}): Promise<SigningDocumentSession> => {
+ if (existingDocumentId) {
+ const reused = await getReusableSigningDocumentSession({
+ documentId: existingDocumentId,
+ });
+
+ if (reused) {
+ return reused;
+ }
+ }
+
+ return createSigningDocumentFromTemplate({
+ signingTemplateId,
+ externalId,
+ signerEmail,
+ signerName,
+ });
+};
+
+export const getSignedDocumentDetails = async (documentId: number) => {
+ const signingClient = getSigningClient();
+ const document = await signingClient.documents.get({ documentId });
+
+ const signedRecipient =
+ document.recipients.find(
+ (recipient) => recipient.signingStatus === "SIGNED",
+ ) || document.recipients[0];
+
+ return {
+ document,
+ signedRecipient,
+ };
+};
+
+const moveSigningDocumentToTeamFolder = async ({
+ documentId,
+ currentFolderId,
+ teamId,
+}: {
+ documentId: number;
+ currentFolderId: string | null | undefined;
+ teamId: string;
+}) => {
+ try {
+ const { documentFolderId } = await ensureTeamSigningFolders(teamId);
+
+ if (!documentFolderId || currentFolderId === documentFolderId) {
+ return;
+ }
+
+ const signingClient = getSigningClient();
+
+ await signingClient.documents.update({
+ documentId,
+ data: {
+ folderId: documentFolderId,
+ },
+ });
+ } catch (error) {
+ // Folder placement is best-effort: never block status sync on it.
+ console.error(
+ "[signing] Failed to move signed document into the team folder.",
+ error,
+ );
+ }
+};
+
+export const syncAgreementResponseWithSigningDocument = async ({
+ agreementResponseId,
+ documentId,
+ signingStatus,
+}: {
+ agreementResponseId: string;
+ documentId: number;
+ signingStatus?: SigningStatus;
+}) => {
+ // Callers of `/signing/complete` are unauthenticated, so enforce the
+ // document <-> response binding below (these reads are independent, run in parallel).
+ const [existingResponse, signedDetails] = await Promise.all([
+ prisma.agreementResponse.findUnique({
+ where: { id: agreementResponseId },
+ select: {
+ id: true,
+ signingExternalId: true,
+ signingStatus: true,
+ agreement: {
+ select: {
+ id: true,
+ teamId: true,
+ signingEnvelopeId: true,
+ signingTemplateId: true,
+ },
+ },
+ },
+ }),
+ getSignedDocumentDetails(documentId),
+ ]);
+
+ if (!existingResponse) {
+ throw new TeamError("Agreement signing session was not found.");
+ }
+
+ const { document, signedRecipient } = signedDetails;
+
+ // Document <-> session binding: the document must carry the externalId we
+ // minted for this response, and it must belong to the agreement template.
+ if (
+ !existingResponse.signingExternalId ||
+ document.externalId !== existingResponse.signingExternalId
+ ) {
+ throw new TeamError(
+ "Signed document does not belong to this signing session.",
+ );
+ }
+
+ // Signing spawns a new DOCUMENT envelope, so template membership is verified
+ // via `document.templateId === agreement.signingTemplateId`, not envelopeId.
+ if (existingResponse.agreement?.signingTemplateId) {
+ const parsedTemplateId = SIGNING_TEMPLATE_ID_SCHEMA.safeParse(
+ existingResponse.agreement.signingTemplateId,
+ );
+
+ if (
+ parsedTemplateId.success &&
+ document.templateId &&
+ document.templateId !== parsedTemplateId.data
+ ) {
+ throw new TeamError(
+ "Signed document does not belong to this agreement template.",
+ );
+ }
+ }
+
+ const recipientEmail = signedRecipient?.email?.trim();
+ const recipientName = signedRecipient?.name?.trim();
+
+ const agreementResponse = await prisma.agreementResponse.update({
+ where: {
+ id: agreementResponseId,
+ },
+ data: {
+ signingStatus:
+ signingStatus || (document.completedAt ? "COMPLETED" : "SIGNED"),
+ signingEnvelopeId: document.envelopeId,
+ // Persist the numeric documentId so each download is a single keyed Documenso call.
+ signingDocumentId: documentId,
+ signedAt: signedRecipient?.signedAt
+ ? new Date(signedRecipient.signedAt)
+ : null,
+ completedAt: document.completedAt ? new Date(document.completedAt) : null,
+ // Overwrite the seeded identity with the provider's authoritative value, but only when present so we don't clobber it with an empty string.
+ ...(recipientEmail ? { signerEmail: recipientEmail } : {}),
+ ...(recipientName ? { signerName: recipientName } : {}),
+ },
+ include: {
+ agreement: {
+ select: {
+ teamId: true,
+ },
+ },
+ },
+ });
+
+ // Best-effort folder move via `waitUntil` so it survives past the response on serverless runtimes that freeze after responding.
+ if (agreementResponse.agreement?.teamId) {
+ waitUntil(
+ moveSigningDocumentToTeamFolder({
+ documentId,
+ currentFolderId: document.folderId,
+ teamId: agreementResponse.agreement.teamId,
+ }).catch((error) => {
+ console.error("[signing] background folder move failed", error);
+ }),
+ );
+ }
+
+ return agreementResponse;
+};
+
+export const findAgreementResponseByExternalId = async (
+ signingExternalId: string,
+) => {
+ return prisma.agreementResponse.findUnique({
+ where: {
+ signingExternalId,
+ },
+ include: {
+ agreement: {
+ select: {
+ id: true,
+ teamId: true,
+ signingProvider: true,
+ },
+ },
+ },
+ });
+};
+
+export const getAgreementResponseForAccess = async ({
+ agreementResponseId,
+ agreementId,
+ linkId,
+ signerEmail,
+ signerName,
+ requireSignerEmail,
+ requireSignerName,
+ skipSignerIdentityCheck,
+}: {
+ agreementResponseId?: string | null;
+ agreementId?: string | null;
+ linkId?: string | null;
+ signerEmail?: string | null;
+ signerName?: string | null;
+ requireSignerEmail?: boolean;
+ requireSignerName?: boolean;
+ // Set when an HMAC-bound cookie (`pm_sas_{linkId}`) already proves browser ownership — stronger than an email/name match.
+ skipSignerIdentityCheck?: boolean;
+}) => {
+ if (!agreementResponseId || !agreementId) {
+ throw new TeamError("Agreement signing is required before continuing.");
+ }
+
+ const agreementResponse = await prisma.agreementResponse.findUnique({
+ where: {
+ id: agreementResponseId,
+ },
+ });
+
+ if (!agreementResponse || agreementResponse.agreementId !== agreementId) {
+ throw new TeamError(
+ "Agreement signing could not be verified for this link.",
+ );
+ }
+
+ // C3: prevent replaying a response against a different link reusing the same agreement (legacy rows without a linkId fall through).
+ if (
+ linkId &&
+ agreementResponse.linkId &&
+ agreementResponse.linkId !== linkId
+ ) {
+ throw new TeamError(
+ "Agreement signing could not be verified for this link.",
+ );
+ }
+
+ if (!getAgreementResponseSignedState(agreementResponse.signingStatus)) {
+ throw new TeamError(
+ "Agreement signing is still pending. Please finish signing to continue.",
+ );
+ }
+
+ if (!skipSignerIdentityCheck) {
+ assertAgreementResponseSignerIdentity({
+ agreementResponse,
+ signerEmail,
+ signerName,
+ requireSignerEmail,
+ requireSignerName,
+ });
+ }
+
+ return agreementResponse;
+};
+
+export const getSignedAgreementResponseForViewer = async ({
+ agreementResponseId,
+ agreementId,
+ linkId,
+}: {
+ agreementResponseId: string;
+ agreementId: string;
+ linkId: string;
+}) => {
+ const agreementResponse = await prisma.agreementResponse.findUnique({
+ where: {
+ id: agreementResponseId,
+ },
+ select: {
+ id: true,
+ agreementId: true,
+ linkId: true,
+ signerEmail: true,
+ signerName: true,
+ signingStatus: true,
+ },
+ });
+
+ if (
+ !agreementResponse ||
+ agreementResponse.agreementId !== agreementId ||
+ agreementResponse.linkId !== linkId ||
+ !getAgreementResponseSignedState(agreementResponse.signingStatus)
+ ) {
+ return null;
+ }
+
+ return agreementResponse;
+};
+
+/** Resolve the response gating access: SIGNING agreements need a pre-created SIGNED/COMPLETED response; legacy checkbox agreements get a SIGNED response created inline. */
+export const ensureAgreementResponseForAccess = async ({
+ agreement,
+ linkId,
+ agreementResponseId,
+ hasConfirmedAgreement,
+ signerEmail,
+ signerName,
+ requireSignerEmail,
+ requireSignerName,
+ skipSignerIdentityCheck,
+}: {
+ agreement: {
+ id: string;
+ signingProvider?: string | null;
+ contentType?: string | null;
+ requireName?: boolean | null;
+ };
+ linkId: string;
+ agreementResponseId?: string | null;
+ hasConfirmedAgreement?: boolean | null;
+ signerEmail?: string | null;
+ signerName?: string | null;
+ requireSignerEmail?: boolean;
+ requireSignerName?: boolean;
+ skipSignerIdentityCheck?: boolean;
+}) => {
+ if (isSigningAgreement(agreement)) {
+ return getAgreementResponseForAccess({
+ agreementResponseId,
+ agreementId: agreement.id,
+ linkId,
+ signerEmail,
+ signerName,
+ requireSignerEmail,
+ requireSignerName:
+ requireSignerName ?? agreement.requireName ?? undefined,
+ skipSignerIdentityCheck,
+ });
+ }
+
+ if (!hasConfirmedAgreement) {
+ throw new TeamError("Agreement to NDA is required.");
+ }
+
+ const trimmedEmail =
+ typeof signerEmail === "string" && signerEmail.trim().length > 0
+ ? signerEmail.trim()
+ : null;
+ const trimmedName =
+ typeof signerName === "string" && signerName.trim().length > 0
+ ? signerName.trim()
+ : null;
+
+ const now = new Date();
+
+ return prisma.agreementResponse.create({
+ data: {
+ agreementId: agreement.id,
+ linkId,
+ signerEmail: trimmedEmail,
+ signerName: trimmedName,
+ signingStatus: "SIGNED",
+ signedAt: now,
+ completedAt: now,
+ },
+ });
+};
+
+export const getSigningAgreementCreateData = ({
+ teamId,
+ name,
+ content,
+ contentType,
+ requireName,
+}: {
+ teamId: string;
+ name: string;
+ content?: string;
+ contentType: "LINK" | "TEXT" | "SIGNING";
+ requireName: boolean;
+}): Prisma.AgreementCreateInput => {
+ const trimmedName = name.trim();
+
+ if (contentType === "SIGNING") {
+ return {
+ team: {
+ connect: {
+ id: teamId,
+ },
+ },
+ name: trimmedName,
+ content:
+ content?.trim() ||
+ `Embedded signing flow for ${trimmedName}. This agreement is managed in Papermark.`,
+ contentType,
+ signingProvider: "DOCUMENSO",
+ requireName,
+ };
+ }
+
+ return {
+ team: {
+ connect: {
+ id: teamId,
+ },
+ },
+ name: trimmedName,
+ content: content?.trim() || "",
+ contentType,
+ signingProvider: "LEGACY",
+ requireName,
+ };
+};
+
+export const getSigningEmbedConfig = () => {
+ return {
+ host: getSigningHost(),
+ };
+};
diff --git a/lib/signing/client.ts b/lib/signing/client.ts
new file mode 100644
index 00000000..1050e453
--- /dev/null
+++ b/lib/signing/client.ts
@@ -0,0 +1,49 @@
+import { Documenso } from "@documenso/sdk-typescript";
+
+import { TeamError } from "@/lib/errorHandler";
+
+const DEFAULT_SIGNING_HOST = "https://app.documenso.com";
+
+const stripTrailingSlash = (value: string) => value.replace(/\/$/, "");
+
+export const getSigningHost = () => {
+ return stripTrailingSlash(
+ process.env.NEXT_PUBLIC_SIGNING_HOST || DEFAULT_SIGNING_HOST,
+ );
+};
+
+export const getSigningApiUrl = () => {
+ return stripTrailingSlash(
+ process.env.SIGNING_API_URL || `${getSigningHost()}/api/v2`,
+ );
+};
+
+export const getSigningWebhookSecret = (): string | null => {
+ const secret = process.env.SIGNING_WEBHOOK_SECRET;
+
+ if (!secret) {
+ return null;
+ }
+
+ return secret;
+};
+
+let signingClient: Documenso | null = null;
+
+export const getSigningClient = () => {
+ const apiKey = process.env.SIGNING_API_KEY;
+
+ if (!apiKey) {
+ throw new TeamError("SIGNING_API_KEY environment variable is not set.");
+ }
+
+ if (!signingClient) {
+ signingClient = new Documenso({
+ apiKey,
+ serverURL: getSigningApiUrl(),
+ timeoutMs: 30000,
+ });
+ }
+
+ return signingClient;
+};
diff --git a/lib/signing/download-token.ts b/lib/signing/download-token.ts
new file mode 100644
index 00000000..f63cc451
--- /dev/null
+++ b/lib/signing/download-token.ts
@@ -0,0 +1,152 @@
+import crypto from "crypto";
+
+import { TeamError } from "@/lib/errorHandler";
+
+// Short-lived HMAC token scoped to a single (agreementResponseId, linkId) pair so a visitor can fetch only that signed PDF before the access form is submitted.
+
+const TOKEN_TTL_MS = 30 * 60 * 1000; // 30 minutes
+
+export const SIGNED_DOWNLOAD_COOKIE_NAME = "pm_sds";
+export const SIGNED_DOWNLOAD_COOKIE_PATH = "/api/agreements/signing";
+
+interface DownloadTokenPayload {
+ agreementResponseId: string;
+ linkId: string;
+ exp: number;
+}
+
+const getTokenSecret = (): string => {
+ const secret = process.env.NEXTAUTH_SECRET;
+ if (!secret) {
+ // We deliberately throw here so a misconfigured deploy fails loudly
+ // instead of silently issuing unauthenticated downloads.
+ throw new TeamError(
+ "Signing download token cannot be issued: NEXTAUTH_SECRET is not set.",
+ );
+ }
+ return secret;
+};
+
+const sign = (payloadB64: string, secret: string): string =>
+ crypto.createHmac("sha256", secret).update(payloadB64).digest("base64url");
+
+export const mintSignedAgreementDownloadToken = ({
+ agreementResponseId,
+ linkId,
+}: {
+ agreementResponseId: string;
+ linkId: string;
+}): { token: string; expiresAt: number; maxAgeSeconds: number } => {
+ const secret = getTokenSecret();
+ const expiresAt = Date.now() + TOKEN_TTL_MS;
+
+ const payload: DownloadTokenPayload = {
+ agreementResponseId,
+ linkId,
+ exp: expiresAt,
+ };
+
+ const payloadB64 = Buffer.from(JSON.stringify(payload)).toString("base64url");
+ const signature = sign(payloadB64, secret);
+
+ return {
+ token: `${payloadB64}.${signature}`,
+ expiresAt,
+ maxAgeSeconds: Math.floor(TOKEN_TTL_MS / 1000),
+ };
+};
+
+export const verifySignedAgreementDownloadToken = (
+ token: string | undefined | null,
+ expected: { agreementResponseId: string; linkId: string },
+): boolean => {
+ if (!token || typeof token !== "string") {
+ return false;
+ }
+
+ const parts = token.split(".");
+ if (parts.length !== 2) {
+ return false;
+ }
+
+ const [payloadB64, signature] = parts;
+ if (!payloadB64 || !signature) {
+ return false;
+ }
+
+ let secret: string;
+ try {
+ secret = getTokenSecret();
+ } catch {
+ return false;
+ }
+
+ const expectedSignature = sign(payloadB64, secret);
+ const signatureBuffer = Buffer.from(signature);
+ const expectedBuffer = Buffer.from(expectedSignature);
+
+ if (signatureBuffer.length !== expectedBuffer.length) {
+ return false;
+ }
+
+ if (!crypto.timingSafeEqual(signatureBuffer, expectedBuffer)) {
+ return false;
+ }
+
+ let payload: DownloadTokenPayload;
+ try {
+ const parsed = JSON.parse(
+ Buffer.from(payloadB64, "base64url").toString("utf8"),
+ ) as DownloadTokenPayload | null;
+ if (!parsed || typeof parsed !== "object") {
+ return false;
+ }
+ payload = parsed;
+ } catch {
+ return false;
+ }
+
+ if (
+ typeof payload.agreementResponseId !== "string" ||
+ typeof payload.linkId !== "string" ||
+ typeof payload.exp !== "number"
+ ) {
+ return false;
+ }
+
+ if (payload.exp < Date.now()) {
+ return false;
+ }
+
+ if (
+ payload.agreementResponseId !== expected.agreementResponseId ||
+ payload.linkId !== expected.linkId
+ ) {
+ return false;
+ }
+
+ return true;
+};
+
+// Cookie serializer; path-scoped to `/api/agreements/signing` so it only attaches to signing requests.
+export const buildSignedAgreementDownloadCookie = ({
+ token,
+ maxAgeSeconds,
+ secure,
+}: {
+ token: string;
+ maxAgeSeconds: number;
+ secure: boolean;
+}): string => {
+ const parts = [
+ `${SIGNED_DOWNLOAD_COOKIE_NAME}=${token}`,
+ `Path=${SIGNED_DOWNLOAD_COOKIE_PATH}`,
+ `Max-Age=${maxAgeSeconds}`,
+ "HttpOnly",
+ "SameSite=Lax",
+ ];
+ if (secure) {
+ parts.push("Secure");
+ }
+ return parts.join("; ");
+};
diff --git a/lib/signing/download.ts b/lib/signing/download.ts
new file mode 100644
index 00000000..2aa5951e
--- /dev/null
+++ b/lib/signing/download.ts
@@ -0,0 +1,107 @@
+export const getErrorMessageFromResponse = async (
+ response: Response,
+ fallback: string,
+) => {
+ const rawMessage = await response.text().catch(() => "");
+
+ if (!rawMessage) {
+ return fallback;
+ }
+
+ try {
+ const parsed = JSON.parse(rawMessage) as {
+ message?: string;
+ error?: string;
+ };
+
+ return parsed.message || parsed.error || fallback;
+ } catch {
+ return rawMessage;
+ }
+};
+
+const filenameFromDisposition = (disposition: string | null) => {
+ if (!disposition) return null;
+
+ const starMatch = disposition.match(/filename\*=UTF-8''([^;]+)/i);
+ if (starMatch?.[1]) {
+ try {
+ return decodeURIComponent(starMatch[1]);
+ } catch {
+ return starMatch[1];
+ }
+ }
+
+ const quotedMatch = disposition.match(/filename="([^"]+)"/i);
+ if (quotedMatch?.[1]) return quotedMatch[1];
+
+ const bareMatch = disposition.match(/filename=([^;]+)/i);
+ return bareMatch?.[1]?.trim() ?? null;
+};
+
+const filenameFromDownloadUrl = (url: string) => {
+ try {
+ const disposition = new URL(url).searchParams.get(
+ "response-content-disposition",
+ );
+ return filenameFromDisposition(disposition);
+ } catch {
+ return null;
+ }
+};
+
+export const buildTeamSignedAgreementDownloadUrl = ({
+ teamId,
+ agreementId,
+ responseId,
+}: {
+ teamId: string;
+ agreementId: string;
+ responseId: string;
+}) =>
+ `/api/teams/${teamId}/agreements/${agreementId}/responses/${responseId}/download`;
+
+export const downloadSignedAgreement = async ({
+ url,
+ fallbackFilename = "agreement_signed.pdf",
+}: {
+ url: string;
+ fallbackFilename?: string;
+}) => {
+ if (typeof window === "undefined" || typeof document === "undefined") {
+ throw new Error(
+ "Signed agreement downloads can only be triggered from the browser.",
+ );
+ }
+
+ const response = await fetch(url);
+
+ if (!response.ok) {
+ throw new Error(
+ await getErrorMessageFromResponse(
+ response,
+ "Failed to download the signed agreement.",
+ ),
+ );
+ }
+
+ const blob = await response.blob();
+ const filename =
+ filenameFromDisposition(response.headers.get("content-disposition")) ||
+ filenameFromDownloadUrl(response.url) ||
+ fallbackFilename;
+ const objectUrl = URL.createObjectURL(blob);
+
+ const anchor = document.createElement("a");
+ anchor.href = objectUrl;
+ anchor.download = filename;
+ anchor.rel = "noopener";
+ anchor.style.display = "none";
+ document.body.appendChild(anchor);
+ anchor.click();
+ anchor.remove();
+
+ // Defer revoke so Safari/WebKit has time to start the download before the
+ // blob URL is invalidated; revoking synchronously can abort the download.
+ setTimeout(() => URL.revokeObjectURL(objectUrl), 0);
+};
diff --git a/lib/signing/envelopes.ts b/lib/signing/envelopes.ts
new file mode 100644
index 00000000..5bef15b3
--- /dev/null
+++ b/lib/signing/envelopes.ts
@@ -0,0 +1,62 @@
+import { TeamError } from "@/lib/errorHandler";
+
+import { getSigningClient } from "./client";
+
+/** O(1) keyed lookup of a Documenso V2 envelope by its `envelopeId` — prefer over the old paginated find/filter helpers wherever the id is known. */
+export const getEnvelope = (envelopeId: string) =>
+ getSigningClient().envelopes.get({ envelopeId });
+
+/** Mint a pre-signed download URL for a signed envelope: fast path via the numeric `documentId`, legacy fallback resolves the envelope's primary item. */
+export const getEnvelopeSignedDownloadUrl = async ({
+ envelopeId,
+ documentId,
+}: {
+ envelopeId: string;
+ documentId?: number | null;
+}): Promise<{ url: string }> => {
+ const signingClient = getSigningClient();
+
+ if (documentId) {
+ const download = await signingClient.document.documentDownload({
+ documentId,
+ version: "signed",
+ });
+
+ if (!download.downloadUrl) {
+ throw new TeamError(
+ "Documenso did not return a download URL for the signed agreement.",
+ );
+ }
+
+ return { url: download.downloadUrl };
+ }
+
+ // Legacy path: resolve the envelope and use the envelope-item download route.
+ const envelope = await getEnvelope(envelopeId);
+ const primaryItem =
+ envelope.envelopeItems.find((item) => item.order === 1) ??
+ envelope.envelopeItems[0];
+
+ if (!primaryItem) {
+ throw new TeamError(
+ "Signed agreement file could not be located in the signing envelope.",
+ );
+ }
+
+ const itemDownload = await signingClient.envelopes.items.download({
+ envelopeItemId: primaryItem.id,
+ version: "signed",
+ });
+
+ // The SDK types this response body as `any`, but in practice it's `{ downloadUrl: string }` — extract defensively and error if the shape changes.
+ const url = (itemDownload.result as { downloadUrl?: unknown } | undefined)
+ ?.downloadUrl;
+
+ if (typeof url !== "string" || url.length === 0) {
+ throw new TeamError(
+ "Documenso did not return a download URL for the signed agreement.",
+ );
+ }
+
+ return { url };
+};
diff --git a/lib/signing/mirror.ts b/lib/signing/mirror.ts
new file mode 100644
index 00000000..94e3fbc1
--- /dev/null
+++ b/lib/signing/mirror.ts
@@ -0,0 +1,224 @@
+import { PutObjectCommand } from "@aws-sdk/client-s3";
+import { DocumentStorageType } from "@prisma/client";
+import { put as putBlob } from "@vercel/blob";
+
+import { getTeamS3ClientAndConfig } from "@/lib/files/aws-client";
+import prisma from "@/lib/prisma";
+import { buildContentDisposition, safeSlugify } from "@/lib/utils";
+
+import { getEnvelopeSignedDownloadUrl } from "./envelopes";
+
+// Documenso caps signed PDFs at 50 MB by default; mirror with the same ceiling
+// so a malformed upstream response can never blow out our process memory.
+const MAX_SIGNED_PDF_BYTES = 50 * 1024 * 1024;
+
+const buildSignedFileKey = ({
+ teamId,
+ agreementId,
+ agreementResponseId,
+}: {
+ teamId: string;
+ agreementId: string;
+ agreementResponseId: string;
+}) => `${teamId}/agreements/${agreementId}/signed/${agreementResponseId}.pdf`;
+
+const buildSignedFileName = ({
+ agreementName,
+ signerName,
+}: {
+ agreementName: string;
+ signerName: string | null;
+}) => {
+ const safeAgreement = safeSlugify(agreementName).slice(0, 60) || "agreement";
+
+ if (!signerName) {
+ return `${safeAgreement}_signed.pdf`;
+ }
+
+ const safeSigner = safeSlugify(signerName).slice(0, 40);
+ return safeSigner
+ ? `${safeAgreement}_signed_${safeSigner}.pdf`
+ : `${safeAgreement}_signed.pdf`;
+};
+
+const fetchSignedPdf = async (url: string): Promise<Buffer> => {
+ const controller = new AbortController();
+ const timeoutId = setTimeout(() => controller.abort(), 30_000);
+
+ let response: Response;
+ try {
+ response = await fetch(url, { signal: controller.signal });
+ } finally {
+ clearTimeout(timeoutId);
+ }
+
+ if (!response.ok) {
+ throw new Error(
+ `Failed to fetch signed PDF from Documenso (status ${response.status})`,
+ );
+ }
+
+ const advertisedLength = response.headers.get("content-length");
+ if (advertisedLength) {
+ const advertised = Number.parseInt(advertisedLength, 10);
+ if (Number.isFinite(advertised) && advertised > MAX_SIGNED_PDF_BYTES) {
+ throw new Error(
+ `Signed PDF exceeds mirror cap (${advertised} > ${MAX_SIGNED_PDF_BYTES} bytes)`,
+ );
+ }
+ }
+
+ if (!response.body) {
+ const fallback = await response.arrayBuffer();
+ if (fallback.byteLength > MAX_SIGNED_PDF_BYTES) {
+ throw new Error("Signed PDF exceeds mirror cap");
+ }
+ return Buffer.from(fallback);
+ }
+
+ const reader = response.body.getReader();
+ const chunks: Buffer[] = [];
+ let total = 0;
+
+ while (true) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ if (!value) continue;
+
+ total += value.byteLength;
+ if (total > MAX_SIGNED_PDF_BYTES) {
+ await reader.cancel().catch(() => {});
+ throw new Error("Signed PDF exceeds mirror cap");
+ }
+ chunks.push(Buffer.from(value));
+ }
+
+ return Buffer.concat(chunks, total);
+};
+
+const uploadToS3 = async ({
+ teamId,
+ key,
+ contentDisposition,
+ body,
+}: {
+ teamId: string;
+ key: string;
+ contentDisposition: string;
+ body: Buffer;
+}) => {
+ const { client, config } = await getTeamS3ClientAndConfig(teamId);
+
+ await client.send(
+ new PutObjectCommand({
+ Bucket: config.bucket,
+ Key: key,
+ Body: body,
+ ContentType: "application/pdf",
+ ContentDisposition: contentDisposition,
+ }),
+ );
+
+ // S3 buckets are private; the object key is the stored reference and
+ // downloads are served via short-lived presigned URLs.
+ return { storageType: DocumentStorageType.S3_PATH, fileKey: key };
+};
+
+const uploadToBlob = async ({ key, body }: { key: string; body: Buffer }) => {
+ // `addRandomSuffix` makes the public blob URL unguessable; persist the returned URL (not the deterministic key) so `getFile` resolves the real object.
+ const blob = await putBlob(key, body, {
+ access: "public",
+ addRandomSuffix: true,
+ contentType: "application/pdf",
+ });
+
+ return { storageType: DocumentStorageType.VERCEL_BLOB, fileKey: blob.url };
+};
+
+/** Mirror a signed Documenso PDF into team storage (S3/Blob); idempotent and non-fatal — downloads fall back to a direct Documenso call when the mirror is missing. */
+export const mirrorSignedAgreementToStorage = async ({
+ agreementResponseId,
+}: {
+ agreementResponseId: string;
+}) => {
+ const response = await prisma.agreementResponse.findUnique({
+ where: { id: agreementResponseId },
+ select: {
+ id: true,
+ signerName: true,
+ signingEnvelopeId: true,
+ signingDocumentId: true,
+ signedFileKey: true,
+ agreement: {
+ select: {
+ id: true,
+ name: true,
+ teamId: true,
+ },
+ },
+ },
+ });
+
+ if (!response) {
+ return { mirrored: false, reason: "response-not-found" as const };
+ }
+
+ if (response.signedFileKey) {
+ return { mirrored: false, reason: "already-mirrored" as const };
+ }
+
+ if (!response.signingEnvelopeId) {
+ return { mirrored: false, reason: "missing-envelope" as const };
+ }
+
+ const { url } = await getEnvelopeSignedDownloadUrl({
+ envelopeId: response.signingEnvelopeId,
+ documentId: response.signingDocumentId,
+ });
+
+ const body = await fetchSignedPdf(url);
+
+ const teamId = response.agreement.teamId;
+ const agreementId = response.agreement.id;
+ const signedFileName = buildSignedFileName({
+ agreementName: response.agreement.name,
+ signerName: response.signerName,
+ });
+ const signedFileKey = buildSignedFileKey({
+ teamId,
+ agreementId,
+ agreementResponseId: response.id,
+ });
+
+ const transport = process.env.NEXT_PUBLIC_UPLOAD_TRANSPORT;
+
+ // Persist whatever the uploader returns as `fileKey`: S3 needs the key, VERCEL_BLOB needs the returned (random-suffixed) URL.
+ const { storageType, fileKey } =
+ transport === "s3"
+ ? await uploadToS3({
+ teamId,
+ key: signedFileKey,
+ contentDisposition: buildContentDisposition(
+ signedFileName,
+ signedFileName,
+ ),
+ body,
+ })
+ : await uploadToBlob({ key: signedFileKey, body });
+
+ await prisma.agreementResponse.update({
+ where: { id: response.id },
+ data: {
+ signedFileKey: fileKey,
+ signedFileName,
+ signedFileStorageType: storageType,
+ },
+ });
+
+ return {
+ mirrored: true as const,
+ signedFileKey: fileKey,
+ signedFileName,
+ signedFileStorageType: storageType,
+ };
+};
diff --git a/lib/signing/template-upload.ts b/lib/signing/template-upload.ts
new file mode 100644
index 00000000..75f3459f
--- /dev/null
+++ b/lib/signing/template-upload.ts
@@ -0,0 +1,8 @@
+export const SIGNING_TEMPLATE_PDF_CONTENT_TYPE = "application/pdf";
+export const MAX_SIGNING_TEMPLATE_PDF_BYTES = 30 * 1024 * 1024;
+export const MAX_SIGNING_TEMPLATE_PDF_MB = Math.floor(
+ MAX_SIGNING_TEMPLATE_PDF_BYTES / (1024 * 1024),
+);
+
+export const getSigningTemplateTooLargeMessage = () =>
+ `PDF is too large for signing setup (max ${MAX_SIGNING_TEMPLATE_PDF_MB} MB).`;
diff --git a/lib/swr/use-agreement-responses.ts b/lib/swr/use-agreement-responses.ts
new file mode 100644
index 00000000..79109174
--- /dev/null
+++ b/lib/swr/use-agreement-responses.ts
@@ -0,0 +1,80 @@
+import { useTeam } from "@/context/team-context";
+import useSWR from "swr";
+
+import { fetcher } from "@/lib/utils";
+
+export interface AgreementResponseSummary {
+ id: string;
+ signingStatus: string;
+ signingEnvelopeId: string | null;
+ signingExternalId: string | null;
+ signedAt: string | null;
+ completedAt: string | null;
+ createdAt: string;
+ // Captured from the access form / signing provider, even when the visitor abandons before a View exists.
+ linkId: string | null;
+ signerEmail: string | null;
+ signerName: string | null;
+ // Hydrated server-side when there's no View but a linkId, so the UI can show the originating link.
+ link: {
+ id: string;
+ name: string | null;
+ } | null;
+ view: {
+ id: string;
+ viewerEmail: string | null;
+ viewerName: string | null;
+ viewedAt: string;
+ linkId: string;
+ link: {
+ id: string;
+ name: string | null;
+ } | null;
+ document: {
+ id: string;
+ name: string;
+ } | null;
+ dataroom: {
+ id: string;
+ name: string;
+ } | null;
+ } | null;
+}
+
+export interface AgreementResponsesPayload {
+ agreement: {
+ id: string;
+ name: string;
+ contentType: string;
+ signingProvider: string;
+ isSigning: boolean;
+ };
+ responses: AgreementResponseSummary[];
+}
+
+const EMPTY_RESPONSES: AgreementResponseSummary[] = [];
+
+export function useAgreementResponses(agreementId?: string | null) {
+ const teamInfo = useTeam();
+ const teamId = teamInfo?.currentTeam?.id;
+
+ const { data, error, mutate, isLoading } = useSWR<AgreementResponsesPayload>(
+ teamId && agreementId
+ ? `/api/teams/${teamId}/agreements/${agreementId}/responses`
+ : null,
+ fetcher,
+ {
+ dedupingInterval: 30000,
+ revalidateOnFocus: false,
+ keepPreviousData: true,
+ },
+ );
+
+ return {
+ agreement: data?.agreement,
+ responses: data?.responses ?? EMPTY_RESPONSES,
+ loading: isLoading,
+ error,
+ mutate,
+ };
+}
diff --git a/lib/swr/use-agreements.ts b/lib/swr/use-agreements.ts
index 6043f135..195a9ac1 100644
--- a/lib/swr/use-agreements.ts
+++ b/lib/swr/use-agreements.ts
@@ -7,6 +7,7 @@ import { fetcher } from "@/lib/utils";
export interface AgreementWithLinksCount extends Agreement {
_count: {
links: number;
+ responses: number;
};
}
diff --git a/lib/swr/use-document.ts b/lib/swr/use-document.ts
index a96d9db3..7e5d8b92 100644
--- a/lib/swr/use-document.ts
+++ b/lib/swr/use-document.ts
@@ -106,8 +106,13 @@ interface ViewWithDuration extends View {
agreementResponse: {
id: string;
agreementId: string;
+ signingStatus: string;
+ signedAt: string | null;
+ completedAt: string | null;
agreement: {
name: string;
+ contentType: string;
+ signingProvider: string;
};
} | null;
versionNumber: number;
diff --git a/lib/trigger/queues.ts b/lib/trigger/queues.ts
index f63ad8af..8cf4ce89 100644
--- a/lib/trigger/queues.ts
+++ b/lib/trigger/queues.ts
@@ -39,6 +39,11 @@ export const processDocumentForAIQueue = queue({
concurrencyLimit: 10,
});
+export const signingTemplateSetupQueue = queue({
+ name: "signing-template-setup",
+ concurrencyLimit: 5,
+});
+
export const addFileToVectorStoreQueue = queue({
name: "add-file-to-vector-store",
concurrencyLimit: 10,
diff --git a/lib/trigger/setup-signing-template.ts b/lib/trigger/setup-signing-template.ts
new file mode 100644
index 00000000..6056fff3
--- /dev/null
+++ b/lib/trigger/setup-signing-template.ts
@@ -0,0 +1,162 @@
+import { DocumentStorageType } from "@prisma/client";
+import { AbortTaskRunError, logger, metadata, task } from "@trigger.dev/sdk";
+
+import { ONE_HOUR } from "@/lib/constants";
+import { getFile } from "@/lib/files/get-file";
+import prisma from "@/lib/prisma";
+import {
+ buildAgreementSigningExternalId,
+ createSigningTemplateEnvelope,
+ ensureTeamSigningFolders,
+ isSigningAgreement,
+} from "@/lib/signing/agreements";
+import {
+ MAX_SIGNING_TEMPLATE_PDF_BYTES,
+ getSigningTemplateTooLargeMessage,
+} from "@/lib/signing/template-upload";
+import { signingTemplateSetupQueue } from "@/lib/trigger/queues";
+
+type SetupSigningTemplatePayload = {
+ agreementId: string;
+ teamId: string;
+ file: {
+ fileName: string;
+ data: string;
+ storageType: DocumentStorageType;
+ fileSize: number;
+ };
+};
+
+type SetupStatus = {
+ progress: number;
+ text: string;
+};
+
+const setStatus = (status: SetupStatus) => {
+ metadata.set("status", status);
+};
+
+export const setupSigningTemplateTask = task({
+ id: "setup-signing-template",
+ queue: signingTemplateSetupQueue,
+ retry: { maxAttempts: 2 },
+ run: async (payload: SetupSigningTemplatePayload) => {
+ setStatus({ progress: 0, text: "Initializing signing template..." });
+
+ if (payload.file.fileSize > MAX_SIGNING_TEMPLATE_PDF_BYTES) {
+ throw new AbortTaskRunError(getSigningTemplateTooLargeMessage());
+ }
+
+ const agreement = await prisma.agreement.findFirst({
+ where: {
+ id: payload.agreementId,
+ teamId: payload.teamId,
+ deletedAt: null,
+ },
+ select: {
+ id: true,
+ name: true,
+ contentType: true,
+ signingProvider: true,
+ signingExternalId: true,
+ signingEnvelopeId: true,
+ },
+ });
+
+ if (!agreement) {
+ throw new AbortTaskRunError("Agreement not found.");
+ }
+
+ if (!isSigningAgreement(agreement)) {
+ throw new AbortTaskRunError(
+ "Only embedded signing agreements can attach a PDF template.",
+ );
+ }
+
+ if (agreement.signingEnvelopeId) {
+ throw new AbortTaskRunError(
+ "This agreement is already linked to a signing template.",
+ );
+ }
+
+ setStatus({ progress: 15, text: "Retrieving uploaded PDF..." });
+
+ const fileUrl = await getFile({
+ type: payload.file.storageType,
+ data: payload.file.data,
+ expiresIn: ONE_HOUR,
+ });
+
+ const fileResponse = await fetch(fileUrl);
+ if (!fileResponse.ok) {
+ logger.error("Failed to fetch signing template PDF", {
+ status: fileResponse.status,
+ agreementId: payload.agreementId,
+ teamId: payload.teamId,
+ });
+ throw new AbortTaskRunError("Failed to retrieve uploaded PDF.");
+ }
+
+ const pdfBuffer = Buffer.from(await fileResponse.arrayBuffer());
+ if (pdfBuffer.length === 0) {
+ throw new AbortTaskRunError("The uploaded PDF is empty.");
+ }
+
+ if (pdfBuffer.length > MAX_SIGNING_TEMPLATE_PDF_BYTES) {
+ throw new AbortTaskRunError(getSigningTemplateTooLargeMessage());
+ }
+
+ const externalId =
+ agreement.signingExternalId ||
+ buildAgreementSigningExternalId(payload.teamId, agreement.id);
+
+ let templateFolderId: string | null = null;
+ try {
+ setStatus({ progress: 35, text: "Preparing signing folder..." });
+ ({ templateFolderId } = await ensureTeamSigningFolders(payload.teamId));
+ } catch (folderError) {
+ logger.warn("Failed to ensure team signing folders during setup", {
+ error: folderError instanceof Error ? folderError.message : folderError,
+ teamId: payload.teamId,
+ });
+ }
+
+ setStatus({ progress: 55, text: "Creating signing template..." });
+
+ const template = await createSigningTemplateEnvelope({
+ title: agreement.name,
+ externalId,
+ folderId: templateFolderId,
+ file: {
+ fileName: payload.file.fileName,
+ content: new Uint8Array(pdfBuffer),
+ },
+ });
+
+ setStatus({ progress: 85, text: "Saving signing template..." });
+
+ const updatedAgreement = await prisma.agreement.update({
+ where: {
+ id: agreement.id,
+ },
+ data: {
+ signingExternalId: externalId,
+ signingEnvelopeId: template.envelopeId,
+ signingTemplateId: String(template.id),
+ },
+ select: {
+ signingEnvelopeId: true,
+ signingTemplateId: true,
+ signingExternalId: true,
+ },
+ });
+
+ setStatus({ progress: 100, text: "Signing template ready." });
+
+ return {
+ externalId: updatedAgreement.signingExternalId,
+ envelopeId: updatedAgreement.signingEnvelopeId,
+ templateId: updatedAgreement.signingTemplateId,
+ };
+ },
+});
diff --git a/next.config.mjs b/next.config.mjs
index 34880394..a94f0bd6 100644
--- a/next.config.mjs
+++ b/next.config.mjs
@@ -312,6 +312,15 @@ const nextConfig = {
];
},
experimental: {
+ // Rewrite barrel imports (e.g. `import { Icon } from "lucide-react"`) to
+ // direct submodule imports at build time. Cuts dev boot, cold starts and
+ // HMR for these large re-export packages without losing ergonomic imports.
+ optimizePackageImports: [
+ "lucide-react",
+ "@tremor/react",
+ "date-fns",
+ "lodash",
+ ],
outputFileTracingIncludes: {
"/api/mupdf/*": ["./node_modules/mupdf/dist/*.wasm"],
// Jackson SAML routes need jose + openid-client for crypto
diff --git a/package-lock.json b/package-lock.json
index 80033000..4abccb92 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -23,6 +23,8 @@
"@dnd-kit/core": "^6.3.1",
"@dnd-kit/sortable": "^10.0.0",
"@dnd-kit/utilities": "^3.2.2",
+ "@documenso/embed-react": "^0.6.0",
+ "@documenso/sdk-typescript": "^0.8.1",
"@github/webauthn-json": "^2.1.1",
"@hookform/resolvers": "^5.2.2",
"@jitsu/js": "^1.10.4",
@@ -3306,6 +3308,28 @@
"react": ">=16.8.0"
}
},
+ "node_modules/@documenso/embed-react": {
+ "version": "0.6.1",
+ "resolved": "https://registry.npmjs.org/@documenso/embed-react/-/embed-react-0.6.1.tgz",
+ "integrity": "sha512-xGHMF7G8nNWaD3FbQjEMdz0D6fU9oB8ibHo5U4qAKl76ijiVD5vzlvidXvNSxIUJLsuXIKQHCu0RUpsHZpkPNw==",
+ "license": "MIT",
+ "peerDependencies": {
+ "react": "^18.0.0 || ^19.0.0",
+ "react-dom": "^18.0.0 || ^19.0.0"
+ }
+ },
+ "node_modules/@documenso/sdk-typescript": {
+ "version": "0.8.1",
+ "resolved": "https://registry.npmjs.org/@documenso/sdk-typescript/-/sdk-typescript-0.8.1.tgz",
+ "integrity": "sha512-+i9vMb+GL6acZLv+AJjRnbR/sQKRkP3q5qAqSJ3d7f/Ut6fl+GN7q36LcbbuYnw4Yeq3UHZXI+Zx0HGxJXd7BQ==",
+ "dependencies": {
+ "@modelcontextprotocol/sdk": "^1.26.0",
+ "zod": "^3.25.0 || ^4.0.0"
+ },
+ "bin": {
+ "mcp": "bin/mcp-server.js"
+ }
+ },
"node_modules/@electric-sql/client": {
"version": "1.0.14",
"resolved": "https://registry.npmjs.org/@electric-sql/client/-/client-1.0.14.tgz",
diff --git a/package.json b/package.json
index 0fc1496c..f8b64024 100644
--- a/package.json
+++ b/package.json
@@ -35,6 +35,8 @@
"@dnd-kit/core": "^6.3.1",
"@dnd-kit/sortable": "^10.0.0",
"@dnd-kit/utilities": "^3.2.2",
+ "@documenso/embed-react": "^0.6.0",
+ "@documenso/sdk-typescript": "^0.8.1",
"@github/webauthn-json": "^2.1.1",
"@hookform/resolvers": "^5.2.2",
"@jitsu/js": "^1.10.4",
diff --git a/pages/api/agreements/signing/[agreementResponseId]/download.ts b/pages/api/agreements/signing/[agreementResponseId]/download.ts
new file mode 100644
index 00000000..e60c158d
--- /dev/null
+++ b/pages/api/agreements/signing/[agreementResponseId]/download.ts
@@ -0,0 +1,258 @@
+import { NextApiRequest, NextApiResponse } from "next";
+
+import { waitUntil } from "@vercel/functions";
+import { parse as parseCookieHeader } from "cookie";
+
+import { getDataroomSessionByLinkIdInPagesRouter } from "@/lib/auth/dataroom-auth";
+import { verifyLinkSessionInPagesRouter } from "@/lib/auth/link-session";
+import { TeamError, errorhandler } from "@/lib/errorHandler";
+import { getFile } from "@/lib/files/get-file";
+import prisma from "@/lib/prisma";
+import { getAgreementResponseSignedState } from "@/lib/signing/agreements";
+import { getEnvelopeSignedDownloadUrl } from "@/lib/signing/envelopes";
+import { mirrorSignedAgreementToStorage } from "@/lib/signing/mirror";
+import {
+ getSignedAgreementAccessCookieName,
+ verifySignedAgreementAccessToken,
+} from "@/lib/signing/access-token";
+import {
+ SIGNED_DOWNLOAD_COOKIE_NAME,
+ verifySignedAgreementDownloadToken,
+} from "@/lib/signing/download-token";
+import { buildContentDisposition } from "@/lib/utils";
+
+// `waitUntil` requires response streaming to be enabled on Pages API routes.
+export const config = {
+ supportsResponseStreaming: true,
+};
+
+// Clamp to Documenso's 50MB upload cap to bound memory and avoid OOM on the fallback path.
+const MAX_SIGNED_PDF_BYTES = 50 * 1024 * 1024;
+
+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`);
+ }
+
+ try {
+ const { agreementResponseId } = req.query as {
+ agreementResponseId: string;
+ };
+
+ const agreementResponse = await prisma.agreementResponse.findUnique({
+ where: {
+ id: agreementResponseId,
+ },
+ select: {
+ id: true,
+ linkId: true,
+ signerEmail: true,
+ signingStatus: true,
+ signingExternalId: true,
+ signingEnvelopeId: true,
+ signingDocumentId: true,
+ signedFileKey: true,
+ signedFileName: true,
+ signedFileStorageType: true,
+ agreement: {
+ select: {
+ name: true,
+ teamId: true,
+ id: true,
+ },
+ },
+ },
+ });
+
+ if (!agreementResponse) {
+ throw new TeamError("Signed agreement was not found.");
+ }
+
+ if (!getAgreementResponseSignedState(agreementResponse.signingStatus)) {
+ throw new TeamError("Signed agreement is not ready yet.");
+ }
+
+ // C2: this unauthenticated endpoint requires a binding proof tied to this `linkId` (link/dataroom session cookie or the `pm_sds` signing-session cookie); otherwise anyone who learns an `agreementResponseId` could stream the signed PDF.
+ if (!agreementResponse.linkId) {
+ throw new TeamError("Signed agreement is not tied to a visitor link.");
+ }
+
+ const [linkSession, dataroomSession] = await Promise.all([
+ verifyLinkSessionInPagesRouter(req, agreementResponse.linkId),
+ getDataroomSessionByLinkIdInPagesRouter(req, agreementResponse.linkId),
+ ]);
+
+ let authorized = !!linkSession || !!dataroomSession;
+
+ if (!authorized) {
+ const downloadToken =
+ parseCookieHeader(req.headers.cookie || "")[
+ SIGNED_DOWNLOAD_COOKIE_NAME
+ ];
+ authorized = verifySignedAgreementDownloadToken(downloadToken, {
+ agreementResponseId: agreementResponse.id,
+ linkId: agreementResponse.linkId,
+ });
+ }
+
+ if (!authorized) {
+ const accessToken =
+ parseCookieHeader(req.headers.cookie || "")[
+ getSignedAgreementAccessCookieName(agreementResponse.linkId)
+ ];
+ authorized = verifySignedAgreementAccessToken(accessToken, {
+ linkId: agreementResponse.linkId,
+ agreementId: agreementResponse.agreement.id,
+ agreementResponseId: agreementResponse.id,
+ });
+ }
+
+ if (!authorized) {
+ return res.status(401).end("Unauthorized");
+ }
+
+ // Defense-in-depth: when the link session carries an email, require it to match the signer (other proofs rely on the linkId/responseId binding above).
+ const sessionEmail = linkSession?.email ?? null;
+ if (
+ agreementResponse.signerEmail &&
+ sessionEmail &&
+ sessionEmail.toLowerCase() !==
+ agreementResponse.signerEmail.toLowerCase()
+ ) {
+ return res.status(403).end("Forbidden");
+ }
+
+ const safeName =
+ agreementResponse.agreement.name
+ .replace(/[^a-z0-9\-_]/gi, "_")
+ .toLowerCase()
+ .substring(0, 50) || "agreement";
+ const fallbackName = `${safeName}_signed.pdf`;
+
+ // Fast path: mirror is ready, serve from our own storage with a 302.
+ if (
+ agreementResponse.signedFileKey &&
+ agreementResponse.signedFileStorageType
+ ) {
+ const filename = agreementResponse.signedFileName || fallbackName;
+ const url = await getFile({
+ type: agreementResponse.signedFileStorageType,
+ data: agreementResponse.signedFileKey,
+ isDownload: true,
+ responseContentDisposition: buildContentDisposition(
+ filename,
+ fallbackName,
+ ),
+ });
+ return res.redirect(302, url);
+ }
+
+ if (!agreementResponse.signingEnvelopeId) {
+ throw new TeamError("Signed agreement envelope could not be found.");
+ }
+
+ // Fallback path: mint a download URL keyed by envelopeId/documentId (no paginated scan or folder lookup).
+ const { url: downloadUrl } = await getEnvelopeSignedDownloadUrl({
+ envelopeId: agreementResponse.signingEnvelopeId,
+ documentId: agreementResponse.signingDocumentId,
+ });
+
+ // Kick off a background mirror so the next click is served from storage; `waitUntil` keeps the function alive past the response without blocking the user.
+ waitUntil(
+ mirrorSignedAgreementToStorage({
+ agreementResponseId: agreementResponse.id,
+ }).catch((error) => {
+ console.error(
+ "[signing] background mirror during download fallback failed",
+ error,
+ );
+ }),
+ );
+
+ const controller = new AbortController();
+ const timeoutId = setTimeout(() => controller.abort(), 30000);
+
+ let fileResponse: Response;
+ try {
+ fileResponse = await fetch(downloadUrl, { signal: controller.signal });
+ } finally {
+ clearTimeout(timeoutId);
+ }
+
+ if (!fileResponse.ok) {
+ throw new TeamError("Failed to fetch the signed agreement file.");
+ }
+
+ // H5: enforce a hard cap — check the upstream Content-Length first and refuse oversized responses before allocating memory.
+ const contentLengthHeader = fileResponse.headers.get("content-length");
+ if (contentLengthHeader) {
+ const advertised = Number.parseInt(contentLengthHeader, 10);
+ if (
+ Number.isFinite(advertised) &&
+ advertised > MAX_SIGNED_PDF_BYTES
+ ) {
+ throw new TeamError("Signed agreement file is too large to download.");
+ }
+ }
+
+ const buffer = await readResponseBodyWithCap(
+ fileResponse,
+ MAX_SIGNED_PDF_BYTES,
+ );
+
+ res.setHeader(
+ "Content-Type",
+ fileResponse.headers.get("content-type") || "application/pdf",
+ );
+ res.setHeader("X-Content-Type-Options", "nosniff");
+ res.setHeader(
+ "Content-Disposition",
+ buildContentDisposition(fallbackName, fallbackName),
+ );
+ res.setHeader("Content-Length", buffer.byteLength.toString());
+ res.setHeader("Cache-Control", "private, no-store");
+ return res.send(buffer);
+ } catch (error) {
+ return errorhandler(error, res);
+ }
+}
+
+async function readResponseBodyWithCap(
+ response: Response,
+ maxBytes: number,
+): Promise<Buffer> {
+ if (!response.body) {
+ const fallback = await response.arrayBuffer();
+ if (fallback.byteLength > maxBytes) {
+ throw new TeamError("Signed agreement file is too large to download.");
+ }
+ return Buffer.from(fallback);
+ }
+
+ const reader = response.body.getReader();
+ const chunks: Buffer[] = [];
+ let total = 0;
+
+ while (true) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ if (!value) continue;
+
+ total += value.byteLength;
+ if (total > maxBytes) {
+ try {
+ await reader.cancel();
+ } catch {
+ // ignore cancel failures
+ }
+ throw new TeamError("Signed agreement file is too large to download.");
+ }
+ chunks.push(Buffer.from(value));
+ }
+
+ return Buffer.concat(chunks, total);
+}
diff --git a/pages/api/agreements/signing/complete.ts b/pages/api/agreements/signing/complete.ts
new file mode 100644
index 00000000..e6584c5c
--- /dev/null
+++ b/pages/api/agreements/signing/complete.ts
@@ -0,0 +1,78 @@
+import { NextApiRequest, NextApiResponse } from "next";
+
+import { z } from "zod";
+
+import { TeamError, errorhandler } from "@/lib/errorHandler";
+import {
+ buildSignedAgreementAccessCookie,
+ mintSignedAgreementAccessToken,
+} from "@/lib/signing/access-token";
+import { syncAgreementResponseWithSigningDocument } from "@/lib/signing/agreements";
+
+// `syncAgreementResponseWithSigningDocument` schedules a background folder
+// move via `waitUntil`, which requires response streaming on Pages API.
+export const config = {
+ supportsResponseStreaming: true,
+};
+
+const completeAgreementSigningSchema = z.object({
+ agreementResponseId: z.string().min(1, "Agreement response ID is required."),
+ documentId: z.number().int().positive("Signing document ID is required."),
+});
+
+export default async function handle(
+ req: NextApiRequest,
+ res: NextApiResponse,
+) {
+ if (req.method !== "POST") {
+ res.setHeader("Allow", ["POST"]);
+ return res.status(405).end(`Method ${req.method} Not Allowed`);
+ }
+
+ try {
+ const parseResult = completeAgreementSigningSchema.safeParse(req.body);
+
+ if (!parseResult.success) {
+ throw new TeamError("A valid signing completion payload is required.");
+ }
+
+ const { agreementResponseId, documentId } = parseResult.data;
+
+ // `syncAgreementResponseWithSigningDocument` enforces the document↔response binding (externalId + template/envelope must match), so a caller can't pair their pending response with another team's signed documentId.
+ const updatedAgreementResponse =
+ await syncAgreementResponseWithSigningDocument({
+ agreementResponseId,
+ documentId,
+ });
+
+ const cookies: string[] = [];
+
+ if (updatedAgreementResponse.linkId) {
+ const accessCookie = mintSignedAgreementAccessToken({
+ agreementResponseId: updatedAgreementResponse.id,
+ linkId: updatedAgreementResponse.linkId,
+ agreementId: updatedAgreementResponse.agreementId,
+ });
+
+ cookies.push(
+ buildSignedAgreementAccessCookie({
+ linkId: updatedAgreementResponse.linkId,
+ token: accessCookie.token,
+ maxAgeSeconds: accessCookie.maxAgeSeconds,
+ secure: process.env.NODE_ENV === "production",
+ }),
+ );
+ }
+
+ if (cookies.length > 0) {
+ res.setHeader("Set-Cookie", cookies);
+ }
+
+ return res.status(200).json({
+ id: updatedAgreementResponse.id,
+ signingStatus: updatedAgreementResponse.signingStatus,
+ });
+ } catch (error) {
+ return errorhandler(error, res);
+ }
+}
diff --git a/pages/api/agreements/signing/session.ts b/pages/api/agreements/signing/session.ts
new file mode 100644
index 00000000..f4848295
--- /dev/null
+++ b/pages/api/agreements/signing/session.ts
@@ -0,0 +1,343 @@
+import { NextApiRequest, NextApiResponse } from "next";
+
+import { parse as parseCookieHeader } from "cookie";
+import { z } from "zod";
+
+import { TeamError, errorhandler } from "@/lib/errorHandler";
+import prisma from "@/lib/prisma";
+import { ratelimit } from "@/lib/redis";
+import {
+ buildSignedAgreementAccessCookie,
+ getSignedAgreementAccessCookieName,
+ mintSignedAgreementAccessToken,
+ parseSignedAgreementAccessToken,
+ verifySignedAgreementAccessToken,
+} from "@/lib/signing/access-token";
+import {
+ buildAgreementResponseSigningExternalId,
+ getAgreementResponseSignedState,
+ getAgreementSigningToken,
+ getSigningEmbedConfig,
+ isSigningAgreement,
+} from "@/lib/signing/agreements";
+import {
+ SIGNED_DOWNLOAD_COOKIE_NAME,
+ buildSignedAgreementDownloadCookie,
+ mintSignedAgreementDownloadToken,
+ verifySignedAgreementDownloadToken,
+} from "@/lib/signing/download-token";
+import { getIpAddress } from "@/lib/utils/ip";
+
+const optionalEmailSchema = z.preprocess((value) => {
+ if (typeof value !== "string") {
+ return value;
+ }
+
+ const trimmedValue = value.trim().toLowerCase();
+
+ return trimmedValue.length > 0 ? trimmedValue : null;
+}, z.string().email().nullable().optional());
+
+const optionalNameSchema = z.preprocess((value) => {
+ if (typeof value !== "string") {
+ return value;
+ }
+
+ const trimmedValue = value.trim();
+
+ return trimmedValue.length > 0 ? trimmedValue : null;
+}, z.string().max(255).nullable().optional());
+
+const createSigningSessionSchema = z.object({
+ agreementId: z.string().min(1, "Agreement ID is required."),
+ linkId: z.string().min(1, "Link ID is required."),
+ email: optionalEmailSchema,
+ name: optionalNameSchema,
+ agreementResponseId: z
+ .string()
+ .min(1)
+ .nullable()
+ .optional()
+ .transform((value) => value ?? undefined),
+});
+
+const resolveContinuityAgreementResponseId = ({
+ linkId,
+ agreementId,
+ cookies,
+ requestedAgreementResponseId,
+}: {
+ linkId: string;
+ agreementId: string;
+ cookies: Record<string, string | undefined>;
+ requestedAgreementResponseId?: string;
+}): string | null => {
+ const accessCookie = cookies[getSignedAgreementAccessCookieName(linkId)];
+ const accessPayload = parseSignedAgreementAccessToken(accessCookie);
+ const downloadToken = cookies[SIGNED_DOWNLOAD_COOKIE_NAME];
+
+ const accessResponseId =
+ accessPayload &&
+ accessPayload.linkId === linkId &&
+ accessPayload.agreementId === agreementId
+ ? accessPayload.agreementResponseId
+ : null;
+
+ const downloadResponseId =
+ requestedAgreementResponseId &&
+ verifySignedAgreementDownloadToken(downloadToken, {
+ agreementResponseId: requestedAgreementResponseId,
+ linkId,
+ })
+ ? requestedAgreementResponseId
+ : null;
+
+ if (accessResponseId && downloadResponseId) {
+ return accessResponseId === downloadResponseId ? accessResponseId : null;
+ }
+
+ if (accessResponseId) {
+ return accessResponseId;
+ }
+
+ if (downloadResponseId) {
+ return downloadResponseId;
+ }
+
+ if (
+ requestedAgreementResponseId &&
+ verifySignedAgreementAccessToken(accessCookie, {
+ linkId,
+ agreementId,
+ agreementResponseId: requestedAgreementResponseId,
+ })
+ ) {
+ return requestedAgreementResponseId;
+ }
+
+ return null;
+};
+
+export default async function handle(
+ req: NextApiRequest,
+ res: NextApiResponse,
+) {
+ if (req.method !== "POST") {
+ res.setHeader("Allow", ["POST"]);
+ return res.status(405).end(`Method ${req.method} Not Allowed`);
+ }
+
+ try {
+ const parseResult = createSigningSessionSchema.safeParse(req.body);
+
+ if (!parseResult.success) {
+ throw new TeamError("A valid agreement signing request is required.");
+ }
+
+ const { agreementId, linkId, email, name, agreementResponseId } =
+ parseResult.data;
+
+ const ipAddressValue = getIpAddress(req.headers);
+ // Run the independent rate-limit checks and agreement read in parallel; we still bail on a 429 before further work.
+ const [linkLimit, ipLimit, agreement] = await Promise.all([
+ ratelimit(100, "1 m").limit(`signing-session:${linkId}`),
+ ratelimit(20, "1 m").limit(`signing-session:ip:${ipAddressValue}`),
+ prisma.agreement.findFirst({
+ where: {
+ id: agreementId,
+ deletedAt: null,
+ links: {
+ some: {
+ id: linkId,
+ deletedAt: null,
+ enableAgreement: true,
+ },
+ },
+ },
+ select: {
+ id: true,
+ teamId: true,
+ signingProvider: true,
+ contentType: true,
+ signingEnvelopeId: true,
+ signingTemplateId: true,
+ signingExternalId: true,
+ },
+ }),
+ ]);
+
+ if (!linkLimit.success || !ipLimit.success) {
+ return res.status(429).json({
+ message: "Too many signing requests. Please try again in a minute.",
+ });
+ }
+
+ if (!agreement) {
+ throw new TeamError("Agreement signing is not available for this link.");
+ }
+
+ if (!isSigningAgreement(agreement)) {
+ throw new TeamError("This agreement does not support embedded signing.");
+ }
+
+ if (!agreement.signingEnvelopeId || !agreement.signingTemplateId) {
+ throw new TeamError(
+ "This agreement has not finished syncing with the signing provider yet.",
+ );
+ }
+
+ const cookies = parseCookieHeader(req.headers.cookie || "");
+ const continuityAgreementResponseId = resolveContinuityAgreementResponseId({
+ linkId,
+ agreementId,
+ cookies,
+ requestedAgreementResponseId: agreementResponseId,
+ });
+
+ if (continuityAgreementResponseId) {
+ const existingResponse = await prisma.agreementResponse.findUnique({
+ where: {
+ id: continuityAgreementResponseId,
+ },
+ select: {
+ id: true,
+ agreementId: true,
+ linkId: true,
+ signingStatus: true,
+ signingExternalId: true,
+ },
+ });
+
+ if (
+ existingResponse &&
+ existingResponse.agreementId === agreementId &&
+ existingResponse.linkId === linkId
+ ) {
+ if (getAgreementResponseSignedState(existingResponse.signingStatus)) {
+ const accessCookie = mintSignedAgreementAccessToken({
+ agreementResponseId: existingResponse.id,
+ linkId,
+ agreementId,
+ });
+
+ res.setHeader("Set-Cookie", [
+ buildSignedAgreementAccessCookie({
+ linkId,
+ token: accessCookie.token,
+ maxAgeSeconds: accessCookie.maxAgeSeconds,
+ secure: process.env.NODE_ENV === "production",
+ }),
+ ]);
+
+ return res.status(200).json({
+ alreadySigned: true,
+ agreementResponseId: existingResponse.id,
+ signingStatus: existingResponse.signingStatus,
+ });
+ }
+
+ if (!existingResponse.signingExternalId) {
+ throw new TeamError(
+ "Signing session is missing its external identifier.",
+ );
+ }
+
+ // Direct-link signing: Documenso mints the per-visitor document at completion (stamped with this response's externalId so `/signing/complete` can bind it back), so we only persist the access-form identity here when provided.
+ if (email || name) {
+ await prisma.agreementResponse.update({
+ where: {
+ id: existingResponse.id,
+ },
+ data: {
+ ...(email ? { signerEmail: email } : {}),
+ ...(name ? { signerName: name } : {}),
+ },
+ });
+ }
+
+ const { token } = await getAgreementSigningToken({
+ signingTemplateId: agreement.signingTemplateId,
+ });
+
+ const downloadCookie = mintSignedAgreementDownloadToken({
+ agreementResponseId: existingResponse.id,
+ linkId,
+ });
+
+ res.setHeader("Set-Cookie", [
+ buildSignedAgreementDownloadCookie({
+ token: downloadCookie.token,
+ maxAgeSeconds: downloadCookie.maxAgeSeconds,
+ secure: process.env.NODE_ENV === "production",
+ }),
+ ]);
+
+ return res.status(200).json({
+ agreementResponseId: existingResponse.id,
+ externalId: existingResponse.signingExternalId,
+ token,
+ ...getSigningEmbedConfig(),
+ });
+ }
+ }
+
+ const updatedAgreementResponse = await prisma.$transaction(async (tx) => {
+ const created = await tx.agreementResponse.create({
+ data: {
+ agreementId: agreement.id,
+ linkId,
+ signerEmail: email ?? null,
+ signerName: name ?? null,
+ },
+ });
+
+ const externalId = buildAgreementResponseSigningExternalId(
+ agreement.teamId,
+ created.id,
+ );
+
+ return tx.agreementResponse.update({
+ where: {
+ id: created.id,
+ },
+ data: {
+ signingExternalId: externalId,
+ },
+ select: {
+ id: true,
+ signingExternalId: true,
+ },
+ });
+ });
+
+ if (!updatedAgreementResponse.signingExternalId) {
+ throw new TeamError("Failed to initialize the signing session.");
+ }
+
+ // Direct-link signing: resolve the template's shared direct-link token; Documenso creates the per-visitor document lazily at completion (stamped with this response's externalId) so `/signing/complete` can bind it back.
+ const { token } = await getAgreementSigningToken({
+ signingTemplateId: agreement.signingTemplateId,
+ });
+
+ const downloadCookie = mintSignedAgreementDownloadToken({
+ agreementResponseId: updatedAgreementResponse.id,
+ linkId,
+ });
+ res.setHeader("Set-Cookie", [
+ buildSignedAgreementDownloadCookie({
+ token: downloadCookie.token,
+ maxAgeSeconds: downloadCookie.maxAgeSeconds,
+ secure: process.env.NODE_ENV === "production",
+ }),
+ ]);
+
+ return res.status(200).json({
+ agreementResponseId: updatedAgreementResponse.id,
+ externalId: updatedAgreementResponse.signingExternalId,
+ token,
+ ...getSigningEmbedConfig(),
+ });
+ } catch (error) {
+ return errorhandler(error, res);
+ }
+}
diff --git a/pages/api/agreements/signing/status.ts b/pages/api/agreements/signing/status.ts
new file mode 100644
index 00000000..f4e70e3c
--- /dev/null
+++ b/pages/api/agreements/signing/status.ts
@@ -0,0 +1,134 @@
+import { NextApiRequest, NextApiResponse } from "next";
+
+import { parse as parseCookieHeader } from "cookie";
+import { z } from "zod";
+
+import { errorhandler } from "@/lib/errorHandler";
+import prisma from "@/lib/prisma";
+import { ratelimit } from "@/lib/redis";
+import {
+ getSignedAgreementAccessCookieName,
+ parseSignedAgreementAccessToken,
+} from "@/lib/signing/access-token";
+import { getSignedAgreementResponseForViewer } from "@/lib/signing/agreements";
+import {
+ SIGNED_DOWNLOAD_COOKIE_NAME,
+ verifySignedAgreementDownloadToken,
+} from "@/lib/signing/download-token";
+import { getIpAddress } from "@/lib/utils/ip";
+
+const signingStatusQuerySchema = z.object({
+ linkId: z.string().min(1, "Link ID is required."),
+ agreementId: z.string().min(1, "Agreement ID is required."),
+ agreementResponseId: z.string().min(1).optional(),
+});
+
+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`);
+ }
+
+ try {
+ const parseResult = signingStatusQuerySchema.safeParse(req.query);
+
+ if (!parseResult.success) {
+ return res.status(200).json({ signed: false });
+ }
+
+ const { linkId, agreementId, agreementResponseId } = parseResult.data;
+
+ const ipAddressValue = getIpAddress(req.headers);
+ const ipLimit = await ratelimit(30, "1 m").limit(
+ `signing-status:ip:${ipAddressValue}`,
+ );
+
+ if (!ipLimit.success) {
+ return res.status(429).json({
+ message: "Too many requests. Please try again in a minute.",
+ });
+ }
+
+ const linkHasAgreement = await prisma.link.findFirst({
+ where: {
+ id: linkId,
+ deletedAt: null,
+ enableAgreement: true,
+ agreementId,
+ },
+ select: {
+ id: true,
+ },
+ });
+
+ if (!linkHasAgreement) {
+ return res.status(200).json({ signed: false });
+ }
+
+ const cookies = parseCookieHeader(req.headers.cookie || "");
+ const accessCookie = cookies[getSignedAgreementAccessCookieName(linkId)];
+ const accessPayload = parseSignedAgreementAccessToken(accessCookie);
+ const signedAccessAgreementResponseId =
+ accessPayload &&
+ accessPayload.linkId === linkId &&
+ accessPayload.agreementId === agreementId
+ ? accessPayload.agreementResponseId
+ : null;
+ let resolvedAgreementResponseId: string | null = null;
+
+ if (signedAccessAgreementResponseId) {
+ resolvedAgreementResponseId = signedAccessAgreementResponseId;
+ } else if (agreementResponseId) {
+ // Honor the hint only with proof of an active signing session (the `pm_sds` cookie); never trust a localStorage hint alone, or a leaked `agreementResponseId` could claim the signed state.
+ const downloadToken = cookies[SIGNED_DOWNLOAD_COOKIE_NAME];
+ const hasPendingSessionProof = verifySignedAgreementDownloadToken(
+ downloadToken,
+ {
+ agreementResponseId,
+ linkId,
+ },
+ );
+
+ if (hasPendingSessionProof) {
+ resolvedAgreementResponseId = agreementResponseId;
+ }
+ }
+
+ if (!resolvedAgreementResponseId) {
+ return res.status(200).json({ signed: false });
+ }
+
+ const signedResponse = await getSignedAgreementResponseForViewer({
+ agreementResponseId: resolvedAgreementResponseId,
+ agreementId,
+ linkId,
+ });
+
+ if (!signedResponse) {
+ return res.status(200).json({ signed: false });
+ }
+
+ const canReturnSignerIdentity =
+ signedAccessAgreementResponseId === signedResponse.id;
+
+ const response = {
+ signed: true,
+ agreementResponseId: signedResponse.id,
+ signingStatus: signedResponse.signingStatus,
+ // Only echo signer identity to the browser holding the post-signing access cookie; the session/download proof can restore signed state but not private identity.
+ signerEmail: canReturnSignerIdentity
+ ? signedResponse.signerEmail
+ : undefined,
+ signerName: canReturnSignerIdentity
+ ? signedResponse.signerName
+ : undefined,
+ };
+
+ return res.status(200).json(response);
+ } catch (error) {
+ return errorhandler(error, res);
+ }
+}
diff --git a/pages/api/file/tus/[[...file]].ts b/pages/api/file/tus/[[...file]].ts
index a007337b..2f8187cb 100644
--- a/pages/api/file/tus/[[...file]].ts
+++ b/pages/api/file/tus/[[...file]].ts
@@ -76,16 +76,33 @@ const tusServer = new Server({
typeof tusError.status_code === "number" &&
typeof tusError.body === "string"
) {
- const errorResponse: TusErrorResponse = {
+ return {
status_code: tusError.status_code,
body: tusError.body,
- };
- return errorResponse;
+ } satisfies TusErrorResponse;
}
}
+ const e = err as
+ | (Error & { cause?: unknown; code?: unknown; $metadata?: unknown })
+ | undefined;
+
+ console.error("[tus] upload error", {
+ url: req.url,
+ method: req.method,
+ name: e?.name,
+ message: e?.message,
+ code: e?.code,
+ cause: e?.cause,
+ awsMetadata: e?.$metadata,
+ stack: e?.stack,
+ });
+
log({
- message: "Error uploading a file. Error: \n\n" + err,
+ message:
+ `Error uploading a file. ${e?.name ?? "Unknown"}: ${e?.message ?? String(err)}` +
+ (e?.code ? ` (code: ${String(e.code)})` : "") +
+ (e?.stack ? `\n\n\`\`\`\n${e.stack}\n\`\`\`` : ""),
type: "error",
});
return { status_code: 500, body: "Internal Server Error" };
@@ -261,6 +278,17 @@ const tusServer = new Server({
return res;
} catch (error) {
+ const e = error as
+ | (Error & { code?: unknown; $metadata?: unknown })
+ | undefined;
+ console.error("[tus] onUploadFinish error", {
+ uploadId: upload.id,
+ name: e?.name,
+ message: e?.message,
+ code: e?.code,
+ awsMetadata: e?.$metadata,
+ stack: e?.stack,
+ });
throw { status_code: 500, body: "Error updating metadata" };
}
},
@@ -270,14 +298,32 @@ export default async function handler(
req: NextApiRequest,
res: NextApiResponse,
) {
- // Get the session
- const session = await getServerSession(req, res, authOptions);
- const userId = (session?.user as CustomUser | undefined)?.id;
- if (!userId) {
- return res.status(401).json({ message: "Unauthorized" });
- }
-
- (req as TusAuthenticatedRequest).papermarkUserId = userId;
+ try {
+ const session = await getServerSession(req, res, authOptions);
+ const userId = (session?.user as CustomUser | undefined)?.id;
+ if (!userId) {
+ return res.status(401).json({ message: "Unauthorized" });
+ }
- return tusServer.handle(req, res);
+ (req as TusAuthenticatedRequest).papermarkUserId = userId;
+
+ return await tusServer.handle(req, res);
+ } catch (error) {
+ const e = error as
+ | (Error & { cause?: unknown; code?: unknown; $metadata?: unknown })
+ | undefined;
+ console.error("[tus] handler crash", {
+ url: req.url,
+ method: req.method,
+ name: e?.name,
+ message: e?.message,
+ code: e?.code,
+ cause: e?.cause,
+ awsMetadata: e?.$metadata,
+ stack: e?.stack,
+ });
+ if (!res.headersSent) {
+ res.status(500).json({ message: "Internal Server Error" });
+ }
+ }
}
diff --git a/pages/api/teams/[teamId]/agreements/[agreementId]/download.ts b/pages/api/teams/[teamId]/agreements/[agreementId]/download.ts
index 4c072e21..503570ab 100644
--- a/pages/api/teams/[teamId]/agreements/[agreementId]/download.ts
+++ b/pages/api/teams/[teamId]/agreements/[agreementId]/download.ts
@@ -53,9 +53,14 @@ export default async function handle(
id: true,
name: true,
content: true,
+ contentType: true,
+ signingProvider: true,
requireName: true,
createdAt: true,
updatedAt: true,
+ signingExternalId: true,
+ signingEnvelopeId: true,
+ signingTemplateId: true,
_count: {
select: {
links: true,
@@ -208,12 +213,21 @@ AGREEMENT DETAILS
================
Name: ${agreement.name}
+Signing Provider: ${agreement.signingProvider}
+Content Type: ${agreement.contentType}
URL: ${agreement.content}
Requires Name: ${agreement.requireName ? "Yes" : "No"}
Created: ${agreement.createdAt.toLocaleDateString()} at ${agreement.createdAt.toLocaleTimeString()}
Last Updated: ${agreement.updatedAt.toLocaleDateString()} at ${agreement.updatedAt.toLocaleTimeString()}
Team: ${team.name}
+SIGNING METADATA
+================
+
+External ID: ${agreement.signingExternalId || "N/A"}
+Envelope ID: ${agreement.signingEnvelopeId || "N/A"}
+Template ID: ${agreement.signingTemplateId || "N/A"}
+
USAGE STATISTICS
===============
diff --git a/pages/api/teams/[teamId]/agreements/[agreementId]/index.ts b/pages/api/teams/[teamId]/agreements/[agreementId]/index.ts
index add7d843..f2f82133 100644
--- a/pages/api/teams/[teamId]/agreements/[agreementId]/index.ts
+++ b/pages/api/teams/[teamId]/agreements/[agreementId]/index.ts
@@ -2,17 +2,126 @@ import { NextApiRequest, NextApiResponse } from "next";
import { authOptions } from "@/pages/api/auth/[...nextauth]";
import { getServerSession } from "next-auth/next";
+import { z } from "zod";
import { errorhandler } from "@/lib/errorHandler";
import prisma from "@/lib/prisma";
import { CustomUser } from "@/lib/types";
+import { validateContent } from "@/lib/utils/sanitize-html";
+
+const updateAgreementSchema = z.object({
+ name: z
+ .string()
+ .min(1, "Name is required")
+ .max(150, "Name must be less than 150 characters")
+ .optional(),
+ content: z
+ .string()
+ .max(1500, "Content must be less than 1500 characters")
+ .optional(),
+ requireName: z.boolean().optional(),
+});
export default async function handle(
req: NextApiRequest,
res: NextApiResponse,
) {
- if (req.method === "PUT") {
- // PUT /api/teams/:teamId/agreements/:agreementId
+ if (req.method === "PATCH") {
+ const session = await getServerSession(req, res, authOptions);
+ if (!session) {
+ res.status(401).end("Unauthorized");
+ return;
+ }
+
+ const userId = (session.user as CustomUser).id;
+ const { teamId, agreementId } = req.query as {
+ teamId: string;
+ agreementId: string;
+ };
+
+ if (!teamId || !agreementId) {
+ return res.status(401).json("Unauthorized");
+ }
+
+ try {
+ const team = await prisma.team.findUnique({
+ where: {
+ id: teamId,
+ users: {
+ some: {
+ userId,
+ },
+ },
+ },
+ select: { id: true },
+ });
+
+ if (!team) {
+ return res.status(401).json("Unauthorized");
+ }
+
+ const parseResult = updateAgreementSchema.safeParse(req.body);
+ if (!parseResult.success) {
+ return res.status(400).json({
+ error: "Invalid request body",
+ details: parseResult.error.flatten().fieldErrors,
+ });
+ }
+
+ const existing = await prisma.agreement.findFirst({
+ where: {
+ id: agreementId,
+ teamId,
+ deletedAt: null,
+ },
+ select: { id: true, contentType: true },
+ });
+
+ if (!existing) {
+ return res.status(404).json({ error: "Agreement not found" });
+ }
+
+ const { name, content, requireName } = parseResult.data;
+
+ const data: {
+ name?: string;
+ content?: string;
+ requireName?: boolean;
+ } = {};
+
+ if (typeof name === "string") {
+ data.name = name.trim();
+ }
+ if (typeof requireName === "boolean") {
+ data.requireName = requireName;
+ }
+ if (typeof content === "string") {
+ if (existing.contentType === "SIGNING") {
+ return res.status(400).json({
+ error:
+ "Signing agreement content is managed through the signing template and cannot be edited here.",
+ });
+ }
+ data.content =
+ existing.contentType === "LINK"
+ ? content.trim()
+ : validateContent(content, 1500);
+ }
+
+ if (Object.keys(data).length === 0) {
+ return res.status(400).json({ error: "No fields to update" });
+ }
+
+ const updated = await prisma.agreement.update({
+ where: { id: agreementId },
+ data,
+ });
+
+ return res.status(200).json(updated);
+ } catch (error) {
+ errorhandler(error, res);
+ }
+ } else if (req.method === "PUT") {
const session = await getServerSession(req, res, authOptions);
if (!session) {
res.status(401).end("Unauthorized");
@@ -44,8 +153,7 @@ export default async function handle(
errorhandler(error, res);
}
} else {
- // We only allow GET and POST requests
- res.setHeader("Allow", ["PUT"]);
+ res.setHeader("Allow", ["PATCH", "PUT"]);
return res.status(405).end(`Method ${req.method} Not Allowed`);
}
}
diff --git a/pages/api/teams/[teamId]/agreements/[agreementId]/responses/[responseId]/download.ts b/pages/api/teams/[teamId]/agreements/[agreementId]/responses/[responseId]/download.ts
new file mode 100644
index 00000000..7e678176
--- /dev/null
+++ b/pages/api/teams/[teamId]/agreements/[agreementId]/responses/[responseId]/download.ts
@@ -0,0 +1,167 @@
+import { NextApiRequest, NextApiResponse } from "next";
+
+import { authOptions } from "@/pages/api/auth/[...nextauth]";
+import { waitUntil } from "@vercel/functions";
+import { getServerSession } from "next-auth/next";
+
+import { TeamError, errorhandler } from "@/lib/errorHandler";
+import { getFile } from "@/lib/files/get-file";
+import prisma from "@/lib/prisma";
+import { getAgreementResponseSignedState } from "@/lib/signing/agreements";
+import { getEnvelopeSignedDownloadUrl } from "@/lib/signing/envelopes";
+import { mirrorSignedAgreementToStorage } from "@/lib/signing/mirror";
+import { buildContentDisposition } from "@/lib/utils";
+import { CustomUser } from "@/lib/types";
+
+// `waitUntil` requires response streaming to be enabled on Pages API routes.
+export const config = {
+ supportsResponseStreaming: true,
+};
+
+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 session = await getServerSession(req, res, authOptions);
+ if (!session) {
+ return res.status(401).end("Unauthorized");
+ }
+
+ const userId = (session.user as CustomUser).id;
+ const { teamId, agreementId, responseId } = req.query as {
+ teamId: string;
+ agreementId: string;
+ responseId: string;
+ };
+
+ if (!teamId || !agreementId || !responseId) {
+ return res.status(400).json({ error: "Missing required parameters" });
+ }
+
+ try {
+ const agreementResponse = await prisma.agreementResponse.findFirst({
+ where: {
+ id: responseId,
+ agreementId,
+ agreement: {
+ teamId,
+ team: {
+ users: {
+ some: {
+ userId,
+ },
+ },
+ },
+ },
+ },
+ select: {
+ id: true,
+ signingStatus: true,
+ signingExternalId: true,
+ signingEnvelopeId: true,
+ signingDocumentId: true,
+ signedFileKey: true,
+ signedFileName: true,
+ signedFileStorageType: true,
+ agreement: {
+ select: {
+ name: true,
+ },
+ },
+ view: {
+ select: {
+ viewerEmail: true,
+ viewerName: true,
+ },
+ },
+ },
+ });
+
+ if (!agreementResponse) {
+ throw new TeamError("Signed agreement was not found.");
+ }
+
+ if (!getAgreementResponseSignedState(agreementResponse.signingStatus)) {
+ throw new TeamError("Signed agreement is not ready yet.");
+ }
+
+ const fallbackName = buildFallbackFilename({
+ agreementName: agreementResponse.agreement.name,
+ viewerName: agreementResponse.view?.viewerName,
+ viewerEmail: agreementResponse.view?.viewerEmail,
+ });
+
+ // Fast path: serve the webhook-mirrored PDF straight from our own storage, with zero Documenso traffic.
+ if (
+ agreementResponse.signedFileKey &&
+ agreementResponse.signedFileStorageType
+ ) {
+ const filename = agreementResponse.signedFileName || fallbackName;
+ const url = await getFile({
+ type: agreementResponse.signedFileStorageType,
+ data: agreementResponse.signedFileKey,
+ isDownload: true,
+ responseContentDisposition: buildContentDisposition(
+ filename,
+ filename,
+ ),
+ });
+ return res.redirect(302, url);
+ }
+
+ if (!agreementResponse.signingEnvelopeId) {
+ throw new TeamError("Signed agreement envelope could not be found.");
+ }
+
+ // Fallback for responses not yet mirrored: a single keyed Documenso call.
+ const { url: downloadUrl } = await getEnvelopeSignedDownloadUrl({
+ envelopeId: agreementResponse.signingEnvelopeId,
+ documentId: agreementResponse.signingDocumentId,
+ });
+
+ // Best-effort mirror so the next click serves from our storage; the user doesn't wait for it.
+ waitUntil(
+ mirrorSignedAgreementToStorage({
+ agreementResponseId: agreementResponse.id,
+ }).catch((error) => {
+ console.error(
+ "[signing] background mirror during download fallback failed",
+ error,
+ );
+ }),
+ );
+
+ // Redirect to the short-lived pre-signed URL instead of streaming bytes back through this function.
+ return res.redirect(302, downloadUrl);
+ } catch (error) {
+ return errorhandler(error, res);
+ }
+}
+
+const sanitizeSegment = (value: string, max: number) =>
+ value
+ .replace(/[^a-z0-9\-_]/gi, "_")
+ .toLowerCase()
+ .substring(0, max);
+
+const buildFallbackFilename = ({
+ agreementName,
+ viewerName,
+ viewerEmail,
+}: {
+ agreementName: string;
+ viewerName?: string | null;
+ viewerEmail?: string | null;
+}) => {
+ const safeName = sanitizeSegment(agreementName, 50) || "agreement";
+ const signerSlug = sanitizeSegment(viewerName || viewerEmail || "", 40);
+
+ return signerSlug
+ ? `${safeName}_signed_${signerSlug}.pdf`
+ : `${safeName}_signed.pdf`;
+};
diff --git a/pages/api/teams/[teamId]/agreements/[agreementId]/responses/index.ts b/pages/api/teams/[teamId]/agreements/[agreementId]/responses/index.ts
new file mode 100644
index 00000000..97bf6ed4
--- /dev/null
+++ b/pages/api/teams/[teamId]/agreements/[agreementId]/responses/index.ts
@@ -0,0 +1,163 @@
+import { NextApiRequest, NextApiResponse } from "next";
+
+import { authOptions } from "@/pages/api/auth/[...nextauth]";
+import { getServerSession } from "next-auth/next";
+
+import { errorhandler } from "@/lib/errorHandler";
+import prisma from "@/lib/prisma";
+import { isSigningAgreement } from "@/lib/signing/agreements";
+import { CustomUser } from "@/lib/types";
+
+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 session = await getServerSession(req, res, authOptions);
+ if (!session) {
+ return res.status(401).end("Unauthorized");
+ }
+
+ const userId = (session.user as CustomUser).id;
+ const { teamId, agreementId } = req.query as {
+ teamId: string;
+ agreementId: string;
+ };
+
+ if (!teamId || !agreementId) {
+ return res.status(400).json({ error: "Missing required parameters" });
+ }
+
+ try {
+ const agreement = await prisma.agreement.findFirst({
+ where: {
+ id: agreementId,
+ teamId,
+ team: {
+ users: {
+ some: {
+ userId,
+ },
+ },
+ },
+ },
+ select: {
+ id: true,
+ name: true,
+ contentType: true,
+ signingProvider: true,
+ signingEnvelopeId: true,
+ signingTemplateId: true,
+ },
+ });
+
+ if (!agreement) {
+ return res.status(404).json({ error: "Agreement not found" });
+ }
+
+ const signing = isSigningAgreement(agreement);
+
+ const responses = await prisma.agreementResponse.findMany({
+ where: {
+ agreementId,
+ ...(signing
+ ? {
+ signingStatus: {
+ in: ["SIGNED", "COMPLETED"],
+ },
+ }
+ : {}),
+ },
+ orderBy: [{ createdAt: "desc" }],
+ select: {
+ id: true,
+ signingStatus: true,
+ signingEnvelopeId: true,
+ signingExternalId: true,
+ signedAt: true,
+ completedAt: true,
+ createdAt: true,
+ linkId: true,
+ signerEmail: true,
+ signerName: true,
+ view: {
+ select: {
+ id: true,
+ viewerEmail: true,
+ viewerName: true,
+ viewedAt: true,
+ linkId: true,
+ link: {
+ select: {
+ id: true,
+ name: true,
+ },
+ },
+ document: {
+ select: {
+ id: true,
+ name: true,
+ },
+ },
+ dataroom: {
+ select: {
+ id: true,
+ name: true,
+ },
+ },
+ },
+ },
+ },
+ });
+
+ // Resolve link names for signed-but-incomplete responses that have no View, only a top-level linkId.
+ const orphanLinkIds = Array.from(
+ new Set(
+ responses
+ .filter((response) => !response.view && response.linkId)
+ .map((response) => response.linkId!)
+ .filter((value): value is string => typeof value === "string"),
+ ),
+ );
+
+ const orphanLinks =
+ orphanLinkIds.length > 0
+ ? await prisma.link.findMany({
+ where: {
+ id: { in: orphanLinkIds },
+ teamId,
+ },
+ select: { id: true, name: true },
+ })
+ : [];
+
+ const orphanLinksById = new Map(
+ orphanLinks.map((link) => [link.id, link]),
+ );
+
+ const responsesWithLink = responses.map((response) => ({
+ ...response,
+ link:
+ response.linkId && !response.view
+ ? orphanLinksById.get(response.linkId) ?? null
+ : null,
+ }));
+
+ return res.status(200).json({
+ agreement: {
+ id: agreement.id,
+ name: agreement.name,
+ contentType: agreement.contentType,
+ signingProvider: agreement.signingProvider,
+ isSigning: signing,
+ },
+ responses: responsesWithLink,
+ });
+ } catch (error) {
+ return errorhandler(error, res);
+ }
+}
diff --git a/pages/api/teams/[teamId]/agreements/[agreementId]/signing/presign.ts b/pages/api/teams/[teamId]/agreements/[agreementId]/signing/presign.ts
new file mode 100644
index 00000000..1dea28b2
--- /dev/null
+++ b/pages/api/teams/[teamId]/agreements/[agreementId]/signing/presign.ts
@@ -0,0 +1,127 @@
+import { NextApiRequest, NextApiResponse } from "next";
+
+import { getServerSession } from "next-auth/next";
+
+import { authOptions } from "@/lib/auth/auth-options";
+import { TeamError, errorhandler } from "@/lib/errorHandler";
+import prisma from "@/lib/prisma";
+import {
+ deleteSigningTemplateDirectLink,
+ ensureSigningTemplateViewerRecipient,
+ getSigningEmbedConfig,
+ isSigningAgreement,
+} from "@/lib/signing/agreements";
+import { getSigningClient } from "@/lib/signing/client";
+import { CustomUser } from "@/lib/types";
+
+export default async function handle(
+ req: NextApiRequest,
+ res: NextApiResponse,
+) {
+ if (req.method !== "POST") {
+ res.setHeader("Allow", ["POST"]);
+ return res.status(405).end(`Method ${req.method} Not Allowed`);
+ }
+
+ const session = await getServerSession(req, res, authOptions);
+
+ if (!session) {
+ return res.status(401).end("Unauthorized");
+ }
+
+ const userId = (session.user as CustomUser).id;
+ const { teamId, agreementId } = req.query as {
+ teamId: string;
+ agreementId: string;
+ };
+
+ try {
+ const agreement = await prisma.agreement.findFirst({
+ where: {
+ id: agreementId,
+ teamId,
+ deletedAt: null,
+ team: {
+ users: {
+ some: {
+ userId,
+ },
+ },
+ },
+ },
+ select: {
+ id: true,
+ signingExternalId: true,
+ signingEnvelopeId: true,
+ signingTemplateId: true,
+ signingProvider: true,
+ contentType: true,
+ _count: {
+ select: {
+ responses: {
+ where: {
+ signingStatus: {
+ in: ["SIGNED", "COMPLETED"],
+ },
+ },
+ },
+ },
+ },
+ },
+ });
+
+ if (!agreement) {
+ throw new TeamError("Agreement not found.");
+ }
+
+ if (!isSigningAgreement(agreement)) {
+ throw new TeamError(
+ "Only embedded signing agreements can launch authoring.",
+ );
+ }
+
+ if (!agreement.signingEnvelopeId) {
+ throw new TeamError(
+ "This signing agreement is missing its template. Please create a new signing agreement.",
+ );
+ }
+
+ if (!agreement.signingTemplateId) {
+ throw new TeamError(
+ "This signing agreement is missing its numeric template id. Please re-upload the agreement.",
+ );
+ }
+
+ if (agreement._count.responses > 0) {
+ throw new TeamError(
+ "Signing fields cannot be edited after signatures have been collected.",
+ );
+ }
+
+ await deleteSigningTemplateDirectLink({
+ signingTemplateId: agreement.signingTemplateId,
+ });
+
+ await ensureSigningTemplateViewerRecipient({
+ envelopeId: agreement.signingEnvelopeId,
+ });
+
+ const signingClient = getSigningClient();
+ const presignToken =
+ await signingClient.embedding.embeddingPresignCreateEmbeddingPresignToken(
+ {
+ expiresIn: 3600,
+ },
+ );
+
+ return res.status(200).json({
+ presignToken: presignToken.token,
+ expiresAt: presignToken.expiresAt,
+ externalId: agreement.signingExternalId,
+ envelopeId: agreement.signingEnvelopeId,
+ ...getSigningEmbedConfig(),
+ });
+ } catch (error) {
+ return errorhandler(error, res);
+ }
+}
diff --git a/pages/api/teams/[teamId]/agreements/[agreementId]/signing/setup-status.ts b/pages/api/teams/[teamId]/agreements/[agreementId]/signing/setup-status.ts
new file mode 100644
index 00000000..1bb31160
--- /dev/null
+++ b/pages/api/teams/[teamId]/agreements/[agreementId]/signing/setup-status.ts
@@ -0,0 +1,144 @@
+import { NextApiRequest, NextApiResponse } from "next";
+
+import { runs } from "@trigger.dev/sdk";
+import { getServerSession } from "next-auth/next";
+import { z } from "zod";
+
+import { authOptions } from "@/lib/auth/auth-options";
+import { TeamError, errorhandler } from "@/lib/errorHandler";
+import prisma from "@/lib/prisma";
+import {
+ getSigningEmbedConfig,
+ isSigningAgreement,
+} from "@/lib/signing/agreements";
+import { getSigningClient } from "@/lib/signing/client";
+import { CustomUser } from "@/lib/types";
+
+const setupStatusQuerySchema = z.object({
+ runId: z.string().min(1),
+});
+
+const setupTaskOutputSchema = z.object({
+ externalId: z.string().nullable(),
+ envelopeId: z.string().min(1),
+ templateId: z.string().min(1),
+});
+
+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 session = await getServerSession(req, res, authOptions);
+
+ if (!session) {
+ return res.status(401).end("Unauthorized");
+ }
+
+ const userId = (session.user as CustomUser).id;
+ const { teamId, agreementId } = req.query as {
+ teamId: string;
+ agreementId: string;
+ };
+
+ try {
+ const parseResult = setupStatusQuerySchema.safeParse(req.query);
+
+ if (!parseResult.success) {
+ throw new TeamError("A valid signing setup run ID is required.");
+ }
+
+ const agreement = await prisma.agreement.findFirst({
+ where: {
+ id: agreementId,
+ teamId,
+ deletedAt: null,
+ team: {
+ users: {
+ some: {
+ userId,
+ },
+ },
+ },
+ },
+ select: {
+ id: true,
+ contentType: true,
+ signingProvider: true,
+ },
+ });
+
+ if (!agreement) {
+ throw new TeamError("Agreement not found.");
+ }
+
+ if (!isSigningAgreement(agreement)) {
+ throw new TeamError(
+ "Only embedded signing agreements can check signing setup.",
+ );
+ }
+
+ const run = await runs.retrieve(parseResult.data.runId);
+ const metadata = run.metadata as Record<string, unknown> | undefined;
+
+ if (metadata?.teamId !== teamId || metadata?.agreementId !== agreement.id) {
+ return res.status(403).end("Unauthorized");
+ }
+
+ if (run.isFailed) {
+ console.error("[signing] setup task failed", {
+ agreementId,
+ teamId,
+ runId: run.id,
+ status: run.status,
+ });
+ return res
+ .status(500)
+ .end("Failed to start the signing template authoring flow.");
+ }
+
+ if (!run.isCompleted) {
+ return res.status(202).json({
+ runId: run.id,
+ status: run.status,
+ metadata: run.metadata,
+ });
+ }
+
+ const output = setupTaskOutputSchema.safeParse(run.output);
+
+ if (!output.success) {
+ console.error("[signing] setup task returned invalid output", {
+ agreementId,
+ teamId,
+ runId: run.id,
+ issues: output.error.issues,
+ });
+ throw new TeamError(
+ "Signing setup completed with invalid provider metadata.",
+ );
+ }
+
+ const signingClient = getSigningClient();
+ const presignToken =
+ await signingClient.embedding.embeddingPresignCreateEmbeddingPresignToken(
+ {
+ expiresIn: 3600,
+ },
+ );
+
+ return res.status(200).json({
+ presignToken: presignToken.token,
+ expiresAt: presignToken.expiresAt,
+ externalId: output.data.externalId,
+ envelopeId: output.data.envelopeId,
+ ...getSigningEmbedConfig(),
+ });
+ } catch (error) {
+ return errorhandler(error, res);
+ }
+}
diff --git a/pages/api/teams/[teamId]/agreements/[agreementId]/signing/setup.ts b/pages/api/teams/[teamId]/agreements/[agreementId]/signing/setup.ts
new file mode 100644
index 00000000..bbf1c602
--- /dev/null
+++ b/pages/api/teams/[teamId]/agreements/[agreementId]/signing/setup.ts
@@ -0,0 +1,167 @@
+import { NextApiRequest, NextApiResponse } from "next";
+
+import { DocumentStorageType } from "@prisma/client";
+import { auth } from "@trigger.dev/sdk";
+import { getServerSession } from "next-auth/next";
+import { z } from "zod";
+
+import { authOptions } from "@/lib/auth/auth-options";
+import { TeamError, errorhandler } from "@/lib/errorHandler";
+import prisma from "@/lib/prisma";
+import { isSigningAgreement } from "@/lib/signing/agreements";
+import {
+ MAX_SIGNING_TEMPLATE_PDF_BYTES,
+ SIGNING_TEMPLATE_PDF_CONTENT_TYPE,
+ getSigningTemplateTooLargeMessage,
+} from "@/lib/signing/template-upload";
+import { setupSigningTemplateTask } from "@/lib/trigger/setup-signing-template";
+import { CustomUser } from "@/lib/types";
+
+export const config = {
+ maxDuration: 60,
+};
+
+const setupSigningTemplateSchema = z.object({
+ fileName: z.string().trim().min(1).optional(),
+ contentType: z.literal(SIGNING_TEMPLATE_PDF_CONTENT_TYPE),
+ file: z.object({
+ data: z.string().min(1),
+ storageType: z.nativeEnum(DocumentStorageType),
+ fileSize: z.number().int().positive(),
+ }),
+});
+
+const sanitizeFileName = (raw: string | undefined | null) => {
+ const fallback = "agreement.pdf";
+
+ if (!raw) {
+ return fallback;
+ }
+
+ try {
+ const decoded = decodeURIComponent(raw);
+ const trimmed = decoded.trim().replace(/[\r\n]+/g, " ");
+ return trimmed.length > 0 ? trimmed : fallback;
+ } catch {
+ return fallback;
+ }
+};
+
+export default async function handle(
+ req: NextApiRequest,
+ res: NextApiResponse,
+) {
+ if (req.method !== "POST") {
+ res.setHeader("Allow", ["POST"]);
+ return res.status(405).end(`Method ${req.method} Not Allowed`);
+ }
+
+ const session = await getServerSession(req, res, authOptions);
+
+ if (!session) {
+ return res.status(401).end("Unauthorized");
+ }
+
+ const userId = (session.user as CustomUser).id;
+ const { teamId, agreementId } = req.query as {
+ teamId: string;
+ agreementId: string;
+ };
+
+ try {
+ const parseResult = setupSigningTemplateSchema.safeParse(req.body);
+
+ if (!parseResult.success) {
+ throw new TeamError(
+ "Upload the agreement as a PDF before starting signing setup.",
+ );
+ }
+
+ const setupRequest = parseResult.data;
+
+ if (setupRequest.file.fileSize > MAX_SIGNING_TEMPLATE_PDF_BYTES) {
+ throw new TeamError(getSigningTemplateTooLargeMessage());
+ }
+
+ const agreement = await prisma.agreement.findFirst({
+ where: {
+ id: agreementId,
+ teamId,
+ deletedAt: null,
+ team: {
+ users: {
+ some: {
+ userId,
+ },
+ },
+ },
+ },
+ select: {
+ id: true,
+ name: true,
+ contentType: true,
+ signingProvider: true,
+ signingExternalId: true,
+ signingEnvelopeId: true,
+ },
+ });
+
+ if (!agreement) {
+ throw new TeamError("Agreement not found.");
+ }
+
+ if (!isSigningAgreement(agreement)) {
+ throw new TeamError(
+ "Only embedded signing agreements can attach a PDF template.",
+ );
+ }
+
+ if (agreement.signingEnvelopeId) {
+ throw new TeamError(
+ "This agreement is already linked to a signing template.",
+ );
+ }
+
+ const fileName = sanitizeFileName(setupRequest.fileName);
+
+ const run = await setupSigningTemplateTask.trigger(
+ {
+ agreementId: agreement.id,
+ teamId,
+ file: {
+ fileName,
+ data: setupRequest.file.data,
+ storageType: setupRequest.file.storageType,
+ fileSize: setupRequest.file.fileSize,
+ },
+ },
+ {
+ idempotencyKey: `${teamId}-${agreement.id}-signing-template-setup`,
+ tags: [`team_${teamId}`, `agreement_${agreement.id}`],
+ concurrencyKey: teamId,
+ metadata: {
+ teamId,
+ agreementId: agreement.id,
+ userId,
+ },
+ },
+ );
+
+ // Read-only token so the client can follow setup via Trigger.dev Realtime instead of polling.
+ const publicAccessToken = await auth.createPublicToken({
+ scopes: {
+ read: {
+ runs: [run.id],
+ },
+ },
+ expirationTime: "15m",
+ });
+
+ return res.status(202).json({
+ runId: run.id,
+ publicAccessToken,
+ });
+ } catch (error) {
+ return errorhandler(error, res);
+ }
+}
diff --git a/pages/api/teams/[teamId]/agreements/[agreementId]/signing/sync.ts b/pages/api/teams/[teamId]/agreements/[agreementId]/signing/sync.ts
new file mode 100644
index 00000000..274a041e
--- /dev/null
+++ b/pages/api/teams/[teamId]/agreements/[agreementId]/signing/sync.ts
@@ -0,0 +1,201 @@
+import { NextApiRequest, NextApiResponse } from "next";
+
+import { getServerSession } from "next-auth/next";
+import { z } from "zod";
+
+import { TeamError, errorhandler } from "@/lib/errorHandler";
+import prisma from "@/lib/prisma";
+import {
+ deleteSigningTemplateDirectLink,
+ ensureSigningTemplateDirectLink,
+ ensureSigningTemplateViewerRecipient,
+ ensureTeamSigningFolders,
+ isSigningAgreement,
+} from "@/lib/signing/agreements";
+import { getSigningClient } from "@/lib/signing/client";
+import { getEnvelope } from "@/lib/signing/envelopes";
+import { CustomUser } from "@/lib/types";
+
+import { authOptions } from "../../../../../auth/[...nextauth]";
+
+const syncAgreementSchema = z.object({
+ envelopeId: z.string().min(1, "Envelope ID is required."),
+});
+
+export default async function handle(
+ req: NextApiRequest,
+ res: NextApiResponse,
+) {
+ if (req.method !== "POST") {
+ res.setHeader("Allow", ["POST"]);
+ return res.status(405).end(`Method ${req.method} Not Allowed`);
+ }
+
+ const session = await getServerSession(req, res, authOptions);
+
+ if (!session) {
+ return res.status(401).end("Unauthorized");
+ }
+
+ const userId = (session.user as CustomUser).id;
+ const { teamId, agreementId } = req.query as {
+ teamId: string;
+ agreementId: string;
+ };
+
+ try {
+ const parseResult = syncAgreementSchema.safeParse(req.body);
+
+ if (!parseResult.success) {
+ console.warn("[signing] sync schema parse failed", {
+ issues: parseResult.error.issues,
+ });
+ throw new TeamError("A valid signing envelope ID is required.");
+ }
+
+ const agreement = await prisma.agreement.findFirst({
+ where: {
+ id: agreementId,
+ teamId,
+ deletedAt: null,
+ team: {
+ users: {
+ some: {
+ userId,
+ },
+ },
+ },
+ },
+ select: {
+ id: true,
+ name: true,
+ signingProvider: true,
+ signingExternalId: true,
+ signingEnvelopeId: true,
+ signingTemplateId: true,
+ contentType: true,
+ },
+ });
+
+ if (!agreement) {
+ throw new TeamError("Agreement not found.");
+ }
+
+ if (!isSigningAgreement(agreement)) {
+ throw new TeamError(
+ "Only embedded signing agreements can sync provider metadata.",
+ );
+ }
+
+ // Only sync the envelope already bound to this agreement; never trust an arbitrary request envelopeId that could attach an unrelated template.
+ if (
+ !agreement.signingEnvelopeId ||
+ agreement.signingEnvelopeId !== parseResult.data.envelopeId
+ ) {
+ console.warn("[signing] sync rejected unbound envelope", {
+ agreementId,
+ requestedEnvelopeId: parseResult.data.envelopeId,
+ boundEnvelopeId: agreement.signingEnvelopeId,
+ });
+ throw new TeamError(
+ "This signing envelope is not bound to the agreement.",
+ );
+ }
+
+ // Single keyed envelope lookup instead of a separate get plus paginated find.
+ const signingClient = getSigningClient();
+ const envelope = await getEnvelope(parseResult.data.envelopeId);
+
+ if (envelope.type !== "TEMPLATE") {
+ console.warn("[signing] sync rejected non-TEMPLATE envelope", {
+ envelopeId: envelope.id,
+ type: envelope.type,
+ status: envelope.status,
+ });
+ throw new TeamError(
+ "Signing envelopes must be templates before they can be attached to an agreement.",
+ );
+ }
+
+ // Stored signingTemplateId is the source of truth (TEMPLATE envelopes report null); fall back to the envelope only if it carries one.
+ const templateId =
+ agreement.signingTemplateId ??
+ (envelope.templateId ? String(envelope.templateId) : null);
+
+ if (!templateId) {
+ throw new TeamError(
+ "Agreement is missing the numeric signing template id. Re-upload the agreement to fix this.",
+ );
+ }
+
+ await deleteSigningTemplateDirectLink({
+ signingTemplateId: templateId,
+ });
+
+ await ensureSigningTemplateViewerRecipient({
+ envelopeId: envelope.id,
+ });
+
+ let templateFolderId: string | null = null;
+ try {
+ ({ templateFolderId } = await ensureTeamSigningFolders(teamId));
+ } catch (folderError) {
+ // Folder placement is best-effort: never block envelope sync on it.
+ console.error(
+ "[signing] Failed to ensure team signing folders during sync.",
+ folderError,
+ );
+ }
+
+ const shouldUpdateFolder =
+ templateFolderId !== null && envelope.folderId !== templateFolderId;
+
+ await signingClient.envelopes.update({
+ envelopeId: envelope.id,
+ data: {
+ title: agreement.name,
+ externalId: agreement.signingExternalId,
+ ...(shouldUpdateFolder ? { folderId: templateFolderId } : {}),
+ },
+ meta: {
+ subject: agreement.name,
+ distributionMethod: "NONE",
+ emailSettings: {
+ recipientSigningRequest: false,
+ recipientRemoved: false,
+ recipientSigned: false,
+ documentPending: false,
+ documentCompleted: false,
+ documentDeleted: false,
+ ownerDocumentCompleted: false,
+ ownerRecipientExpired: false,
+ ownerDocumentCreated: false,
+ },
+ },
+ });
+
+ // Mint the direct link once the template is saved; idempotent, so re-runs return the existing token.
+ await ensureSigningTemplateDirectLink({
+ signingTemplateId: templateId,
+ });
+
+ const updatedAgreement = await prisma.agreement.update({
+ where: {
+ id: agreementId,
+ },
+ data: {
+ signingEnvelopeId: envelope.id,
+ signingTemplateId: templateId,
+ },
+ });
+
+ return res.status(200).json(updatedAgreement);
+ } catch (error) {
+ console.error("[signing] sync handler error", {
+ agreementId,
+ teamId,
+ message: error instanceof Error ? error.message : String(error),
+ });
+ return errorhandler(error, res);
+ }
+}
diff --git a/pages/api/teams/[teamId]/agreements/index.ts b/pages/api/teams/[teamId]/agreements/index.ts
index bb80bcd4..4f7f0940 100644
--- a/pages/api/teams/[teamId]/agreements/index.ts
+++ b/pages/api/teams/[teamId]/agreements/index.ts
@@ -5,6 +5,10 @@ import { z } from "zod";
import { errorhandler } from "@/lib/errorHandler";
import prisma from "@/lib/prisma";
+import {
+ buildAgreementSigningExternalId,
+ getSigningAgreementCreateData,
+} from "@/lib/signing/agreements";
import { CustomUser } from "@/lib/types";
import { log } from "@/lib/utils";
import { validateContent } from "@/lib/utils/sanitize-html";
@@ -12,18 +16,28 @@ import { validateContent } from "@/lib/utils/sanitize-html";
import { authOptions } from "../../../auth/[...nextauth]";
// Zod schema for agreement creation
-const createAgreementSchema = z.object({
- name: z
- .string()
- .min(1, "Name is required")
- .max(150, "Name must be less than 150 characters"),
- content: z
- .string()
- .min(1, "Content is required")
- .max(1500, "Content must be less than 1500 characters"),
- contentType: z.enum(["LINK", "TEXT"]).default("LINK"),
- requireName: z.boolean().default(false),
-});
+const createAgreementSchema = z
+ .object({
+ name: z
+ .string()
+ .min(1, "Name is required")
+ .max(150, "Name must be less than 150 characters"),
+ content: z
+ .string()
+ .max(1500, "Content must be less than 1500 characters")
+ .optional(),
+ contentType: z.enum(["LINK", "TEXT", "SIGNING"]).default("SIGNING"),
+ requireName: z.boolean().default(false),
+ })
+ .superRefine((data, ctx) => {
+ if (data.contentType !== "SIGNING" && !data.content?.trim()) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: "Content is required",
+ path: ["content"],
+ });
+ }
+ });
export default async function handle(
req: NextApiRequest,
@@ -59,6 +73,13 @@ export default async function handle(
deletedAt: null,
},
},
+ responses: {
+ where: {
+ signingStatus: {
+ in: ["SIGNED", "COMPLETED"],
+ },
+ },
+ },
},
},
},
@@ -117,17 +138,37 @@ export default async function handle(
const { name, content, contentType, requireName } = parseResult.data;
- // Sanitize content using existing sanitization logic
- const sanitizedContent = validateContent(content, 1500);
+ const sanitizedContent =
+ contentType === "SIGNING"
+ ? content?.trim()
+ : validateContent(content || "", 1500);
+
+ const agreement = await prisma.$transaction(async (tx) => {
+ const created = await tx.agreement.create({
+ data: getSigningAgreementCreateData({
+ teamId,
+ name,
+ content: sanitizedContent,
+ contentType,
+ requireName,
+ }),
+ });
- const agreement = await prisma.agreement.create({
- data: {
- teamId,
- name: name.trim(),
- content: sanitizedContent,
- contentType: contentType || "LINK",
- requireName,
- },
+ if (contentType === "SIGNING") {
+ return tx.agreement.update({
+ where: {
+ id: created.id,
+ },
+ data: {
+ signingExternalId: buildAgreementSigningExternalId(
+ teamId,
+ created.id,
+ ),
+ },
+ });
+ }
+
+ return created;
});
return res.status(201).json(agreement);
diff --git a/pages/api/teams/[teamId]/datarooms/[id]/views/index.ts b/pages/api/teams/[teamId]/datarooms/[id]/views/index.ts
index 720458c8..02ac62d3 100644
--- a/pages/api/teams/[teamId]/datarooms/[id]/views/index.ts
+++ b/pages/api/teams/[teamId]/datarooms/[id]/views/index.ts
@@ -76,9 +76,14 @@ export default async function handle(
select: {
id: true,
agreementId: true,
+ signingStatus: true,
+ signedAt: true,
+ completedAt: true,
agreement: {
select: {
name: true,
+ contentType: true,
+ signingProvider: true,
},
},
},
diff --git a/pages/api/teams/[teamId]/documents/[id]/views/index.ts b/pages/api/teams/[teamId]/documents/[id]/views/index.ts
index e8f7cbf3..150f5ec8 100644
--- a/pages/api/teams/[teamId]/documents/[id]/views/index.ts
+++ b/pages/api/teams/[teamId]/documents/[id]/views/index.ts
@@ -49,7 +49,14 @@ type ViewWithExtras = View & {
agreementResponse: {
id: string;
agreementId: string;
- agreement: { name: string };
+ signingStatus: string;
+ signedAt: Date | null;
+ completedAt: Date | null;
+ agreement: {
+ name: string;
+ contentType: string;
+ signingProvider: string;
+ };
} | null;
};
@@ -301,9 +308,14 @@ export default async function handle(
select: {
id: true,
agreementId: true,
+ signingStatus: true,
+ signedAt: true,
+ completedAt: true,
agreement: {
select: {
name: true,
+ contentType: true,
+ signingProvider: true,
},
},
},
diff --git a/pages/settings/agreements.tsx b/pages/settings/agreements.tsx
index 773b0d9d..8ac6d9de 100644
--- a/pages/settings/agreements.tsx
+++ b/pages/settings/agreements.tsx
@@ -1,11 +1,14 @@
-import { useMemo, useState } from "react";
+import { useCallback, useMemo, useState } from "react";
import { useTeam } from "@/context/team-context";
import { PlanEnum } from "@/ee/stripe/constants";
import { CircleHelpIcon, FileTextIcon, PlusIcon } from "lucide-react";
import { mutate } from "swr";
-import { useAgreements } from "@/lib/swr/use-agreements";
+import {
+ AgreementWithLinksCount,
+ useAgreements,
+} from "@/lib/swr/use-agreements";
import { usePlan } from "@/lib/swr/use-billing";
import AgreementCard from "@/components/agreements/agreement-card";
@@ -29,17 +32,55 @@ export default function NdaAgreements() {
const { isTrial, isBusiness, isDatarooms, isDataroomsPlus } = usePlan();
const [isOpen, setIsOpen] = useState<boolean>(false);
+ const [editingAgreement, setEditingAgreement] =
+ useState<AgreementWithLinksCount | null>(null);
const activeAgreements = useMemo(() => {
return agreements?.filter((agreement) => !agreement.deletedAt) || [];
}, [agreements]);
- const handleAgreementDeletion = (deletedAgreementId: string) => {
- mutate(
- `/api/teams/${teamInfo?.currentTeam?.id}/agreements`,
- agreements?.filter((agreement) => agreement.id !== deletedAgreementId),
- false,
- );
+ const displayedAgreements = useMemo(
+ () => [...activeAgreements].reverse(),
+ [activeAgreements],
+ );
+
+ const teamId = teamInfo?.currentTeam?.id;
+
+ const handleAgreementDeletion = useCallback(
+ (deletedAgreementId: string) => {
+ mutate(
+ `/api/teams/${teamId}/agreements`,
+ (current?: AgreementWithLinksCount[]) =>
+ current?.filter((agreement) => agreement.id !== deletedAgreementId),
+ false,
+ );
+ },
+ [teamId],
+ );
+
+ const handleAgreementEdit = useCallback(
+ (agreement: AgreementWithLinksCount) => {
+ setEditingAgreement(agreement);
+ setIsOpen(true);
+ },
+ [],
+ );
+
+ const handleSheetOpenChange: React.Dispatch<
+ React.SetStateAction<boolean>
+ > = (value) => {
+ setIsOpen((prev) => {
+ const next = typeof value === "function" ? value(prev) : value;
+ if (!next) {
+ setEditingAgreement(null);
+ }
+ return next;
+ });
+ };
+
+ const handleCreateNew = () => {
+ setEditingAgreement(null);
+ setIsOpen(true);
};
return (
@@ -67,7 +108,7 @@ export default function NdaAgreements() {
</div>
<ul className="flex items-center justify-between gap-4">
{isTrial || isBusiness || isDatarooms || isDataroomsPlus ? (
- <Button variant="outline" onClick={() => setIsOpen(true)}>
+ <Button variant="outline" onClick={handleCreateNew}>
<FileTextIcon className="h-4 w-4" />
Create agreement
</Button>
@@ -98,11 +139,12 @@ export default function NdaAgreements() {
) : activeAgreements.length !== 0 ? (
<div>
<ul>
- {[...activeAgreements].reverse().map((agreement) => (
+ {displayedAgreements.map((agreement) => (
<li key={agreement.id} className="mt-4">
<AgreementCard
agreement={agreement}
onDelete={handleAgreementDeletion}
+ onEdit={handleAgreementEdit}
/>
</li>
))}
@@ -120,7 +162,7 @@ export default function NdaAgreements() {
</p>
</div>
{(isTrial || isBusiness || isDatarooms || isDataroomsPlus) && (
- <Button variant="outline" onClick={() => setIsOpen(true)}>
+ <Button variant="outline" onClick={handleCreateNew}>
<FileTextIcon className="h-4 w-4" />
Create NDA agreement
</Button>
@@ -129,7 +171,11 @@ export default function NdaAgreements() {
)}
</div>
</main>
- <AgreementSheet isOpen={isOpen} setIsOpen={setIsOpen} />
+ <AgreementSheet
+ isOpen={isOpen}
+ setIsOpen={handleSheetOpenChange}
+ editAgreement={editingAgreement}
+ />
</AppLayout>
);
}
diff --git a/prisma/migrations/20260312000000_add_documenso_agreements/migration.sql b/prisma/migrations/20260312000000_add_documenso_agreements/migration.sql
new file mode 100644
index 00000000..e66b3d8b
--- /dev/null
+++ b/prisma/migrations/20260312000000_add_documenso_agreements/migration.sql
@@ -0,0 +1,36 @@
+-- AlterTable
+ALTER TABLE "Agreement"
+ADD COLUMN "signingProvider" TEXT NOT NULL DEFAULT 'LEGACY',
+ADD COLUMN "signingExternalId" TEXT,
+ADD COLUMN "signingEnvelopeId" TEXT,
+ADD COLUMN "signingTemplateId" TEXT;
+
+-- AlterTable
+ALTER TABLE "AgreementResponse"
+ALTER COLUMN "viewId" DROP NOT NULL,
+ADD COLUMN "signingStatus" TEXT NOT NULL DEFAULT 'PENDING',
+ADD COLUMN "signingExternalId" TEXT,
+ADD COLUMN "signingEnvelopeId" TEXT,
+ADD COLUMN "signedAt" TIMESTAMP(3),
+ADD COLUMN "completedAt" TIMESTAMP(3),
+ADD COLUMN "linkId" TEXT,
+ADD COLUMN "signerEmail" TEXT,
+ADD COLUMN "signerName" TEXT,
+ADD COLUMN "signingDocumentId" INTEGER,
+ADD COLUMN "signedFileKey" TEXT,
+ADD COLUMN "signedFileName" TEXT,
+ADD COLUMN "signedFileStorageType" "DocumentStorageType";
+
+-- CreateIndex
+CREATE UNIQUE INDEX "Agreement_signingExternalId_key"
+ON "Agreement"("signingExternalId");
+
+-- CreateIndex
+CREATE UNIQUE INDEX "AgreementResponse_signingExternalId_key"
+ON "AgreementResponse"("signingExternalId");
+
+-- CreateIndex
+CREATE INDEX "AgreementResponse_linkId_idx" ON "AgreementResponse"("linkId");
+
+-- CreateIndex
+CREATE INDEX "AgreementResponse_signerEmail_idx" ON "AgreementResponse"("signerEmail");
diff --git a/prisma/schema/schema.prisma b/prisma/schema/schema.prisma
index acb760e8..f5e49771 100644
--- a/prisma/schema/schema.prisma
+++ b/prisma/schema/schema.prisma
@@ -369,10 +369,15 @@ model FeedbackResponse {
}
model Agreement {
- id String @id @default(cuid())
- name String // Easily identifiable name for the agreement
- content String // This will store the agreement content (URL or text)
- contentType String @default("LINK") // "LINK" or "TEXT" - determines how content should be displayed
+ id String @id @default(cuid())
+ name String // Easily identifiable name for the agreement
+ content String // This will store the agreement content (URL or text)
+ contentType String @default("LINK") // "LINK" or "TEXT" - determines how content should be displayed
+ signingProvider String @default("LEGACY")
+
+ signingExternalId String? @unique
+ signingEnvelopeId String?
+ signingTemplateId String?
links Link[]
responses AgreementResponse[]
@@ -395,14 +400,35 @@ model AgreementResponse {
id String @id @default(cuid())
agreementId String
agreement Agreement @relation(fields: [agreementId], references: [id], onDelete: Cascade)
- viewId String @unique
- view View @relation(fields: [viewId], references: [id], onDelete: Cascade)
+ viewId String? @unique
+ view View? @relation(fields: [viewId], references: [id], onDelete: Cascade)
+
+ linkId String?
+
+ signerEmail String?
+ signerName String?
+
+ signingStatus String @default("PENDING")
+ signingExternalId String? @unique
+ signingEnvelopeId String?
+ signingDocumentId Int?
+ signedAt DateTime?
+ completedAt DateTime?
+
+ // Papermark-side mirror of the signed PDF. Populated by the signing webhook
+ // once the document is final so downloads can be served from our own storage
+ // without depending on Documenso's uptime.
+ signedFileKey String?
+ signedFileName String?
+ signedFileStorageType DocumentStorageType?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@index([agreementId])
@@index([viewId])
+ @@index([linkId])
+ @@index([signerEmail])
}
model IncomingWebhook {