Skip to content

Open-source document signature platform. Not affiliated with DocuSign.

TypeScript

Let the sender choose a signing deadline for each envelope

Clauded513ef984b7e
diff --git a/db/migrations/20261114090000_envelope_deadline.sql b/db/migrations/20261114090000_envelope_deadline.sql
new file mode 100644
index 0000000..4055a0d
--- /dev/null
+++ b/db/migrations/20261114090000_envelope_deadline.sql
@@ -0,0 +1,40 @@
+-- A deadline for each envelope, chosen by the sender when it is sent.
+--
+-- * envelopes.expires_at: when the request stops being signable. Every
+-- signing link of the envelope expires at this moment. Null on envelopes
+-- sent before this migration, whose links keep their own seven-day life.
+-- * envelopes.expiry_notified_at: set once the daily job has told the sender
+-- that the deadline passed, so it tells them only once.
+-- * audit_events: two new kinds, for a changed deadline and a passed one.
+
+alter table public.envelopes
+ add column if not exists expires_at bigint,
+ add column if not exists expiry_notified_at bigint;
+
+create index if not exists idx_envelopes_expiry_due
+ on public.envelopes(expires_at)
+ where status = 'sent'
+ and expires_at is not null
+ and expiry_notified_at is null;
+
+alter table public.audit_events
+ drop constraint if exists audit_events_event_check;
+
+alter table public.audit_events
+ add constraint audit_events_event_check
+ check (event in (
+ 'created',
+ 'sent',
+ 'viewed',
+ 'consented',
+ 'verified',
+ 'verification_failed',
+ 'signed',
+ 'declined',
+ 'reminded_manual',
+ 'email_sent',
+ 'completed',
+ 'voided',
+ 'deadline_changed',
+ 'expired'
+ ));
diff --git a/src/app/api/envelopes/[id]/deadline/route.ts b/src/app/api/envelopes/[id]/deadline/route.ts
new file mode 100644
index 0000000..4d7c44d
--- /dev/null
+++ b/src/app/api/envelopes/[id]/deadline/route.ts
@@ -0,0 +1,101 @@
+import { NextResponse } from "next/server";
+
+import { requireVerifiedSenderSession } from "@/lib/auth/route-session";
+import { getDb } from "@/lib/db/connection";
+import { changeEnvelopeDeadline, EnvelopeMutationError } from "@/lib/envelopes";
+import { changeDeadlineSchema } from "@/lib/schemas/envelope";
+import { logRouteError } from "@/lib/security/logging";
+import {
+ applyRateLimit,
+ buildRateLimitKey,
+} from "@/lib/security/route-controls";
+import {
+ getClientIpAddress,
+ getRequestPathname,
+ getRequestUserAgent,
+} from "@/lib/security/request";
+
+type EnvelopeDeadlineRouteContext = {
+ params: Promise<{
+ id: string;
+ }>;
+};
+
+const noStore = { "cache-control": "private, no-store" };
+
+// Gives an envelope that is out for signature a new deadline, counted in
+// days from now. Works on an expired one too, which is how it is revived.
+export async function POST(
+ request: Request,
+ context: EnvelopeDeadlineRouteContext,
+) {
+ const sessionResult = await requireVerifiedSenderSession(request);
+
+ if (sessionResult instanceof Response) {
+ return sessionResult;
+ }
+
+ const session = sessionResult;
+ const { id } = await context.params;
+ const ipAddress = getClientIpAddress(request.headers);
+ const rateLimitResponse = await applyRateLimit({
+ category: "envelope_deadline",
+ key: buildRateLimitKey(["envelope-deadline", session.user.id, id]),
+ limit: 20,
+ request,
+ userId: session.user.id,
+ windowMs: 60 * 60 * 1000,
+ });
+
+ if (rateLimitResponse) {
+ rateLimitResponse.headers.set("cache-control", "private, no-store");
+ return rateLimitResponse;
+ }
+
+ const parsed = changeDeadlineSchema.safeParse(
+ await request.json().catch(() => null),
+ );
+
+ if (!parsed.success) {
+ return NextResponse.json(
+ { error: "Choose a deadline between 1 and 365 days from now." },
+ { headers: noStore, status: 400 },
+ );
+ }
+
+ try {
+ const result = await changeEnvelopeDeadline(
+ session.user.id,
+ id,
+ {
+ expiresInDays: parsed.data.expiresInDays,
+ ipAddress,
+ senderEmail: session.user.email,
+ userAgent: getRequestUserAgent(request.headers),
+ },
+ { database: getDb() },
+ );
+
+ return NextResponse.json(result, { headers: noStore, status: 200 });
+ } catch (error) {
+ if (error instanceof EnvelopeMutationError) {
+ return NextResponse.json(
+ { error: error.message },
+ { headers: noStore, status: error.statusCode },
+ );
+ }
+
+ logRouteError(error, {
+ category: "envelope_deadline_failure",
+ ipAddress,
+ message: "Unexpected failure while changing an envelope deadline.",
+ path: getRequestPathname(request),
+ userId: session.user.id,
+ });
+
+ return NextResponse.json(
+ { error: "Unable to change the deadline." },
+ { headers: noStore, status: 500 },
+ );
+ }
+}
diff --git a/src/app/api/envelopes/[id]/send/route.ts b/src/app/api/envelopes/[id]/send/route.ts
index 9e4bada..61beced 100644
--- a/src/app/api/envelopes/[id]/send/route.ts
+++ b/src/app/api/envelopes/[id]/send/route.ts
@@ -3,6 +3,7 @@ import { NextResponse } from "next/server";
import { requireVerifiedSenderSession } from "@/lib/auth/route-session";
import { getDb } from "@/lib/db/connection";
import { EnvelopeMutationError, sendDraftEnvelope } from "@/lib/envelopes";
+import { sendEnvelopeOptionsSchema } from "@/lib/schemas/envelope";
import { logRouteError } from "@/lib/security/logging";
import {
applyRateLimit,
@@ -21,6 +22,7 @@ type EnvelopeSendRouteContext = {
};
type SendEnvelopeRequest = {
+ expiresInDays?: unknown;
permittedUseConfirmed?: boolean;
};
@@ -65,11 +67,23 @@ export async function POST(
);
}
+ const options = sendEnvelopeOptionsSchema.safeParse({
+ expiresInDays: body.expiresInDays ?? undefined,
+ });
+
+ if (!options.success) {
+ return NextResponse.json(
+ { error: "Choose a deadline between 1 and 365 days from now." },
+ { status: 400 },
+ );
+ }
+
try {
const result = await sendDraftEnvelope(
session.user.id,
id,
{
+ expiresInDays: options.data.expiresInDays,
ipAddress,
senderEmail: session.user.email,
senderName:
diff --git a/src/app/api/internal/retention/route.ts b/src/app/api/internal/retention/route.ts
index fb5bdf3..bcae3a3 100644
--- a/src/app/api/internal/retention/route.ts
+++ b/src/app/api/internal/retention/route.ts
@@ -3,14 +3,15 @@ import { NextResponse } from "next/server";
import {
identifyRetentionCaller,
isCronLockedOutByOlderSecret,
- retentionSweepFailed,
+ retentionJobFailed,
runRetentionJob,
} from "@/lib/retention-job";
import { logRouteError } from "@/lib/security/logging";
import { getClientIpAddress, getRequestPathname } from "@/lib/security/request";
-// The daily cleanup. Vercel's cron job calls this with GET (see
-// vercel.json); a scheduler elsewhere can use POST as before.
+// The daily job: the cleanup, then expiry notices for envelopes whose
+// deadline passed. Vercel's cron job calls this with GET (see vercel.json);
+// a scheduler elsewhere can use POST as before.
//
// With a job secret configured, only a caller that presents it gets in, and
// it gets the summary back. With none, anyone may call and gets an empty
@@ -32,12 +33,13 @@ async function handle(request: Request) {
try {
const outcome = await runRetentionJob({ caller });
- const failed =
- outcome.status === "ran" && retentionSweepFailed(outcome.summary);
+ const failed = outcome.status === "ran" && retentionJobFailed(outcome);
if (caller === "authorized") {
return NextResponse.json(
- outcome.status === "ran" ? outcome.summary : outcome,
+ outcome.status === "ran"
+ ? { ...outcome.summary, schedule: outcome.schedule }
+ : outcome,
{ status: failed ? 500 : 200 },
);
}
diff --git a/src/components/dashboard/dashboard-documents-surface.tsx b/src/components/dashboard/dashboard-documents-surface.tsx
index 55ace2c..fde95a5 100644
--- a/src/components/dashboard/dashboard-documents-surface.tsx
+++ b/src/components/dashboard/dashboard-documents-surface.tsx
@@ -273,8 +273,15 @@ function EnvelopeCard({
<span className="flex flex-wrap items-center justify-between gap-x-3 gap-y-1.5 px-1 pb-0.5">
<span
- aria-label={`Status: ${statusLabelMap[envelope.status]}`}
- className={cn("pill", statusPillClasses[envelope.status])}
+ aria-label={`Status: ${
+ envelope.expired ? "Expired" : statusLabelMap[envelope.status]
+ }`}
+ className={cn(
+ "pill",
+ envelope.expired
+ ? "pill-danger"
+ : statusPillClasses[envelope.status],
+ )}
>
{envelope.statusLabel}
</span>
diff --git a/src/components/envelopes/envelope-detail-shell.tsx b/src/components/envelopes/envelope-detail-shell.tsx
index d40ecaf..913a295 100644
--- a/src/components/envelopes/envelope-detail-shell.tsx
+++ b/src/components/envelopes/envelope-detail-shell.tsx
@@ -25,6 +25,10 @@ import type {
EnvelopeDetailData,
EnvelopeDetailTimelineItem,
} from "@/lib/envelopes";
+import {
+ DEFAULT_ENVELOPE_DEADLINE_DAYS,
+ ENVELOPE_DEADLINE_DAY_OPTIONS,
+} from "@/lib/types/domain";
import { getSignerPalette } from "./signer-palette";
type EnvelopeDetailShellProps = {
@@ -60,7 +64,7 @@ type EnvelopeDetailRecord = {
title: string;
};
-type ModalState = "delete-draft" | "void-envelope" | null;
+type ModalState = "change-deadline" | "delete-draft" | "void-envelope" | null;
const statusPillClasses: Record<EnvelopeStatus, string> = {
completed: "pill-success",
@@ -113,6 +117,7 @@ export function EnvelopeDetailShell({
}: EnvelopeDetailShellProps) {
const [activeModal, setActiveModal] = useState<ModalState>(null);
const [actionError, setActionError] = useState<string | null>(null);
+ const [isChangingDeadline, setIsChangingDeadline] = useState(false);
const [isDeletingDraft, setIsDeletingDraft] = useState(false);
const [isSendingReminder, setIsSendingReminder] = useState(false);
const [isVoidingEnvelope, setIsVoidingEnvelope] = useState(false);
@@ -170,6 +175,8 @@ export function EnvelopeDetailShell({
timeline: record.timeline,
title: record.title,
};
+ const deadline = activeRecord.status === "sent" ? record.deadline : null;
+ const isExpired = Boolean(deadline?.expired);
const manualReminderState = record.manualReminder ?? null;
const reminderLimited =
activeRecord.status === "sent" &&
@@ -179,6 +186,13 @@ export function EnvelopeDetailShell({
activeRecord.status === "sent" && manualReminderState?.nextAvailableAtLabel
? `You can send another reminder after ${manualReminderState.nextAvailableAtLabel}.`
: null;
+ const deadlineText = !deadline
+ ? null
+ : isExpired
+ ? `Expired ${deadline.expiresAtLabel}. Nobody can sign until you set a new deadline.`
+ : deadline.expiresAtLabel
+ ? `Expires ${deadline.expiresAtLabel}.`
+ : "No deadline. Each signing link lasts seven days.";
const activeSigner =
activeRecord.status === "sent"
? activeRecord.signers.find((signer) => signer.status === "waiting")
@@ -224,6 +238,33 @@ export function EnvelopeDetailShell({
}
}
+ async function handleConfirmChangeDeadline(expiresInDays: number) {
+ setActionError(null);
+ setIsChangingDeadline(true);
+
+ try {
+ const response = await fetch(`/api/envelopes/${envelopeId}/deadline`, {
+ body: JSON.stringify({ expiresInDays }),
+ headers: { "content-type": "application/json" },
+ method: "POST",
+ });
+ const payload = (await response.json().catch(() => null)) as {
+ error?: string;
+ } | null;
+
+ if (response.ok || response.status === 404 || response.status === 409) {
+ window.location.reload();
+ return;
+ }
+
+ setActionError(payload?.error ?? "Unable to change the deadline.");
+ } catch {
+ setActionError("Unable to change the deadline.");
+ } finally {
+ setIsChangingDeadline(false);
+ }
+ }
+
async function handleConfirmDeleteDraft() {
setActionError(null);
setIsDeletingDraft(true);
@@ -310,9 +351,13 @@ export function EnvelopeDetailShell({
</h1>
<div className="flex flex-wrap items-center gap-x-3 gap-y-2">
<span
- className={`pill ${statusPillClasses[activeRecord.status]}`}
+ className={`pill ${
+ isExpired
+ ? "pill-danger"
+ : statusPillClasses[activeRecord.status]
+ }`}
>
- {statusLabelMap[activeRecord.status]}
+ {isExpired ? "Expired" : statusLabelMap[activeRecord.status]}
</span>
<p className="text-sm text-(--secondary)">
Created {activeRecord.createdAtLabel}
@@ -391,6 +436,32 @@ export function EnvelopeDetailShell({
</p>
) : null}
+ {deadlineText ? (
+ <div
+ className={`mt-5 flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between ${
+ isExpired ? "notice notice-danger" : "well px-5 py-3.5"
+ }`}
+ >
+ <p
+ className={
+ isExpired ? undefined : "text-sm leading-6 text-(--secondary)"
+ }
+ >
+ {deadlineText}
+ </p>
+ <button
+ className="btn-quiet shrink-0"
+ onClick={() => {
+ setActionError(null);
+ setActiveModal("change-deadline");
+ }}
+ type="button"
+ >
+ {isExpired ? "Set a new deadline" : "Change deadline"}
+ </button>
+ </div>
+ ) : null}
+
{actionError ? (
<div className="notice notice-danger mt-5" role="alert">
{actionError}
@@ -507,6 +578,16 @@ export function EnvelopeDetailShell({
</article>
</section>
+ {activeModal === "change-deadline" ? (
+ <DeadlineDialog
+ errorMessage={actionError}
+ expired={isExpired}
+ onCancel={() => setActiveModal(null)}
+ onConfirm={handleConfirmChangeDeadline}
+ processing={isChangingDeadline}
+ />
+ ) : null}
+
{activeModal === "delete-draft" ? (
<ConfirmationDialog
confirmLabel="Delete draft"
@@ -541,6 +622,93 @@ export function EnvelopeDetailShell({
);
}
+type DeadlineDialogProps = {
+ errorMessage?: string | null;
+ expired: boolean;
+ onCancel: () => void;
+ onConfirm: (expiresInDays: number) => void | Promise<void>;
+ processing?: boolean;
+};
+
+function DeadlineDialog({
+ errorMessage,
+ expired,
+ onCancel,
+ onConfirm,
+ processing = false,
+}: DeadlineDialogProps) {
+ const [days, setDays] = useState<number>(DEFAULT_ENVELOPE_DEADLINE_DAYS);
+
+ return (
+ <Dialog
+ open
+ onOpenChange={(open) => {
+ if (!open && !processing) {
+ onCancel();
+ }
+ }}
+ >
+ <DialogContent className="max-w-md sm:p-8" showCloseButton={false}>
+ <div className="space-y-4">
+ <DialogHeader className="space-y-3">
+ <DialogTitle>
+ {expired ? "Set a new deadline" : "Change the deadline"}
+ </DialogTitle>
+ <DialogDescription asChild>
+ <div className="space-y-2 text-sm leading-6 text-(--secondary)">
+ <p>
+ The new deadline counts from now.{" "}
+ {expired
+ ? "The signing link that was already sent will work again."
+ : "The signing link that was already sent keeps working until then."}
+ </p>
+ </div>
+ </DialogDescription>
+ </DialogHeader>
+
+ <label className="grid gap-1.5">
+ <span className="text-[0.8125rem] font-semibold text-(--secondary)">
+ Signing deadline
+ </span>
+ <select
+ autoFocus
+ className="field-input"
+ disabled={processing}
+ onChange={(event) => setDays(Number(event.target.value))}
+ value={days}
+ >
+ {ENVELOPE_DEADLINE_DAY_OPTIONS.map((option) => (
+ <option key={option} value={option}>
+ {option} days from now
+ </option>
+ ))}
+ </select>
+ </label>
+
+ {errorMessage ? (
+ <div className="notice notice-danger" role="alert">
+ <p>{errorMessage}</p>
+ </div>
+ ) : null}
+
+ <div className="flex flex-col-reverse gap-3 pt-2 sm:flex-row sm:justify-end">
+ <ShellButton
+ disabled={processing}
+ onClick={onCancel}
+ variant="secondary"
+ >
+ Cancel
+ </ShellButton>
+ <ShellButton loading={processing} onClick={() => onConfirm(days)}>
+ {processing ? "Saving..." : "Save deadline"}
+ </ShellButton>
+ </div>
+ </div>
+ </DialogContent>
+ </Dialog>
+ );
+}
+
type ConfirmationDialogProps = {
confirmLabel: string;
description: readonly string[];
diff --git a/src/components/envelopes/review-shell.tsx b/src/components/envelopes/review-shell.tsx
index 9cb9f2e..7fc6c70 100644
--- a/src/components/envelopes/review-shell.tsx
+++ b/src/components/envelopes/review-shell.tsx
@@ -17,6 +17,10 @@ import {
} from "@/components/ui/dialog";
import type { ReviewEnvelopeData } from "@/lib/envelopes";
import { PERMITTED_USE_PATH } from "@/lib/permitted-uses";
+import {
+ DEFAULT_ENVELOPE_DEADLINE_DAYS,
+ ENVELOPE_DEADLINE_DAY_OPTIONS,
+} from "@/lib/types/domain";
import { getSignerPalette } from "./signer-palette";
const envelopeSteps = ["Upload", "Signers", "Place fields", "Review"];
@@ -61,6 +65,9 @@ export function ReviewShell({
initialState,
record,
}: ReviewShellProps) {
+ const [deadlineDays, setDeadlineDays] = useState<number>(
+ DEFAULT_ENVELOPE_DEADLINE_DAYS,
+ );
const [isConfirmationOpen, setIsConfirmationOpen] = useState(false);
const [notice, setNotice] = useState<string | null>(null);
const [sendPhase, setSendPhase] = useState<SendPhase>("idle");
@@ -107,6 +114,7 @@ export function ReviewShell({
try {
const response = await fetch(`/api/envelopes/${envelopeId}/send`, {
body: JSON.stringify({
+ expiresInDays: deadlineDays,
permittedUseConfirmed: true,
}),
headers: {
@@ -320,6 +328,32 @@ export function ReviewShell({
sign. Each signer is notified in order after the previous signer
completes.
</p>
+
+ <div className="well mt-4 p-4">
+ <label className="grid gap-1.5 sm:max-w-xs">
+ <span className="text-[0.8125rem] font-semibold text-(--secondary)">
+ Signing deadline
+ </span>
+ <select
+ className="field-input"
+ disabled={sendPhase === "sending" || Boolean(notice)}
+ onChange={(event) =>
+ setDeadlineDays(Number(event.target.value))
+ }
+ value={deadlineDays}
+ >
+ {ENVELOPE_DEADLINE_DAY_OPTIONS.map((days) => (
+ <option key={days} value={days}>
+ {days} days
+ </option>
+ ))}
+ </select>
+ </label>
+ <p className="mt-2 text-sm leading-6 text-(--secondary)">
+ Signing links stop working after this. You can change the
+ deadline later from the envelope.
+ </p>
+ </div>
</article>
</div>
@@ -344,6 +378,7 @@ export function ReviewShell({
{isConfirmationOpen ? (
<SendConfirmationDialog
+ deadlineDays={deadlineDays}
errorMessage={sendPhase === "error" ? sendError : null}
firstSignerName={firstSigner?.name ?? "Signer 1"}
isSending={sendPhase === "sending"}
@@ -358,6 +393,7 @@ export function ReviewShell({
}
type SendConfirmationDialogProps = {
+ deadlineDays: number;
errorMessage: string | null;
firstSignerName: string;
isSending: boolean;
@@ -368,6 +404,7 @@ type SendConfirmationDialogProps = {
};
function SendConfirmationDialog({
+ deadlineDays,
errorMessage,
firstSignerName,
isSending,
@@ -398,7 +435,8 @@ function SendConfirmationDialog({
{signerCount === 1 ? "signer" : "signers"}.{" "}
{signerCount === 1
? `${firstSignerName} will be notified immediately.`
- : `The first signer (${firstSignerName}) will be notified immediately.`}
+ : `The first signer (${firstSignerName}) will be notified immediately.`}{" "}
+ The request expires in {deadlineDays} days.
</p>
</div>
</DialogDescription>
diff --git a/src/components/landing/landing-shell.tsx b/src/components/landing/landing-shell.tsx
index f1e030a..25971e9 100644
--- a/src/components/landing/landing-shell.tsx
+++ b/src/components/landing/landing-shell.tsx
@@ -108,7 +108,7 @@ const securityPillars: readonly SecurityPillar[] = [
},
{
title: "Secure signing links",
- body: "Each signer gets a unique cryptographic token. Links expire after 7 days and can't be guessed or reused.",
+ body: "Each signer gets a unique cryptographic token. Links expire at the deadline the sender sets and can't be guessed or reused.",
icon: Link2,
},
{
diff --git a/src/lib/envelope-deadline.dbtest.ts b/src/lib/envelope-deadline.dbtest.ts
new file mode 100644
index 0000000..3795c08
--- /dev/null
+++ b/src/lib/envelope-deadline.dbtest.ts
@@ -0,0 +1,355 @@
+import assert from "node:assert/strict";
+import { randomUUID } from "node:crypto";
+import { after, before, test } from "node:test";
+
+import type pg from "pg";
+
+import { openTestDatabase } from "./db/test-database.ts";
+import { runEnvelopeSchedule } from "./envelope-schedule.ts";
+import { changeEnvelopeDeadline, EnvelopeMutationError } from "./envelopes.ts";
+import { ReminderMutationError, sendManualEnvelopeNudge } from "./reminders.ts";
+import { verifyAuditChain } from "./services/audit.ts";
+import type {
+ EmailService,
+ TransactionalEmailMessage,
+} from "./services/email.ts";
+import { issueSigningLink } from "./services/signing-links.ts";
+import { recordSignerConsent, SigningAccessError } from "./signing.ts";
+import { ELECTRONIC_RECORDS_DISCLOSURE_VERSION } from "./electronic-records-disclosure.ts";
+
+// An envelope's deadline against a real Postgres: what a passed deadline
+// stops, what a new one brings back, and the one notice the daily job sends.
+// Run with `npm run test:db`.
+
+process.env.APP_URL ??= "https://sign.example.test";
+
+const DAY = 24 * 60 * 60;
+
+let database: pg.Pool;
+const createdUsers: string[] = [];
+
+before(async () => {
+ database = await openTestDatabase();
+});
+
+after(async () => {
+ await database.query(`delete from public."user" where id = any($1)`, [
+ createdUsers,
+ ]);
+ await database.end();
+});
+
+function unixNow() {
+ return Math.floor(Date.now() / 1000);
+}
+
+/** An envelope out for signature, waiting on its one signer. */
+async function createSentEnvelope({
+ expiresAt,
+ status = "sent",
+}: {
+ expiresAt: number | null;
+ status?: "draft" | "sent";
+}) {
+ const userId = randomUUID();
+ const envelopeId = randomUUID();
+ const signerId = randomUUID();
+ const sentAt = unixNow() - 40 * DAY;
+ const link = await issueSigningLink({
+ expiresInSeconds: 60,
+ issuedAt: sentAt,
+ });
+
+ createdUsers.push(userId);
+ await database.query(
+ `insert into public."user" (id, name, email, role) values ($1, 'Sam Sender', $2, 'user')`,
+ [userId, `${userId}@example.test`],
+ );
+ await database.query(
+ `
+ insert into envelopes (
+ id, user_id, title, status, source_pdf_key, source_pdf_filename,
+ source_pdf_size_bytes, page_count, source_pdf_hash, sent_at, expires_at
+ ) values ($1, $2, 'Lease', $3, $4, 'lease.pdf', 10, 1, $5, $6, $7)
+ `,
+ [
+ envelopeId,
+ userId,
+ status,
+ `test/${envelopeId}.pdf`,
+ "a".repeat(64),
+ status === "sent" ? sentAt : null,
+ expiresAt,
+ ],
+ );
+ await database.query(
+ `
+ insert into signers (
+ id, envelope_id, name, email, sign_order, status,
+ signing_token_hash, signing_token_expires_at, last_notified_at
+ ) values ($1, $2, 'Riley Recipient', $3, 1, $4, $5, $6, $7)
+ `,
+ [
+ signerId,
+ envelopeId,
+ `${signerId}@example.test`,
+ status === "sent" ? "notified" : "pending",
+ status === "sent" ? link.tokenHash : null,
+ status === "sent" ? link.exp : null,
+ status === "sent" ? sentAt : null,
+ ],
+ );
+
+ return { envelopeId, signerId, token: link.token, userId };
+}
+
+async function readEnvelope(envelopeId: string) {
+ const result = await database.query<{
+ expires_at: number | null;
+ expiry_notified_at: number | null;
+ }>(`select expires_at, expiry_notified_at from envelopes where id = $1`, [
+ envelopeId,
+ ]);
+
+ return result.rows[0]!;
+}
+
+async function auditEvents(envelopeId: string) {
+ const result = await database.query<{ event: string }>(
+ `select event from audit_events where envelope_id = $1 order by sequence`,
+ [envelopeId],
+ );
+
+ return result.rows.map((row) => row.event);
+}
+
+function consent(token: string) {
+ return recordSignerConsent(
+ token,
+ { disclosureVersion: ELECTRONIC_RECORDS_DISCLOSURE_VERSION },
+ { database },
+ );
+}
+
+function recordingEmailService(failWith?: Error) {
+ const sent: TransactionalEmailMessage[] = [];
+ const service: EmailService = {
+ async send(message) {
+ if (failWith) {
+ throw failWith;
+ }
+
+ sent.push(message);
+
+ return { accepted: [message.to], messageId: "m-1", rejected: [] };
+ },
+ async sendBatch() {
+ throw new Error("not used");
+ },
+ };
+
+ return { sent, service };
+}
+
+test("a passed deadline stops signing, and a new one brings the same link back", async () => {
+ const { envelopeId, signerId, token, userId } = await createSentEnvelope({
+ expiresAt: unixNow() - 60,
+ });
+
+ await assert.rejects(consent(token), (error: unknown) => {
+ assert.ok(error instanceof SigningAccessError);
+ assert.equal(error.state, "expired");
+ return true;
+ });
+
+ const before = unixNow();
+ const changed = await changeEnvelopeDeadline(
+ userId,
+ envelopeId,
+ { expiresInDays: 7, senderEmail: "[email protected]" },
+ { database },
+ );
+
+ assert.ok(changed.expiresAt >= before + 7 * DAY);
+ assert.equal((await readEnvelope(envelopeId)).expires_at, changed.expiresAt);
+
+ const signer = await database.query<{ signing_token_expires_at: number }>(
+ `select signing_token_expires_at from signers where id = $1`,
+ [signerId],
+ );
+
+ // The link the signer already holds now lasts until the new deadline.
+ assert.equal(signer.rows[0]?.signing_token_expires_at, changed.expiresAt);
+ assert.ok((await consent(token)).consentedAt > 0);
+ assert.deepEqual(await auditEvents(envelopeId), [
+ "deadline_changed",
+ "consented",
+ ]);
+ assert.equal((await verifyAuditChain(envelopeId, database)).ok, true);
+});
+
+test("a link that outlives the envelope's deadline does not work past it", async () => {
+ const { signerId, token } = await createSentEnvelope({
+ expiresAt: unixNow() - 60,
+ });
+
+ await database.query(
+ `update signers set signing_token_expires_at = $1 where id = $2`,
+ [unixNow() + DAY, signerId],
+ );
+
+ await assert.rejects(consent(token), SigningAccessError);
+});
+
+test("only the owner of an envelope that is out can change its deadline", async () => {
+ const sent = await createSentEnvelope({ expiresAt: unixNow() + DAY });
+ const draft = await createSentEnvelope({ expiresAt: null, status: "draft" });
+ const input = { expiresInDays: 7, senderEmail: "[email protected]" };
+
+ await assert.rejects(
+ changeEnvelopeDeadline(draft.userId, sent.envelopeId, input, { database }),
+ (error: unknown) =>
+ error instanceof EnvelopeMutationError && error.statusCode === 404,
+ );
+ await assert.rejects(
+ changeEnvelopeDeadline(draft.userId, draft.envelopeId, input, { database }),
+ (error: unknown) =>
+ error instanceof EnvelopeMutationError && error.statusCode === 409,
+ );
+ assert.deepEqual(await auditEvents(sent.envelopeId), []);
+});
+
+test("a reminder is refused once the deadline has passed", async () => {
+ const { envelopeId, userId } = await createSentEnvelope({
+ expiresAt: unixNow() - 60,
+ });
+
+ await assert.rejects(
+ sendManualEnvelopeNudge(
+ userId,
+ envelopeId,
+ { senderEmail: "[email protected]", senderName: "Sam Sender" },
+ { database },
+ ),
+ (error: unknown) => {
+ assert.ok(error instanceof ReminderMutationError);
+ assert.equal(error.statusCode, 409);
+ assert.match(error.message, /^This request expired on /);
+ return true;
+ },
+ );
+ assert.deepEqual(await auditEvents(envelopeId), []);
+});
+
+test("the daily job tells the sender once that a deadline passed", async () => {
+ const now = unixNow();
+ const expired = await createSentEnvelope({ expiresAt: now - 60 });
+ const open = await createSentEnvelope({ expiresAt: now + DAY });
+ const legacy = await createSentEnvelope({ expiresAt: null });
+ const { sent, service } = recordingEmailService();
+
+ const first = await runEnvelopeSchedule({
+ database,
+ emailService: service,
+ now,
+ });
+ const mine = sent.filter((message) => message.to.startsWith(expired.userId));
+
+ assert.equal(first.expiryNoticeFailures.length, 0);
+ assert.equal(mine.length, 1);
+ assert.equal(mine[0]?.template, "expiry_notice");
+ assert.equal(mine[0]?.subject, '"Lease" expired before everyone signed');
+ assert.match(mine[0]?.textBody ?? "", /still waiting on Riley Recipient \(/);
+ assert.match(
+ mine[0]?.textBody ?? "",
+ new RegExp(`/envelopes/${expired.envelopeId}$`),
+ );
+ assert.equal(
+ (await readEnvelope(expired.envelopeId)).expiry_notified_at,
+ now,
+ );
+ assert.deepEqual(await auditEvents(expired.envelopeId), ["expired"]);
+
+ // Nothing for one still inside its deadline, or one that never had one.
+ assert.equal(
+ sent.some(
+ (message) =>
+ message.to.startsWith(open.userId) ||
+ message.to.startsWith(legacy.userId),
+ ),
+ false,
+ );
+
+ await runEnvelopeSchedule({
+ database,
+ emailService: service,
+ now: now + DAY,
+ });
+
+ assert.equal(
+ sent.filter((message) => message.to.startsWith(expired.userId)).length,
+ 1,
+ );
+
+ // A new deadline that passes in turn is a new thing to tell.
+ const changed = await changeEnvelopeDeadline(
+ expired.userId,
+ expired.envelopeId,
+ { expiresInDays: 1, senderEmail: "[email protected]" },
+ { database },
+ );
+
+ assert.equal(
+ (await readEnvelope(expired.envelopeId)).expiry_notified_at,
+ null,
+ );
+
+ await runEnvelopeSchedule({
+ database,
+ emailService: service,
+ now: changed.expiresAt + 1,
+ });
+
+ assert.equal(
+ sent.filter((message) => message.to.startsWith(expired.userId)).length,
+ 2,
+ );
+ assert.deepEqual(await auditEvents(expired.envelopeId), [
+ "expired",
+ "deadline_changed",
+ "expired",
+ ]);
+ assert.equal((await verifyAuditChain(expired.envelopeId, database)).ok, true);
+});
+
+test("a notice whose email fails is tried again on the next run", async () => {
+ const now = unixNow();
+ const { envelopeId, userId } = await createSentEnvelope({
+ expiresAt: now - 60,
+ });
+ const failing = recordingEmailService(new Error("mail is down"));
+
+ const failed = await runEnvelopeSchedule({
+ database,
+ emailService: failing.service,
+ now,
+ });
+
+ assert.ok(failed.expiryNoticeFailures.includes(envelopeId));
+ assert.equal((await readEnvelope(envelopeId)).expiry_notified_at, null);
+ assert.deepEqual(await auditEvents(envelopeId), []);
+
+ const working = recordingEmailService();
+
+ await runEnvelopeSchedule({
+ database,
+ emailService: working.service,
+ now: now + 60,
+ });
+
+ assert.equal(
+ working.sent.filter((message) => message.to.startsWith(userId)).length,
+ 1,
+ );
+ assert.deepEqual(await auditEvents(envelopeId), ["expired"]);
+});
diff --git a/src/lib/envelope-deadline.test.ts b/src/lib/envelope-deadline.test.ts
new file mode 100644
index 0000000..ce0091a
--- /dev/null
+++ b/src/lib/envelope-deadline.test.ts
@@ -0,0 +1,77 @@
+import assert from "node:assert/strict";
+import { test } from "node:test";
+
+import {
+ deadlineFromDays,
+ EnvelopeDeadlinePassedError,
+ formatDeadline,
+ isEnvelopeExpired,
+ parseDeadlineDays,
+ signingLinkLifetimeSeconds,
+} from "./envelope-deadline.ts";
+import { buildDeadlineLine } from "./services/signing-invitation-email.ts";
+import { SIGNING_LINK_TTL_SECONDS } from "./types/domain.ts";
+
+const DAY = 24 * 60 * 60;
+const NOW = 1_800_000_000;
+
+test("a deadline is a whole number of days from now, thirty by default", () => {
+ assert.equal(deadlineFromDays(NOW), NOW + 30 * DAY);
+ assert.equal(deadlineFromDays(NOW, 3), NOW + 3 * DAY);
+});
+
+test("only whole days from 1 to 365 are accepted", () => {
+ assert.equal(parseDeadlineDays(14), 14);
+ assert.equal(parseDeadlineDays(365), 365);
+
+ for (const refused of [0, -1, 366, 1.5, "14", null, undefined, Number.NaN]) {
+ assert.equal(parseDeadlineDays(refused), null);
+ }
+});
+
+test("only an envelope out for signature can be expired", () => {
+ assert.equal(
+ isEnvelopeExpired({ expiresAt: NOW - 1, status: "sent" }, NOW),
+ true,
+ );
+ // The deadline itself is the first moment it no longer counts.
+ assert.equal(
+ isEnvelopeExpired({ expiresAt: NOW, status: "sent" }, NOW),
+ true,
+ );
+ assert.equal(
+ isEnvelopeExpired({ expiresAt: NOW + 1, status: "sent" }, NOW),
+ false,
+ );
+ // Sent before deadlines existed.
+ assert.equal(
+ isEnvelopeExpired({ expiresAt: null, status: "sent" }, NOW),
+ false,
+ );
+
+ for (const status of ["draft", "completed", "declined", "voided"]) {
+ assert.equal(isEnvelopeExpired({ expiresAt: NOW - 1, status }, NOW), false);
+ }
+});
+
+test("a signing link lives until the envelope's deadline", () => {
+ assert.equal(signingLinkLifetimeSeconds(NOW + 5 * DAY, NOW), 5 * DAY);
+ assert.equal(signingLinkLifetimeSeconds(null, NOW), SIGNING_LINK_TTL_SECONDS);
+ assert.throws(
+ () => signingLinkLifetimeSeconds(NOW, NOW),
+ EnvelopeDeadlinePassedError,
+ );
+});
+
+test("a deadline is written out in full, in UTC", () => {
+ // 2027-01-15 08:00:00 UTC
+ assert.equal(
+ formatDeadline(1_800_000_000),
+ "January 15, 2027 at 8:00 AM UTC",
+ );
+ assert.equal(
+ buildDeadlineLine(1_800_000_000),
+ "This request expires on January 15, 2027 at 8:00 AM UTC.",
+ );
+ assert.equal(buildDeadlineLine(null), null);
+});
diff --git a/src/lib/envelope-deadline.ts b/src/lib/envelope-deadline.ts
new file mode 100644
index 0000000..4b375fc
--- /dev/null
+++ b/src/lib/envelope-deadline.ts
@@ -0,0 +1,92 @@
+import {
+ DEFAULT_ENVELOPE_DEADLINE_DAYS,
+ MAX_ENVELOPE_DEADLINE_DAYS,
+ SIGNING_LINK_TTL_SECONDS,
+} from "./types/domain.ts";
+
+// The deadline of an envelope: the moment after which nobody can sign it.
+//
+// The sender picks a number of days when sending and can change it while the
+// envelope is out. Every signing link of the envelope expires at the
+// deadline, whenever the link was issued. A sent envelope whose deadline has
+// passed is shown as expired; it is still "sent" underneath, so setting a
+// later deadline brings it back.
+
+const SECONDS_PER_DAY = 24 * 60 * 60;
+
+export class EnvelopeDeadlinePassedError extends Error {
+ readonly expiresAt: number;
+
+ constructor(expiresAt: number) {
+ super(
+ `This request expired on ${formatDeadline(expiresAt)}. Set a new deadline first.`,
+ );
+ this.name = "EnvelopeDeadlinePassedError";
+ this.expiresAt = expiresAt;
+ }
+}
+
+/** A whole number of days from 1 to the maximum, or null when it is not one. */
+export function parseDeadlineDays(value: unknown): number | null {
+ return typeof value === "number" &&
+ Number.isInteger(value) &&
+ value >= 1 &&
+ value <= MAX_ENVELOPE_DEADLINE_DAYS
+ ? value
+ : null;
+}
+
+export function deadlineFromDays(
+ nowUnixTimestamp: number,
+ days: number = DEFAULT_ENVELOPE_DEADLINE_DAYS,
+): number {
+ return nowUnixTimestamp + days * SECONDS_PER_DAY;
+}
+
+/** True for an envelope that is out for signature and past its deadline. */
+export function isEnvelopeExpired(
+ envelope: { expiresAt?: number | null; status: string },
+ nowUnixTimestamp: number,
+): boolean {
+ return (
+ envelope.status === "sent" &&
+ typeof envelope.expiresAt === "number" &&
+ envelope.expiresAt <= nowUnixTimestamp
+ );
+}
+
+/**
+ * How long a signing link issued now should live. It ends at the envelope's
+ * deadline. An envelope without one (sent before deadlines existed) keeps
+ * the old seven days per link.
+ */
+export function signingLinkLifetimeSeconds(
+ envelopeExpiresAt: number | null | undefined,
+ issuedAt: number,
+): number {
+ if (typeof envelopeExpiresAt !== "number") {
+ return SIGNING_LINK_TTL_SECONDS;
+ }
+
+ if (envelopeExpiresAt <= issuedAt) {
+ throw new EnvelopeDeadlinePassedError(envelopeExpiresAt);
+ }
+
+ return envelopeExpiresAt - issuedAt;
+}
+
+const deadlineFormatter = new Intl.DateTimeFormat("en-US", {
+ day: "numeric",
+ hour: "numeric",
+ minute: "2-digit",
+ month: "long",
+ timeZone: "UTC",
+ year: "numeric",
+});
+
+/** "December 12, 2026 at 9:20 PM UTC" */
+export function formatDeadline(unixTimestamp: number): string {
+ return `${deadlineFormatter
+ .format(new Date(unixTimestamp * 1000))
+ .replace(/[  ]/g, " ")} UTC`;
+}
diff --git a/src/lib/envelope-schedule.ts b/src/lib/envelope-schedule.ts
new file mode 100644
index 0000000..149e38d
--- /dev/null
+++ b/src/lib/envelope-schedule.ts
@@ -0,0 +1,233 @@
+import { type DbPool, queryMany, withTransaction } from "./db/connection.ts";
+import { formatDeadline } from "./envelope-deadline.ts";
+import { lockEnvelopeAuditChain, recordAuditEvent } from "./services/audit.ts";
+import { createEmailService, type EmailService } from "./services/email.ts";
+import { resolveAppUrl } from "./utils/env.ts";
+
+// What the daily job does for envelopes that are out for signature: it tells
+// a sender once when a deadline has passed with signatures still missing.
+//
+// It runs from the same cron call as the cleanup (see retention-job.ts), so
+// an install needs no second schedule. Each envelope is claimed in the
+// database before its email goes out, and the claim is given back if the
+// email fails, so a failed run is retried the next day and a second run
+// never sends twice.
+
+const BATCH_SIZE = 200;
+
+export type EnvelopeScheduleSummary = {
+ expiryNoticeFailures: string[];
+ expiryNoticesSent: number;
+};
+
+type ExpiredEnvelopeRow = {
+ expiresAt: number;
+ id: string;
+ ownerEmail: string;
+ ownerName: string | null;
+ signerEmail: string | null;
+ signerName: string | null;
+ title: string;
+};
+
+async function listExpiredEnvelopesToNotify(
+ now: number,
+ database: DbPool,
+): Promise<ExpiredEnvelopeRow[]> {
+ return queryMany<ExpiredEnvelopeRow>(
+ database,
+ `
+ SELECT
+ e.id,
+ e.title,
+ e.expires_at AS "expiresAt",
+ u.email AS "ownerEmail",
+ u.name AS "ownerName",
+ s.name AS "signerName",
+ s.email AS "signerEmail"
+ FROM envelopes e
+ JOIN "user" u ON u.id = e.user_id
+ LEFT JOIN signers s
+ ON s.envelope_id = e.id
+ AND s.status = 'notified'
+ WHERE e.status = 'sent'
+ AND e.expires_at IS NOT NULL
+ AND e.expires_at <= $1
+ AND e.expiry_notified_at IS NULL
+ ORDER BY e.expires_at ASC, e.id ASC
+ LIMIT ${BATCH_SIZE}
+ `,
+ [now],
+ );
+}
+
+/**
+ * Marks the envelope as told and notes the passed deadline in its audit
+ * trail. False when there is nothing to tell any more: the sender moved the
+ * deadline, the envelope was finished or voided, or another run got here.
+ */
+async function claimExpiryNotice(
+ envelope: ExpiredEnvelopeRow,
+ now: number,
+ database: DbPool,
+): Promise<boolean> {
+ return withTransaction(async (tx) => {
+ const claimed = await tx.query(
+ `
+ UPDATE envelopes
+ SET expiry_notified_at = $1
+ WHERE id = $2
+ AND status = 'sent'
+ AND expires_at = $3
+ AND expiry_notified_at IS NULL
+ `,
+ [now, envelope.id, envelope.expiresAt],
+ );
+
+ if (claimed.rowCount !== 1) {
+ return false;
+ }
+
+ await recordAuditEvent(
+ {
+ actorType: "system",
+ createdAt: now,
+ envelopeId: envelope.id,
+ event: "expired",
+ metadata: { expiresAt: envelope.expiresAt },
+ },
+ tx,
+ );
+
+ return true;
+ }, database);
+}
+
+/** Gives a claim back after its email failed, so the next run tries again. */
+async function releaseExpiryNotice(
+ envelope: ExpiredEnvelopeRow,
+ now: number,
+ database: DbPool,
+): Promise<void> {
+ await withTransaction(async (tx) => {
+ await lockEnvelopeAuditChain(envelope.id, tx);
+
+ const removed = await tx.query(
+ `
+ DELETE FROM audit_events
+ WHERE envelope_id = $1
+ AND event = 'expired'
+ AND created_at = $2
+ -- Only while it is still the newest link of the audit chain.
+ AND sequence = (
+ SELECT max(sequence) FROM audit_events WHERE envelope_id = $1
+ )
+ `,
+ [envelope.id, now],
+ );
+
+ // An event chained after it keeps the note in place, and then the
+ // envelope stays marked: the trail must not say "expired" twice.
+ if (removed.rowCount === 1) {
+ await tx.query(
+ `
+ UPDATE envelopes
+ SET expiry_notified_at = NULL
+ WHERE id = $1 AND expiry_notified_at = $2
+ `,
+ [envelope.id, now],
+ );
+ }
+ }, database);
+}
+
+function buildExpiryNotice(envelope: ExpiredEnvelopeRow) {
+ const appUrl = resolveAppUrl();
+ const link = appUrl ? `${appUrl}/envelopes/${envelope.id}` : null;
+ const waitingOn =
+ envelope.signerName && envelope.signerEmail
+ ? ` It was still waiting on ${envelope.signerName} (${envelope.signerEmail}).`
+ : "";
+
+ return {
+ subject: `"${envelope.title}" expired before everyone signed`,
+ template: "expiry_notice" as const,
+ textBody: [
+ `Hello ${envelope.ownerName?.trim() || envelope.ownerEmail},`,
+ "",
+ `The deadline for "${envelope.title}" passed on ${formatDeadline(envelope.expiresAt)}.${waitingOn} Nobody can sign it now.`,
+ "",
+ "To give signers more time, open the envelope and set a new deadline. The signing link that was already sent will work again. If the document is no longer needed, void it.",
+ ...(link ? ["", link] : []),
+ ].join("\n"),
+ to: envelope.ownerEmail,
+ };
+}
+
+async function sendExpiryNotices(
+ now: number,
+ database: DbPool,
+ emailService: () => EmailService,
+ summary: EnvelopeScheduleSummary,
+): Promise<void> {
+ const expired = await listExpiredEnvelopesToNotify(now, database);
+
+ for (const envelope of expired) {
+ try {
+ if (!(await claimExpiryNotice(envelope, now, database))) {
+ continue;
+ }
+
+ try {
+ await emailService().send(buildExpiryNotice(envelope), {
+ idempotencyKey: `expiry-notice/${envelope.id}/${envelope.expiresAt}`,
+ });
+ } catch (error) {
+ await releaseExpiryNotice(envelope, now, database).catch(
+ (releaseError: unknown) => {
+ console.error(
+ `Failed to give back the expiry notice claim for envelope ${envelope.id}:`,
+ releaseError,
+ );
+ },
+ );
+
+ throw error;
+ }
+
+ summary.expiryNoticesSent += 1;
+ } catch (error) {
+ summary.expiryNoticeFailures.push(envelope.id);
+ console.error(`Expiry notice failed for envelope ${envelope.id}:`, error);
+ }
+ }
+}
+
+export async function runEnvelopeSchedule({
+ database,
+ emailService,
+ now = Math.floor(Date.now() / 1000),
+}: {
+ database: DbPool;
+ emailService?: EmailService;
+ now?: number;
+}): Promise<EnvelopeScheduleSummary> {
+ const summary: EnvelopeScheduleSummary = {
+ expiryNoticeFailures: [],
+ expiryNoticesSent: 0,
+ };
+ let service = emailService;
+ // Made only when there is something to send: an install without email
+ // set up yet must not fail the whole job.
+ const getEmailService = () => (service ??= createEmailService());
+
+ await sendExpiryNotices(now, database, getEmailService, summary);
+
+ return summary;
+}
+
+export function envelopeScheduleFailed(
+ summary: EnvelopeScheduleSummary,
+): boolean {
+ return summary.expiryNoticeFailures.length > 0;
+}
diff --git a/src/lib/envelopes.ts b/src/lib/envelopes.ts
index bed32ad..b0ab41a 100644
--- a/src/lib/envelopes.ts
+++ b/src/lib/envelopes.ts
@@ -10,8 +10,15 @@ import {
withTransaction,
} from "./db/connection.ts";
import {
+ deadlineFromDays,
+ formatDeadline,
+ isEnvelopeExpired,
+} from "./envelope-deadline.ts";
+import {
+ changeDeadlineResponseSchema,
envelopeListFiltersSchema,
type AuditEventRecord,
+ type ChangeDeadlineResponse,
envelopeCreateResponseSchema,
envelopePageSchema,
envelopeRecordSchema,
@@ -93,6 +100,8 @@ type CreateDraftEnvelopeInput = {
};
type SendDraftEnvelopeInput = {
+ /** How many days signers get. The default applies when left out. */
+ expiresInDays?: number;
ipAddress?: string | null;
senderEmail: string;
senderName: string;
@@ -119,6 +128,7 @@ type EnvelopeRow = {
createdAt: number;
declinedAt: number | null;
evidenceKey: string | null;
+ expiresAt: number | null;
id: string;
pageCount: number;
sentAt: number | null;
@@ -215,6 +225,8 @@ type PersistedFieldRecord = FieldRecord & {
export type DashboardEnvelopeListItem = {
contextLine: string;
createdAtLabel: string;
+ /** Out for signature and past its deadline. */
+ expired?: boolean;
id: string;
searchableEmails: readonly string[];
status: EnvelopeRecord["status"];
@@ -296,8 +308,17 @@ export type EnvelopeDetailManualReminderState = {
nextAvailableAtLabel: string | null;
};
+export type EnvelopeDetailDeadline = {
+ /** True once the deadline has passed and nobody can sign any more. */
+ expired: boolean;
+ /** Null for an envelope sent before deadlines existed. */
+ expiresAtLabel: string | null;
+};
+
export type EnvelopeDetailData = {
createdAtLabel: string;
+ /** Set while the envelope is out for signature. */
+ deadline: EnvelopeDetailDeadline | null;
envelopeId: string;
manualReminder: EnvelopeDetailManualReminderState | null;
signers: readonly EnvelopeDetailSignerView[];
@@ -369,8 +390,10 @@ const TIMELINE_TONE_MAP: Record<
completed: "success",
consented: "neutral",
created: "accent",
+ deadline_changed: "neutral",
declined: "danger",
email_sent: "neutral",
+ expired: "danger",
reminded_manual: "neutral",
sent: "neutral",
signed: "success",
@@ -656,6 +679,7 @@ async function getEnvelopeByIdForUser(
completed_at AS "completedAt",
declined_at AS "declinedAt",
voided_at AS "voidedAt",
+ expires_at AS "expiresAt",
created_at AS "createdAt",
updated_at AS "updatedAt"
FROM envelopes
@@ -855,6 +879,10 @@ function buildDashboardContextLine(
signers.find((signer) => signer.status === "notified") ??
signers.find((signer) => signer.status === "pending");
+ if (isEnvelopeExpired(envelope, Math.floor(Date.now() / 1000))) {
+ return `Expired ${formatShortDate(envelope.expiresAt!)} · was waiting on: ${currentSigner?.email ?? "—"}`;
+ }
+
return `Waiting on: ${currentSigner?.email ?? "—"}`;
}
@@ -884,6 +912,10 @@ function buildDashboardStatusLabel(
envelope: EnvelopeRecord,
signers: readonly PersistedSignerRecord[],
): string {
+ if (isEnvelopeExpired(envelope, Math.floor(Date.now() / 1000))) {
+ return "Expired";
+ }
+
// With one signer "Sent" says it all. With several, say how many are done.
if (envelope.status === "sent" && signers.length > 1) {
const signedCount = signers.filter(
@@ -1006,6 +1038,12 @@ function buildTimelineDescription(event: AuditEventRecord): string {
return "Final signed PDF and certificate generated";
case "voided":
return "Envelope voided by sender";
+ case "deadline_changed":
+ return typeof event.metadata?.expiresAt === "number"
+ ? `Deadline set to ${formatDeadline(event.metadata.expiresAt)}`
+ : "Deadline changed";
+ case "expired":
+ return "Deadline passed before everyone signed";
default:
return event.event;
}
@@ -1134,6 +1172,7 @@ export async function listEnvelopesForUser(
completed_at AS "completedAt",
declined_at AS "declinedAt",
voided_at AS "voidedAt",
+ expires_at AS "expiresAt",
created_at AS "createdAt",
updated_at AS "updatedAt"
FROM envelopes
@@ -1158,6 +1197,7 @@ export async function listEnvelopesForUser(
return {
contextLine: buildDashboardContextLine(envelope, signers, fields),
createdAtLabel: formatShortDate(envelope.createdAt),
+ expired: isEnvelopeExpired(envelope, Math.floor(Date.now() / 1000)),
id: envelope.id,
searchableEmails: signers.map((signer) => signer.email),
status: envelope.status,
@@ -1229,8 +1269,13 @@ export async function getEnvelopeDetailDataForUser(
const currentSigner = signers.find((signer) => signer.status === "notified");
let manualReminder: EnvelopeDetailManualReminderState | null = null;
- if (envelope.status === "sent" && currentSigner) {
- const nowUnixTimestamp = Math.floor(Date.now() / 1000);
+ const nowUnixTimestamp = Math.floor(Date.now() / 1000);
+ const expired = isEnvelopeExpired(envelope, nowUnixTimestamp);
+
+ if (envelope.status === "sent" && currentSigner && expired) {
+ // A reminder would carry a link that no longer works.
+ manualReminder = { canSend: false, nextAvailableAtLabel: null };
+ } else if (envelope.status === "sent" && currentSigner) {
const nextAvailableAt =
typeof currentSigner.lastNudgedAt === "number"
? getManualNudgeAvailableAt(currentSigner.lastNudgedAt)
@@ -1251,6 +1296,16 @@ export async function getEnvelopeDetailDataForUser(
return {
createdAtLabel: formatLongDate(envelope.createdAt),
+ deadline:
+ envelope.status === "sent"
+ ? {
+ expired,
+ expiresAtLabel:
+ typeof envelope.expiresAt === "number"
+ ? formatDeadline(envelope.expiresAt)
+ : null,
+ }
+ : null,
envelopeId,
manualReminder,
signers: signerViews,
@@ -1583,7 +1638,9 @@ export async function sendDraftEnvelope(
const sentAt = Math.floor(Date.now() / 1000);
const sentAuditAt = Math.max(sentAt, envelope.createdAt + 1);
+ const expiresAt = deadlineFromDays(sentAt, input.expiresInDays);
const issuedLink = await issueSigningLink({
+ expiresInSeconds: expiresAt - sentAt,
issuedAt: sentAt,
});
@@ -1595,12 +1652,14 @@ export async function sendDraftEnvelope(
SET
status = 'sent',
sent_at = $1,
- updated_at = $2
+ updated_at = $2,
+ expires_at = $5,
+ expiry_notified_at = NULL
WHERE id = $3
AND user_id = $4
AND status = 'draft'
`,
- [sentAt, sentAt, envelopeId, userId],
+ [sentAt, sentAt, envelopeId, userId, expiresAt],
);
if (updatedEnvelope.rowCount !== 1) {
@@ -1670,6 +1729,7 @@ export async function sendDraftEnvelope(
ipAddress: input.ipAddress ?? null,
metadata: {
// The send route refuses a send without this confirmation.
+ expiresAt,
permittedUseConfirmed: true,
permittedUseVersion: PERMITTED_USE_VERSION,
signerEmail: firstSigner.email,
@@ -1693,6 +1753,7 @@ export async function sendDraftEnvelope(
buildSigningInvitationEmail({
branding: await getBranding(),
envelopeTitle: envelope.title,
+ expiresAt,
senderName: input.senderName,
signerEmail: firstSigner.email,
signerName: firstSigner.name,
@@ -1708,6 +1769,7 @@ export async function sendDraftEnvelope(
SET
status = 'draft',
sent_at = NULL,
+ expires_at = NULL,
updated_at = $1
WHERE id = $2
AND user_id = $3
@@ -1775,12 +1837,102 @@ export async function sendDraftEnvelope(
return sendEnvelopeResponseSchema.parse({
envelopeId,
+ expiresAt,
notifiedSignerName: firstSigner.name,
redirectPath: `/envelopes/${envelopeId}`,
sentAt,
});
}
+type ChangeEnvelopeDeadlineInput = {
+ expiresInDays: number;
+ ipAddress?: string | null;
+ senderEmail: string;
+ userAgent?: string | null;
+};
+
+/**
+ * Gives an envelope that is out for signature a new deadline, counted from
+ * now. The current signer's link is kept and simply lives until the new
+ * deadline, so a link that had expired works again.
+ */
+export async function changeEnvelopeDeadline(
+ userId: string,
+ envelopeId: string,
+ input: ChangeEnvelopeDeadlineInput,
+ {
+ database = getDb(),
+ nowUnixTimestamp = Math.floor(Date.now() / 1000),
+ }: { database?: DbPool; nowUnixTimestamp?: number } = {},
+): Promise<ChangeDeadlineResponse> {
+ const expiresAt = deadlineFromDays(nowUnixTimestamp, input.expiresInDays);
+
+ await withTransaction(async (tx) => {
+ const current = await queryOne<{
+ expiresAt: number | null;
+ status: EnvelopeRecord["status"];
+ }>(
+ tx,
+ `
+ SELECT expires_at AS "expiresAt", status
+ FROM envelopes
+ WHERE id = $1 AND user_id = $2
+ FOR UPDATE
+ `,
+ [envelopeId, userId],
+ );
+
+ if (!current) {
+ throw new EnvelopeMutationError("Envelope not found.", 404);
+ }
+
+ if (current.status !== "sent") {
+ throw new EnvelopeMutationError(
+ "Only an envelope that is out for signature has a deadline to change.",
+ 409,
+ );
+ }
+
+ await tx.query(
+ `
+ UPDATE envelopes
+ SET expires_at = $1, expiry_notified_at = NULL, updated_at = $2
+ WHERE id = $3
+ `,
+ [expiresAt, nowUnixTimestamp, envelopeId],
+ );
+ await tx.query(
+ `
+ UPDATE signers
+ SET signing_token_expires_at = $1, updated_at = $2
+ WHERE envelope_id = $3
+ AND status = 'notified'
+ AND signing_token_hash IS NOT NULL
+ `,
+ [expiresAt, nowUnixTimestamp, envelopeId],
+ );
+ await recordAuditEvent(
+ {
+ actorEmail: input.senderEmail,
+ actorType: "sender",
+ createdAt: nowUnixTimestamp,
+ envelopeId,
+ event: "deadline_changed",
+ ipAddress: input.ipAddress ?? null,
+ metadata: { expiresAt, previousExpiresAt: current.expiresAt },
+ userAgent: input.userAgent ?? null,
+ },
+ tx,
+ );
+ }, database);
+
+ return changeDeadlineResponseSchema.parse({
+ envelopeId,
+ expiresAt,
+ expiresAtLabel: formatDeadline(expiresAt),
+ });
+}
+
export async function voidSentEnvelope(
userId: string,
envelopeId: string,
diff --git a/src/lib/reminders.ts b/src/lib/reminders.ts
index 94dd562..121a61f 100644
--- a/src/lib/reminders.ts
+++ b/src/lib/reminders.ts
@@ -1,4 +1,9 @@
import { type Branding } from "./branding.ts";
+import {
+ formatDeadline,
+ isEnvelopeExpired,
+ signingLinkLifetimeSeconds,
+} from "./envelope-deadline.ts";
import {
type DbExecutor,
type DbPool,
@@ -18,6 +23,7 @@ import {
recordEmailSent,
} from "./services/audit.ts";
import { createEmailService } from "./services/email.ts";
+import { buildDeadlineLine } from "./services/signing-invitation-email.ts";
import { withUserEmailLegalFooter } from "./services/email-legal-footer.ts";
import {
formatReminderAvailableAt,
@@ -30,6 +36,7 @@ import {
import { escapeHtml } from "./utils/html.ts";
type ReminderEnvelopeRow = {
+ expiresAt: number | null;
id: string;
status: EnvelopeRecord["status"];
title: string;
@@ -59,6 +66,7 @@ type ManualNudgeInput = {
};
type PersistedManualNudge = {
+ envelopeExpiresAt: number | null;
envelopeId: string;
envelopeTitle: string;
issuedLink: IssuedSigningLink;
@@ -121,6 +129,7 @@ async function getEnvelopeByIdForUser(
user_id AS "userId",
title,
status,
+ expires_at AS "expiresAt",
updated_at AS "updatedAt"
FROM envelopes
WHERE id = $1
@@ -163,6 +172,7 @@ function buildReminderEmail(input: {
branding: Branding;
envelopeId: string;
envelopeTitle: string;
+ expiresAt?: number | null;
senderName: string;
signerEmail: string;
signerName: string;
@@ -170,6 +180,7 @@ function buildReminderEmail(input: {
}) {
const subject = `${input.senderName} sent you a reminder to sign "${input.envelopeTitle}"`;
const introLine = `${input.senderName} sent you a reminder to sign "${input.envelopeTitle}" through ${input.branding.productName}.`;
+ const deadlineLine = buildDeadlineLine(input.expiresAt);
const textBody = [
`Hi ${input.signerName},`,
"",
@@ -177,6 +188,7 @@ function buildReminderEmail(input: {
"",
"Review and sign the document here:",
input.signingUrl,
+ ...(deadlineLine ? ["", deadlineLine] : []),
"",
`You do not need a ${input.branding.productName} account to sign.`,
"If you receive a newer invitation or reminder link, use the newest one.",
@@ -185,6 +197,7 @@ function buildReminderEmail(input: {
`<p>Hi ${escapeHtml(input.signerName)},</p>`,
`<p>${escapeHtml(introLine)}</p>`,
`<p><a href="${escapeHtml(input.signingUrl)}">Review and sign the document</a></p>`,
+ deadlineLine ? `<p>${escapeHtml(deadlineLine)}</p>` : "",
`<p>You do not need a ${escapeHtml(input.branding.productName)} account to sign.</p>`,
"<p>If you receive a newer invitation or reminder link, use the newest one.</p>",
].join("");
@@ -234,7 +247,19 @@ async function persistManualNudge(
);
}
+ if (isEnvelopeExpired(envelope, dispatchedAt)) {
+ throw new ReminderMutationError(
+ `This request expired on ${formatDeadline(envelope.expiresAt!)}. Set a new deadline before sending a reminder.`,
+ 409,
+ );
+ }
+
+ // The reminder's link ends at the envelope's deadline, like every other.
const issuedLink = await issueSigningLink({
+ expiresInSeconds: signingLinkLifetimeSeconds(
+ envelope.expiresAt,
+ dispatchedAt,
+ ),
issuedAt: dispatchedAt,
});
return withTransaction(async (tx) => {
@@ -255,6 +280,14 @@ async function persistManualNudge(
);
}
+ // The deadline may have been moved since the link was issued.
+ if (persistedEnvelope.expiresAt !== envelope.expiresAt) {
+ throw new ReminderMutationError(
+ "This envelope's deadline just changed. Try again.",
+ 409,
+ );
+ }
+
const persistedSigner = await getCurrentSignerForEnvelope(envelopeId, tx);
if (!persistedSigner) {
@@ -343,6 +376,7 @@ async function persistManualNudge(
);
return {
+ envelopeExpiresAt: persistedEnvelope.expiresAt,
envelopeId,
envelopeTitle: persistedEnvelope.title,
issuedLink,
@@ -391,6 +425,7 @@ export async function sendManualEnvelopeNudge(
branding: await getBranding(),
envelopeId: persisted.envelopeId,
envelopeTitle: persisted.envelopeTitle,
+ expiresAt: persisted.envelopeExpiresAt,
senderName: persisted.senderName,
signerEmail: persisted.signerEmail,
signerName: persisted.signerName,
diff --git a/src/lib/retention-job.ts b/src/lib/retention-job.ts
index 11588a7..a06c551 100644
--- a/src/lib/retention-job.ts
+++ b/src/lib/retention-job.ts
@@ -1,17 +1,24 @@
import { createHash, timingSafeEqual } from "node:crypto";
import { getDb, type DbPool } from "./db/connection.ts";
+import {
+ envelopeScheduleFailed,
+ runEnvelopeSchedule,
+ type EnvelopeScheduleSummary,
+} from "./envelope-schedule.ts";
import { runRetentionSweep, type RetentionSweepSummary } from "./retention.ts";
import {
consumeRateLimit,
deleteExpiredRateLimits,
} from "./security/rate-limit.ts";
+import type { EmailService } from "./services/email.ts";
import type { StorageService } from "./services/storage.ts";
import { isMissingSchemaError } from "./settings.ts";
import { getEnv, type EnvSource } from "./utils/env.ts";
-// The daily cleanup: stale drafts, queued account deletions, expired
-// download links and finished rate limit windows.
+// The daily job. First the cleanup: stale drafts, queued account deletions,
+// expired download links and finished rate limit windows. Then the envelopes
+// that are out for signature: see envelope-schedule.ts.
//
// On Vercel it is called by a cron job (see vercel.json). A click-to-deploy
// install has no secret for that call, because nobody typed one in, so the
@@ -31,7 +38,12 @@ const ANONYMOUS_RUN_INTERVAL_MS = 60 * 60 * 1000;
export type RetentionCaller = "anonymous" | "authorized" | "denied";
export type RetentionJobOutcome =
- | { status: "ran"; summary: RetentionSweepSummary }
+ | {
+ /** Null when that part could not run. The cleanup still counts. */
+ schedule: EnvelopeScheduleSummary | null;
+ status: "ran";
+ summary: RetentionSweepSummary;
+ }
| { status: "skipped"; reason: "already_running" | "ran_recently" };
function digest(value: string): Buffer {
@@ -105,10 +117,12 @@ export function isCronLockedOutByOlderSecret(
export async function runRetentionJob({
caller,
database = getDb(),
+ emailService,
storageService,
}: {
caller: Exclude<RetentionCaller, "denied">;
database?: DbPool;
+ emailService?: EmailService;
storageService?: StorageService;
}): Promise<RetentionJobOutcome> {
if (caller === "anonymous") {
@@ -143,7 +157,11 @@ export async function runRetentionJob({
return { reason: "already_running", status: "skipped" };
}
- const summary = await runRetentionSweep({ database, storageService });
+ const summary = await runRetentionSweep({
+ database,
+ emailService,
+ storageService,
+ });
await deleteExpiredRateLimits(database).catch((error: unknown) => {
// A database from before rate limits were kept in it has no table to
@@ -153,7 +171,21 @@ export async function runRetentionJob({
}
});
- return { status: "ran", summary };
+ const schedule = await runEnvelopeSchedule({
+ database,
+ emailService,
+ }).catch((error: unknown) => {
+ // A database from before deadlines has no column to read: nothing is
+ // due there. Anything else is a failure worth a red cron run.
+ if (!isMissingSchemaError(error)) {
+ console.error("The envelope schedule failed:", error);
+ return null;
+ }
+
+ return { expiryNoticeFailures: [], expiryNoticesSent: 0 };
+ });
+
+ return { schedule, status: "ran", summary };
} finally {
await lockClient.query("rollback").catch(() => undefined);
lockClient.release();
@@ -167,3 +199,14 @@ export function retentionSweepFailed(summary: RetentionSweepSummary): boolean {
summary.finishedEnvelopeDeletionFailures.length > 0
);
}
+
+/** True when any part of a finished run left work undone. */
+export function retentionJobFailed(
+ outcome: Extract<RetentionJobOutcome, { status: "ran" }>,
+): boolean {
+ return (
+ retentionSweepFailed(outcome.summary) ||
+ outcome.schedule === null ||
+ envelopeScheduleFailed(outcome.schedule)
+ );
+}
diff --git a/src/lib/schemas/envelope.ts b/src/lib/schemas/envelope.ts
index 8636f62..be9f194 100644
--- a/src/lib/schemas/envelope.ts
+++ b/src/lib/schemas/envelope.ts
@@ -5,6 +5,7 @@ import {
auditEventTypes,
downloadFileTypes,
envelopeStatuses,
+ MAX_ENVELOPE_DEADLINE_DAYS,
} from "../types/domain.ts";
import {
emailSchema,
@@ -30,8 +31,30 @@ export const envelopeCreateResponseSchema = z.object({
title: envelopeTitleSchema,
});
+export const deadlineDaysSchema = z
+ .number()
+ .int()
+ .min(1)
+ .max(MAX_ENVELOPE_DEADLINE_DAYS);
+
+/** What the sender chooses on the last step before sending. */
+export const sendEnvelopeOptionsSchema = z.object({
+ expiresInDays: deadlineDaysSchema.optional(),
+});
+
+export const changeDeadlineSchema = z.object({
+ expiresInDays: deadlineDaysSchema,
+});
+
+export const changeDeadlineResponseSchema = z.object({
+ envelopeId: idSchema,
+ expiresAt: unixTimestampSchema,
+ expiresAtLabel: z.string().trim().min(1),
+});
+
export const sendEnvelopeResponseSchema = z.object({
envelopeId: idSchema,
+ expiresAt: unixTimestampSchema.nullable().optional(),
notifiedSignerName: z.string().trim().min(1).max(160),
redirectPath: z.string().trim().min(1),
sentAt: unixTimestampSchema,
@@ -102,6 +125,8 @@ export const envelopeRecordSchema = z.object({
completedAt: unixTimestampSchema.nullable().optional(),
declinedAt: unixTimestampSchema.nullable().optional(),
voidedAt: unixTimestampSchema.nullable().optional(),
+ /** When the request stops being signable. See envelope-deadline.ts. */
+ expiresAt: unixTimestampSchema.nullable().optional(),
createdAt: unixTimestampSchema,
updatedAt: unixTimestampSchema,
});
@@ -110,6 +135,10 @@ export type CreateEnvelopeResponse = z.infer<
typeof envelopeCreateResponseSchema
>;
export type SendEnvelopeResponse = z.infer<typeof sendEnvelopeResponseSchema>;
+export type SendEnvelopeOptions = z.infer<typeof sendEnvelopeOptionsSchema>;
+export type ChangeDeadlineResponse = z.infer<
+ typeof changeDeadlineResponseSchema
+>;
export type VoidEnvelopeResponse = z.infer<typeof voidEnvelopeResponseSchema>;
export type ManualNudgeResponse = z.infer<typeof manualNudgeResponseSchema>;
export type EnvelopeListFilters = z.infer<typeof envelopeListFiltersSchema>;
diff --git a/src/lib/services/signing-invitation-email.ts b/src/lib/services/signing-invitation-email.ts
index 76ef743..b57f220 100644
--- a/src/lib/services/signing-invitation-email.ts
+++ b/src/lib/services/signing-invitation-email.ts
@@ -1,4 +1,5 @@
import { type Branding } from "../branding.ts";
+import { formatDeadline } from "../envelope-deadline.ts";
import { escapeHtml } from "../utils/html.ts";
import { withUserEmailLegalFooter } from "./email-legal-footer.ts";
import { type TransactionalEmailMessage } from "./email.ts";
@@ -6,17 +7,29 @@ import { type TransactionalEmailMessage } from "./email.ts";
type SigningInvitationEmailInput = {
branding: Branding;
envelopeTitle: string;
+ /** The envelope's deadline, when it has one. */
+ expiresAt?: number | null;
senderName: string;
signerEmail: string;
signerName: string;
signingUrl: string;
};
+/** "This request expires on …", or nothing for an envelope with no deadline. */
+export function buildDeadlineLine(
+ expiresAt: number | null | undefined,
+): string | null {
+ return typeof expiresAt === "number"
+ ? `This request expires on ${formatDeadline(expiresAt)}.`
+ : null;
+}
+
export function buildSigningInvitationEmail(
input: SigningInvitationEmailInput,
): TransactionalEmailMessage {
const { productName } = input.branding;
const subject = `${input.senderName} requested your signature on "${input.envelopeTitle}"`;
+ const deadlineLine = buildDeadlineLine(input.expiresAt);
const textBody = [
`Hi ${input.signerName},`,
"",
@@ -24,6 +37,7 @@ export function buildSigningInvitationEmail(
"",
"Review and sign the document here:",
input.signingUrl,
+ ...(deadlineLine ? ["", deadlineLine] : []),
"",
`You do not need a ${productName} account to sign.`,
"If you receive a newer invitation or reminder link, use the newest one.",
@@ -32,6 +46,7 @@ export function buildSigningInvitationEmail(
`<p>Hi ${escapeHtml(input.signerName)},</p>`,
`<p>${escapeHtml(input.senderName)} sent you &ldquo;${escapeHtml(input.envelopeTitle)}&rdquo; through ${escapeHtml(productName)}.</p>`,
`<p><a href="${escapeHtml(input.signingUrl)}">Review and sign the document</a></p>`,
+ deadlineLine ? `<p>${escapeHtml(deadlineLine)}</p>` : "",
`<p>You do not need a ${escapeHtml(productName)} account to sign.</p>`,
"<p>If you receive a newer invitation or reminder link, use the newest one.</p>",
].join("");
diff --git a/src/lib/signing.ts b/src/lib/signing.ts
index 9848f9d..5a662a5 100644
--- a/src/lib/signing.ts
+++ b/src/lib/signing.ts
@@ -75,6 +75,7 @@ import { requireConfigValue } from "./services/service-config.ts";
import { RECIPIENT_DOWNLOAD_LINK_TTL_SECONDS } from "./types/domain.ts";
import { getEnv } from "./utils/env.ts";
import { escapeHtml } from "./utils/html.ts";
+import { isEnvelopeExpired } from "./envelope-deadline.ts";
import {
buildElectronicRecordsDisclosure,
CONSENT_STATEMENT,
@@ -113,6 +114,7 @@ type SigningEnvelopeRow = {
createdAt: number;
declinedAt: number | null;
evidenceKey: string | null;
+ expiresAt: number | null;
id: string;
pageCount: number;
sentAt: number | null;
@@ -477,6 +479,7 @@ async function getEnvelopeRow(
completed_at AS "completedAt",
declined_at AS "declinedAt",
voided_at AS "voidedAt",
+ expires_at AS "expiresAt",
created_at AS "createdAt",
updated_at AS "updatedAt"
FROM envelopes
@@ -1417,7 +1420,9 @@ async function resolveSigningContext(
signer.status !== "notified" ||
signer.envelopeId !== envelopeRow.id ||
signer.signingTokenHash !== signerRow.signingTokenHash ||
- (signingTokenExpiresAt !== null && signingTokenExpiresAt < now)
+ (signingTokenExpiresAt !== null && signingTokenExpiresAt < now) ||
+ // The envelope's own deadline, whatever the link says.
+ isEnvelopeExpired(envelopeRow, now)
) {
throw new SigningAccessError("expired");
}
@@ -1765,6 +1770,12 @@ export async function submitSigningForToken(
}
nextSignerLink = await issueSigningLink({
+ // Until the envelope's deadline. The signer who just finished was
+ // inside it a moment ago, so a minute is kept in hand.
+ expiresInSeconds:
+ typeof context.envelope.expiresAt === "number"
+ ? Math.max(60, context.envelope.expiresAt - submittedAt)
+ : undefined,
issuedAt: submittedAt,
});
}
@@ -1928,6 +1939,7 @@ export async function submitSigningForToken(
buildSigningInvitationEmail({
branding: await getBranding(),
envelopeTitle: context.envelope.title,
+ expiresAt: context.envelope.expiresAt,
senderName: normalizeSenderName(context.sender),
signerEmail: nextSigner.email,
signerName: nextSigner.name,
diff --git a/src/lib/types/domain.ts b/src/lib/types/domain.ts
index 50069df..ab26cf0 100644
--- a/src/lib/types/domain.ts
+++ b/src/lib/types/domain.ts
@@ -4,6 +4,11 @@ export const SIGNING_LINK_TTL_SECONDS = 7 * 24 * 60 * 60;
export const RECIPIENT_DOWNLOAD_LINK_TTL_SECONDS = 7 * 24 * 60 * 60;
export const MANUAL_NUDGE_COOLDOWN_SECONDS = 24 * 60 * 60;
+/** How long signers get, in days: what the send step offers, and its limits. */
+export const ENVELOPE_DEADLINE_DAY_OPTIONS = [3, 7, 14, 30, 60, 90] as const;
+export const DEFAULT_ENVELOPE_DEADLINE_DAYS = 30;
+export const MAX_ENVELOPE_DEADLINE_DAYS = 365;
+
export const envelopeStatuses = [
"draft",
"sent",
@@ -42,6 +47,8 @@ export const auditEventTypes = [
"email_sent",
"completed",
"voided",
+ "deadline_changed",
+ "expired",
] as const;
export const auditActorTypes = ["sender", "signer", "system"] as const;
@@ -62,6 +69,7 @@ export const emailTemplateKinds = [
"void_notification",
"password_reset",
"retention_notice",
+ "expiry_notice",
"test_email",
] as const;