Closes the silence after the first signing invitation. Three real improvements on top of the existing webhook plumbing, all aligned with the Documenso v1.32 + v2 webhook payload shape (verified against the official OpenAPI spec + Context7 docs): 1. Cascading "your turn" emails — when DOCUMENT_SIGNED / DOCUMENT_ RECIPIENT_COMPLETED / RECIPIENT_SIGNED fires for a recipient, handleRecipientSigned now resolves the next pending signer in signing order and sends them the branded sendSigningInvitation() email with the embedded-host-wrapped URL. Stamps invitedAt so a duplicate webhook retry doesn't re-send. 2. On-completion PDF distribution — handleDocumentCompleted now re- reads the just-committed signedFileId, resolves all signers, and fires sendSigningCompleted() to every recipient with the signed PDF attached. resolveAttachments in lib/email already pulls bytes through getStorageBackend() so this works under both the s3/minio and filesystem backends without changes. Failures fall through to logger.error rather than throwing — the document is already marked completed and the admin can re-trigger manually. 3. Token-based recipient matching — Documenso v1 + v2 webhook recipients carry a `token` field (per the OpenAPI spec); same token appears in the document-create response. Captured at send time into the existing document_signers.signing_token column (already in schema from Phase 1) and used by handleRecipientSigned + handleDocumentOpened before falling back to email match. Robust against the case where one email serves multiple roles on a contract — which is the documented gap in the legacy nocodb-based handler. Supporting changes: - New helper module lib/services/documenso-signers.ts with extractSigningToken() (URL-tail fallback), DOC_TYPE_LABEL map, and nextPendingSigner() picker. 11 unit tests cover the token-regex, the helper picks the lowest pending signing-order, and rejects declined/signed correctly. - documenso-client normalizeDocument now reads `token` from both `recipients[]` and the legacy capital-R `Recipient[]` array Documenso v1.32 sometimes ships in webhooks. - documents.service signer-update at send time prefers the explicit token field, falling back to extractSigningToken(signingUrl) for any v2 deployment whose distribute response omits it. Out of scope for Phase 2 (per the build plan): - Custom-doc upload-to-Documenso path (Phase 3) - Recipient + field-placement UI (Phase 4) - DNS-rebinding hardening + circuit-breaker (deferred-refactor list) - Auto-reminder cron — manual "Send reminder" button + auto-reminder toggle remain manual until Phase 6 polish Tests: 1315/1315 vitest ✅ + 11 new tests for documenso-signers ✅; tsc clean. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
854 lines
30 KiB
TypeScript
854 lines
30 KiB
TypeScript
import pRetry, { AbortError } from 'p-retry';
|
|
|
|
import { env } from '@/lib/env';
|
|
import { CodedError } from '@/lib/errors';
|
|
import { logger } from '@/lib/logger';
|
|
import { getPortDocumensoConfig, type DocumensoApiVersion } from '@/lib/services/port-config';
|
|
import { fetchWithTimeout, FetchTimeoutError } from '@/lib/fetch-with-timeout';
|
|
|
|
interface DocumensoCreds {
|
|
baseUrl: string;
|
|
apiKey: string;
|
|
apiVersion: DocumensoApiVersion;
|
|
}
|
|
|
|
async function resolveCreds(portId?: string): Promise<DocumensoCreds> {
|
|
if (!portId) {
|
|
return {
|
|
baseUrl: env.DOCUMENSO_API_URL,
|
|
apiKey: env.DOCUMENSO_API_KEY,
|
|
apiVersion: env.DOCUMENSO_API_VERSION,
|
|
};
|
|
}
|
|
const cfg = await getPortDocumensoConfig(portId);
|
|
return { baseUrl: cfg.apiUrl, apiKey: cfg.apiKey, apiVersion: cfg.apiVersion };
|
|
}
|
|
|
|
async function documensoFetchOnce(
|
|
path: string,
|
|
options: RequestInit | undefined,
|
|
portId: string | undefined,
|
|
): Promise<unknown> {
|
|
const { baseUrl, apiKey } = await resolveCreds(portId);
|
|
let res: Response;
|
|
try {
|
|
res = await fetchWithTimeout(`${baseUrl}${path}`, {
|
|
...options,
|
|
headers: {
|
|
Authorization: `Bearer ${apiKey}`,
|
|
'Content-Type': 'application/json',
|
|
...options?.headers,
|
|
},
|
|
});
|
|
} catch (err) {
|
|
if (err instanceof FetchTimeoutError) {
|
|
// Retry timeouts — transient network issue.
|
|
throw new CodedError('DOCUMENSO_TIMEOUT', {
|
|
internalMessage: `${path} timed out after ${err.timeoutMs}ms`,
|
|
});
|
|
}
|
|
throw err;
|
|
}
|
|
|
|
if (!res.ok) {
|
|
const err = await res.text();
|
|
logger.error({ path, status: res.status, err, portId }, 'Documenso API error');
|
|
if (res.status === 401 || res.status === 403) {
|
|
// Auth failures are not retryable — wrong key won't fix itself.
|
|
throw new AbortError(
|
|
new CodedError('DOCUMENSO_AUTH_FAILURE', {
|
|
internalMessage: `${path} → ${res.status}`,
|
|
}),
|
|
);
|
|
}
|
|
if (res.status >= 400 && res.status < 500 && res.status !== 429) {
|
|
// 4xx (other than 429) means we sent something Documenso rejected —
|
|
// retrying won't help. 429 (rate-limit) goes through the retry path
|
|
// with backoff so we politely re-attempt after delay.
|
|
throw new AbortError(
|
|
new CodedError('DOCUMENSO_UPSTREAM_ERROR', {
|
|
internalMessage: `${path} → ${res.status}: ${err}`,
|
|
}),
|
|
);
|
|
}
|
|
// 5xx + 429 → transient, retry.
|
|
throw new CodedError('DOCUMENSO_UPSTREAM_ERROR', {
|
|
internalMessage: `${path} → ${res.status}: ${err}`,
|
|
});
|
|
}
|
|
|
|
return res.json();
|
|
}
|
|
|
|
/**
|
|
* Wraps every Documenso call in p-retry: 3 attempts total (1 + 2 retries)
|
|
* with exponential backoff (1s, 4s) + jitter. AbortError short-circuits
|
|
* for auth failures and 4xx-not-429 — those will never succeed on retry.
|
|
*
|
|
* This recovers the "single connection blip drops the whole signing flow"
|
|
* scenario the audit's services pass flagged.
|
|
*/
|
|
async function documensoFetch(
|
|
path: string,
|
|
options?: RequestInit,
|
|
portId?: string,
|
|
): Promise<unknown> {
|
|
return pRetry(() => documensoFetchOnce(path, options, portId), {
|
|
retries: 2,
|
|
factor: 2,
|
|
minTimeout: 1000,
|
|
randomize: true,
|
|
onFailedAttempt: (ctx) => {
|
|
logger.warn(
|
|
{
|
|
path,
|
|
portId,
|
|
attempt: ctx.attemptNumber,
|
|
retriesLeft: ctx.retriesLeft,
|
|
err: ctx.error.message,
|
|
},
|
|
'Documenso fetch retry',
|
|
);
|
|
},
|
|
});
|
|
}
|
|
|
|
// Documenso 2.x renamed top-level `id` → `documentId` and recipient `id` →
|
|
// `recipientId`; v1.13 still uses `id`. Normalize both shapes to the legacy
|
|
// `id` form that this codebase consumes everywhere downstream.
|
|
function normalizeDocument(raw: unknown): DocumensoDocument {
|
|
const r = (raw ?? {}) as Record<string, unknown>;
|
|
const id = String(r.documentId ?? r.id ?? '');
|
|
const status = String(r.status ?? 'PENDING');
|
|
// v1.32+ payloads carry a `Recipient` (capital R) array as a legacy
|
|
// duplicate of `recipients` — fall through to it so we still resolve
|
|
// tokens / URLs when only the legacy field is populated.
|
|
const recipientsRaw =
|
|
(r.recipients as Array<Record<string, unknown>> | undefined) ??
|
|
(r.Recipient as Array<Record<string, unknown>> | undefined) ??
|
|
[];
|
|
const recipients = recipientsRaw.map((rec) => ({
|
|
id: String(rec.recipientId ?? rec.id ?? ''),
|
|
name: String(rec.name ?? ''),
|
|
email: String(rec.email ?? ''),
|
|
role: String(rec.role ?? ''),
|
|
signingOrder: Number(rec.signingOrder ?? 0),
|
|
status: String(rec.signingStatus ?? rec.status ?? 'PENDING'),
|
|
signingUrl: typeof rec.signingUrl === 'string' ? rec.signingUrl : undefined,
|
|
embeddedUrl: typeof rec.embeddedUrl === 'string' ? rec.embeddedUrl : undefined,
|
|
// Per-recipient signing token — required on the v1 Recipient model,
|
|
// present on every v2 envelope-distribute response. Documenso uses
|
|
// it as the URL tail (`/sign/<token>`) so it also matches what we
|
|
// see on subsequent webhook deliveries.
|
|
token: typeof rec.token === 'string' ? rec.token : undefined,
|
|
}));
|
|
return { id, status, recipients };
|
|
}
|
|
|
|
export interface DocumensoRecipient {
|
|
name: string;
|
|
email: string;
|
|
role: string;
|
|
signingOrder: number;
|
|
}
|
|
|
|
export interface DocumensoDocument {
|
|
id: string;
|
|
status: string;
|
|
recipients: Array<{
|
|
id: string;
|
|
name: string;
|
|
email: string;
|
|
role: string;
|
|
signingOrder: number;
|
|
status: string;
|
|
signingUrl?: string;
|
|
embeddedUrl?: string;
|
|
/** v1 + v2 recipient token. Used to populate
|
|
* `document_signers.signing_token` so the webhook handler can
|
|
* match recipients without leaning on email (which may be reused
|
|
* across roles). */
|
|
token?: string;
|
|
}>;
|
|
}
|
|
|
|
/**
|
|
* When EMAIL_REDIRECT_TO is set (dev / staging), rewrite every recipient
|
|
* email so Documenso doesn't accidentally email real clients during a
|
|
* data import / migration dry-run. Names are prefixed with the original
|
|
* email so the recipient (you) can tell who would have received the doc.
|
|
*
|
|
* In production this env var is unset and recipients flow through unchanged.
|
|
*/
|
|
function applyRecipientRedirect(recipients: DocumensoRecipient[]): DocumensoRecipient[] {
|
|
if (!env.EMAIL_REDIRECT_TO) return recipients;
|
|
return recipients.map((r) => ({
|
|
...r,
|
|
name: `${r.name} (was: ${r.email})`,
|
|
email: env.EMAIL_REDIRECT_TO!,
|
|
}));
|
|
}
|
|
|
|
/**
|
|
* Same idea for the template-generate endpoint, which takes a payload
|
|
* shape with recipient email/name nested inside `formValues` (Documenso
|
|
* v1.13) or `recipients` (Documenso 2.x). We rewrite both shapes.
|
|
*/
|
|
function applyPayloadRedirect(payload: Record<string, unknown>): Record<string, unknown> {
|
|
if (!env.EMAIL_REDIRECT_TO) return payload;
|
|
const out: Record<string, unknown> = { ...payload };
|
|
// 2.x recipient shape
|
|
if (Array.isArray(out.recipients)) {
|
|
out.recipients = (out.recipients as Array<Record<string, unknown>>).map((r) => ({
|
|
...r,
|
|
name: `${String(r.name ?? '')} (was: ${String(r.email ?? '')})`,
|
|
email: env.EMAIL_REDIRECT_TO,
|
|
}));
|
|
}
|
|
// v1.13 formValues shape - keys vary per template; key by anything that
|
|
// looks like an email field. The conservative approach: only touch keys
|
|
// that already hold a string and end with `Email` / `email`.
|
|
if (out.formValues && typeof out.formValues === 'object') {
|
|
const fv = { ...(out.formValues as Record<string, unknown>) };
|
|
for (const key of Object.keys(fv)) {
|
|
if (/email$/i.test(key) && typeof fv[key] === 'string') {
|
|
fv[key] = env.EMAIL_REDIRECT_TO;
|
|
}
|
|
}
|
|
out.formValues = fv;
|
|
}
|
|
return out;
|
|
}
|
|
|
|
/**
|
|
* Optional metadata applied to the document on creation. v1 accepts
|
|
* `redirectUrl` and `subject`/`message` on its `/documents` endpoint.
|
|
* v2's `/envelope/create` accepts the same plus `signingOrder` for
|
|
* PARALLEL-vs-SEQUENTIAL signing enforcement.
|
|
*/
|
|
export interface CreateDocumentMeta {
|
|
subject?: string;
|
|
message?: string;
|
|
redirectUrl?: string;
|
|
/** v2 only. v1 ignores. */
|
|
signingOrder?: 'PARALLEL' | 'SEQUENTIAL';
|
|
}
|
|
|
|
export async function createDocument(
|
|
title: string,
|
|
pdfBase64: string,
|
|
recipients: DocumensoRecipient[],
|
|
portId?: string,
|
|
meta?: CreateDocumentMeta,
|
|
): Promise<DocumensoDocument> {
|
|
const safeRecipients = applyRecipientRedirect(recipients);
|
|
if (env.EMAIL_REDIRECT_TO) {
|
|
logger.info(
|
|
{ redirected: safeRecipients.length, original: recipients.map((r) => r.email) },
|
|
'Documenso recipients redirected to EMAIL_REDIRECT_TO',
|
|
);
|
|
}
|
|
const { apiVersion } = await resolveCreds(portId);
|
|
|
|
if (apiVersion === 'v2') {
|
|
// v2: multipart /envelope/create with payload + files. Convert the
|
|
// base64 PDF to a Buffer and ship it under `files`. Returns
|
|
// `{ id: envelopeId }` only — caller distributes separately via
|
|
// sendDocument(envelopeId).
|
|
const { baseUrl, apiKey } = await resolveCreds(portId);
|
|
const pdfBuffer = Buffer.from(pdfBase64, 'base64');
|
|
const form = new FormData();
|
|
const payload = {
|
|
type: 'DOCUMENT',
|
|
title,
|
|
recipients: safeRecipients.map((r, i) => ({
|
|
email: r.email,
|
|
name: r.name,
|
|
role: r.role,
|
|
signingOrder: r.signingOrder || i + 1,
|
|
})),
|
|
...(meta
|
|
? {
|
|
meta: {
|
|
...(meta.subject ? { subject: meta.subject } : {}),
|
|
...(meta.message ? { message: meta.message } : {}),
|
|
...(meta.redirectUrl ? { redirectUrl: meta.redirectUrl } : {}),
|
|
...(meta.signingOrder ? { signingOrder: meta.signingOrder } : {}),
|
|
},
|
|
}
|
|
: {}),
|
|
};
|
|
form.append('payload', JSON.stringify(payload));
|
|
form.append(
|
|
'files',
|
|
new Blob([pdfBuffer], { type: 'application/pdf' }),
|
|
`${title.replace(/[^a-z0-9-_]+/gi, '-')}.pdf`,
|
|
);
|
|
|
|
let res: Response;
|
|
try {
|
|
res = await fetchWithTimeout(`${baseUrl}/api/v2/envelope/create`, {
|
|
method: 'POST',
|
|
headers: { Authorization: `Bearer ${apiKey}` },
|
|
body: form,
|
|
});
|
|
} catch (err) {
|
|
if (err instanceof FetchTimeoutError) {
|
|
throw new CodedError('DOCUMENSO_TIMEOUT', {
|
|
internalMessage: `/api/v2/envelope/create timed out after ${err.timeoutMs}ms`,
|
|
});
|
|
}
|
|
throw err;
|
|
}
|
|
if (!res.ok) {
|
|
const errText = await res.text();
|
|
logger.error(
|
|
{ status: res.status, err: errText, portId },
|
|
'Documenso v2 envelope/create error',
|
|
);
|
|
if (res.status === 401 || res.status === 403) {
|
|
throw new CodedError('DOCUMENSO_AUTH_FAILURE', {
|
|
internalMessage: `v2 envelope/create → ${res.status}`,
|
|
});
|
|
}
|
|
throw new CodedError('DOCUMENSO_UPSTREAM_ERROR', {
|
|
internalMessage: `v2 envelope/create → ${res.status}: ${errText}`,
|
|
});
|
|
}
|
|
const created = (await res.json()) as Record<string, unknown>;
|
|
// v2 returns just `{ id }`. Re-fetch the full envelope so the
|
|
// caller gets recipients (without signing URLs — those come after
|
|
// distribute). Keeps shape identical to v1's createDocument response.
|
|
const envelopeId = String(created.id ?? created.documentId ?? '');
|
|
return getDocument(envelopeId, portId);
|
|
}
|
|
|
|
// v1: existing path. Meta keys are accepted at the top level.
|
|
return documensoFetch(
|
|
'/api/v1/documents',
|
|
{
|
|
method: 'POST',
|
|
body: JSON.stringify({
|
|
title,
|
|
document: pdfBase64,
|
|
recipients: safeRecipients,
|
|
...(meta?.subject || meta?.message || meta?.redirectUrl
|
|
? {
|
|
meta: {
|
|
...(meta.subject ? { subject: meta.subject } : {}),
|
|
...(meta.message ? { message: meta.message } : {}),
|
|
...(meta.redirectUrl ? { redirectUrl: meta.redirectUrl } : {}),
|
|
},
|
|
}
|
|
: {}),
|
|
}),
|
|
},
|
|
portId,
|
|
).then(normalizeDocument);
|
|
}
|
|
|
|
export async function generateDocumentFromTemplate(
|
|
templateId: number,
|
|
payload: Record<string, unknown>,
|
|
portId?: string,
|
|
): Promise<DocumensoDocument> {
|
|
const safePayload = applyPayloadRedirect(payload);
|
|
if (env.EMAIL_REDIRECT_TO) {
|
|
logger.info(
|
|
{ templateId },
|
|
'Documenso template-generate payload redirected to EMAIL_REDIRECT_TO',
|
|
);
|
|
}
|
|
return documensoFetch(
|
|
`/api/v1/templates/${templateId}/generate-document`,
|
|
{
|
|
method: 'POST',
|
|
body: JSON.stringify(safePayload),
|
|
},
|
|
portId,
|
|
).then(normalizeDocument);
|
|
}
|
|
|
|
/**
|
|
* Tell Documenso to actually email the document to its recipients. The
|
|
* recipients themselves are set at create-time (and rerouted to
|
|
* EMAIL_REDIRECT_TO when set), but this is a belt-and-braces guard for
|
|
* documents that may have been created BEFORE the redirect was turned on
|
|
* (i.e. real-recipient documents now triggered by an automation while
|
|
* we're trying to hold comms). When the redirect is on we skip the API
|
|
* call entirely and return a synthetic "still pending" response.
|
|
*/
|
|
export async function sendDocument(docId: string, portId?: string): Promise<DocumensoDocument> {
|
|
if (env.EMAIL_REDIRECT_TO) {
|
|
logger.warn(
|
|
{ docId, portId, redirect: env.EMAIL_REDIRECT_TO },
|
|
'sendDocument SKIPPED - EMAIL_REDIRECT_TO is set, outbound comms paused',
|
|
);
|
|
// Return the existing doc shape so downstream code doesn't see an
|
|
// unexpected null. The document remains in DRAFT/PENDING from
|
|
// Documenso's perspective.
|
|
return getDocument(docId, portId);
|
|
}
|
|
const { apiVersion } = await resolveCreds(portId);
|
|
|
|
if (apiVersion === 'v2') {
|
|
// v2: POST /api/v2/envelope/distribute with body { envelopeId }.
|
|
// Returns the envelope with per-recipient signingUrl fields populated —
|
|
// this is one of the genuine v2 wins (saves a separate GET round-trip).
|
|
const distributed = (await documensoFetch(
|
|
'/api/v2/envelope/distribute',
|
|
{
|
|
method: 'POST',
|
|
body: JSON.stringify({ envelopeId: docId }),
|
|
},
|
|
portId,
|
|
)) as Record<string, unknown>;
|
|
// Distribute response shape: { success, id, recipients: [...] }.
|
|
// The recipients carry name/email/token/role/signingOrder/signingUrl.
|
|
// Normalize by re-wrapping into the document shape that downstream
|
|
// callers already consume.
|
|
return normalizeDocument({
|
|
id: distributed.id,
|
|
// v2 doesn't return `status` on the distribute response — the call
|
|
// itself moves the envelope from DRAFT to PENDING, so PENDING is
|
|
// the correct authoritative state.
|
|
status: 'PENDING',
|
|
recipients: distributed.recipients,
|
|
});
|
|
}
|
|
|
|
return documensoFetch(
|
|
`/api/v1/documents/${docId}/send`,
|
|
{
|
|
method: 'POST',
|
|
},
|
|
portId,
|
|
).then(normalizeDocument);
|
|
}
|
|
|
|
export async function getDocument(docId: string, portId?: string): Promise<DocumensoDocument> {
|
|
const { apiVersion } = await resolveCreds(portId);
|
|
// v1: GET /api/v1/documents/{id}
|
|
// v2: GET /api/v2/envelope/{id} — same response normalizer (id ↔ documentId,
|
|
// recipientId ↔ id handled by normalizeDocument).
|
|
const path = apiVersion === 'v2' ? `/api/v2/envelope/${docId}` : `/api/v1/documents/${docId}`;
|
|
return documensoFetch(path, undefined, portId).then(normalizeDocument);
|
|
}
|
|
|
|
/**
|
|
* Email a signing reminder to one recipient. Skipped entirely when
|
|
* EMAIL_REDIRECT_TO is set - the recipient's stored email may still be
|
|
* a real client address from before the redirect was enabled.
|
|
*/
|
|
export async function sendReminder(
|
|
docId: string,
|
|
signerId: string,
|
|
portId?: string,
|
|
): Promise<void> {
|
|
if (env.EMAIL_REDIRECT_TO) {
|
|
logger.warn(
|
|
{ docId, signerId, portId, redirect: env.EMAIL_REDIRECT_TO },
|
|
'sendReminder SKIPPED - EMAIL_REDIRECT_TO is set, outbound comms paused',
|
|
);
|
|
return;
|
|
}
|
|
const { apiVersion } = await resolveCreds(portId);
|
|
|
|
if (apiVersion === 'v2') {
|
|
// v2 sends reminders via redistribute. Documenso 2.x doesn't expose a
|
|
// recipient-targeted reminder endpoint directly; instead /envelope/redistribute
|
|
// resends to all pending recipients on the envelope. Single-recipient
|
|
// targeting requires admin-side filtering. For now we redistribute the
|
|
// entire envelope, which is functionally equivalent for the typical
|
|
// case (most reminders go to the one outstanding signer).
|
|
await documensoFetch(
|
|
'/api/v2/envelope/redistribute',
|
|
{
|
|
method: 'POST',
|
|
body: JSON.stringify({ envelopeId: docId, recipientIds: [signerId] }),
|
|
},
|
|
portId,
|
|
);
|
|
return;
|
|
}
|
|
await documensoFetch(
|
|
`/api/v1/documents/${docId}/recipients/${signerId}/remind`,
|
|
{
|
|
method: 'POST',
|
|
},
|
|
portId,
|
|
);
|
|
}
|
|
|
|
export async function downloadSignedPdf(docId: string, portId?: string): Promise<Buffer> {
|
|
const { baseUrl, apiKey, apiVersion } = await resolveCreds(portId);
|
|
// v2: /api/v2/envelope/{id}/download (mirrors the v1 path under the
|
|
// envelope namespace). v1: existing /documents/{id}/download.
|
|
const path =
|
|
apiVersion === 'v2'
|
|
? `/api/v2/envelope/${docId}/download`
|
|
: `/api/v1/documents/${docId}/download`;
|
|
let res: Response;
|
|
try {
|
|
res = await fetchWithTimeout(`${baseUrl}${path}`, {
|
|
headers: { Authorization: `Bearer ${apiKey}` },
|
|
});
|
|
} catch (err) {
|
|
if (err instanceof FetchTimeoutError) {
|
|
throw new CodedError('DOCUMENSO_TIMEOUT', {
|
|
internalMessage: `${path} timed out after ${err.timeoutMs}ms`,
|
|
});
|
|
}
|
|
throw err;
|
|
}
|
|
|
|
if (!res.ok) {
|
|
const err = await res.text();
|
|
logger.error({ docId, status: res.status, err, portId }, 'Documenso download error');
|
|
if (res.status === 401 || res.status === 403) {
|
|
throw new CodedError('DOCUMENSO_AUTH_FAILURE', {
|
|
internalMessage: `${path} → ${res.status}`,
|
|
});
|
|
}
|
|
throw new CodedError('DOCUMENSO_UPSTREAM_ERROR', {
|
|
internalMessage: `${path} → ${res.status}: ${err}`,
|
|
});
|
|
}
|
|
|
|
const arrayBuffer = await res.arrayBuffer();
|
|
return Buffer.from(arrayBuffer);
|
|
}
|
|
|
|
/** Convenience health-check used by the admin "Test connection" button. */
|
|
export async function checkDocumensoHealth(
|
|
portId?: string,
|
|
): Promise<{ ok: boolean; status?: number; error?: string; apiVersion?: DocumensoApiVersion }> {
|
|
try {
|
|
const { baseUrl, apiKey, apiVersion } = await resolveCreds(portId);
|
|
// Both v1 and v2 expose /api/v1/health (v2 keeps the v1 path for
|
|
// backward compat). If a v2 deployment ever moves this we'll add a
|
|
// v2 branch — but as of Documenso 2.x there isn't a v2 health path.
|
|
const res = await fetchWithTimeout(`${baseUrl}/api/v1/health`, {
|
|
headers: { Authorization: `Bearer ${apiKey}` },
|
|
});
|
|
return { ok: res.ok, status: res.status, apiVersion };
|
|
} catch (err) {
|
|
return { ok: false, error: err instanceof Error ? err.message : 'Unknown error' };
|
|
}
|
|
}
|
|
|
|
// ─── Version-aware abstractions (Phase A PR2) ─────────────────────────────────
|
|
//
|
|
// Documenso v1.13 and v2.x diverge on field placement and document deletion:
|
|
//
|
|
// v1.13: per-field POST /api/v1/documents/{id}/fields with PIXEL coords;
|
|
// DELETE /api/v1/documents/{id} for void.
|
|
// v2.x: bulk POST /api/v2/envelope/field/create-many with PERCENT
|
|
// coords (0-100) and rich `fieldMeta`;
|
|
// DELETE /api/v2/envelope/{id} for void.
|
|
//
|
|
// Callers always work in PERCENT (0-100). For v1 the abstraction multiplies by
|
|
// the page dimensions returned by Documenso (cached per docId for the lifetime
|
|
// of the process - fields for a given doc usually go in a single batch).
|
|
|
|
/**
|
|
* Every field type Documenso supports across v1 and v2. The earlier
|
|
* subset (SIGNATURE/INITIALS/DATE/TEXT/EMAIL) covered the EOI flow's
|
|
* needs but locks out custom-uploaded contracts/reservations that
|
|
* may need checkboxes (e.g. "Lease vs Purchase"), dropdowns (e.g.
|
|
* "Berth class A/B/C"), or radio groups. Extending now so the
|
|
* field-placement UI can surface the full palette without later
|
|
* widening this type and patching every call site.
|
|
*
|
|
* Per-type fieldMeta expectations (passed through verbatim):
|
|
* - SIGNATURE / FREE_SIGNATURE / INITIALS / DATE / EMAIL / NAME — no meta
|
|
* - TEXT — { text?: string, label?: string, required?: bool, readOnly?: bool }
|
|
* - NUMBER — { numberFormat?: string, min?: number, max?: number, required?: bool }
|
|
* - CHECKBOX — { values: Array<{ checked: bool, value: string }>, validationRule?: string }
|
|
* - DROPDOWN — { values: Array<{ value: string }>, defaultValue?: string }
|
|
* - RADIO — { values: Array<{ checked: bool, value: string }> }
|
|
*
|
|
* `fieldMeta` is sent verbatim to v2's create-many endpoint and
|
|
* silently ignored by v1 (which doesn't accept the property). v1
|
|
* rendering of TEXT/NUMBER/CHECKBOX/DROPDOWN/RADIO falls back to
|
|
* blank-input behaviour without the meta.
|
|
*/
|
|
export type DocumensoFieldType =
|
|
| 'SIGNATURE'
|
|
| 'FREE_SIGNATURE'
|
|
| 'INITIALS'
|
|
| 'DATE'
|
|
| 'EMAIL'
|
|
| 'NAME'
|
|
| 'TEXT'
|
|
| 'NUMBER'
|
|
| 'CHECKBOX'
|
|
| 'DROPDOWN'
|
|
| 'RADIO';
|
|
|
|
/**
|
|
* Typed metadata shapes per field type — surfaces what fieldMeta
|
|
* actually carries in well-known cases. Used by the field-placement
|
|
* UI to render the right config form per field type. Pass-through to
|
|
* Documenso retains the loose `Record<string, unknown>` shape so we
|
|
* can ship without locking down every property.
|
|
*/
|
|
export interface DocumensoTextFieldMeta {
|
|
text?: string;
|
|
label?: string;
|
|
required?: boolean;
|
|
readOnly?: boolean;
|
|
}
|
|
export interface DocumensoNumberFieldMeta {
|
|
numberFormat?: string;
|
|
min?: number;
|
|
max?: number;
|
|
required?: boolean;
|
|
}
|
|
export interface DocumensoChoiceOption {
|
|
value: string;
|
|
/** Whether the option is pre-selected. Applies to checkbox + radio. */
|
|
checked?: boolean;
|
|
}
|
|
export interface DocumensoChoiceFieldMeta {
|
|
values: DocumensoChoiceOption[];
|
|
defaultValue?: string;
|
|
validationRule?: string;
|
|
}
|
|
|
|
/**
|
|
* Returns true when this field type expects a fieldMeta payload from
|
|
* the placement UI (so the UI can prompt the rep to configure
|
|
* options, defaults, validation, etc). Field types not in this list
|
|
* carry no per-instance configuration beyond position + recipient.
|
|
*/
|
|
export function fieldTypeNeedsMeta(type: DocumensoFieldType): boolean {
|
|
return (
|
|
type === 'TEXT' ||
|
|
type === 'NUMBER' ||
|
|
type === 'CHECKBOX' ||
|
|
type === 'DROPDOWN' ||
|
|
type === 'RADIO'
|
|
);
|
|
}
|
|
|
|
export interface DocumensoFieldPlacement {
|
|
/** Documenso recipient id; v1 expects number, v2 string - coerced internally. */
|
|
recipientId: number | string;
|
|
type: DocumensoFieldType;
|
|
pageNumber: number;
|
|
/** All four are 0-100 percent of page dimensions. */
|
|
pageX: number;
|
|
pageY: number;
|
|
pageWidth: number;
|
|
pageHeight: number;
|
|
/** Optional v2 fieldMeta - passed through verbatim, ignored on v1. */
|
|
fieldMeta?: Record<string, unknown>;
|
|
}
|
|
|
|
export interface DocumensoPageDimensions {
|
|
width: number;
|
|
height: number;
|
|
}
|
|
|
|
const DEFAULT_PAGE_DIMENSIONS: DocumensoPageDimensions = { width: 595, height: 842 }; // A4 pt
|
|
|
|
const pageDimensionCache = new Map<string, DocumensoPageDimensions>();
|
|
|
|
/** Test seam - clears the page-dimension memoization. */
|
|
export function __resetDocumensoCachesForTests(): void {
|
|
pageDimensionCache.clear();
|
|
}
|
|
|
|
async function getPageDimensions(docId: string, portId?: string): Promise<DocumensoPageDimensions> {
|
|
const cached = pageDimensionCache.get(docId);
|
|
if (cached) return cached;
|
|
// v1 doesn't expose page dimensions cleanly via the public API; the auto-
|
|
// placement use case is footer-anchored signature fields, where a default A4
|
|
// page rendered by Documenso is a safe assumption. Real page dims can be
|
|
// wired in a follow-up by parsing the document/document-data endpoints.
|
|
void portId;
|
|
pageDimensionCache.set(docId, DEFAULT_PAGE_DIMENSIONS);
|
|
return DEFAULT_PAGE_DIMENSIONS;
|
|
}
|
|
|
|
/**
|
|
* Place one or more fields on a Documenso document. Coordinates are PERCENT
|
|
* (0-100) and converted to pixels for v1 internally.
|
|
*
|
|
* v1: dispatches one POST per field (no bulk endpoint).
|
|
* v2: single bulk POST.
|
|
*/
|
|
export async function placeFields(
|
|
docId: string,
|
|
fields: DocumensoFieldPlacement[],
|
|
portId?: string,
|
|
): Promise<void> {
|
|
if (fields.length === 0) return;
|
|
const { baseUrl, apiKey, apiVersion } = await resolveCreds(portId);
|
|
|
|
if (apiVersion === 'v2') {
|
|
const v2Fields = fields.map((f) => ({
|
|
recipientId: String(f.recipientId),
|
|
type: f.type,
|
|
pageNumber: f.pageNumber,
|
|
positionX: f.pageX,
|
|
positionY: f.pageY,
|
|
width: f.pageWidth,
|
|
height: f.pageHeight,
|
|
...(f.fieldMeta ? { fieldMeta: f.fieldMeta } : {}),
|
|
}));
|
|
// Note: v2 endpoint shape (envelopeId/recipientId types) must be
|
|
// confirmed against a live Documenso 2.x instance - see PR11 realapi
|
|
// suite. Spec risk register flags this drift as the top v2 risk.
|
|
const res = await fetchWithTimeout(`${baseUrl}/api/v2/envelope/field/create-many`, {
|
|
method: 'POST',
|
|
headers: {
|
|
Authorization: `Bearer ${apiKey}`,
|
|
'Content-Type': 'application/json',
|
|
},
|
|
body: JSON.stringify({ envelopeId: docId, fields: v2Fields }),
|
|
});
|
|
if (!res.ok) {
|
|
const err = await res.text();
|
|
logger.error({ docId, status: res.status, err, portId }, 'Documenso v2 placeFields error');
|
|
if (res.status === 401 || res.status === 403) {
|
|
throw new CodedError('DOCUMENSO_AUTH_FAILURE', {
|
|
internalMessage: `v2 placeFields ${docId} → ${res.status}`,
|
|
});
|
|
}
|
|
throw new CodedError('DOCUMENSO_UPSTREAM_ERROR', {
|
|
internalMessage: `v2 placeFields ${docId} → ${res.status}: ${err}`,
|
|
});
|
|
}
|
|
return;
|
|
}
|
|
|
|
const dims = await getPageDimensions(docId, portId);
|
|
for (const f of fields) {
|
|
const body = {
|
|
recipientId: typeof f.recipientId === 'string' ? Number(f.recipientId) : f.recipientId,
|
|
type: f.type,
|
|
pageNumber: f.pageNumber,
|
|
pageX: Math.round((f.pageX / 100) * dims.width),
|
|
pageY: Math.round((f.pageY / 100) * dims.height),
|
|
pageWidth: Math.round((f.pageWidth / 100) * dims.width),
|
|
pageHeight: Math.round((f.pageHeight / 100) * dims.height),
|
|
};
|
|
// Retry transient failures so one flaky 5xx mid-loop doesn't leave
|
|
// the document with a partial field set. 3 attempts at 250 / 500 /
|
|
// 1000 ms; 4xx responses (validation errors) fail-fast.
|
|
let lastError: { status: number; body: string } | null = null;
|
|
for (let attempt = 0; attempt < 3; attempt += 1) {
|
|
const res = await fetchWithTimeout(`${baseUrl}/api/v1/documents/${docId}/fields`, {
|
|
method: 'POST',
|
|
headers: {
|
|
Authorization: `Bearer ${apiKey}`,
|
|
'Content-Type': 'application/json',
|
|
},
|
|
body: JSON.stringify(body),
|
|
});
|
|
if (res.ok) {
|
|
lastError = null;
|
|
break;
|
|
}
|
|
const errBody = await res.text().catch(() => '');
|
|
lastError = { status: res.status, body: errBody };
|
|
// Don't retry on 4xx — that's a validation error, won't change.
|
|
if (res.status >= 400 && res.status < 500) break;
|
|
// Backoff: 250ms, 500ms (skipped on the 3rd iteration because we exit).
|
|
if (attempt < 2) {
|
|
await new Promise((r) => setTimeout(r, 250 * Math.pow(2, attempt)));
|
|
}
|
|
}
|
|
if (lastError) {
|
|
logger.error(
|
|
{ docId, status: lastError.status, err: lastError.body, portId },
|
|
'Documenso v1 placeField error',
|
|
);
|
|
if (lastError.status === 401 || lastError.status === 403) {
|
|
throw new CodedError('DOCUMENSO_AUTH_FAILURE', {
|
|
internalMessage: `v1 placeField ${docId} → ${lastError.status}`,
|
|
});
|
|
}
|
|
throw new CodedError('DOCUMENSO_UPSTREAM_ERROR', {
|
|
internalMessage: `v1 placeField ${docId} → ${lastError.status}: ${lastError.body}`,
|
|
});
|
|
}
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Auto-position one SIGNATURE field per recipient at the last-page footer,
|
|
* staggered horizontally so multiple signers don't overlap. Used by the
|
|
* upload-path wizard - admins can refine in Documenso afterwards.
|
|
*
|
|
* Layout (percent of page):
|
|
* y = 88 (footer band)
|
|
* height = 6
|
|
* width = min(20, 80 / N)
|
|
* x = i * (80/N) + (40 - 80/N * N / 2) (centered row)
|
|
*/
|
|
export async function placeDefaultSignatureFields(
|
|
docId: string,
|
|
recipients: Array<{ id: number | string; pageNumber: number }>,
|
|
portId?: string,
|
|
): Promise<void> {
|
|
if (recipients.length === 0) return;
|
|
const fields: DocumensoFieldPlacement[] = computeDefaultSignatureLayout(recipients);
|
|
await placeFields(docId, fields, portId);
|
|
}
|
|
|
|
/** Pure function exported for unit testing layout math. */
|
|
export function computeDefaultSignatureLayout(
|
|
recipients: Array<{ id: number | string; pageNumber: number }>,
|
|
): DocumensoFieldPlacement[] {
|
|
const n = recipients.length;
|
|
if (n === 0) return [];
|
|
const slot = Math.min(20, 80 / n); // percent width per signer
|
|
const rowWidth = slot * n;
|
|
const startX = 50 - rowWidth / 2;
|
|
return recipients.map((r, i) => ({
|
|
recipientId: r.id,
|
|
type: 'SIGNATURE',
|
|
pageNumber: r.pageNumber,
|
|
pageX: Math.max(0, startX + i * slot),
|
|
pageY: 88,
|
|
pageWidth: slot,
|
|
pageHeight: 6,
|
|
}));
|
|
}
|
|
|
|
/**
|
|
* Void/cancel a Documenso document.
|
|
*
|
|
* v1: DELETE /api/v1/documents/{id}
|
|
* v2: DELETE /api/v2/envelope/{id}
|
|
*
|
|
* Idempotent on 404 (already gone) - logs and resolves.
|
|
*/
|
|
export async function voidDocument(docId: string, portId?: string): Promise<void> {
|
|
const { baseUrl, apiKey, apiVersion } = await resolveCreds(portId);
|
|
const path = apiVersion === 'v2' ? `/api/v2/envelope/${docId}` : `/api/v1/documents/${docId}`;
|
|
const res = await fetchWithTimeout(`${baseUrl}${path}`, {
|
|
method: 'DELETE',
|
|
headers: { Authorization: `Bearer ${apiKey}` },
|
|
});
|
|
if (res.status === 404) {
|
|
logger.warn({ docId, portId }, 'Documenso voidDocument: already deleted');
|
|
return;
|
|
}
|
|
if (!res.ok) {
|
|
const err = await res.text();
|
|
logger.error({ docId, status: res.status, err, portId }, 'Documenso voidDocument error');
|
|
if (res.status === 401 || res.status === 403) {
|
|
throw new CodedError('DOCUMENSO_AUTH_FAILURE', {
|
|
internalMessage: `voidDocument ${docId} → ${res.status}`,
|
|
});
|
|
}
|
|
throw new CodedError('DOCUMENSO_UPSTREAM_ERROR', {
|
|
internalMessage: `voidDocument ${docId} → ${res.status}: ${err}`,
|
|
});
|
|
}
|
|
}
|