Skip to content

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

TypeScript

Say what happened to the envelope on a spent signing link

Claude5361dc228619
diff --git a/db/migrations/20261119090000_spent_signing_links.sql b/db/migrations/20261119090000_spent_signing_links.sql
new file mode 100644
index 0000000..b049b11
--- /dev/null
+++ b/db/migrations/20261119090000_spent_signing_links.sql
@@ -0,0 +1,13 @@
+-- The hash of the signing link a signer last held, kept once signing,
+-- declining or voiding has taken the link away. It opens nothing: it lets
+-- the page an old invitation opens say what happened to the envelope
+-- (signed, completed, declined, voided) instead of asking the signer for a
+-- new link the sender cannot send. Cleared when an envelope goes back to
+-- draft or is sent again, so a link from before then reads as expired.
+
+alter table public.signers
+ add column if not exists spent_signing_token_hash text;
+
+create index if not exists idx_signers_spent_signing_token_hash
+ on public.signers(spent_signing_token_hash)
+ where spent_signing_token_hash is not null;
diff --git a/src/app/sign/[token]/page.tsx b/src/app/sign/[token]/page.tsx
index 831a371..bd685ec 100644
--- a/src/app/sign/[token]/page.tsx
+++ b/src/app/sign/[token]/page.tsx
@@ -32,7 +32,13 @@ export default async function SignPage({
const signatureProblem =
SIGNATURE_PROBLEMS.find((problem) => problem === problemParam) ?? null;
let initialState:
- "already-signed" | "declined" | "error" | "expired" | "voided" | undefined;
+ | "already-signed"
+ | "completed"
+ | "declined"
+ | "error"
+ | "expired"
+ | "voided"
+ | undefined;
let record: Awaited<ReturnType<typeof getSigningPayloadForToken>> | null =
null;
let verification: SigningVerificationState | null = null;
diff --git a/src/components/signing/signing-shell.tsx b/src/components/signing/signing-shell.tsx
index b675f84..e615f18 100644
--- a/src/components/signing/signing-shell.tsx
+++ b/src/components/signing/signing-shell.tsx
@@ -12,7 +12,7 @@ import {
} from "./signing-live-shell";
type SigningUnavailableState =
- "already-signed" | "declined" | "error" | "expired" | "voided";
+ "already-signed" | "completed" | "declined" | "error" | "expired" | "voided";
type SigningShellProps = {
initialState?: SigningUnavailableState;
@@ -40,6 +40,11 @@ const tokenStateCopy: Record<
title: "You've already signed",
description: "You already completed your signature for this document.",
},
+ completed: {
+ title: "This envelope has been completed",
+ description:
+ "Everyone has signed this document. No further action is needed.",
+ },
voided: {
title: "This envelope has been voided",
description:
diff --git a/src/lib/envelopes.ts b/src/lib/envelopes.ts
index 75520b8..79bb593 100644
--- a/src/lib/envelopes.ts
+++ b/src/lib/envelopes.ts
@@ -2631,6 +2631,7 @@ export async function sendDraftEnvelope(
SET
status = 'pending',
signing_token_hash = NULL,
+ spent_signing_token_hash = NULL,
signing_token_expires_at = NULL,
turn_started_at = NULL,
last_notified_at = NULL,
@@ -2790,6 +2791,7 @@ export async function sendDraftEnvelope(
SET
status = 'pending',
signing_token_hash = NULL,
+ spent_signing_token_hash = NULL,
signing_token_expires_at = NULL,
turn_started_at = NULL,
last_notified_at = NULL,
@@ -3532,6 +3534,7 @@ export async function voidSentEnvelope(
`
UPDATE signers
SET
+ spent_signing_token_hash = signing_token_hash,
signing_token_hash = NULL,
signing_token_expires_at = NULL,
updated_at = $1
diff --git a/src/lib/schemas/signing.ts b/src/lib/schemas/signing.ts
index d83226b..f8630af 100644
--- a/src/lib/schemas/signing.ts
+++ b/src/lib/schemas/signing.ts
@@ -17,6 +17,7 @@ import {
export const signingUnavailableStateSchema = z.enum([
"expired",
"already-signed",
+ "completed",
"voided",
"declined",
]);
diff --git a/src/lib/signing.ts b/src/lib/signing.ts
index f950d5e..7bf1363 100644
--- a/src/lib/signing.ts
+++ b/src/lib/signing.ts
@@ -274,6 +274,7 @@ const signingUnavailableStatusCodeMap: Record<
number
> = {
"already-signed": 409,
+ completed: 409,
declined: 409,
expired: 410,
voided: 409,
@@ -300,6 +301,8 @@ function getSigningUnavailableMessage(
switch (state) {
case "already-signed":
return "You've already signed.";
+ case "completed":
+ return "This envelope has been completed.";
case "declined":
return "This envelope has been declined.";
case "voided":
@@ -1756,6 +1759,47 @@ export async function recordSignerConsent(
return { consentedAt };
}
+/**
+ * What a link that signing, declining or voiding took away should say. It
+ * opens nothing: it only tells the signer what became of the envelope, so
+ * they are not sent to ask for a new link the sender cannot send. Any other
+ * link that opens nothing has expired.
+ */
+async function getSpentSigningLinkState(
+ tokenHash: string,
+ database: DbExecutor,
+): Promise<SigningUnavailableResponse["state"]> {
+ const spent = await queryOne<{
+ envelopeStatus: SigningEnvelopeRow["status"];
+ signerStatus: SigningSignerRow["status"];
+ }>(
+ database,
+ `
+ SELECT
+ envelopes.status AS "envelopeStatus",
+ signers.status AS "signerStatus"
+ FROM signers
+ JOIN envelopes ON envelopes.id = signers.envelope_id
+ WHERE signers.spent_signing_token_hash = $1
+ LIMIT 1
+ `,
+ [tokenHash],
+ );
+
+ switch (spent?.envelopeStatus) {
+ case "completed":
+ return "completed";
+ case "declined":
+ return "declined";
+ case "voided":
+ return "voided";
+ case "sent":
+ return spent.signerStatus === "signed" ? "already-signed" : "expired";
+ default:
+ return "expired";
+ }
+}
+
async function resolveSigningContext(
token: string,
{
@@ -1770,7 +1814,9 @@ async function resolveSigningContext(
);
if (!signerRow) {
- throw new SigningAccessError("expired");
+ throw new SigningAccessError(
+ await getSpentSigningLinkState(hashOpaqueToken(token), database),
+ );
}
const envelopeRow = await getEnvelopeRow(signerRow.envelopeId, database);
@@ -2628,6 +2674,7 @@ export async function submitSigningForToken(
UPDATE signers
SET
status = 'signed',
+ spent_signing_token_hash = signing_token_hash,
signing_token_hash = NULL,
signing_token_expires_at = NULL,
signed_at = $1,
@@ -2894,6 +2941,7 @@ export async function submitSigningForToken(
UPDATE signers
SET
status = 'signed',
+ spent_signing_token_hash = signing_token_hash,
signing_token_hash = NULL,
signing_token_expires_at = NULL,
signed_at = $1,
@@ -3269,6 +3317,7 @@ export async function declineSigningForToken(
UPDATE signers
SET
status = 'declined',
+ spent_signing_token_hash = signing_token_hash,
signing_token_hash = NULL,
signing_token_expires_at = NULL,
declined_at = $1,
diff --git a/src/lib/spent-signing-link.dbtest.ts b/src/lib/spent-signing-link.dbtest.ts
new file mode 100644
index 0000000..dda37f7
--- /dev/null
+++ b/src/lib/spent-signing-link.dbtest.ts
@@ -0,0 +1,292 @@
+import assert from "node:assert/strict";
+import { createHash, randomUUID } from "node:crypto";
+import { mkdtemp, rm } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { after, before, test } from "node:test";
+
+import { PDFDocument } from "pdf-lib";
+import type pg from "pg";
+
+import { openTestDatabase } from "./db/test-database.ts";
+import { ELECTRONIC_RECORDS_DISCLOSURE_VERSION } from "./electronic-records-disclosure.ts";
+import { voidSentEnvelope } from "./envelopes.ts";
+import { issueSigningLink } from "./services/signing-links.ts";
+import {
+ createStorageService,
+ type StorageService,
+} from "./services/storage.ts";
+import {
+ declineSigningForToken,
+ getSigningPayloadForToken,
+ recordSignerConsent,
+ SigningAccessError,
+ submitSigningForToken,
+} from "./signing.ts";
+
+// What an invitation says once it can no longer be used, against a real
+// Postgres. Signing, declining and voiding all retire the link, and the page
+// it opens should say what happened to the envelope rather than ask the
+// signer for a new link the sender cannot send. Run with `npm run test:db`.
+
+process.env.APP_URL ??= "https://sign.example.test";
+
+const DAY = 24 * 60 * 60;
+
+// A PNG of one transparent pixel, standing in for a drawn signature.
+const DRAWN_SIGNATURE =
+ "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==";
+
+let database: pg.Pool;
+let storageDir: string;
+let storageService: StorageService;
+const createdUsers: string[] = [];
+
+before(async () => {
+ database = await openTestDatabase();
+ // The seal and the emails read the install's settings through the shared
+ // pool.
+ globalThis.__signudocPgPool = database;
+ storageDir = await mkdtemp(path.join(tmpdir(), "signudoc-spent-link-"));
+ Object.assign(process.env, {
+ EMAIL_CAPTURE_DIR: path.join(storageDir, "outbox"),
+ EMAIL_DRIVER: "capture",
+ STORAGE_DRIVER: "local",
+ STORAGE_LOCAL_DIR: storageDir,
+ });
+ storageService = createStorageService();
+});
+
+after(async () => {
+ await database.query(`delete from public."user" where id = any($1)`, [
+ createdUsers,
+ ]);
+ await database.end();
+ await rm(storageDir, { force: true, recursive: true });
+});
+
+/**
+ * A sent envelope whose first signer holds an open, consented link. With
+ * `withSecondSigner`, a second signer waits behind them, so the first
+ * signature does not finish the envelope.
+ */
+async function createSentEnvelope({ withSecondSigner = false } = {}) {
+ const userId = randomUUID();
+ const envelopeId = randomUUID();
+ const signerId = randomUUID();
+ const fieldId = randomUUID();
+ const now = Math.floor(Date.now() / 1000);
+ const link = await issueSigningLink({ expiresInSeconds: DAY, issuedAt: now });
+ const sourcePdf = await PDFDocument.create();
+
+ sourcePdf.addPage([612, 792]);
+
+ const sourcePdfBytes = await sourcePdf.save();
+ const sourcePdfKey = `test/${envelopeId}.pdf`;
+
+ await storageService.putObject({
+ body: sourcePdfBytes,
+ contentType: "application/pdf",
+ key: sourcePdfKey,
+ });
+
+ 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', 'sent', $3, 'lease.pdf', $4, 1, $5, $6, $7)
+ `,
+ [
+ envelopeId,
+ userId,
+ sourcePdfKey,
+ sourcePdfBytes.length,
+ createHash("sha256").update(sourcePdfBytes).digest("hex"),
+ now,
+ now + DAY,
+ ],
+ );
+ await database.query(
+ `
+ insert into envelope_pages (id, envelope_id, page_number, width_pt, height_pt)
+ values ($1, $2, 1, 612, 792)
+ `,
+ [randomUUID(), envelopeId],
+ );
+ 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, 'notified', $4, $5, $6)
+ `,
+ [
+ signerId,
+ envelopeId,
+ `${signerId}@example.test`,
+ link.tokenHash,
+ link.exp,
+ now,
+ ],
+ );
+ await database.query(
+ `
+ insert into fields (
+ id, envelope_id, signer_id, type, page, x, y, width, height
+ ) values ($1, $2, $3, 'signature', 1, 0.1, 0.1, 0.2, 0.1)
+ `,
+ [fieldId, envelopeId, signerId],
+ );
+
+ if (withSecondSigner) {
+ const secondId = randomUUID();
+
+ await database.query(
+ `
+ insert into signers (id, envelope_id, name, email, sign_order, status)
+ values ($1, $2, 'Casey Second', $3, 2, 'pending')
+ `,
+ [secondId, envelopeId, `${secondId}@example.test`],
+ );
+ await database.query(
+ `
+ insert into fields (
+ id, envelope_id, signer_id, type, page, x, y, width, height
+ ) values ($1, $2, $3, 'signature', 1, 0.1, 0.4, 0.2, 0.1)
+ `,
+ [randomUUID(), envelopeId, secondId],
+ );
+ }
+
+ await recordSignerConsent(
+ link.token,
+ { disclosureVersion: ELECTRONIC_RECORDS_DISCLOSURE_VERSION },
+ { database },
+ );
+
+ return { envelopeId, fieldId, token: link.token, userId };
+}
+
+type Envelope = Awaited<ReturnType<typeof createSentEnvelope>>;
+
+function signEnvelope(envelope: Envelope) {
+ return submitSigningForToken(
+ envelope.token,
+ {
+ clientTimezoneOffsetMinutes: 0,
+ fields: [
+ {
+ fieldId: envelope.fieldId,
+ imageDataUrl: DRAWN_SIGNATURE,
+ inputMethod: "drawn",
+ type: "signature",
+ },
+ ],
+ },
+ { database },
+ );
+}
+
+/** The state the signing page shows for a link that opens nothing. */
+async function unavailableState(token: string) {
+ try {
+ await getSigningPayloadForToken(token, { database });
+ } catch (error) {
+ assert.ok(error instanceof SigningAccessError, String(error));
+ return { message: error.message, state: error.state };
+ }
+
+ assert.fail("The link still opened the document.");
+}
+
+async function envelopeStatus(envelopeId: string) {
+ const result = await database.query<{ status: string }>(
+ `select status from envelopes where id = $1`,
+ [envelopeId],
+ );
+
+ return result.rows[0]?.status;
+}
+
+test("a link reopened after the envelope is completed says it is complete", async () => {
+ const envelope = await createSentEnvelope();
+
+ await signEnvelope(envelope);
+ assert.equal(await envelopeStatus(envelope.envelopeId), "completed");
+
+ const reopened = await unavailableState(envelope.token);
+
+ assert.equal(reopened.state, "completed");
+ assert.doesNotMatch(reopened.message, /new signing link|expired/i);
+ assert.equal(await envelopeStatus(envelope.envelopeId), "completed");
+});
+
+test("a link reopened after the envelope is voided says it was voided", async () => {
+ const envelope = await createSentEnvelope();
+
+ await voidSentEnvelope(
+ envelope.userId,
+ envelope.envelopeId,
+ { senderEmail: "[email protected]", senderName: "Sam Sender" },
+ { database },
+ );
+ assert.equal(await envelopeStatus(envelope.envelopeId), "voided");
+
+ const reopened = await unavailableState(envelope.token);
+
+ assert.equal(reopened.state, "voided");
+ assert.equal(await envelopeStatus(envelope.envelopeId), "voided");
+});
+
+test("a link reopened after its signer declined says the envelope was declined", async () => {
+ const envelope = await createSentEnvelope();
+
+ await declineSigningForToken(
+ envelope.token,
+ { reason: "Not what we agreed." },
+ { database },
+ );
+
+ assert.equal((await unavailableState(envelope.token)).state, "declined");
+});
+
+test("a link reopened after its signer signed, with others still to sign, says they signed", async () => {
+ const envelope = await createSentEnvelope({ withSecondSigner: true });
+
+ await signEnvelope(envelope);
+ assert.equal(await envelopeStatus(envelope.envelopeId), "sent");
+
+ assert.equal(
+ (await unavailableState(envelope.token)).state,
+ "already-signed",
+ );
+});
+
+test("a signer who signed and then sees the envelope voided is told it was voided", async () => {
+ const envelope = await createSentEnvelope({ withSecondSigner: true });
+
+ await signEnvelope(envelope);
+ await voidSentEnvelope(
+ envelope.userId,
+ envelope.envelopeId,
+ { senderEmail: "[email protected]", senderName: "Sam Sender" },
+ { database },
+ );
+
+ assert.equal((await unavailableState(envelope.token)).state, "voided");
+});
+
+test("a link that was never issued still reads as expired", async () => {
+ const { token } = await issueSigningLink({
+ expiresInSeconds: DAY,
+ issuedAt: Math.floor(Date.now() / 1000),
+ });
+
+ assert.equal((await unavailableState(token)).state, "expired");
+});