Merge branch 'main' into fix/name-input-invalid-characters

This commit is contained in:
Catalin Pit
2026-06-25 08:29:40 +03:00
committed by GitHub
272 changed files with 16244 additions and 2563 deletions
@@ -3,7 +3,7 @@ import { getEnvelopeById } from '@documenso/lib/server-only/envelope/get-envelop
import { getPresignGetUrl } from '@documenso/lib/universal/upload/server-actions';
import { isDocumentCompleted } from '@documenso/lib/utils/document';
import type { DocumentData } from '@prisma/client';
import { DocumentDataType, EnvelopeType } from '@prisma/client';
import { DocumentDataType, DocumentStatus, EnvelopeType } from '@prisma/client';
import { authenticatedProcedure } from '../trpc';
import {
@@ -58,7 +58,12 @@ export const downloadDocumentBetaRoute = authenticatedProcedure
});
}
if (version === 'signed' && !isDocumentCompleted(envelope.status)) {
// A cancelled document was never sealed, so its data is the unsigned original.
// Treat it as not-completed here so a "signed" version is never served for it.
// REJECTED and COMPLETED keep their prior behavior.
const hasSignedArtifact = isDocumentCompleted(envelope.status) && envelope.status !== DocumentStatus.CANCELLED;
if (version === 'signed' && !hasSignedArtifact) {
throw new AppError(AppErrorCode.INVALID_REQUEST, {
message: 'Document is not completed yet.',
});
@@ -4,7 +4,7 @@ import { getEnvelopeWhereInput } from '@documenso/lib/server-only/envelope/get-e
import { generateCertificatePdf } from '@documenso/lib/server-only/pdf/generate-certificate-pdf';
import { isDocumentCompleted } from '@documenso/lib/utils/document';
import { prisma } from '@documenso/prisma';
import { EnvelopeType } from '@prisma/client';
import { DocumentStatus, EnvelopeType } from '@prisma/client';
import { authenticatedProcedure } from '../trpc';
import {
@@ -60,7 +60,9 @@ export const downloadDocumentCertificateRoute = authenticatedProcedure
});
}
if (!isDocumentCompleted(envelope.status)) {
// A cancelled document was never sealed/completed, so a signing certificate
// must not be generated for it. REJECTED and COMPLETED keep their prior behavior.
if (!isDocumentCompleted(envelope.status) || envelope.status === DocumentStatus.CANCELLED) {
throw new AppError('DOCUMENT_NOT_COMPLETE');
}
@@ -19,6 +19,7 @@ export const ZFindDocumentsInternalResponseSchema = ZFindResultResponse.extend({
[ExtendedDocumentStatus.PENDING]: z.number(),
[ExtendedDocumentStatus.COMPLETED]: z.number(),
[ExtendedDocumentStatus.REJECTED]: z.number(),
[ExtendedDocumentStatus.CANCELLED]: z.number(),
[ExtendedDocumentStatus.INBOX]: z.number(),
[ExtendedDocumentStatus.ALL]: z.number(),
}),
@@ -0,0 +1,43 @@
import { executeTspSign } from '@documenso/ee/server-only/signing/csc/execute-tsp-sign';
import { AppError, AppErrorCode } from '@documenso/lib/errors/app-error';
import { procedure } from '../trpc';
import { ZCscSignEnvelopeRequestSchema, ZCscSignEnvelopeResponseSchema } from './csc-sign-envelope.types';
/**
* Internal mutation that drives the CSC TSP sign-time pipeline.
*
* `executeTspSign` does the heavy lifting (capture → batched signHash →
* embed → tx). This route wraps it in a 15s `Promise.race` so an unresponsive
* TSP surfaces as `CSC_TSP_TIMEOUT` instead of hanging the request. The
* idle-timer is a soft cap on TSP round-trip latency; the underlying tx
* keeps running on the server until it completes or errors.
*/
const SIGN_TIMEOUT_MS = 15_000;
export const cscSignEnvelopeRoute = procedure
.input(ZCscSignEnvelopeRequestSchema)
.output(ZCscSignEnvelopeResponseSchema)
.mutation(async ({ input, ctx }) => {
const result = await Promise.race([
executeTspSign({
sessionId: input.sessionId,
recipientToken: input.recipientToken,
requestMetadata: ctx.metadata.requestMetadata,
}),
new Promise<never>((_, reject) =>
setTimeout(
() =>
reject(
new AppError(AppErrorCode.CSC_TSP_TIMEOUT, {
message: 'CSC TSP did not respond within 15s.',
}),
),
SIGN_TIMEOUT_MS,
),
),
]);
return result;
});
@@ -0,0 +1,13 @@
import { z } from 'zod';
export const ZCscSignEnvelopeRequestSchema = z.object({
recipientToken: z.string().min(1),
sessionId: z.string().min(1),
});
export const ZCscSignEnvelopeResponseSchema = z.object({
outcome: z.enum(['signed', 'already_signed']),
});
export type TCscSignEnvelopeRequest = z.infer<typeof ZCscSignEnvelopeRequestSchema>;
export type TCscSignEnvelopeResponse = z.infer<typeof ZCscSignEnvelopeResponseSchema>;
@@ -2,6 +2,7 @@ import { router } from '../trpc';
import { createOrganisationEmailRoute } from './create-organisation-email';
import { createOrganisationEmailDomainRoute } from './create-organisation-email-domain';
import { createSubscriptionRoute } from './create-subscription';
import { cscSignEnvelopeRoute } from './csc-sign-envelope';
import { declineLinkOrganisationAccountRoute } from './decline-link-organisation-account';
import { deleteOrganisationEmailRoute } from './delete-organisation-email';
import { deleteOrganisationEmailDomainRoute } from './delete-organisation-email-domain';
@@ -55,4 +56,7 @@ export const enterpriseRouter = router({
get: getInvoicesRoute,
},
},
csc: {
signEnvelope: cscSignEnvelopeRoute,
},
});
@@ -0,0 +1,95 @@
import { cancelDocument } from '@documenso/lib/server-only/document/cancel-document';
import { getMultipleEnvelopeWhereInput } from '@documenso/lib/server-only/envelope/get-envelopes-by-ids';
import { prisma } from '@documenso/prisma';
import { EnvelopeType } from '@prisma/client';
import pMap from 'p-map';
import { authenticatedProcedure } from '../trpc';
import { ZBulkCancelEnvelopesRequestSchema, ZBulkCancelEnvelopesResponseSchema } from './bulk-cancel-envelopes.types';
export const bulkCancelEnvelopesRoute = authenticatedProcedure
.input(ZBulkCancelEnvelopesRequestSchema)
.output(ZBulkCancelEnvelopesResponseSchema)
.mutation(async ({ input, ctx }) => {
const { teamId, user } = ctx;
const { envelopeIds, reason } = input;
ctx.logger.info({
input: {
envelopeIds,
},
});
// Cancelling only applies to documents. Templates are filtered out here so
// selecting a template never counts towards a cancellation.
const { envelopeWhereInput } = await getMultipleEnvelopeWhereInput({
ids: {
type: 'envelopeId',
ids: envelopeIds,
},
userId: user.id,
teamId,
type: EnvelopeType.DOCUMENT,
});
const envelopes = await prisma.envelope.findMany({
where: envelopeWhereInput,
select: {
id: true,
},
});
const results = await pMap(
envelopes,
async (envelope) => {
const { id: envelopeId } = envelope;
try {
await cancelDocument({
id: {
type: 'envelopeId',
id: envelopeId,
},
userId: user.id,
teamId,
reason,
requestMetadata: ctx.metadata,
});
return {
success: true,
envelopeId,
};
} catch (err) {
ctx.logger.warn(
{
envelopeId,
error: err,
},
'Failed to cancel envelope during bulk cancel',
);
return {
success: false,
envelopeId,
};
}
},
{
concurrency: 10,
stopOnError: false,
},
);
const cancelledCount = results.filter((r) => r.success).length;
const failedIds = results.filter((r) => !r.success).map((r) => r.envelopeId);
// Include envelope IDs that were not attempted (unauthorized/not found/not a document).
const attemptedIds = new Set(envelopes.map((e) => e.id));
const unattemptedIds = envelopeIds.filter((id) => !attemptedIds.has(id));
return {
cancelledCount,
failedIds: [...failedIds, ...unattemptedIds],
};
});
@@ -0,0 +1,21 @@
import { z } from 'zod';
// Keeping this as a private API for a little while until we're sure it's stable
// and the request/response schemas are finalized.
export const ZBulkCancelEnvelopesRequestSchema = z.object({
envelopeIds: z
.array(z.string())
.min(1)
.max(100)
.describe('The IDs of the envelopes to cancel. The maximum number of envelopes you can cancel at once is 100.'),
reason: z.string().optional(),
});
export const ZBulkCancelEnvelopesResponseSchema = z.object({
cancelledCount: z.number(),
failedIds: z.array(z.string()),
});
export type TBulkCancelEnvelopesRequest = z.infer<typeof ZBulkCancelEnvelopesRequestSchema>;
export type TBulkCancelEnvelopesResponse = z.infer<typeof ZBulkCancelEnvelopesResponseSchema>;
@@ -0,0 +1,37 @@
import { cancelDocument } from '@documenso/lib/server-only/document/cancel-document';
import { ZGenericSuccessResponse } from '../schema';
import { authenticatedProcedure } from '../trpc';
import {
cancelEnvelopeMeta,
ZCancelEnvelopeRequestSchema,
ZCancelEnvelopeResponseSchema,
} from './cancel-envelope.types';
export const cancelEnvelopeRoute = authenticatedProcedure
.meta(cancelEnvelopeMeta)
.input(ZCancelEnvelopeRequestSchema)
.output(ZCancelEnvelopeResponseSchema)
.mutation(async ({ input, ctx }) => {
const { teamId } = ctx;
const { envelopeId, reason } = input;
ctx.logger.info({
input: {
envelopeId,
},
});
await cancelDocument({
id: {
type: 'envelopeId',
id: envelopeId,
},
userId: ctx.user.id,
teamId,
reason,
requestMetadata: ctx.metadata,
});
return ZGenericSuccessResponse;
});
@@ -0,0 +1,23 @@
import { z } from 'zod';
import { ZSuccessResponseSchema } from '../schema';
import type { TrpcRouteMeta } from '../trpc';
export const cancelEnvelopeMeta: TrpcRouteMeta = {
openapi: {
method: 'POST',
path: '/envelope/cancel',
summary: 'Cancel envelope',
tags: ['Envelope'],
},
};
export const ZCancelEnvelopeRequestSchema = z.object({
envelopeId: z.string(),
reason: z.string().optional(),
});
export const ZCancelEnvelopeResponseSchema = ZSuccessResponseSchema;
export type TCancelEnvelopeRequest = z.infer<typeof ZCancelEnvelopeRequestSchema>;
export type TCancelEnvelopeResponse = z.infer<typeof ZCancelEnvelopeResponseSchema>;
@@ -13,7 +13,7 @@ export const duplicateEnvelopeRoute = authenticatedProcedure
.output(ZDuplicateEnvelopeResponseSchema)
.mutation(async ({ input, ctx }) => {
const { teamId } = ctx;
const { envelopeId } = input;
const { envelopeId, includeRecipients, includeFields } = input;
ctx.logger.info({
input: {
@@ -28,6 +28,10 @@ export const duplicateEnvelopeRoute = authenticatedProcedure
type: 'envelopeId',
id: envelopeId,
},
overrides: {
includeRecipients,
includeFields,
},
});
return {
@@ -13,7 +13,17 @@ export const duplicateEnvelopeMeta: TrpcRouteMeta = {
};
export const ZDuplicateEnvelopeRequestSchema = z.object({
envelopeId: z.string(),
envelopeId: z.string().min(1).describe('The ID of the envelope to duplicate.'),
includeRecipients: z
.boolean()
.optional()
.default(true)
.describe('Whether to copy the recipients to the duplicated envelope. Defaults to true.'),
includeFields: z
.boolean()
.optional()
.default(true)
.describe('Whether to copy the fields to the duplicated envelope. Requires includeRecipients. Defaults to true.'),
});
export const ZDuplicateEnvelopeResponseSchema = z.object({
@@ -0,0 +1,65 @@
import { AppError, AppErrorCode } from '@documenso/lib/errors/app-error';
import { rejectDocumentOnBehalfOf } from '@documenso/lib/server-only/document/reject-document-on-behalf-of';
import { getEnvelopeWhereInput } from '@documenso/lib/server-only/envelope/get-envelope-by-id';
import { prisma } from '@documenso/prisma';
import { EnvelopeType } from '@prisma/client';
import { authenticatedProcedure } from '../../trpc';
import {
rejectEnvelopeRecipientOnBehalfOfMeta,
ZRejectEnvelopeRecipientOnBehalfOfRequestSchema,
ZRejectEnvelopeRecipientOnBehalfOfResponseSchema,
} from './reject-envelope-recipient-on-behalf-of.types';
export const rejectEnvelopeRecipientOnBehalfOfRoute = authenticatedProcedure
.meta(rejectEnvelopeRecipientOnBehalfOfMeta)
.input(ZRejectEnvelopeRecipientOnBehalfOfRequestSchema)
.output(ZRejectEnvelopeRecipientOnBehalfOfResponseSchema)
.mutation(async ({ input, ctx }) => {
const { teamId, user } = ctx;
const { envelopeId, recipientId, reason, actAsEmail } = input;
ctx.logger.info({
input: {
envelopeId,
recipientId,
},
});
// This is an external-only action: it must only be reachable through the
// public API, never the internal app TRPC handler.
if (ctx.metadata.source !== 'apiV2') {
throw new AppError(AppErrorCode.UNAUTHORIZED, {
message: 'This route is only accessible via the public API',
});
}
await rejectDocumentOnBehalfOf({
envelopeId,
recipientId,
userId: user.id,
teamId,
reason,
actAsEmail,
requestMetadata: ctx.metadata,
});
const { envelopeWhereInput } = await getEnvelopeWhereInput({
id: { type: 'envelopeId', id: envelopeId },
type: EnvelopeType.DOCUMENT,
userId: user.id,
teamId,
});
const recipient = await prisma.recipient.findFirstOrThrow({
where: {
id: recipientId,
envelope: envelopeWhereInput,
},
include: {
fields: true,
},
});
return recipient;
});
@@ -0,0 +1,35 @@
import { ZEnvelopeRecipientSchema } from '@documenso/lib/types/recipient';
import { zEmail } from '@documenso/lib/utils/zod';
import { z } from 'zod';
import type { TrpcRouteMeta } from '../../trpc';
export const rejectEnvelopeRecipientOnBehalfOfMeta: TrpcRouteMeta = {
openapi: {
method: 'POST',
path: '/envelope/recipient/{recipientId}/reject',
summary: 'Reject envelope recipient on behalf of',
description:
'Records a rejection on behalf of a recipient. Use this when a recipient has declined to ' +
'sign outside of the platform. The rejection is flagged as external in the document audit ' +
'log. By default the action is attributed to the API user; supply `actAsEmail` to attribute ' +
'it to a specific team member.',
tags: ['Envelope Recipients'],
},
};
export const ZRejectEnvelopeRecipientOnBehalfOfRequestSchema = z.object({
envelopeId: z.string().describe('The ID of the envelope the recipient belongs to.'),
recipientId: z.number().describe('The ID of the recipient to reject the document on behalf of.'),
reason: z.string().min(1).describe('The reason the recipient rejected the document.'),
actAsEmail: zEmail()
.optional()
.describe('The email of the team member to attribute the rejection to. Defaults to the API user when omitted.'),
});
export const ZRejectEnvelopeRecipientOnBehalfOfResponseSchema = ZEnvelopeRecipientSchema;
export type TRejectEnvelopeRecipientOnBehalfOfRequest = z.infer<typeof ZRejectEnvelopeRecipientOnBehalfOfRequestSchema>;
export type TRejectEnvelopeRecipientOnBehalfOfResponse = z.infer<
typeof ZRejectEnvelopeRecipientOnBehalfOfResponseSchema
>;
@@ -1,4 +1,5 @@
import { AppError, AppErrorCode } from '@documenso/lib/errors/app-error';
import { assertEnvelopeMutable } from '@documenso/lib/server-only/envelope/assert-envelope-mutable';
import { getEnvelopeWhereInput } from '@documenso/lib/server-only/envelope/get-envelope-by-id';
import { UNSAFE_replaceEnvelopeItemPdf } from '@documenso/lib/server-only/envelope-item/replace-envelope-item-pdf';
import { getEnvelopeItemPermissions } from '@documenso/lib/utils/envelope';
@@ -59,6 +60,8 @@ export const replaceEnvelopeItemPdfRoute = authenticatedProcedure
});
}
assertEnvelopeMutable(envelope);
if (envelope.internalVersion !== 2) {
throw new AppError(AppErrorCode.INVALID_REQUEST, {
message: 'PDF replacement is only supported for version 2 envelopes',
@@ -3,8 +3,10 @@ import { createAttachmentRoute } from './attachment/create-attachment';
import { deleteAttachmentRoute } from './attachment/delete-attachment';
import { findAttachmentsRoute } from './attachment/find-attachments';
import { updateAttachmentRoute } from './attachment/update-attachment';
import { bulkCancelEnvelopesRoute } from './bulk-cancel-envelopes';
import { bulkDeleteEnvelopesRoute } from './bulk-delete-envelopes';
import { bulkMoveEnvelopesRoute } from './bulk-move-envelopes';
import { cancelEnvelopeRoute } from './cancel-envelope';
import { createEnvelopeRoute } from './create-envelope';
import { createEnvelopeItemsRoute } from './create-envelope-items';
import { deleteEnvelopeRoute } from './delete-envelope';
@@ -20,6 +22,7 @@ import { updateEnvelopeFieldsRoute } from './envelope-fields/update-envelope-fie
import { createEnvelopeRecipientsRoute } from './envelope-recipients/create-envelope-recipients';
import { deleteEnvelopeRecipientRoute } from './envelope-recipients/delete-envelope-recipient';
import { getEnvelopeRecipientRoute } from './envelope-recipients/get-envelope-recipient';
import { rejectEnvelopeRecipientOnBehalfOfRoute } from './envelope-recipients/reject-envelope-recipient-on-behalf-of';
import { reportRecipientRoute } from './envelope-recipients/report-recipient';
import { updateEnvelopeRecipientsRoute } from './envelope-recipients/update-envelope-recipients';
import { findEnvelopeAuditLogsRoute } from './find-envelope-audit-logs';
@@ -68,6 +71,7 @@ export const envelopeRouter = router({
delete: deleteEnvelopeRecipientRoute,
set: setEnvelopeRecipientsRoute,
report: reportRecipientRoute,
rejectOnBehalfOf: rejectEnvelopeRecipientOnBehalfOfRoute,
},
field: {
get: getEnvelopeFieldRoute,
@@ -85,6 +89,7 @@ export const envelopeRouter = router({
bulk: {
move: bulkMoveEnvelopesRoute,
delete: bulkDeleteEnvelopesRoute,
cancel: bulkCancelEnvelopesRoute,
},
editor: {
get: getEditorEnvelopeRoute,
@@ -95,6 +100,7 @@ export const envelopeRouter = router({
use: useEnvelopeRoute,
update: updateEnvelopeRoute,
delete: deleteEnvelopeRoute,
cancel: cancelEnvelopeRoute,
duplicate: duplicateEnvelopeRoute,
saveAsTemplate: saveAsTemplateRoute,
distribute: distributeEnvelopeRoute,
@@ -1,3 +1,4 @@
import { prepareCscRecipientSigning } from '@documenso/ee/server-only/signing/csc/prepare-recipient-signing';
import { completeDocumentWithToken } from '@documenso/lib/server-only/document/complete-document-with-token';
import { rejectDocumentWithToken } from '@documenso/lib/server-only/document/reject-document-with-token';
import { createEnvelopeRecipients } from '@documenso/lib/server-only/recipient/create-envelope-recipients';
@@ -6,6 +7,9 @@ import { getRecipientById } from '@documenso/lib/server-only/recipient/get-recip
import { setDocumentRecipients } from '@documenso/lib/server-only/recipient/set-document-recipients';
import { setTemplateRecipients } from '@documenso/lib/server-only/recipient/set-template-recipients';
import { updateEnvelopeRecipients } from '@documenso/lib/server-only/recipient/update-envelope-recipients';
import { isTspEnvelope } from '@documenso/lib/types/signature-level';
import { unsafeBuildEnvelopeIdQuery } from '@documenso/lib/utils/envelope';
import { prisma } from '@documenso/prisma';
import { EnvelopeType } from '@prisma/client';
import { ZGenericSuccessResponse, ZSuccessResponseSchema } from '../schema';
@@ -13,6 +17,7 @@ import { authenticatedProcedure, procedure, router } from '../trpc';
import { findRecipientSuggestionsRoute } from './find-recipient-suggestions';
import {
ZCompleteDocumentWithTokenMutationSchema,
ZCompleteDocumentWithTokenResponseSchema,
ZCreateDocumentRecipientRequestSchema,
ZCreateDocumentRecipientResponseSchema,
ZCreateDocumentRecipientsRequestSchema,
@@ -559,6 +564,7 @@ export const recipientRouter = router({
*/
completeDocumentWithToken: procedure
.input(ZCompleteDocumentWithTokenMutationSchema)
.output(ZCompleteDocumentWithTokenResponseSchema)
.mutation(async ({ input, ctx }) => {
const { token, documentId, accessAuthOptions, nextSigner, recipientOverride } = input;
@@ -568,6 +574,25 @@ export const recipientRouter = router({
},
});
// Branch on TSP envelopes before any SES side effects: TSP recipients
// can't complete via this route — they go through the CSC sync sign
// flow (`enterprise.csc.signEnvelope`). This route returns the redirect URL
// for the credential-scope OAuth round-trip.
const envelope = await prisma.envelope.findFirstOrThrow({
where: {
...unsafeBuildEnvelopeIdQuery({ type: 'documentId', id: documentId }, EnvelopeType.DOCUMENT),
recipients: { some: { token } },
},
select: { signatureLevel: true, internalVersion: true },
});
if (isTspEnvelope(envelope)) {
return await prepareCscRecipientSigning({
recipientToken: token,
requestMetadata: ctx.metadata.requestMetadata,
});
}
await completeDocumentWithToken({
token,
id: {
@@ -580,6 +605,8 @@ export const recipientRouter = router({
userId: ctx.user?.id,
requestMetadata: ctx.metadata.requestMetadata,
});
return { status: 'SIGNED' as const };
}),
/**
@@ -178,6 +178,20 @@ export const ZCompleteDocumentWithTokenMutationSchema = z.object({
export type TCompleteDocumentWithTokenMutationSchema = z.infer<typeof ZCompleteDocumentWithTokenMutationSchema>;
/**
* Discriminated response: SES envelopes return `{ status: 'SIGNED' }` after
* the in-place completion; TSP (AES/QES) envelopes return
* `{ status: 'REDIRECT', redirectUrl }` pointing at the credential-scope
* OAuth authorize endpoint. Frontend callers can branch on `status` —
* existing callers ignored the response and remain compatible.
*/
export const ZCompleteDocumentWithTokenResponseSchema = z.discriminatedUnion('status', [
z.object({ status: z.literal('REDIRECT'), redirectUrl: z.string() }),
z.object({ status: z.literal('SIGNED') }),
]);
export type TCompleteDocumentWithTokenResponseSchema = z.infer<typeof ZCompleteDocumentWithTokenResponseSchema>;
export const ZRejectDocumentWithTokenMutationSchema = z.object({
token: z.string(),
documentId: z.number(),