Digital signatures
A digital signature seals a PDF as it was at the moment of signing. The engine reads every signature in a document, tells you what changed after it, and signs a field for you. It never sees your private key: it hands you the fingerprint of the file (a digest), your key signs it, and the engine writes the result into the PDF.
import { sign, webCryptoSigner } from '@embedpdf/core-signature';
const { signatures } = await doc.signatures.list();
const field = signatures.find((signature) => !signature.signed)!.field;
await sign(doc, {
field,
key: webCryptoSigner({ privateKey, certificateChain }),
signer: { name: 'Ada Lovelace', reason: 'Approved' },
});Signing needs doc.sign, and doc.forms.read to find the field with list(); see
Permissions.
The cryptography (building a signature from a key, checking one against its certificate) lives in its own package, which works with both engines:
npm install @embedpdf/core-signatureIt runs in every modern browser, and in Node from 22.12 on (on Node 20, from 20.19): see In Node.
Sign a field#
sign() signs a field in one call. It gets the digest from the engine, has your key sign it,
checks the result and writes it into the document. When anything fails, it cancels, and the
document is as it was.
import { sign, webCryptoSigner } from '@embedpdf/core-signature';
const result = await sign(doc, {
field,
key: webCryptoSigner({ privateKey, certificateChain }),
signer: { reason: 'Approved', location: 'Amsterdam' },
});
result.signature; // the new signature, as list() returns itkey is what signs the digest, one of:
| Key | Use it when |
|---|---|
webCryptoSigner({ privateKey, certificateChain }) | You hold a WebCrypto key and its certificates (DER, the signer’s first). |
remoteSigner({ sign }) | A signing service or HSM turns a digest into a finished signature (CMS). |
createTestSigner() | Tests and demos: a throwaway key with a self-signed certificate. |
A signing service that holds the key for you fits the first two; see Sign with a signing service.
After signing, the document is the signed file: list() shows the new signature, and
doc.download() returns the signed PDF. When the signature your key returns doesn’t match what
the engine prepared, sign() fails with SignatureRefused and the message says why.
Options#
sign() and prepare() take these options. sign() also takes the key, and
timestampAuthority and timestampTrust to timestamp the signature:
| Option | What it is | Default |
|---|---|---|
field | The signature field to sign. It must not be signed yet. | |
kind | 'signature', or 'timestamp' for a document timestamp. | 'signature' |
signer | { name, reason, location, contactInfo, signedAt }, written into the signature. | none; signedAt now |
appearance | The mark the field’s box shows: a PNG, a JPEG or a one-page PDF. | none |
certify | { permission: 1 | 2 | 3 }: certify the document. | not certified |
lock | Fields this signature locks. | none |
digest | 'sha256', 'sha384' or 'sha512'. | 'sha256', or the key’s hash with sign() |
subFilter | 'ETSI.CAdES.detached' or 'adbe.pkcs7.detached'. | 'ETSI.CAdES.detached' |
contentsSizeBytes | Bytes reserved for the signature, from 256 to 4 MiB. | 8192; 16384 with a timestampAuthority |
appearance is the mark the field shows once it is signed. Pass the picture’s bytes, a
Uint8Array or a Blob, in the formats a stamp takes: a
PNG, a JPEG or a one-page PDF.
await sign(doc, { field, key, appearance: png });The mark is drawn at its own size and fitted whole into the field’s box, upright when the field
is turned. { pdf: bytes } still works, for a one-page PDF only: an image under it is refused.
The field needs a widget to carry an appearance; without one, the call fails with
SignatureRefused. Bytes of another format fail with InvalidArg, and so does a PDF with more
than one page; take the page you want out first with doc.pages.extract().
Timestamp a signature#
A signature says when it was made, but that time comes from the signer’s own clock, and anyone can set a clock. A timestamp is a second opinion: a timestamp authority, a service whose only job is this, signs a statement that the signature existed by a certain time. With one, a reader can show when a document was signed without taking the signer’s word for it, and the signature can still be judged after the signer’s certificate has expired.
Pass timestampAuthority to sign():
import {
httpTimestampAuthority,
sign,
} from '@embedpdf/core-signature';
const timestampAuthority = httpTimestampAuthority({
url: '/api/timestamp',
});
await sign(doc, { field, key, timestampAuthority });The authority receives a fingerprint of the signature, never the document. Its answer, a timestamp token, is stored inside the signature, so the file gains no extra revision.
A timestamp you ask for is part of the signature you ask for. When the authority can’t be
reached, or its token doesn’t check out, sign() fails and nothing is signed. It never signs
without the timestamp.
Reach the authority from a browser#
Most timestamp authorities can’t be called from a web page: they send no CORS headers. Point
url at a route of your own that passes the request on. The package ships one, for any server
that speaks the Fetch API. In Next.js, for example:
// app/api/timestamp/route.ts
import { timestampRoute } from '@embedpdf/core-signature/server';
export const POST = timestampRoute({
url: 'https://tsa.example.com/',
});It takes headers too, for an authority that wants an API key: the key then stays on your
server. It passes the authority’s reply back with its status, and answers 504 when the
authority doesn’t answer. Who may call your route is yours to decide, as for any route.
On a server, url is the authority’s own address. The company that issued your signing
certificate usually runs a timestamp authority too.
Authority options#
httpTimestampAuthority() takes:
| Option | What it is | Default |
|---|---|---|
url | The authority’s address, or your own route in front of it. | |
hash | The hash it stamps with: 'sha256', 'sha384' or 'sha512'. | 'sha256' |
policy | The policy to ask for, when the authority offers several (an OID). | none |
headers | Sent with each request, such as an API key. | none |
fetch | The fetch to use, for what headers can’t do. | the global |
timeoutMs | How long one attempt may take, in milliseconds. | 10000 |
retries | Further attempts when no answer came. | 1 |
It tries again only when no answer came: a network failure, a timeout, or a busy server (a 5xx or 429 status). A refusal, or an answer that isn’t what was asked for, fails at once. Your key signs once either way.
Any service that turns a digest into an RFC 3161 token works as an authority, not only this one:
a remoteSigner({ sign }) whose sign returns the token for subFilter: 'ETSI.RFC3161'.
Only accept an authority you trust#
A timestamp token is sound when it is consistent with itself, and anyone can make one that is.
Once sealed in, it stays in the signature for good. To seal only a timestamp whose authority
you trust, pass the same trust you check signatures with:
await sign(doc, {
field,
key,
timestampAuthority,
timestampTrust: trust,
});A token from an authority trust doesn’t cover fails the signing, with SignatureRefused, and
nothing is signed. That catches a wrong address before any reader sees the result.
timestampTrust judges a document timestamp the same way,
where the key is the authority: sign(doc, { kind: 'timestamp', key, timestampTrust: trust }).
When it fails#
Every error httpTimestampAuthority() raises carries the authority’s address in
details.authority:
import { EngineError, EngineErrorCode } from '@embedpdf/engine';
try {
await sign(doc, { field, key, timestampAuthority });
} catch (error) {
if (error instanceof EngineError && error.details?.authority) {
notify(
error.code === EngineErrorCode.Network
? 'The timestamp service did not answer. Try again.'
: 'The timestamp service refused the request.',
);
}
}Network: the authority didn’t answer, after its further attempts. From a browser, a missing route of your own is the usual cause, and the message says so.SignatureRefused: the authority said no, or answered with something other than what was asked for: no token, another digest or hash, a token that doesn’t check out, or an authoritytimestampTrustdoesn’t cover. Trying again won’t help.SignatureRefused, withdetails.reason: 'too-large': the signature doesn’t fit the space reserved for it. The message names thecontentsSizeBytesto pass.InvalidArg:timestampAuthoritydoesn’t belong here. A document timestamp is already a timestamp, and so is a signature from a signing service that timestamps it itself. Leave the option out.
To test with a timestamp, use createTestTimestampAuthority(): a throwaway authority that needs
no network. Trust its certificate as a timestamp anchor.
Keep a signature checkable for years#
A certificate can be withdrawn before its end date, for example when its key is stolen. So a reader who checks a signature asks the certificate’s issuer whether it was still good when it signed. That works today. Some years from now it doesn’t: the certificate expires, and its issuer stops answering questions about it.
So ask now, and keep the answers in the file. The signature can then be checked for as long as the file exists, with no network. Acrobat calls such a signature “LTV enabled”.
addValidationInfo() does that, once the signature is made:
import {
addValidationInfo,
httpRevocationSource,
sign,
} from '@embedpdf/core-signature';
const revocation = httpRevocationSource({
url: '/api/revocation',
});
await sign(doc, { field, key, timestampAuthority });
await addValidationInfo(doc, { trust, revocation });For every signature and timestamp in the document, it:
- works out which certificates a reader has to ask about: each one between the signer and the certificate you trust, and the same for each timestamp’s authority;
- takes the answers the file already holds;
- asks
revocationfor the rest, at the addresses the certificates name; - checks every answer: that it is about that certificate, that the certificate’s issuer signed it, and what it says;
- stores what is new, with the certificates a reader needs to follow the same path.
The signature needs a timestamp. An answer says a certificate was good at a certain time, and only a timestamp proves the signature existed by then.
What it stores goes into the file as a revision after the signature, so the signature’s own bytes don’t change and it still verifies. Every answer is signed by the issuer that gave it, so nobody can forge one, and the store itself needs no signature.
One exception: after a certification at level 1, nothing may follow, so
addValidationInfo() fails with ProtectedDocument. Certify at level 2 instead.
| Option | What it is | Default |
|---|---|---|
trust | The certificates you trust, as for checking. | |
revocation | Where the answers come from. | none |
known | Answers and certificates you already have. | none |
fields | The signature fields to cover. | every signature |
partial | Store what there is when something is missing. | false |
maxCrlBytes | The largest list of withdrawn certificates to store. | 1 MiB |
It returns what it added and what a reader now sees:
const result = await addValidationInfo(doc, {
trust,
revocation,
});
result.added; // { certificates: 5, ocspResponses: 1, crls: 1 }
result.verdicts[0].longTerm.enabled; // trueverdicts is what validateSignatures() says about the result, each
signature judged at its timestamp. Calling it again asks for nothing the file already holds and
adds nothing.
All or nothing#
A file that looks finished and isn’t would be found out years later, when nobody can repair it.
So when something is missing, addValidationInfo() fails and stores nothing. The signature is
already in the file, so you can call it again later.
Network: an address didn’t answer.details.sourceis the address.SignatureRefused: an answer is missing, or it is bad news.details.reasonsays which,details.certificatenames the certificate, anddetails.fieldthe signature.
reason | What happened |
|---|---|
'revoked' | A certificate was withdrawn by the time of the signature’s timestamp. |
'no-answer' | No answer that checks out: the certificate names no address, its issuer doesn’t know it, or its list is over maxCrlBytes. |
'no-timestamp' | The signature has no timestamp you trust. |
'untrusted' | The signer doesn’t lead to a certificate in trust. |
With partial: true it stores what it could get and doesn’t fail for what is missing.
verdicts then says what each signature lacks. Use it for a document
other people signed, where an issuer may be gone for good.
Reach the issuers from a browser#
A web page can’t call a certificate’s issuer, for the same reason it can’t call a timestamp
authority. httpRevocationSource() sends each question to a route of your own, which passes it
on. The addresses come from the certificates, so the route must be careful where it goes. Use
the one the package ships, on any server that speaks the Fetch API:
// app/api/revocation/route.ts
import { revocationRoute } from '@embedpdf/core-signature/server';
export const POST = revocationRoute();It only calls http and https addresses, never a private or local one, and limits how large
and how slow an answer may be. What comes back must be an OCSP response, a list of withdrawn
certificates or a certificate, so the route can’t be used to read a web page. Who may call your
route is yours to decide, as for any route.
The route learns which certificate is asked about, and nothing about the document. When you always sign with the same certificate, the answers are the same for every document, and the route keeps them for as long as their issuer says they may be kept.
| Option | What it is | Default |
|---|---|---|
maxBytes | The largest answer it passes on. | 2 MiB |
timeoutMs | How long an issuer may take. | 10000 |
cache | Where it keeps answers: an object with get and set, or false for none. | The process’s memory |
lookup | Resolves a name to its addresses, to refuse a name that leads to a private one. | The runtime’s resolver |
fetch | The fetch it calls issuers with. | The global one |
A list larger than maxBytes never reaches the page, so raise it together with
maxCrlBytes.
The route checks the address a name leads to, and then calls the name. A name that changes its answer in between is not caught. Where that matters, keep the server the route runs on from reaching your private network. On a runtime with no resolver, such as a worker at the edge, names are taken at their word; such a runtime can’t reach a private network to begin with.
httpRevocationSource() takes the same url, headers, fetch, timeoutMs and retries as
httpTimestampAuthority(), and tries again only when no answer came.
To write the route in another language: it receives a JSON POST with kind ('ocsp',
'crl' or 'issuer'), the url to ask, and for 'ocsp' the request in base64 as body. It
sends an OCSP request as a POST with content-type: application/ocsp-request and fetches the
other two with a GET. It answers 200 with the bytes it got, and with an error status when it
has none.
Answers your signing service gave you#
Some signing services return the answers with the signature.
Hand them over as known. When they are enough, you need no revocation at all:
await addValidationInfo(doc, {
trust,
known: {
certificates: service.chain,
ocspResponses: [service.ocspResponse],
},
});known takes certificates, ocspResponses and crls, each a list of DER bytes. They are
checked like any other answer.
Then timestamp the document#
The answers are now in the file, but nothing proves when they were put there. A document timestamp over the file does:
await sign(doc, { kind: 'timestamp', key: timestampAuthority });That is the strongest form a signed PDF has: the signature, the proof of when, the proof that its certificates were good, and a timestamp over all of it.
A timestamp is itself signed with a certificate that expires, usually after some years. Until
then the file proves itself; longTerm.expiresAt in the verdict is that
date. To carry the proof past it, run the same two calls again before it: they store the
answers for the last timestamp’s authority and add a new timestamp over everything. A file
that is never renewed loses nothing it holds. Only the proof of when gets weaker after that
date.
Try it without a certificate authority#
createTestCertificateAuthority() makes a throwaway one that needs no network. It issues a
signer, answers for it, and can withdraw it:
import {
addValidationInfo,
createTestCertificateAuthority,
createTestTimestampAuthority,
sign,
} from '@embedpdf/core-signature';
const authority = await createTestCertificateAuthority();
const key = await authority.issueSigner({
commonName: 'Ada Lovelace',
});
const timestampAuthority = await createTestTimestampAuthority();
const trust = {
anchors: async () => [authority.certificate],
timestampAnchors: async () => [timestampAuthority.certificate],
};
await sign(doc, { field, key, timestampAuthority });
await addValidationInfo(doc, {
trust,
revocation: authority.revocation,
});
authority.revoke(key);issueSigner({ unrevocable: 'validity-assured' }) issues a certificate that
can’t be withdrawn, as a signing service does for one that lives for minutes;
'no-rev-avail' uses the other extension. A signature made with it reads 'good' and
long-term validation enabled with no answer in the file.
Sign in two steps#
When the key is somewhere else (a signing service, a hardware key, another device), sign in two
steps. prepare() reserves room for the signature and returns the digest to sign;
completeSignature() checks what your key returned and writes it in:
import { completeSignature } from '@embedpdf/core-signature';
const prepared = await doc.signatures.prepare({
field,
signer: { name: 'Ada Lovelace', reason: 'Approved' },
});
// prepared.digest is the fingerprint to sign,
// with prepared.algorithm ('sha256').
const cms = await mySigningService.sign(
prepared.digest,
prepared.algorithm,
);
const result = await completeSignature(doc, { prepared, cms });cms is a detached CMS signature (PKCS #7 or CAdES) over the digest: what signing services
return. To build one from a raw key yourself, use buildDetachedCms() from
@embedpdf/core-signature.
completeSignature() is the second half of sign(). It checks that cms signs the digest
that was prepared and fits the space reserved for it, then writes it into the document. A cms
that doesn’t pass fails with SignatureRefused, and nothing is written.
To timestamp the signature, reserve room for the token when you prepare, and pass the authority when you complete:
const prepared = await doc.signatures.prepare({
field,
contentsSizeBytes: 16384,
});
const cms = await mySigningService.sign(
prepared.digest,
prepared.algorithm,
);
await completeSignature(doc, {
prepared,
cms,
timestampAuthority,
});Between the two steps:
- The document is locked. Every other change fails with
SigningPendinguntil you complete or cancel; reading still works. - To give up, call
doc.signatures.cancel(prepared.signingId). It returnsstatus: 'cancelled', and completing that signing afterwards fails withNotFound.
When completeSignature() fails, nothing is written and the signing stays prepared, so your key
doesn’t have to sign again for a problem that passes:
Network: the timestamp authority didn’t answer. CallcompleteSignature()again with the samecms.SignatureRefused: the samecmswill be refused again. Cancel, then prepare and sign again. When the signature didn’t fit, the message names thecontentsSizeBytesto prepare with.
The engine’s own complete()#
completeSignature() ends in a call to the engine, which you can also make yourself:
const result = await doc.signatures.complete({
signingId: prepared.signingId,
cms,
expectedVersion: prepared.expectedVersion,
});- Pass
expectedVersionback as it is. It ties the signature to the version it was made for; a different one fails withSigningVersionMismatch, and you prepare again. - It checks less.
complete()checks thatcmsis one signature that fits the spaceprepare()reserved (contentsSizeBytes); if not, it fails withSignatureRefused. It doesn’t check the cryptography, and it adds no timestamp:completeSignature()andsign()do that before they call it. To check acmsyourself first, useverifyForCompletion(). - Calling it again with the same
cmsreturns the same result, withstatus: 'already-completed'; a differentcmsfails withSignatureRefused.
A signature can’t be undone, and completing one ends undo for every change made before it; see Changes & undo.
A prepared signature waits until you complete or cancel it: prepared.expiresAt is null.
Sign with a signing service#
A certificate that PDF apps such as Acrobat trust out of the box usually comes with a rule: the
key stays in the provider’s certified hardware. So the provider signs for you, and what leaves
your app is only a fingerprint. Services answer in one of two ways, and each fits a key.
The service returns a finished signature (a CMS). That is a remoteSigner:
import { remoteSigner, sign } from '@embedpdf/core-signature';
const key = remoteSigner({
sign: ({ digest, algorithm, subFilter }) =>
signingService.sign(digest, algorithm, subFilter),
});
await sign(doc, { field, key });When the service takes its time, for example because a person approves on their phone, sign in
two steps instead. When its signature already carries a timestamp, leave
timestampAuthority out: the engine checks the timestamp that is there.
The service signs a hash and returns the bare signature (the Cloud Signature Consortium
API’s signHash works this way). That is a key you describe yourself:
import {
ecdsaRawFromDer,
sign,
type RawSigner,
} from '@embedpdf/core-signature';
const key: RawSigner = {
kind: 'raw',
// DER certificates from the service, the signer's first.
certificateChain,
algorithm: 'ECDSA',
hash: 'sha256',
async sign(signedAttributes) {
const hash = new Uint8Array(
await crypto.subtle.digest('SHA-256', signedAttributes),
);
const der = await signingService.signHash(hash);
return ecdsaRawFromDer(der, 'P-256');
},
};
await sign(doc, { field, key, timestampAuthority });signreceives the bytes to sign, not the document’s digest. Hash them with the key’shashand send that hash to the service.- An ECDSA signature goes back as
r || s, the two numbers side by side, as WebCrypto makes it. Most services return DER instead: convert it withecdsaRawFromDer(), or the signature is encoded twice and no reader can check it. An RSA signature goes back as it is. algorithmis'RSA-PKCS1-v1_5','RSA-PSS'or'ECDSA', as the service signs.
The service’s timestamp authority is an httpTimestampAuthority() with its address.
Certify a document#
The first signature in a document can certify it: the signer says which changes may follow.
await sign(doc, { field, key, certify: { permission: 2 } });permission | What may change afterwards |
|---|---|
1 | Nothing. |
2 | Filling in the form and signing. |
3 | Filling in the form, signing and adding or changing comments. |
From the moment it completes, the engine refuses what the certification forbids, with
ProtectedDocument: every level refuses page changes, new or changed fields, attachments and
redaction; 1 and 2 also refuse annotations; 1 also refuses filling in, changing the
metadata and signing, a document timestamp included. Certifying after a
signature already exists fails with SignatureRefused.
Level 1 means no later revision at all. The PDF standard would let a document timestamp and
validation data follow such a certification. Acrobat doesn’t: once anything is added, it reports
the certification as invalid. The engine follows Acrobat, because that is where people open the
file: it refuses those writes, and a file that has them reads as changed after the
certification. For a document that must stay
checkable for years, certify at level 2, where Acrobat
accepts both. To keep the form as it is, lock its fields with the same
signature.
Lock fields#
A signature can lock fields, so nobody changes what the signer saw:
await sign(doc, {
field,
key,
lock: { action: 'include', fields: ['invoice.total', 'invoice.date'] },
});action is 'include' (lock the fields named), 'exclude' (lock all others) or 'all'. A name
covers the fields in its group: 'invoice' locks invoice.total too. Once signed, writing a
locked field fails with ProtectedDocument, and an import skips it.
When you name no lock, a signing locks two kinds of field (see
Signers and groups):
- The rest of its group, when the signature field is in one (
groupId): the group’s other fields as they are when you sign, but not its signature fields, which their signers still sign. - Every field anyone fills in (
assignment: { kind: 'anyone' }) that holds a value, whether the signature field is in a group or not: text that isn’t empty, a box or a radio button that is on, an option that is chosen, a button that holds an image. One still empty stays open for the next signer, and the first signing after it is filled in locks it.
With neither, it locks nothing. A document timestamp is no signer’s, so it adds no field anyone
fills in. Name a lock to choose yourself: the signing locks exactly that.
A signature field can carry a lock of its own, set by whoever made the PDF (its /Lock, which a
signature reads as lock). Signing it locks exactly that: the engine adds no field to it, and a
lock you name must be the same, or the signing fails with SignatureRefused.
Signature fields and their look#
A signature field is a form field of kind 'signature'. Create one like any field (see
Creating form fields):
const { field } = await doc.forms.create({
kind: 'signature',
name: 'approver',
widgets: [{ page: page.ref, rect: { x: 300, y: 682, width: 200, height: 60 } }],
});To draw a mark into a field without signing it, for example a handwritten signature in a viewer
that has no key, use setSignatureAppearance(). The field stays unsigned:
await doc.forms.setSignatureAppearance(field.ref, png);The mark is a PNG, a JPEG or a one-page PDF, as appearance is when you sign, and
{ pdf: bytes } still works here too. It takes the place of the field’s box: from then on its
widgets read hasMark: true, and their style can’t change (see
Move and style widgets).
The mark is a drawing and nothing more: the engine writes nothing else into the field, and reads
hasMark from the drawing itself. So signing the field later, with this mark or another, leaves
every signature made before it as it was.
To take the mark out again, pass null:
await doc.forms.setSignatureAppearance(field.ref, null);The field is empty again: its widgets read hasMark: false and show the field’s box in its
style, which can change again. Undo brings the mark back. A field that has no mark is left as
it is.
A mark is stored once in the file, however many places show it: the same picture in ten signature fields, as a stamp and as a push button’s image is one picture, as it is for stamps. A mark that is signed is stored the same way.
A mark keeps the signatures made before it valid: after an approval signature, and after a
certification that allows form filling, Acrobat reports no change it objects to, and
analyze() reads the mark as 'permitted'.
Once a field is signed, its look is part of what the signature seals, so
setSignatureAppearance() fails with ProtectedDocument, for a mark and for null. To sign
with a mark, pass appearance to sign() or prepare().
Read the signatures#
list() returns every signature field, signed or not, and what the signatures allow:
const { signatures, protection } = await doc.signatures.list();
for (const signature of signatures) {
console.log(signature.fieldName, signature.signed, signature.signer.name);
}| Field | What it is |
|---|---|
field | The signature field’s ref. Pass it to sign() and prepare(). |
fieldName | The field’s full name. |
signed | Whether the field holds a signature. |
signer | What the signer wrote: name, reason, location, contactInfo and signedAt. |
kind | 'signature', or 'timestamp' for a document timestamp. |
docMdp | The certification level the signature declares (1, 2 or 3), or null. |
widget | The field’s widget, with its page and ref, or null when the field has none. Where it shows is its row in doc.forms.list(). |
The signer fields are claims, the same ones you pass when you sign: anyone can write any name.
Who really signed is in the signature’s certificate, which
validateSignatures() checks. signedAt is the signer’s own clock.
protection says what the signatures allow from now on; see
Protection.
The signatures describe the file as it was opened, or as it was last signed. Changes you haven’t saved aren’t part of any signature until you sign.
Check the signatures#
validateSignatures() answers, for each signature: are the signed bytes intact, does the
signature match its certificate, do you trust that certificate, and what changed since.
import { validateSignatures } from '@embedpdf/core-signature';
const results = await validateSignatures(doc, {
trust: { anchors: async () => [rootCertificate] },
});
for (const result of results) {
console.log(result.signature.fieldName, result.summary);
}anchors returns the certificates you trust (DER bytes), for example your company’s root.
| Field | What it answers | Values |
|---|---|---|
integrity | Are the signed bytes unchanged? | 'valid', 'invalid', 'indeterminate' |
cryptography | Does the signature match its own certificate? | 'valid', 'invalid', 'unsupported' |
trust | Does the certificate lead to one you trust? | 'trusted', 'untrusted', 'unknown' |
modifications.verdict | What changed after signing, and is it allowed? | See What changed |
revocation | Was a certificate withdrawn? | 'good', 'revoked', 'unknown' |
summary | All of the above together. | 'valid', 'valid-untrusted', 'invalid', 'indeterminate' |
timestamp | When was it signed, by a clock you trust? | See The timestamp; null without one |
longTerm | Can it be checked from the file alone? | See Long-term validation |
summary is 'invalid' only on proof: bytes that changed, a signature that doesn’t match, a
change the signature forbids, or a certificate that was withdrawn. When something can’t be established, it’s 'indeterminate'.
Without trust, a good signature is 'valid-untrusted' at best.
'trusted' means the certificate leads to one of your anchors and was within its dates
at the time the signature is judged at. Whether it was
withdrawn is a separate answer, in revocation.
By default the check looks at the saved file. Pass until: 'working-copy' to include the changes
you haven’t saved yet: the answer is what the file will say once you save it. A viewer uses this
to warn before a change breaks a signature.
The timestamp#
A signature that carries a timestamp has a verdict of its own for it,
in timestamp:
import { validateSignatures } from '@embedpdf/core-signature';
const results = await validateSignatures(doc, {
trust: {
anchors: async () => [companyRoot],
timestampAnchors: async () => [authorityRoot],
},
});
for (const result of results) {
const stamp = result.timestamp;
if (stamp?.summary === 'valid') {
const authority = stamp.authorityName;
console.log(`Signed by ${stamp.stampedAt}, says ${authority}`);
} else {
const claimed = result.signature.signer.signedAt;
console.log(`Signed at ${claimed}, by the signer's clock`);
}
}| Field | What it is |
|---|---|
summary | 'valid', 'valid-untrusted', 'invalid' or 'indeterminate', as for a signature. |
stampedAt | The time the authority vouches for: the signature existed by then. null when the token can’t be read. |
authorityName | Who vouches for the time: the name in the authority’s certificate, or null when it has none. |
authorityCertificate | The authority’s certificate (DER), or null when it can’t be found. |
cryptography | Whether the token checks out and stamps this signature. |
trust, trustReason | Whether the authority’s certificate leads to one you trust and may issue timestamps, and why not. |
validationTime | When the authority’s certificate was judged. |
stampedAt is the time the token itself carries, where RFC 3161 calls it genTime.
timestampAnchors returns the certificates you trust to say what time it was, apart from
anchors, the ones you trust to say who signed. Keep an authority’s root out of anchors:
there it would vouch for every signer certificate under that root. A trust without
timestampAnchors uses anchors for both, which is right when one root of your own issues
both.
An authority’s certificate must be made for timestamping and nothing else, or trust is
'untrusted' and trustReason says why. A certificate that is itself one of your timestamp
anchors is trusted as it is.
A timestamp’s verdict never changes the signature’s summary. A valid signature with a broken
timestamp is still valid: you know who signed, and only the time is the signer’s word again.
The timestamp proves the signature existed by that time, not that it was made at that moment. It is the latest the document can have been signed.
The time a signature is judged at#
A certificate is good for a while: it expires, and its issuer can withdraw it. What counts for a signature is whether the certificate was good when it signed, and a timestamp you trust proves when that was. So each certificate is judged at the earliest trusted timestamp that covers what it signed, as Acrobat judges it:
- A signer’s certificate, at the signature’s own timestamp or at a document timestamp added after it, whichever is earlier.
- A timestamp authority’s certificate, at a document timestamp added after its token. The last timestamp in the file has nothing after it, so its authority is judged now.
- With no trusted timestamp to go by, now.
A signature whose signer’s certificate has expired since still reads 'valid', when a
timestamp you trust shows it was signed in time. Without one it is judged now, and reads
'valid-untrusted'.
result.validationTime says which it was: its kind is 'timestamp', with the timestamp’s
stampedAt, or 'now'.
genTime still works, until 4.0: it was the name of that time before 3.3. A verdict carries
the same time under both names, and a validationTime you pass may use either.
Revocation is judged at the same time: a certificate withdrawn after the timestamp was still good when it signed.
To judge every certificate as of now, whatever the timestamps prove, pass validationTime:
const results = await validateSignatures(doc, {
trust,
validationTime: { kind: 'now' },
});{ kind: 'earliest-timestamp' } is the default by name.
Revocation#
revocation says whether a certificate between the signer and your anchor was withdrawn, at the
time the signature is judged:
| Value | Meaning |
|---|---|
'good' | Every certificate has an answer that checks out, and none was withdrawn. |
'revoked' | An answer that checks out says one was withdrawn by then. summary is 'invalid', and revocationReason names the certificate. |
'unknown' | Some certificate has no answer, or the signer isn’t trusted, so there is no issuer to check an answer against. summary stays as it was. |
The answers come from the file: what
addValidationInfo() stored, what the signature
itself carries, and what Acrobat stored in files it signed. Nothing is asked over the network.
Each answer is checked by its own signature, wherever in the file it sits.
Only a certificate that has an issuer above it needs an answer. One you trust as it is, such as
your own root, has nobody to withdraw it, so a signer you trust directly reads 'good'.
A certificate that can’t be withdrawn needs no answer either. Some signing services issue a
certificate for one signature, valid for minutes, and run no revocation service for it. Such a
certificate says so itself, in one of two extensions: “validity assured, short term” (ETSI EN
319 412-1) or noRevAvail (RFC 9608). It is then left out, as the EU’s validator leaves it
out: the signature reads 'good' when the certificates above it do, and
long-term validation needs nothing about it. The extension counts on
the certificate of a signer or a timestamp authority, never on one that issues others, and
noRevAvail doesn’t count on a certificate that also names where to ask about it.
An answer speaks for a time. One stored when the document was signed says the certificate was
good then, and says nothing about today. A signature is
judged at its timestamp, so a signature from last year
reads 'good' from the file:
const results = await validateSignatures(doc, { trust });
results[0].revocation; // 'good', from the fileJudged as of now, the same signature reads 'unknown': no stored answer speaks for today.
To ask the issuers what the file doesn’t hold, pass a revocation source, the same one
addValidationInfo() takes. That is the only way a
certificate judged now gets an answer. It stores nothing:
const results = await validateSignatures(doc, {
trust,
revocation,
});Asking tells each issuer that someone is checking that signer’s signature, and from where. A
file that holds its answers tells nobody. A timestamp’s verdict has a revocation of its own,
for its authority.
Long-term validation#
longTerm says whether the file holds everything a reader needs to check the signature without
a network. It always speaks for the signature’s timestamp, whatever validationTime is:
const { longTerm } = results[0];
longTerm.enabled; // true
longTerm.provenAt; // '2026-11-14T21:28:37.237Z'
longTerm.expiresAt; // '2036-01-01T00:00:00.000Z'
longTerm.documentTimestampedAt; // '2026-11-14T21:29:30.387Z'| Field | What it is |
|---|---|
enabled | A timestamp you trust covers the signature, its signer was trusted then, and the file holds a good answer for every certificate: the signer’s and the timestamp authority’s. What Acrobat calls “LTV enabled”. |
provenAt | The time the signature is proven to have existed by, which it is judged at: the earliest timestamp you trust that covers the signature, its own or a document timestamp added after it. null when there is none. |
expiresAt | When the proof the file carries by itself runs out: the day the certificate of the last timestamp covering the signature expires. The signature doesn’t become invalid then; the proof of when it was made gets weaker. null when not enabled. |
documentTimestampedAt | The time of the last document timestamp you trust that was added after the signature, or null when none covers it. |
missing | What stands in the way, one entry per certificate: its name in certificate and a reason, as in All or nothing. Empty when enabled. |
enabled is the question Acrobat asks. A validator that follows the European standard asks one
more: when were the stored answers put in the file? A
document timestamp over them is the proof. So a file is finished
when enabled is true and documentTimestampedAt is not null.
A document timestamp added later also moves expiresAt to its own certificate’s end date. That is
all renewing is. A document timestamp has a longTerm of its
own, for its authority’s certificates.
What changed since a signature#
analyze() compares the document with the version a signature sealed, and says whether what
changed is allowed:
const analysis = await doc.signatures.analyze({
since: { signatureIndex: 0 },
until: 'working-copy',
});
console.log(analysis.verdict);| Verdict | Meaning |
|---|---|
'unchanged' | Nothing changed since the signature. |
'permitted' | Something changed, and the signature allows it, such as a field filled in or another signature. |
'forbidden' | A change the signature doesn’t allow, such as a rotated page. |
'indeterminate' | The engine can’t tell: part of the file can’t be read, or its structure is broken. |
With 'forbidden', the signature itself still checks out, but PDF apps such as Acrobat report
that the document was changed after signing. For what since and until take, see
Analyzing in detail.
A fill writes only the field’s value and its drawing, so filling in a field that a signature
didn’t lock reads 'permitted' for that signature, whoever fills it in.
A signature field that nobody signed may get a new look, such as a
mark: when only its appearance changes, the verdict is
'permitted'. A signed field’s look is part of what its signature sealed, so a new look there
is 'forbidden', even though Acrobat doesn’t report it.
Events#
| Event | Fired by |
|---|---|
signatures.prepared | prepare(), with the signingId and the field. |
signatures.completed | complete(), with what it returned. |
signatures.cancelled | cancel(). |
signatures.validationInfoAdded | addValidationInfo(), with how many of each kind it stored. Read verdicts again. |
document.versioned | complete(): the document is now the signed file. Read revisions, digests and verdicts again. |
sign() fires the same events. See Events.
Permissions#
Reading signatures (list(), analyze(), getContents(), getDigest(),
getValidationInfo()) needs doc.forms.read; downloadRevision() needs doc.download. Signing
(prepare(), complete(), cancel()) needs doc.sign, or fields:sign for the field’s
group, and certifying also doc.sign.certify. addValidationInfo() and a document timestamp
without a field of its own need doc.sign. See Permissions.
A call the document’s own signatures forbid fails with ProtectedDocument, whatever the user’s
permissions. A field that can’t be signed (already signed, read-only, or locked by an earlier
signature) fails with SignatureRefused; the message says why.
Good to know#
Protection: what signatures allow#
protection from list() answers two different questions:
| Field | Question | Values |
|---|---|---|
enforced | What does the engine refuse? | A level, or null when no signer declared a limit. |
judged | What keeps the signatures valid? | A level, or null when nothing is signed. |
certification | The certifying signature and its permission. | null when the document isn’t certified. |
fieldLocks | The fields signatures locked. | A list, empty when no field is locked. |
A level is 'lta' (nothing: a level 1 certification), 'fill' (filling in and signing) or
'annotate' (also comments). 'lta' is named after what the PDF standard would let follow such
a certification, document timestamps and validation data; Acrobat lets nothing follow, and so
does the engine.
enforced is what the engine refuses. Only a certification or a field lock sets it; the calls it
refuses fail with ProtectedDocument. A plain approval signature sets nothing, so every change
stays possible.
judged is what keeps signatures valid in Acrobat. For an approval signature it’s 'annotate':
filling in, signing and commenting keep it valid, while a rotated page, for example, makes
Acrobat report that the document was changed.
Use allows() to hide what the session may not do; a document’s signatures can still refuse a
change, with ProtectedDocument:
if (!doc.security.allows('doc.pages.assemble')) hidePageTools();One save is always refused on a signed document: a rewrite (download({ mode: 'rewrite' }))
would remove every signature, so it fails with ProtectedDocument. The default incremental save
keeps them; see Saving.
Analyzing in detail#
since takes the signature’s position in list() ({ signatureIndex }), or a revision (see
Revisions and byte ranges). until is 'persisted' (the saved file,
the default), 'working-copy' (with your unsaved changes) or { revisionIndex }.
analysis.current.primary is the change that decided the verdict, with the rule that allowed or
forbade it. Show it next to a 'forbidden' verdict.
Revisions and byte ranges#
A PDF that keeps its signatures grows by appending: each save adds a revision at the end of
the file, and the older bytes stay as they were. A signature covers every byte of the revision it
was made in, except the hole it sits in (the signature dictionary’s /ByteRange and /Contents).
list() also returns revisions, oldest first, each with its index, its end (the byte length
of the file at that revision) and the signatureIndex that seals it. Each signature has its
revisionIndex and a coverage:
'whole-revision': it covers exactly one revision. That’s the normal case.'partial': its byte ranges are valid but seal no revision. It can’t be checked against later changes, soanalyze()from it fails withInvalidArg.'malformed': its byte ranges or its signature bytes can’t be used.
chainValid: false means the file’s cross-reference chain is broken or was rebuilt, so no fact
about its bytes can be trusted.
The raw bytes#
For your own verifier: getContents(field) returns the signature (DER, without padding),
getDigest(field, algorithm) hashes the bytes the signature covers ('sha1' works too, for old
signatures), and downloadRevision(index) returns the file exactly as it was at a revision.
How changes are judged#
- A signature is judged on the document as it is now against the revision it sealed. A change that was undone later doesn’t count, and an object written again with the same value isn’t a change.
- A certification also checks every revision in between, so a forbidden change stays forbidden even when a later revision hides it.
- Missing evidence is never a pass: a value the engine can’t read makes the verdict
'indeterminate'. - A push button’s image counts as filling
in, as Acrobat counts it: putting one in or taking it out (
setButtonImage()) is permitted wherever filling in is, after an approval signature and after a certification for form filling. A field a signature locked stays forbidden, and so does a change to the button’s caption, colors orlayout, which is design. - A mark drawn into an unsigned signature field (
setSignatureAppearance()) is permitted at the same levels: see Signature fields and their look. - The rules follow what Acrobat reports.
exploratoryLevelasks what a level would allow; the answer (mode: 'exploratory') isn’t a verdict.detail: 'full'lists every changed object (large; for tools).
Unsaved changes when you sign#
Your unsaved changes become part of the signed version, so the signature seals them too. You don’t need to save before you sign.
Document timestamps#
A signature’s timestamp vouches for one signature. A document timestamp vouches for the whole file as it stands: every signature in it, and everything added since. It adds a revision, as a signature does.
kind: 'timestamp' makes one. With sign(), the key is your timestamp authority, the same
object you pass as timestampAuthority:
const result = await sign(doc, {
kind: 'timestamp',
key: timestampAuthority,
});
result.signature.kind; // 'timestamp'A document timestamp lives in a signature field. Without a field the engine makes one for
it, with no size, so it shows nowhere on the page. The field is added in the same revision as
the timestamp, under a name no other field has, such as Timestamp1;
result.signature.fieldName says which. Pass field to use one of your own.
After a certification at level 1 a document timestamp is refused, with
ProtectedDocument, like every other change.
A key you hold can’t make one, so sign() fails with InvalidArg. In two steps, the cms is
the authority’s token over prepared.digest.
validateSignatures() reads a document timestamp like a signature: integrity says whether the
file it stamped is intact, and timestamp holds the same verdict a
signature’s timestamp gets, with its stampedAt and authority.
The validation data in the file#
addValidationInfo() decides which answers are worth
keeping. Underneath, the engine reads and stores them as they are:
const stored = await doc.signatures.getValidationInfo();
stored.certificates; // DER bytes, one per certificate
stored.ocspResponses;
stored.crls;
await doc.signatures.addValidationInfo({
ocspResponses: [answer],
});getValidationInfo() reads the document as it is now, so an entry you added and haven’t saved
yet is among them.
doc.signatures.addValidationInfo() checks only that each entry is one DER object of at most
16 MiB, and stores nothing the file already holds. It returns added, the number of new entries
of each kind. An entry that fails the check, such as a certificate still in PEM text, fails the
call with InvalidArg; details.field names it, as in certificates[1], and nothing is stored.
It is a change like any other: it is in the file you next save, as a revision after the signatures, and a signature or timestamp made after it seals it in. It can’t be undone, and undoing another change leaves it in place.
Timestamp something else#
An authority stamps any digest, not only a PDF’s: the daily hash of an audit log, say. Ask it
directly, and check the token later with verifyTimestampToken():
import { verifyTimestampToken } from '@embedpdf/core-signature';
const token = await timestampAuthority.sign({
digest: logHash,
algorithm: 'sha256',
subFilter: 'ETSI.RFC3161',
});
const stamp = await verifyTimestampToken({
token,
digest: logHash,
algorithm: 'sha256',
trust,
});
stamp.summary; // 'valid'It returns a timestamp’s verdict. A token that stamps another digest, or the
same bytes under another hash, is 'invalid'.
In Node#
@embedpdf/core-signature reads and writes certificates with pkijs and asn1js. Both are ES
modules only, and both ask for Node 22.12 or newer, or 20.19 or newer on Node 20. npm warns
when it installs them on an older one.
CommonJS needs nothing more. require() does not load an ES module on every Node, or in Jest,
so the CommonJS files of this package hold the two libraries and what they use.
require('@embedpdf/core-signature') loads no ES module, and neither does a package that loads
it, such as the signature plugin or the React package.
dist/THIRD-PARTY-NOTICES.txt in the package lists what those files hold, with each version and
license, and inlinedDependencies in its package.json has the versions.
Turning protection off#
For tools that must produce or test invalid files, create the engine with
localEngine({ signedDocumentPolicy: 'permit' }): the engine then refuses nothing a signature
forbids. judged and every verdict stay the same.
It is also how to add a document timestamp or validation data after a level 1 certification,
as the PDF standard allows. Acrobat will report that certification as invalid.
Your feedback goes directly to the documentation team.