Signing
Signing and the PDF
Add the public signing page with consent, initials, and a typed signature, render the signed PDF with @react-pdf/renderer in Next.js, store it in Postgres, and email it.
By the end of this page the client opens the link, agrees to sign electronically, initials every page, adopts a signature, and selects Finish. FastAPI stores the signed PDF and emails it to both sides.
The PDF layout lives with the screens, in React, using @react-pdf/renderer. The checks and the stored bytes live in FastAPI. FastAPI asks a protected Next.js route for the PDF, so the logic stays in Python and the layout stays in TypeScript.
Add the signing routes
Replace backend/app/main.py. The highlighted lines are new.
import hashlib
import json
import secrets
import urllib.request
from contextlib import asynccontextmanager
from datetime import UTC, datetime
from fastapi import BackgroundTasks, FastAPI, HTTPException, Request, Response
from pydantic import BaseModel, Field
from sqlalchemy import select, update
from sqlalchemy.orm.attributes import flag_modified
from app import ai
from app.config import settings
from app.db import Base, Contract, SessionDep, engine, new_session
from app.email import send_email
from app.templates import TEMPLATES, build_document
@asynccontextmanager
async def lifespan(app: FastAPI):
Base.metadata.create_all(engine) # Creates the table if it is missing. Never alters it.
# Work that was running when the app stopped will never finish. Retry picks it up.
with new_session() as session:
session.execute(update(Contract).where(Contract.status.in_(["pending", "processing"]))
.values(status="failed", reason="Interrupted by a restart"))
session.commit()
yield
app = FastAPI(title="Contract drafting", lifespan=lifespan)
@app.get("/health")
def health() -> dict:
return {"status": "ok", "company": settings.company_name}
def found[T](row: T | None) -> T:
if row is None:
raise HTTPException(404, "Not found")
return row
# Admin API. Not published: the browser reaches it only through Next.js, which asks for
# the admin password.
class Upload(BaseModel):
notes: str = Field(min_length=20, max_length=50_000)
@app.post("/api/contracts")
def upload(upload: Upload, background: BackgroundTasks, session: SessionDep) -> dict:
title = upload.notes.strip().splitlines()[0].strip("# ")[:120]
contract = Contract(title=title, notes=upload.notes)
session.add(contract)
session.commit()
background.add_task(process, contract.id)
return {"id": contract.id}
@app.get("/api/contracts")
def list_contracts(session: SessionDep) -> list[dict]:
columns = Contract.id, Contract.title, Contract.status, Contract.contract_type
return session.execute(select(*columns).order_by(Contract.id.desc())).mappings().all()
@app.get("/api/contracts/{contract_id}")
def get_contract(contract_id: int, session: SessionDep) -> dict:
return found(session.get(Contract, contract_id)).as_dict()
@app.post("/api/contracts/{contract_id}/retry")
def retry(contract_id: int, background: BackgroundTasks, session: SessionDep) -> dict:
# with_for_update locks the row until commit, so two clicks cannot both pass the check.
contract = found(session.get(Contract, contract_id, with_for_update=True))
if contract.status != "failed":
raise HTTPException(409, "Not failed")
contract.status = "pending"
session.commit()
background.add_task(process, contract_id)
return {"status": "pending"}
def process(contract_id: int) -> None:
"""Runs after the response, in its own session. Every commit shows in the admin page."""
with new_session() as session:
contract = session.get(Contract, contract_id)
contract.status, contract.reason = "processing", None
session.commit()
try:
if not contract.fields: # LLM step 1, then Python decides.
extraction = ai.extract(contract.notes)
reasons = ai.review_reasons(extraction, contract.notes)
contract.contract_type = extraction.contract_type
contract.fields = extraction.model_dump(mode="json")
if reasons:
contract.status, contract.reason = "needs_review", "\n".join(reasons)
session.commit()
return
template = TEMPLATES[contract.contract_type]
contract.title = f"{template['title']}: {contract.fields['client_company']}"
contract.sections = [{"key": key, "title": title, "status": "pending", "text": ""}
for key, (title, _) in template["sections"].items()]
session.commit()
prompts = TEMPLATES[contract.contract_type]["sections"]
for section in [s for s in contract.sections if s["status"] != "done"]: # LLM step 2
section["status"] = "writing"
flag_modified(contract, "sections") # SQLAlchemy can't see changes inside a list.
session.commit()
title, prompt = prompts[section["key"]]
section["text"] = ai.write_section(contract.notes, contract.fields, title, prompt)
section["status"] = "done"
flag_modified(contract, "sections")
session.commit()
contract.status = "drafted"
session.commit()
except Exception as error:
session.rollback()
contract.status, contract.reason = "failed", str(error)
session.commit()
def fingerprint(document: dict) -> str:
return hashlib.sha256(json.dumps(document, sort_keys=True).encode()).hexdigest()
@app.post("/api/contracts/{contract_id}/send")
def send(contract_id: int, background: BackgroundTasks, session: SessionDep) -> dict:
"""Freeze the agreement: from now on, it can only be signed while its hash matches."""
contract = found(session.get(Contract, contract_id, with_for_update=True))
if contract.status != "drafted":
raise HTTPException(409, "Only a drafted contract can be sent.")
document = build_document(contract)
contract.status, contract.token = "sent", secrets.token_urlsafe()
contract.content_hash, contract.sent_at = fingerprint(document), datetime.now(UTC)
session.commit()
link = f"{settings.base_url}/sign/{contract.token}"
client = document["client"]
body = f"Hi {client['name']},\n\nPlease review and sign {document['title']}:\n{link}\n"
background.add_task(send_email, [client["email"]], f"Please sign: {document['title']}", body)
return {"link": link}
# Signing API. Public: the random token in the link is the only key.
@app.get("/api/sign/{token}")
def view(token: str, session: SessionDep) -> dict:
contract = found(session.scalar(select(Contract).where(Contract.token == token)))
keys = ("status", "signer", "signed_at", "content_hash")
return {key: getattr(contract, key) for key in keys} | {"document": build_document(contract)}
class Signature(BaseModel):
consent: bool
initials: str = Field(min_length=1, max_length=12)
@app.post("/api/sign/{token}")
def sign(token: str, signature: Signature, request: Request, background: BackgroundTasks,
session: SessionDep):
"""Evidence: the private link, consent, timestamps and the browser. No IP address."""
query = select(Contract).where(Contract.token == token).with_for_update() # no double signing
contract = found(session.scalar(query))
if not signature.consent:
raise HTTPException(400, "Agree to use electronic records and signatures first.")
if contract.status != "sent":
raise HTTPException(409, "This agreement is already signed.")
document = build_document(contract)
if fingerprint(document) != contract.content_hash:
raise HTTPException(409, "This agreement changed after it was sent. Ask for a new link.")
contract.signer = {
"name": document["client"]["name"],
"initials": signature.initials.strip(),
"user_agent": request.headers.get("user-agent", "")[:300],
}
contract.status, contract.signed_at = "signed", datetime.now(UTC)
contract.pdf = render_pdf(contract, document)
session.commit()
to = [document["client"]["email"], settings.email_from]
body = f"{contract.signer['name']} signed {document['title']}. The signed PDF is attached.\n"
background.add_task(send_email, to, f"Signed: {document['title']}", body, contract.pdf)
return view(token, session)
def render_pdf(contract: Contract, document: dict) -> bytes:
"""Next.js renders the PDF with @react-pdf/renderer. We store the bytes it returns."""
keys = ("signer", "signed_at", "sent_at", "content_hash")
data = json.dumps({k: getattr(contract, k) for k in keys} | {"document": document}, default=str)
headers = {"Authorization": f"Bearer {settings.render_token}"}
request = urllib.request.Request(settings.render_url, data.encode(), headers)
with urllib.request.urlopen(request, timeout=60) as response:
return response.read()
@app.get("/api/sign/{token}/pdf")
def download(token: str, session: SessionDep) -> Response:
"""Always the stored bytes, never a new render."""
pdf = found(session.scalar(select(Contract.pdf).where(Contract.token == token)))
return Response(pdf, media_type="application/pdf",
headers={"Content-Disposition": 'attachment; filename="signed.pdf"'})The signing routes are public. The random token in the link is the only key.
sign checks four things, in this order:
- The token exists.
- The client agreed to sign electronically.
- The contract is still
sent. - A fresh build of the document has the same hash as the one saved at Send.
Then it asks Next.js for the PDF, stores the bytes, and emails them. The evidence is the private link, the consent, the timestamps, and the browser's user agent.
sign loads the contract with with_for_update(), the same lock as send. The lock holds until commit(), after the PDF is stored, so two clicks on Finish cannot sign the contract twice.
download always returns the stored bytes, never a new render. It selects only the pdf column, the one place the app loads the PDF. Two downloads give identical files.
No IP address
Next.js rewrites do not forward the client's address, so FastAPI would only see the address of the Next.js server. The app records no IP address at all, and the certificate says so.
Keep the PDF library on the server
Replace frontend/next.config.ts.
import type { NextConfig } from "next";
// Local runs read the project .env, like the backend. In Docker, Compose sets the variables.
try { process.loadEnvFile("../.env"); } catch {}
const config: NextConfig = {
serverExternalPackages: ["@react-pdf/renderer"],
// The browser talks only to Next.js. Other /api calls go on to FastAPI.
rewrites: async () => [
{ source: "/api/:path*", destination: `${process.env.API_URL || "http://localhost:8000"}/api/:path*` },
],
};
export default config;serverExternalPackages tells Next.js to load @react-pdf/renderer from node_modules at runtime instead of bundling it.
Write the PDF layout
Create the folder frontend/src/lib.
import path from "node:path";
import { Document, Font, Page, StyleSheet, Text, View, renderToBuffer } from "@react-pdf/renderer";
export type Block = { title: string; paragraphs?: string[]; items?: string[]; table?: string[][]; box?: string[][] };
export type Contract = {
status: string; signed_at: string | null; sent_at?: string; content_hash: string;
signer: { name: string; initials: string; user_agent: string } | null;
document: {
ref: string; title: string; company: string; sender: string; acceptance: string;
client: { company: string; name: string; email: string };
pages: { title: string; blocks: Block[] }[];
};
};
const font = (file: string) => path.join(process.cwd(), "public", "fonts", file);
Font.register({ family: "Manrope", fonts: [{ src: font("Manrope-Regular.ttf") }, { src: font("Manrope-Bold.ttf"), fontWeight: 700 }] });
Font.register({ family: "Allura", src: font("Allura-Regular.ttf") });
Font.registerHyphenationCallback((word) => [word]);
const s = StyleSheet.create({
page: { fontFamily: "Manrope", color: "#202020", fontSize: 9.3, paddingTop: 42, paddingBottom: 54, paddingHorizontal: 46 },
header: { flexDirection: "row", alignItems: "center", justifyContent: "space-between", borderBottom: "1 solid #E3E3E3", paddingBottom: 15, marginBottom: 21 },
headerRight: { fontSize: 7.5, color: "#707070", letterSpacing: 1 },
eyebrow: { fontSize: 8, fontWeight: 700, color: "#454545", letterSpacing: 1.8, marginBottom: 13 },
title: { fontWeight: 700, fontSize: 26, lineHeight: 1.15, marginBottom: 20 },
section: { marginBottom: 13 },
sectionTitle: { fontSize: 12, fontWeight: 700, marginBottom: 8, lineHeight: 1.3 },
paragraph: { marginBottom: 7, lineHeight: 1.4 },
item: { flexDirection: "row", marginBottom: 4 },
bullet: { width: 17, flexShrink: 0, fontSize: 8, color: "#686868" },
itemText: { flex: 1, fontSize: 9.3, lineHeight: 1.4 },
row: { flexDirection: "row", borderBottom: "1 solid #E2E2E2", paddingVertical: 6, paddingHorizontal: 10 },
footer: { position: "absolute", bottom: 28, left: 46, fontFamily: "Helvetica", fontSize: 7, color: "#7D7D7D" },
coverTitle: { fontWeight: 700, fontSize: 50, lineHeight: 1.1, marginBottom: 20 },
coverRule: { width: 46, height: 3, backgroundColor: "#333333", marginBottom: 27 },
coverMeta: { marginTop: 92, borderTop: "1 solid #E2E2E2", paddingTop: 22, flexDirection: "row", gap: 30 },
label: { fontSize: 7.3, letterSpacing: 1, color: "#707070", marginBottom: 5 },
value: { fontSize: 10, marginBottom: 4 },
muted: { color: "#707070", fontSize: 8.2 },
initial: { flexDirection: "row", justifyContent: "flex-end", alignItems: "center", marginTop: 12, color: "#707070", fontSize: 8 },
signatures: { flexDirection: "row", gap: 30, marginTop: 32 },
signatureBox: { flex: 1, minHeight: 135, backgroundColor: "#F8F8F8", border: "1 solid #E3E3E3", borderRadius: 4, padding: 17 },
signature: { fontFamily: "Allura", fontSize: 34, marginTop: 14, marginBottom: 10 },
notice: { backgroundColor: "#F7F7F7", padding: 14, borderRadius: 4, fontSize: 8, color: "#686868", marginTop: 24 },
banner: { border: "1 solid #D0D0D0", backgroundColor: "#F5F5F5", borderRadius: 5, padding: 16, marginBottom: 16, flexDirection: "row", justifyContent: "space-between" },
grid: { flexDirection: "row", gap: 22, marginBottom: 8 },
cell: { flex: 1 },
small: { fontSize: 8.5, lineHeight: 1.3, marginBottom: 12 },
});
const CONSENT = "I consent to use electronic records and signatures. I have reviewed this agreement and intend my electronic signature to be binding.";
const UTC = new Intl.DateTimeFormat("en-GB", { year: "numeric", month: "short", day: "2-digit", hour: "2-digit", minute: "2-digit", second: "2-digit", hour12: false, timeZone: "UTC" });
const time = (value?: string | null) => (value ? `${UTC.format(new Date(value))} UTC` : "Not recorded");
function Field({ label, value, note }: { label: string; value: string; note?: string }) {
return <View style={s.cell}><Text style={s.label}>{label}</Text><Text style={s.value}>{value}</Text>{note && <Text style={s.muted}>{note}</Text>}</View>;
}
export async function renderContract(c: Contract): Promise<Buffer> {
const doc = c.document, signer = c.signer!;
const Shell = ({ label, children }: { label: string; children: React.ReactNode }) => (
<Page size="A4" style={s.page}>
<View style={s.header}><Text style={{ fontSize: 18 }}>{doc.company}</Text><Text style={s.headerRight}>{label}</Text></View>
{children}
<Text style={s.footer} fixed render={({ pageNumber, totalPages }) => `AGREEMENT | ${doc.ref} | ${pageNumber} / ${totalPages}`} />
</Page>
);
const label = `${doc.title.toUpperCase()} / AGREEMENT`;
return renderToBuffer(
<Document title={`${doc.title} - ${doc.client.company}`} author={doc.company} creator={doc.company}>
<Shell label={doc.company.toUpperCase()}>
<View style={{ marginTop: 68 }}>
<Text style={s.eyebrow}>AGREEMENT</Text>
<View style={s.coverRule} />
<Text style={s.coverTitle}>{doc.title}</Text>
<Text style={{ fontSize: 10.5, color: "#686868" }}>Prepared for {doc.client.company}</Text>
</View>
<View style={s.coverMeta}>
<Field label="PREPARED FOR" value={doc.client.name} note={doc.client.email} />
<Field label="CREATED BY" value={doc.company} note={doc.sender} />
</View>
<View style={{ marginTop: 28 }}><Text style={s.label}>AGREEMENT REFERENCE</Text><Text style={s.muted}>{doc.ref}</Text><Text style={s.muted}>Issued {time(c.sent_at)}</Text></View>
</Shell>
{doc.pages.map((page, i) => (
<Shell key={i} label={label}>
<Text style={s.eyebrow}>{`0${i + 1} / AGREEMENT`}</Text>
<Text style={s.title}>{page.title}</Text>
{page.blocks.map((b, j) => (
<View key={j} style={s.section}>
<Text style={s.sectionTitle} minPresenceAhead={30}>{b.title}</Text>
{b.paragraphs?.map((p, k) => <Text key={k} style={s.paragraph}>{p}</Text>)}
{b.items?.map((item, k) => <View key={k} style={s.item} wrap={false}><Text style={s.bullet}>•</Text><Text style={s.itemText}>{item}</Text></View>)}
{(b.table || b.box) && (
<View style={{ border: "1 solid #E2E2E2", borderRadius: 4, backgroundColor: b.box ? "#FAFAFA" : undefined }}>
{(b.table || b.box)!.map((row, k) => (
<View key={k} style={[s.row, b.table && k === 0 ? { backgroundColor: "#F7F7F7", fontWeight: 700 } : {}]}>
{row.map((cell, n) => <Text key={n} style={{ flex: n === 0 ? 1.4 : 1, textAlign: n && b.table ? "right" : "left", fontWeight: b.box && n === 0 ? 700 : undefined }}>{cell}</Text>)}
</View>
))}
</View>
)}
</View>
))}
<View style={s.initial}><Text>Acknowledged with initials</Text><Text style={{ fontFamily: "Allura", fontSize: 19, color: "#202020", marginLeft: 10 }}>{signer.initials}</Text></View>
</Shell>
))}
<Shell label={label}>
<Text style={s.eyebrow}>{`0${doc.pages.length + 1} / ACCEPTANCE`}</Text>
<Text style={s.title}>Agreement Acceptance</Text>
<Text style={s.paragraph}>{doc.acceptance}</Text>
<View style={s.signatures}>
<View style={s.signatureBox}>
<Text style={s.label}>CLIENT</Text>
<Text style={s.value}>{signer.name}</Text>
<Text style={s.signature}>{signer.name}</Text>
<View style={{ borderTop: "1 solid #BFBFBF", paddingTop: 8 }}><Text style={s.muted}>Signed electronically</Text><Text style={s.muted}>{time(c.signed_at)}</Text></View>
</View>
<View style={s.signatureBox}>
<Text style={s.label}>{doc.company.toUpperCase()}</Text>
<Text style={s.value}>{doc.company}</Text>
<View style={{ marginTop: 23 }}><Text style={s.muted}>Authorized representative</Text></View>
<Text style={[s.muted, { marginTop: 15 }]}>Representative named in the agreement. No separate countersignature collected.</Text>
</View>
</View>
<View style={s.notice}>
<Text style={[s.label, { marginBottom: 7 }]}>ELECTRONIC SIGNING CONSENT</Text>
<Text>{CONSENT}</Text>
<Text style={{ marginTop: 10 }}>The certificate of completion on the following page records the signing activity associated with this agreement.</Text>
</View>
</Shell>
<Shell label="COMPLETION RECORD">
<Text style={s.eyebrow}>ELECTRONIC SIGNING RECORD</Text>
<Text style={[s.title, { fontSize: 28, marginBottom: 14 }]}>Certificate of completion</Text>
<View style={s.banner}><Text style={{ color: "#333333", fontWeight: 700, fontSize: 11 }}>Signing completed</Text><Text style={{ color: "#333333", fontSize: 8 }}>{time(c.signed_at)}</Text></View>
<View style={s.grid}><Field label="DOCUMENT" value={doc.title} /><Field label="AGREEMENT ID" value={doc.ref} /></View>
<View style={s.grid}>
<Field label="SIGNER NAME" value={signer.name} note={doc.client.email} />
<View style={s.cell}><Text style={s.label}>SIGNATURE ADOPTED</Text><Text style={[s.signature, { margin: 0, fontSize: 28 }]}>{signer.name}</Text><Text style={s.muted}>Typed electronic signature — Initials: {signer.initials}</Text></View>
</View>
<View style={s.grid}><Field label="ACCESS METHOD" value="Unique signing link" note="No independent identity verification" /><Field label="NETWORK ADDRESS OBSERVED" value="Not collected" note="Location not collected" /></View>
<Text style={s.label}>BROWSER / DEVICE REPORTED BY CLIENT</Text><Text style={s.small}>{signer.user_agent || "Not recorded"}</Text>
<Text style={s.label}>CONSENT RECORDED</Text><Text style={s.small}>{CONSENT}</Text>
<Text style={s.sectionTitle}>Activity record</Text>
{[["Sent for signing", c.sent_at], ["Signed", c.signed_at]].map(([name, at]) => (
<View key={name} style={{ flexDirection: "row", paddingVertical: 2, borderBottom: "1 solid #EBEBEB", fontSize: 8 }}><Text style={{ flex: 1, fontWeight: 700 }}>{name}</Text><Text style={{ width: 157, color: "#686868" }}>{time(at)}</Text></View>
))}
<View style={{ marginTop: 19 }} wrap={false}>
<Text style={s.label}>SHA-256 / DOCUMENT PRESENTED FOR SIGNING</Text>
<Text style={{ fontSize: 7.5, color: "#525252", lineHeight: 1.8 }}>{c.content_hash}</Text>
<Text style={[s.muted, { marginTop: 7 }]}>This fingerprint identifies the agreement content frozen when it was sent. This certificate is an application-generated activity record, not a cryptographic PDF signature or a qualified electronic signature.</Text>
</View>
</Shell>
</Document>,
);
}The PDF has a cover, one page per agreement page with the client's initials at the bottom, the acceptance page with the signature in the Allura font, and a certificate of completion with the SHA-256 hash. The fonts are read from public/fonts/. The Contract type is shared with the signing page.
Add the render route
Create the folders frontend/src/app/api/internal/render.
import { renderContract, type Contract } from "@/lib/pdf";
// Only FastAPI calls this route. It sends the signed contract and gets the PDF bytes back.
export async function POST(request: Request) {
const token = process.env.RENDER_TOKEN || "";
if (token.length < 32 || request.headers.get("authorization") !== `Bearer ${token}`)
return Response.json({ error: "Unauthorized" }, { status: 401 });
const pdf = await renderContract((await request.json()) as Contract);
return new Response(new Uint8Array(pdf), { headers: { "Content-Type": "application/pdf" } });
}Only FastAPI calls this route, with RENDER_TOKEN as a bearer token. A route handler wins over the rewrite in next.config.ts, so /api/internal/render stays in Next.js while every other /api path goes to FastAPI. The route refuses to run with a token shorter than 32 characters.
Write the signing page
Create the folders frontend/src/app/sign/[token].
"use client";
import { useEffect, useRef, useState } from "react";
import { useParams } from "next/navigation";
import type { Block, Contract } from "@/lib/pdf";
const CONSENT = "I agree to use electronic records and signatures.";
const SIGNING_CONSENT = "I consent to use electronic records and signatures. I have reviewed this agreement and intend my electronic signature to be binding.";
const ICONS = {
file: "M14 3H5v18h14V8zM14 3v5h5M8 12h8M8 16h6",
check: "m5 12 4 4L19 6",
arrow: "M4 12h16m-6-6 6 6-6 6",
download: "M12 3v12m-5-5 5 5 5-5M5 17v4h14v-4",
pen: "m4 16 11-11 4 4L8 20H4zM13 7l4 4M13 21h8",
};
const Icon = ({ name, size = 20 }: { name: keyof typeof ICONS; size?: number }) => (
<svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
<path d={ICONS[name]} />
</svg>
);
function BlockView({ block }: { block: Block }) {
return (
<section className="contract-section">
<h2>{block.title}</h2>
{block.paragraphs?.map((p, i) => <p key={i}>{p}</p>)}
{!!block.items?.length && <ul>{block.items.map((item, i) => <li key={i}>{item}</li>)}</ul>}
{(block.table || block.box) && (
<table className={block.box ? "terms-box" : "terms-table"}>
<tbody>{(block.table || block.box)!.map((row, i) => <tr key={i}>{row.map((cell, j) => <td key={j}>{cell}</td>)}</tr>)}</tbody>
</table>
)}
</section>
);
}
function Dialog({ open, className, onClose, children }: { open: boolean; className: string; onClose: () => void; children: React.ReactNode }) {
const ref = useRef<HTMLDialogElement>(null);
useEffect(() => {
if (open && !ref.current?.open) ref.current?.showModal();
if (!open && ref.current?.open) ref.current.close();
}, [open]);
return <dialog ref={ref} className={`sign-dialog ${className}`} onCancel={(e) => { e.preventDefault(); onClose(); }}>{children}</dialog>;
}
export default function SignPage() {
const { token } = useParams<{ token: string }>();
const [contract, setContract] = useState<Contract | null>(null);
const [error, setError] = useState("");
const [dialog, setDialog] = useState<"welcome" | "adopt" | "finish" | null>("welcome");
const [consent, setConsent] = useState(false);
const [initials, setInitials] = useState("");
const [adopted, setAdopted] = useState(false);
const [target, setTarget] = useState("");
const [initialed, setInitialed] = useState<number[]>([]);
const [signed, setSigned] = useState(false);
const [busy, setBusy] = useState(false);
async function call(init?: RequestInit) {
setBusy(true);
const response = await fetch(`/api/sign/${token}`, { headers: { "Content-Type": "application/json" }, ...init });
const data = await response.json();
setBusy(false);
if (!response.ok) return setError(typeof data.detail === "string" ? data.detail : "Something went wrong.");
setContract(data);
if (data.status === "signed") window.scrollTo(0, 0);
setInitials((current) => current || data.document.client.name.split(" ").map((w: string) => w[0]).join(""));
}
useEffect(() => { call(); }, []);
if (!contract) return (
<div className="sign-app">
<header className="sign-loading-header"><span className="brand">Contract signing</span></header>
<main className="sign-loading">
<Icon name="file" size={32} />
<h1>{error ? "Document unavailable" : "Loading document…"}</h1>
{error && <p role="alert">{error}</p>}
</main>
</div>
);
const doc = contract.document;
const name = doc.client.name;
const pages = doc.pages.length + 2;
const fields = doc.pages.length + 1;
const complete = initialed.length + (signed ? 1 : 0);
const done = contract.status === "signed";
const label = complete === fields ? "Finish" : complete ? "Next" : "Start";
const pdf = `/api/sign/${token}/pdf`;
function next() {
const page = doc.pages.findIndex((_, i) => !initialed.includes(i));
if (complete === fields) return setDialog("finish");
const field = document.getElementById(page >= 0 ? `field-${page}` : "field-signature");
field?.scrollIntoView({ behavior: "smooth", block: "center" });
field?.focus({ preventScroll: true });
}
function apply(field: string) {
if (field === "signature") setSigned(true);
else setInitialed((list) => [...list, Number(field)]);
setAdopted(true);
setDialog(null);
}
function select(field: string) {
if (adopted && field !== "signature") return apply(field);
setTarget(field);
setDialog("adopt");
}
const heading = (
<div className="paper-document-heading"><span className="brand">{doc.company}</span><span>{doc.ref}</span></div>
);
const footer = (page: number) => (
<div className="sign-paper-footer"><span>AGREEMENT — {doc.ref}</span><span>{page} / {pages}</span></div>
);
return (
<div className={`sign-app${done ? " sign-app-completed" : ""}`}>
<header className="sign-topbar">
<div className="sign-topbar-title">
<span>{done ? "Signing complete" : "Review and complete"}</span>
<span className="sign-document-name">{doc.title}</span>
</div>
<div className="sign-topbar-actions">
<span className="sign-recipient">{name}</span>
{done ? (
<a className="toolbar-download" href={pdf}><Icon name="download" size={17} />Download</a>
) : (
<div className="finish-split"><button disabled={busy || !consent} onClick={next}>{label}</button></div>
)}
</div>
</header>
{done ? (
<main className="sign-completed">
<div className="signed-status" role="img" aria-label="Completed"><Icon name="check" size={26} /></div>
<h1>You’re all done.</h1>
<p>Your document has been signed and completed.</p>
<div className="signed-document-row">
<Icon name="file" size={28} />
<div><strong>{doc.title}</strong><span>Completed {new Date(contract.signed_at!).toLocaleDateString("en-GB", { dateStyle: "long" })}</span></div>
</div>
<a href={pdf} className="sign-button">Download document</a>
<p className="completion-delivery">A copy has been sent to {doc.client.email}.</p>
<p className="completion-certificate">The PDF includes your signed agreement and certificate of completion.</p>
<details className="sign-evidence">
<summary>View document details</summary>
<dl><div><dt>Signed by</dt><dd>{name}</dd></div><div><dt>Document reference</dt><dd>{doc.ref}</dd></div></dl>
<p>Document presented for signing — SHA-256</p>
<code>{contract.content_hash}</code>
</details>
</main>
) : (
<>
<div className="sign-document-strip">
<div><Icon name="file" size={16} /><span>{doc.title}</span><span className="sign-strip-separator" aria-hidden="true" /><span>{pages} pages</span></div>
<span className="local-label">PRIVATE AGREEMENT</span>
</div>
<div className="sign-workspace">
<div className="sign-guidance">
<button className="start-tab" disabled={!consent || busy} onClick={next}>{label}<Icon name="arrow" size={17} /></button>
<span>{complete} of {fields}<br />fields complete</span>
</div>
<main className="sign-paper-stack" aria-label="Agreement document">
{error && <div className="sign-alert" role="alert">{error}</div>}
<article className="sign-paper contract-cover">
<div className="contract-cover-brand"><span className="brand">{doc.company}</span></div>
<div className="contract-cover-title"><span>AGREEMENT</span><h1>{doc.title}</h1><p>Prepared for {doc.client.company}</p></div>
<div className="contract-cover-meta">
<div><span>Created by</span><strong>{doc.company}</strong><p>{doc.sender}</p></div>
<div><span>Prepared for</span><strong>{name}</strong><p>{doc.client.email}</p></div>
</div>
{footer(1)}
</article>
{doc.pages.map((page, i) => (
<article key={i} className="sign-paper">
{heading}
<div className="paper-section-heading">
<h2>{page.title}</h2>
<div className="initial-field-container">
{initialed.includes(i) ? <span className="applied-initials" title="Initials applied">{initials}</span> : (
<button id={`field-${i}`} className="signature-tag initials-tag" aria-label={`Initial ${page.title}`} onClick={() => select(String(i))}>
<span>Initial</span><Icon name="pen" size={17} />
</button>
)}
</div>
</div>
{page.blocks.map((block, j) => <BlockView key={j} block={block} />)}
<div className="page-acknowledgement">
{initialed.includes(i) ? <><Icon name="check" size={13} /> Initials applied</> : "Apply your initials to acknowledge this section."}
</div>
{footer(i + 2)}
</article>
))}
<article className="sign-paper acceptance-paper">
{heading}
<h2>Agreement Acceptance</h2>
<section className="contract-section"><p>{doc.acceptance}</p></section>
<div className="acceptance-parties">
<div>
<h3>Client</h3>
<p>{name}</p>
<div className="signature-line">
{signed ? (
<button className="applied-signature" aria-label="Review adopted signature" onClick={() => { setTarget("signature"); setDialog("adopt"); }}>
<small>Signed by:</small><span>{name}</span><small>{doc.ref}</small>
</button>
) : (
<button id="field-signature" className="signature-tag" onClick={() => select("signature")}><span>Sign</span><Icon name="pen" size={24} /></button>
)}
</div>
<span className="signature-line-label">Electronic signature</span>
</div>
<div>
<h3>{doc.company}</h3>
<p>Authorized representative</p>
<div className="provider-signature-note">{doc.company}<small>Representative named in the agreement.<br />No separate countersignature collected.</small></div>
</div>
</div>
<div className="document-finish-panel">
<div>
<strong>{complete === fields ? "All required fields are complete." : "Complete the required fields to finish."}</strong>
<p>{complete === fields ? "Select Finish to confirm and submit your document." : `${fields - complete} ${fields - complete === 1 ? "field remains" : "fields remain"}. Use Next to find the next required field.`}</p>
</div>
<button className="sign-button" disabled={busy} onClick={next}>{label}</button>
</div>
{footer(pages)}
</article>
</main>
</div>
</>
)}
<footer className="sign-footer"><span>{doc.company}</span><div><span>English</span></div><span>© {new Date().getFullYear()} {doc.company}</span></footer>
<Dialog open={!done && dialog === "welcome"} className="welcome-dialog" onClose={() => {}}>
<div className="welcome-dialog-body">
<span className="brand">{doc.company}</span>
<h1>Review and continue</h1>
<div className="sender-message">
<strong>Message from {doc.company}</strong>
<span>{doc.sender}</span>
<p>{name},</p>
<p>Please review and sign your {doc.title}. You can read the document before completing the required fields.</p>
<p>If you have questions about the agreement, contact <a href={`mailto:${doc.sender}`}>{doc.sender}</a>.</p>
<div className="welcome-document-summary"><Icon name="file" /><span>{doc.title}<small>{pages} pages — {doc.ref}</small></span></div>
</div>
<details className="electronic-disclosure">
<summary>About electronic records and signatures</summary>
<p>You will review and sign this document electronically and can download a completed copy afterwards. Your consent, actions and browser-reported information are recorded with the agreement.</p>
</details>
<label className="sign-checkbox">
<input type="checkbox" checked={consent} onChange={(e) => setConsent(e.target.checked)} />
<span>{CONSENT} <b aria-hidden="true">*</b></span>
</label>
</div>
<div className="dialog-footer">
<span className="dialog-language">English</span>
<div><button className="sign-button" disabled={!consent} onClick={() => setDialog(null)}>Continue</button></div>
</div>
</Dialog>
<Dialog open={dialog === "adopt"} className="adoption-dialog" onClose={() => setDialog(null)}>
<div className="dialog-title"><h1>Adopt Your Signature</h1><button aria-label="Close signature dialog" onClick={() => setDialog(null)}>×</button></div>
<form onSubmit={(e) => { e.preventDefault(); if (initials.trim()) apply(target); }}>
<div className="adoption-body">
<p>Confirm your name and initials.</p>
<div className="adoption-fields">
<div className="adoption-known-name"><span>Full name</span><strong>{name}</strong></div>
<label>Initials <b>*</b><input name="initials" value={initials} onChange={(e) => setInitials(e.target.value)} required maxLength={12} readOnly={adopted} /></label>
</div>
<div className="signature-style-heading">Signature preview</div>
<div className="adoption-preview">
<div><small>Signed by:</small><span>{name}</span><small>{doc.ref}</small></div>
<div><small>Initials</small><span>{initials || "\u2014"}</span></div>
</div>
<p className="adoption-disclosure">Selecting Adopt and Sign applies this electronic mark to the selected field. You can review your document before selecting Finish.</p>
</div>
<div className="dialog-footer adoption-footer">
<button className="sign-button" type="submit">Adopt and Sign</button>
<button className="sign-button secondary" type="button" onClick={() => setDialog(null)}>Cancel</button>
</div>
</form>
</Dialog>
<Dialog open={!done && dialog === "finish"} className="confirmation-dialog" onClose={() => setDialog(null)}>
<div className="dialog-title"><h1>Finish signing</h1><button aria-label="Close finish dialog" onClick={() => setDialog(null)}>×</button></div>
<div className="confirmation-body">
<p>You have completed all required fields.</p>
<div className="finish-document"><Icon name="file" /><strong>{doc.title}</strong></div>
<p>By selecting Finish, you confirm:</p>
<blockquote>{SIGNING_CONSENT}</blockquote>
{error && <p className="dialog-error" role="alert">{error}</p>}
</div>
<div className="dialog-footer right">
<button className="sign-button secondary" disabled={busy} onClick={() => setDialog(null)}>Back to document</button>
<button className="sign-button" disabled={busy} onClick={() => call({ method: "POST", body: JSON.stringify({ consent, initials }) })}>{busy ? "Finishing…" : "Finish"}</button>
</div>
</Dialog>
</div>
);
}The page loads the document from GET /api/sign/<token> and shows a welcome dialog with the consent checkbox. Start and Next jump to the next empty field. The first field opens the dialog to adopt a signature, and every initial after that applies at once. When all fields are done, Finish posts the consent and the initials, and the page switches to "You're all done." with the download.
Everything on this page renders from build_document(), so the page works for all three contract types without knowing which one it shows.
Restart Next.js
next.config.ts changed, so stop pnpm dev with Ctrl+C and start it again.
Check
Process and send a new contract from the admin page, with your own email address in the notes. Open the signing link from the email, or from the admin page.
- Tick the consent box and click Continue.
- Click Start, then Initial on the first page. Check your initials in the dialog and click Adopt and Sign.
- Click Next and Initial for every other page. Then click Sign on the acceptance page and Adopt and Sign once more.
- Click Finish, and Finish again in the dialog.
The page shows "You're all done." Download the PDF. It has your initials on every page, the signature, and a certificate with the SHA-256 hash. The email "Signed: Statement of Work" arrives with the PDF attached, in your inbox and in the demo inbox.
Download the PDF twice from a terminal. The token is the last part of the signing link.
curl -o first.pdf http://localhost:3000/api/sign/<token>/pdf
curl -o second.pdf http://localhost:3000/api/sign/<token>/pdf
cmp first.pdf second.pdf && echo identical
# identicalThen try to break it.
| Test | Expected |
|---|---|
Open http://localhost:3000/sign/nope | "Document unavailable", because the API returns 404 |
| Sign the same contract again | 409, "This agreement is already signed." |
| Sign without consent | 400 |
Call /api/internal/render without the token | 401 |
curl -i -H 'content-type: application/json' -d '{"consent": true, "initials": "DW"}' \
http://localhost:3000/api/sign/<token>
# HTTP/1.1 409 Conflict
curl -i -X POST http://localhost:3000/api/internal/render
# HTTP/1.1 401 UnauthorizedSend "consent": false instead, and the answer is a 400.
The tamper test
Send one more contract, but do not sign it yet. Change a section in the database:
docker compose exec db psql -U postgres -c "update contracts set sections = jsonb_set(sections, '{0,text}', '\"changed\"') where status = 'sent'"Now sign it. Finish shows "This agreement changed after it was sent. Ask for a new link."
Last, upload 02 and 03 as well, and sign one contract of each type. The discovery has one page with a fee box, and the retainer has a terms box instead of a payment table.