Skip to content

Signing ​

Datum signs two different things, and a form can use either, both or neither. A PDF signature proves the document has not changed since it was signed. A submission signature proves who sent exactly these answers.

PDF signatureSubmission signature
StandardPAdES, in the PDF itselfWebAuthn, over the canonical JSON bytes
Who signsThe server with its certificate, or the person with a YubiKey or a certificate fileThe person with a passkey or security key
What it coversThe PDF's bytesThe answers (the envelope, the submission or the values)
Checked byAny PDF viewer, or the host's verify routeThe host that receives the submission

Choose by what you need to prove.

  • The record must be provable as issued, and any viewer should show it: sign the PDF on the server (signature block, a certificate on the host).
  • A person must sign a PDF with their own certificate: the signing agent, with a YubiKey or a certificate file.
  • The answers must be provably those the person sent: a passkey signs the submission. The button option for this is called the passkey option (signature: "webauthn").

The signature block of a PDF layout and the signature option of a button are unrelated: the first seals a PDF, the second asks for a passkey on submit.

PDF signatures ​

The server signs ​

A host with its own certificate can seal every PDF it issues. Turn the seal on and give the host a key (a PKCS#12 file or a PEM key and certificate chain). Any PDF viewer's signature panel then validates the record. A layout's signature block says how its documents are sealed.

KeyMeaningDefault
fieldThe name of the pdf-signature block, or a template's signature field, the signature lands inA new field of its own
certifynoChanges, formFilling or annotations to certify the document, or false for an approval signaturefalse
reason, location, contactInfo, nameWhat the signature says about itself. reason is translated per locale; name defaults to the certificate's common nameNone
subFilterETSI.CAdES.detached (PAdES) or adbe.pkcs7.detached (the older Adobe profile)ETSI.CAdES.detached
appearancefalse for an invisible signature, or where and how it is drawn: page (from 1), rect as [x, y, width, height] in points from the page's top left, lines (the text), fontId, fontSizeVisible, 180 by 48 points at the bottom left of the last page, saying who signed, when and why. A named field takes the field's place
commitmentWhat the signer means by signing: type (approval, origin, receipt, delivery, sender or creation) and a statement. Unlike reason, it is a signed attribute, which verify reads backNone
timestampReserve room for an RFC 3161 timestamp tokenfalse
placeholderBytesThe room reserved for the signature, in bytes, up to 65,536. It must leave 1 KiB beside the certificatesWorked out from the certificates, at least 8 KiB
requiredRefuse to produce a PDF that cannot be signed, instead of producing it unsignedfalse

The digest is always SHA-256. The builder's PDF workspace sets all of these but appearance and placeholderBytes, which are written in the definition.

A certificate may hold an RSA key (PKCS#1 v1.5), or an EC key on the P-256 or P-384 curve. RSASSA-PSS keys, other curves and other key types are refused with the signature failure when the PDF is prepared; RSA-1024 and Ed25519 keys are listed by the signing agent but refused before any PIN is asked. A certificate that has expired, is not yet valid, is about to expire, or whose issuer is not among the certificates sent warns instead of failing.

json
{ "signature": { "field": "server-signature", "certify": "noChanges", "reason": "Received and validated by the intake service", "timestamp": true, "required": true } }

The pdf-signature component places a named signature field in a layout, with a caption and a width and height, so you choose where the visible signature goes. Without one the signature takes a field of its own at the bottom of the last page.

The document-modification policy ​

certify is the document-modification policy. noChanges is the server's record: any later change breaks the signature. formFilling still allows fields to be filled and further signatures added, and annotations also allows annotations. A certifying signature must be the document's first.

Timestamps ​

A timestamp is an RFC 3161 token from a timestamp authority, which proves the PDF existed at that time. Both built hosts can issue tokens from their own timestamp server, or ask a server you name. A timestamp that cannot be fetched produces a warning, never a failed PDF. A token is checked when the PDF is verified, never taken on trust.

The person signs ​

When the person signs with their own certificate, the page cannot reach a YubiKey or a key file on the computer, and must not hold a key. A small local agent does that, tools/piv-agent in the repository, a Python program (3.11 or later) that listens on the loopback address only. It asks for the PIN or passphrase in the operating system's own dialog, so the page never sees it, and it never sees the PDF.

sh
pip install -r requirements.txt
python piv_agent.py --allow-origin https://forms.example.org
python piv_agent.py --p12 ~/signer.p12 --allow-origin https://forms.example.org
python piv_agent.py --key signer.key.pem --cert signer.cert.pem --allow-origin https://forms.example.org

A YubiKey is not required. With no flag the agent signs with the certificate on a YubiKey's PIV applet. --p12 serves a .p12 or .pfx file, and --key with --cert serves a PEM pair. A file is listed under the slot file, its key is read and dropped for every signature, and the dialog is a plain Sign or Cancel when the file has no passphrase. A key in a file is only as safe as the file, so keep it out of shared folders and prefer a passphrase.

FlagMeaningDefault
--allow-origin ORIGINA web origin that may use the agent. Repeat for severalThe development server's two local addresses on port 5173. Always pass your own
--port NThe port on 127.0.0.1. The agent listens on no other interface7391
--slot SLOTThe slot a request that names none signs with. A PIV slot such as 9c (Digital Signature), 9a, 9d, 9e or a retired slot, or file9c; file when a certificate file is given
--serial NWhich YubiKey, when several are plugged inThe one plugged in
--chain PEMIssuer certificates to send after the signer's. A token holds only its own certificate, so without a chain a viewer may not be able to build the signer's chainNone
--p12 FILEA PKCS#12 certificate file to sign withNone
--key PEM, --cert PEMA PEM private key and its certificate (the signer's first, then issuers). Given together, and not with --p12None
--terminal-pinAsk for the PIN or passphrase in the agent's terminal, for a headless or SSH sessionA native dialog
--allow-no-originAlso answer requests without an Origin header, such as curlRefused
--verbose, -vLog each request to stderr, never the PIN, the bytes or the valueOff

The origin list is the consent between web pages: a page that is not listed is refused before anything else happens. The dialog is the consent for each signature. The agent has three routes: GET /health, GET /certificates (the certificates it can sign with, their key types, whether each is usable, and the PIN policy) and POST /sign, one signature at a time.

In the page, createAgentPdfSigner turns the agent into a signer, and pdfSigner makes every PDF the form downloads a signed one. Import it from the bundle you serve; with a bundler, import from @datum/web-components.

js
import { createAgentPdfSigner } from "./datum-form.js";

form.pdfSigner = await createAgentPdfSigner({
  url: "http://127.0.0.1:7391",
  slot: "9c",
  context: { title: "Intake form", reason: "I confirm these answers" }
});
await form.downloadPdf();
form.pdfSigner = undefined;
OptionMeaningDefault
urlWhere the agent listenshttp://127.0.0.1:7391
slotThe slot to sign with9c when the agent lists it, else the only usable certificate; several and no 9c is a no_certificate error
contextWhat the PIN dialog says about the document: title, documentId, field, reason (what the person affirms)Nothing
fetchA fetch to useThe page's

listAgentCertificates(url) returns what the agent can sign with, for a page that lets the person choose. agentPdfSignerFor(entry, options) makes a signer for one of the entries it listed. A signer is any object with certificates (base64 DER, the signer's first) and sign(toBeSigned, algorithm), which returns the signature bytes, so a key service can sign instead of the agent.

pdfSignature carries the settings, over the layout's own, and a timestamper. A timestamper is an object with timestamp(request), which posts the request bytes to a timestamp authority and returns its answer. Set timestamp: true so room is reserved.

js
form.pdfSignature = {
  settings: { certify: "noChanges", reason: "Issued by the intake service", timestamp: true },
  timestamper: {
    async timestamp(request) {
      const response = await fetch("/tsa", { method: "POST", headers: { "Content-Type": "application/timestamp-query" }, body: request });
      return new Uint8Array(await response.arrayBuffer());
    }
  }
};

An agent that cannot sign rejects with a PdfSigningAgentError whose code a page words for the person. The page's own codes are unreachable (no agent answered, or the browser blocked the call) and protocol (something answered that is not the agent). pin_invalid carries attemptsRemaining. The codes are listed in the codes reference.

The example is a page with the form and two buttons. "Draw the PDF" draws the unsigned PDF in the browser. "Sign with my certificate" asks the agent for the certificate and signs into the layout's signature field, exactly as the code above does. Unless the agent is running on your computer with this page's origin in --allow-origin, the page cannot reach it, and the button reports unreachable in the status line and in the log. The agent refuses an origin it does not allow with origin_denied and sends no CORS headers on that reply, so the browser hides it from the page: the page sees unreachable, and the code shows only in the agent's own log. Nothing is simulated: the request goes to http://127.0.0.1:7391 for real. With the agent running (tools/piv-agent) and a token or --p12 file, the same button asks for the PIN in your system's dialog and downloads a PDF signed by your certificate. Your browser may first ask whether the page may reach apps on your device.

index.html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Customer intake, signed</title>
    <link rel="stylesheet" href="/datum/datum-form.css">
    <script type="module" src="/datum/datum-form.js"></script>
  </head>
  <body>
    <datum-form
      id="intake"
      src="/forms/signed-intake.json"
      pdf="auto"
    ></datum-form>
    <p>
      <button id="plain" type="button">Draw the PDF</button>
      <button id="sign" type="button">Sign with my certificate</button>
      <span id="status" role="status"></span>
    </p>

    <script type="module">
      // The bundle exports the client for the local signing agent: no key and no
      // cryptography in the page.
      import { createAgentPdfSigner } from "/datum/datum-form.js";

      const form = document.getElementById("intake");
      form.dataSources = {
        countries: [
          { value: "CA", label: "Canada" },
          { value: "US", label: "United States" },
          { value: "MX", label: "Mexico" }
        ]
      };
      const status = document.getElementById("status");

      // The unsigned PDF, drawn in the browser.
      document.getElementById("plain").addEventListener("click", async () => {
        const { bytes, pageCount } = await form.renderPdf();
        status.textContent = `Drew ${pageCount} page(s), ${bytes.length} bytes, unsigned.`;
      });

      // The agent runs on the person's own computer and listens on the loopback address for
      // the origins it was started with. It asks for the PIN or passphrase in the system's
      // own dialog, so the page never sees it, and it never sees the PDF.
      document.getElementById("sign").addEventListener("click", async () => {
        status.textContent = "Waiting for the prompt on your computer…";
        try {
          // Lists what the agent holds and takes slot 9c, the Digital Signature slot.
          form.pdfSigner = await createAgentPdfSigner({ url: "http://127.0.0.1:7391", slot: "9c" });
          // The layout ends in a signature field. The kernel prepares the bytes, the agent
          // signs them, the kernel embeds the signature and the file downloads.
          const { signature } = await form.downloadPdf();
          status.textContent = `Signed in ${signature.field}.`;
        } catch (error) {
          // error.code: unreachable, origin_denied, no_device, pin_cancelled, pin_invalid,
          // pin_blocked, touch_timeout, busy
          status.textContent = `Not signed (${error.code ?? "error"}): ${error.message}`;
          console.log("not signed:", error.code ?? error.message);
        } finally {
          form.pdfSigner = undefined; // one signed download; the plain PDF stays plain
        }
      });
    </script>
  </body>
</html>
ResultThis page, running. Addresses under /forms//api/ are answered by the example.
What the page did

Nothing yet.

The form is signed-intake.json: its layout ends in a pdf-signature block named applicant-signature.

Two calls ​

Signing is done in two calls, so a private key never enters the sandbox and never has to be exportable. The first call prepares the PDF and returns the exact bytes to be signed. The signer, a server key, a hardware token or a key service, signs them. The second call embeds the signature in the file. A server host offers the same through its PDF routes: render, fill, sign and verify. The operations are in Running the PDF program.

Verifying ​

POST /api/pdf/verify on a built host takes the PDF's bytes and reports each signature: that the byte range frames the file, that nothing was appended after it (coversDocument), the digest, the certification level, any timestamp and whether the signer's certificate is trusted. The host decides trust from the anchors you configure. For a record certified with noChanges, coversDocument: true is the check that nothing changed. The report's fields are in Running the PDF program.

What the program checks, and what you must check:

  • The program checks the structure, that the signed range hashes to the digest, and that the signature names its certificate. It does not check the signature value and does not decide trust. Check the value with the signer's public key over toBeVerified, and judge the certificate against your own anchors. Treating digestMatches as valid skips both.
  • A signature with coversDocument: false has later updates. Read laterRevisions: for a certified document, permitted says whether the certification allows what changed, such as form filling or another signature. It holds only when every signature in reliedOnSignatures is itself valid by your checks. When laterRevisions is missing on such a signature, the changes could not be judged; treat the document as changed.
  • Pass the certificates you already know, such as your timestamp authority's, as knownCertificates (at most 64, each at most 16 KiB), so a token that carries none can still name its signer. Knowing a certificate is not trusting it.

Submission signatures ​

A submission is the answers as canonical JSON, so the same answers always give the same bytes. A passkey or security key signs a hash of those bytes before the form sends them, and the server recomputes the bytes and checks the signature.

SettingValuesEffect
signing-scopeenvelope (default), submission, valuesWhat is signed: the whole envelope, its submission block, or the answers alone
signing-placementembedded (default), wrapperWhether the signatures sit inside the envelope or beside it
sign-witha provider idThe provider every submit signs with. An id with no provider refuses the submit

The signing property sets the same and one more thing, statement: the words the signer agrees to, signed with the answers and recorded on each signature. submit({ signWith, signing }) sets them for one call. These need signing in the features list when one is given.

The page supplies the provider in script. Its code loads as a separate file, datum-form-webauthn-*.js, only when a provider is set; keep it beside datum-form.js.

html
<datum-form id="consent" src="/forms/consent.json" signing-scope="submission" sign-with="webauthn"></datum-form>
<script type="module">
  import { createWebAuthnSigningProvider } from "./datum-form.js";
  document.getElementById("consent").signingProviders = [
    createWebAuthnSigningProvider({ rpId: "forms.example.org", discoverable: true })
  ];
</script>

With a bundler, import the same names from @datum/web-components. A button component can also ask for the signature itself: set its signature to the passkey option, which signs with the provider whose id is webauthn. A submit that names a provider nobody registered is refused as signing.providerMissing, and one whose provider fails as signing.failed, with the provider's own code in errorCode. Nothing is delivered unsigned.

Provider options ​

createWebAuthnSigningProvider(options):

OptionMeaningDefault
rpIdThe relying party id: the page's host, or a registrable suffix of it. RequiredNone
idThe provider id that sign-with and a button namewebauthn
credentialsA function returning the person's registered credentials, each { id, transports?, algorithm?, publicKey? } with id in base64url. Read at each submit. Required unless discoverableNone
discoverableWith no credentials listed, let the browser offer any passkey the person has for the site. The server then finds the key by the credential id in the signaturefalse
userVerificationrequired, preferred or discouragedpreferred
timeoutMilliseconds the prompt waits120000
participantIdWho the signature is attributed toThe first declared participant, else submitter
onSignedCalled with what the authenticator returned, so a store can record the use and the counterNone

The signed document ​

Under embedded placement the signatures ride on the envelope the form delivers.

json
{
  "versionContext": { "form": { "id": "consent", "version": "1" }, "client": { "runtimeVersion": "…", "rendererVersion": "…", "schemaVersion": "…" } },
  "submission": { "locale": "en", "values": { "agree": true } },
  "signatures": [
    {
      "participantId": "submitter",
      "algorithm": "webauthn-es256",
      "signature": "MEUCIQ…",
      "signedAt": 1794998400000,
      "format": { "scope": "submission", "placement": "embedded", "digest": "sha-256", "canonicalization": "jcs" },
      "statement": "I confirm these answers.",
      "webauthn": {
        "credentialId": "AbC…", "authenticatorData": "SZYN…", "clientDataJSON": "eyJ0…", "signature": "MEUCIQ…",
        "userHandle": null, "algorithm": -7, "rpId": "forms.example.org", "origin": "https://forms.example.org", "signedAt": "2026-11-14T12:00:00.000Z"
      }
    }
  ]
}

Under wrapper placement the envelope is untouched and the page delivers detail.signed from the datum-submit event instead: { "format": { … }, "payload": <the envelope>, "signatures": [ … ] }. Send detail.signed ?? detail.submission. algorithm is webauthn-es256 or webauthn-rs256; the inner algorithm is the COSE number, -7 or -257. publicKey appears inside webauthn when the page knew the credential's key.

What is hashed depends on format.scope: the envelope without its signatures, its submission block, or its values, each written as RFC 8785 canonical JSON. With a statement, the text is { "document": <that part>, "statement": <the words> }. The SHA-256 of that text is the challenge the authenticator signed.

Registration ​

A passkey is registered once, and the server keeps its public key. registerCredential creates it in the browser and returns the record to keep.

js
import { registerCredential } from "./datum-form.js";

const record = await registerCredential({
  rpId: "forms.example.org",
  rpName: "Example forms",
  user: { id: "dXNlci0xMjM", name: "ada@example.org", displayName: "Ada" },   // id: a handle of 1 to 64 bytes, base64url, never an email
  name: "Ada's laptop",
  challenge: serverChallenge,       // base64url, at least 16 bytes; left out, a random one
  residentKey: "required"           // so a discoverable provider can find it
});
// Keep { id, publicKey, algorithm, signCount, transports, … } for this user.
await fetch("/passkeys", { method: "POST", body: JSON.stringify(record) });
OptionMeaningDefault
rpId, rpName, user, nameThe relying party, the person (id, name, displayName) and what the person calls this tokenRequired
challengeThe server's challenge, so it can check the registration32 random bytes
userVerificationrequired, preferred or discouragedpreferred
authenticatorAttachmentplatform or cross-platformEither
residentKeyrequired, preferred or discouraged. Use required for signing with discoverablepreferred
excludeCredentialsCredentials already registered, { id, transports? }, so one authenticator is not registered twiceNone
timeoutMilliseconds120000

It resolves with the record: id (base64url), name, publicKey (SPKI, base64), algorithm (-7 ES256 or -257 RS256), transports, attachment, signCount, flags (userVerified, backupEligible, backedUp), createdAt, and for the server's checks userHandle and response (clientDataJSON, authenticatorData, attestationObject, transports). A server that handed out the challenge checks the registration with verifyRegistration(result, { expectedChallenge, expectedOrigins, rpId, requireUserVerification }), which returns valid, per-check checks (type, challenge, origin, rpId, userPresent, userVerified, attestedCredential, credentialId) and a reason. The attestation itself is not judged. A page that is its own relying party stores the record without response and userHandle.

Then sign. The credentials option reads the stored list:

js
const credentials = () => [{ id: record.id, transports: record.transports, algorithm: record.algorithm, publicKey: record.publicKey }];
consent.signingProviders = [createWebAuthnSigningProvider({ rpId: "forms.example.org", credentials })];

Errors ​

A ceremony that fails throws a WebAuthnError with a code, and describeWebAuthnError(error) words it for the person.

CodeMeaning
cancelledThe prompt was dismissed, timed out, or could not open. WebAuthn does not say whether the person had no passkey or closed the prompt, so offer to create one
unsupportedThe browser or device has no WebAuthn, or not the feature asked for
securityThe rpId does not match the page's origin, or the page is not on HTTPS. The most common first failure
in_useThe authenticator already holds a credential for this user (registration)
abortedThe ceremony was aborted
no_credentialsNo credential is registered to sign with, and discoverable is off
protocolThe answer could not be read as WebAuthn's
invalidAn assertion did not verify

What the server checks ​

The server rebuilds the signed bytes from the document, hashes them and checks, one by one, the type, the challenge, the origin, the relying party id, that the person was present, that the person was verified when it requires that, and the signature against the registered key. A host also refuses a replayed assertion, a counter that went backwards and a signature that arrived outside its time window. verifyWebAuthnSubmission runs the checks in your own code, in a browser or wherever WebCrypto exists, and returns one verdict per WebAuthn signature on the document.

js
const verdicts = await verifyWebAuthnSubmission(document, {
  expectedOrigins: ["https://forms.example.org"],
  rpId: "forms.example.org",
  publicKeyFor: (credentialId) => keys.get(credentialId),   // { publicKey, algorithm? } the user registered
  requireUserVerification: true
});
if (!verdicts.length || !verdicts.every((verdict) => verdict.valid)) reject();
Verdict fieldMeaning
validEvery check passed
checkstype, challenge, origin, rpId, userPresent, userVerified, signature: each true or false, so a failure says why
reasonThe first check that failed, in words
flags, signCountThe authenticator's flags and counter. A counter that went backwards is yours to refuse
participantId, credentialId, algorithmWho signed, with which credential
format, statementThe scope and placement the signature was made under, and the words it covers

A signature whose format is missing or unreadable is invalid. Without publicKeyFor, the key archived in the signature is used, which proves only that the signer holds that key, not that it is the person's registered one.

Which host does what ​

The Spring Boot host has the passkey routes (/api/webauthn, enabled with datum.webauthn.enabled, the relying party and the origins), verifies a signed submission when it arrives and records the result on the submission. The FastAPI host serves no passkey routes and does not verify submission signatures. Both host PDF seals, PDF verification and a timestamp server. Elsewhere, a host that runs WASM can do the same with verifyWebAuthnSubmission and its own storage.

For the settings of each host, see Server hosts.

MIT licence. Your forms, your data, your keys.