Skip to content

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

TypeScript

Keep seals checkable for years: PAdES B-LT and B-LTA

Claude7cffe8d9411c
diff --git a/.env.example b/.env.example
index 368c8a3..26a860d 100644
--- a/.env.example
+++ b/.env.example
@@ -86,6 +86,8 @@ EMAIL_DRIVER=capture
# SEAL_P12_PASSWORD=
# An RFC 3161 timestamp server, to add a trusted time to each seal, for
-# example http://timestamp.digicert.com. If the server cannot be reached,
-# the PDF is sealed without a timestamp.
+# example http://timestamp.digicert.com. With it, seals also get long-term
+# validation (PAdES B-LTA): the certificates, revocation answers and an
+# archive timestamp go into the PDF. If the server cannot be reached, the
+# PDF is sealed without a timestamp.
# SEAL_TIMESTAMP_URL=
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index f928963..39d7973 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -25,6 +25,9 @@ jobs:
- run: npm ci
- run: npm run typecheck
- run: npm run lint
+ # Poppler's pdfsig, so the seal tests check signatures the way a PDF
+ # reader does instead of skipping that part.
+ - run: sudo apt-get update && sudo apt-get install -y --no-install-recommends poppler-utils
- run: npm test
# With nothing configured, as on a first deployment whose database
# has not been connected yet: the build must not need any of it.
diff --git a/README.md b/README.md
index 2c05788..132ec55 100644
--- a/README.md
+++ b/README.md
@@ -118,21 +118,21 @@ DocuSign does more, and charges for it per user. SignuDoc does the everyday sign
### The signing loop
-| | SignuDoc | DocuSign eSignature |
-| -------------------------------------------- | ------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------- |
-| **Signing without an account** | ✅ | ✅ |
-| **Signing order** | ✅ in order, up to 10 signers | ✅ in order, at the same time, or mixed |
-| **People who only get a copy** | ✅ | ✅ and more roles: approvers, editors, in-person signers |
-| **Field types** | ✅ signature, initials, date, text, number, checkbox, dropdown, radio, each required or optional | ✅ more types; dropdown, radio and signer attachments need Business Pro |
-| **Templates** | ✅ | ✅ from Personal, shared from Standard |
-| **Deadlines and automatic reminders** | ✅ | ✅ |
-| **Access code and emailed one-time code** | ✅ | ✅ plus SMS, phone, knowledge-based questions and ID checks, as paid add-ons |
-| **Consent to electronic records** | ✅ versioned, recorded in the audit trail | ✅ |
-| **Sealed PDF and certificate of completion** | ✅ PAdES seal, self-signed by default or your own trusted certificate | ✅ seal trusted by PDF readers |
-| **Audit trail** | ✅ hash-chained | ✅ |
-| **Checking a signed copy** | ✅ the seal in a PDF reader, and a public Verify page on your own site | ✅ the seal in a PDF reader |
-| **Retention rules and signer data requests** | ✅ built in | ✅ |
-| **Phones** | ✅ in the browser | ✅ native iPhone and Android apps |
+| | SignuDoc | DocuSign eSignature |
+| -------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------- |
+| **Signing without an account** | ✅ | ✅ |
+| **Signing order** | ✅ in order, up to 10 signers | ✅ in order, at the same time, or mixed |
+| **People who only get a copy** | ✅ | ✅ and more roles: approvers, editors, in-person signers |
+| **Field types** | ✅ signature, initials, date, text, number, checkbox, dropdown, radio, each required or optional | ✅ more types; dropdown, radio and signer attachments need Business Pro |
+| **Templates** | ✅ | ✅ from Personal, shared from Standard |
+| **Deadlines and automatic reminders** | ✅ | ✅ |
+| **Access code and emailed one-time code** | ✅ | ✅ plus SMS, phone, knowledge-based questions and ID checks, as paid add-ons |
+| **Consent to electronic records** | ✅ versioned, recorded in the audit trail | ✅ |
+| **Sealed PDF and certificate of completion** | ✅ PAdES seal, self-signed by default or your own trusted certificate, long-term validation (B-LTA) with a timestamp server | ✅ seal trusted by PDF readers |
+| **Audit trail** | ✅ hash-chained | ✅ |
+| **Checking a signed copy** | ✅ the seal in a PDF reader, and a public Verify page on your own site | ✅ the seal in a PDF reader |
+| **Retention rules and signer data requests** | ✅ built in | ✅ |
+| **Phones** | ✅ in the browser | ✅ native iPhone and Android apps |
### Where DocuSign does more
diff --git a/docs/self-hosting.md b/docs/self-hosting.md
index f1f539b..bde2884 100644
--- a/docs/self-hosting.md
+++ b/docs/self-hosting.md
@@ -83,7 +83,7 @@ A deployment made with the button needs no environment variables. These are ther
| `HOSTED_MODE` | `1` runs SignuDoc as a public service under its own name. See [Hosted mode](#hosted-mode). |
| `RESEND_REGION` | Where Resend sends from when the app adds your domain, for example `eu-west-1`. See [Running in the EU](#running-in-the-eu). |
| `SEAL_P12_BASE64`, `SEAL_P12_PASSWORD` | Seal finished PDFs with a certificate from a certificate authority instead of the install's own. See [Signed PDFs and the seal](#signed-pdfs-and-the-seal). |
-| `SEAL_TIMESTAMP_URL` | An RFC 3161 timestamp server that adds a trusted time to each seal. |
+| `SEAL_TIMESTAMP_URL` | An RFC 3161 timestamp server that adds a trusted time to each seal, and long-term validation. See [Long-term validation](#long-term-validation). |
## Set the site up
@@ -117,6 +117,28 @@ Every finished PDF and audit certificate is sealed with a PAdES signature, so an
By default each install makes its own seal key and self-signed certificate the first time it seals, and keeps the key encrypted in the database with a key derived from `BETTER_AUTH_SECRET` (or the database password, when that is unset). Keep that secret stable: a new one makes a new seal key, and old PDFs still verify but under the old certificate. Readers show a self-signed seal as "validity unknown" until the certificate is trusted. For a seal readers trust on sight, buy a document-signing certificate and set `SEAL_P12_BASE64` and `SEAL_P12_PASSWORD`. `SEAL_TIMESTAMP_URL` adds a trusted time from a timestamp server.
+### Long-term validation
+
+A seal is easy to check while its certificates are valid and their certificate authority still answers. Years later, neither may be true. So when `SEAL_TIMESTAMP_URL` is set, every seal is made to PAdES B-LTA, the level meant for records kept for years:
+
+1. The seal gets a timestamp from the timestamp server (B-T).
+2. The certificates of the seal and of the timestamp server, and an answer from each certificate authority that none of them is revoked (an OCSP response, or the revocation list when there is no OCSP), are added to the PDF's document security store (B-LT).
+3. An archive timestamp is added over all of that (B-LTA), so a reader can show the evidence was there at that time, after the certificates have expired.
+
+Each step only adds to the file, so the seal from step 1 stays intact. With a certificate from a certificate authority but no timestamp server, step 2 still runs, which lets readers check the certificate later, but the seal stays at B-B: a PAdES level above that needs a trusted time. A self-signed seal without a timestamp server is left as it is, since there is no one to ask about it.
+
+The lookups go to the timestamp server and the certificate authorities, outside Vercel. All of a document's lookups together stop after 15 seconds, and if one fails the document keeps the seal it has and the function log says what was missing, so signing never waits on them for long. An archive timestamp keeps the evidence checkable until the timestamp server's own certificate expires, usually years later. Adding a new archive timestamp before then is not automatic yet.
+
+### An advanced electronic seal (eIDAS)
+
+Under eIDAS, a seal is the organization's counterpart of a signature. A seal that meets the four tests of Article 36 (linked only to your organization, identifying it, made with a key under its control, and showing any later change) is an **advanced electronic seal**. To get one:
+
+- Buy a seal certificate that names your organization from a certificate authority, such as an eIDAS seal certificate or an organization-validated document-signing certificate. Choose one on the [EU trusted lists](https://esignature.ec.europa.eu/efda/tl-browser) or Adobe's Approved Trust List, so readers show your organization's name as verified.
+- Get it as a PKCS#12 file with an RSA key (SignuDoc does not read EC keys from a file yet), and set it as `SEAL_P12_BASE64` (the file in base64) and `SEAL_P12_PASSWORD`. Keep the file somewhere safe outside Vercel too: the key in it is what makes the seal yours.
+- Set `SEAL_TIMESTAMP_URL`, so the seal gets long-term validation as above. A timestamp server run by a qualified trust service provider gives a qualified electronic time stamp, which a court presumes accurate (Article 41).
+
+What this gives you: each finished PDF and certificate carries your organization's advanced seal, showing it came from you unchanged. What it does not: the signers' own signatures stay simple electronic signatures, and the seal is not a qualified seal, which needs a qualified certificate held on a qualified device, usually a trust service provider's remote signing service rather than a file. This is not legal advice: whether a seal is enough for a document is for your own counsel.
+
## Running in the EU
By default the parts of an install run in the US. To keep signers' data in the EU:
diff --git a/src/lib/permitted-uses.ts b/src/lib/permitted-uses.ts
index 8b98160..9901e03 100644
--- a/src/lib/permitted-uses.ts
+++ b/src/lib/permitted-uses.ts
@@ -42,7 +42,7 @@ export const WHAT_IT_IS: UseSection = {
export const WHAT_IT_IS_NOT: UseSection = {
heading: "What Signudoc is not",
items: [
- "Not an advanced (AdES) or qualified (QES) electronic signature under eIDAS. The seal on finished PDFs is the install's own, not a qualified seal.",
+ "Not an advanced (AdES) or qualified (QES) electronic signature under eIDAS. The seal on finished PDFs is not a qualified seal: it is the install's own, or, with a seal certificate the organization buys, an advanced electronic seal for the organization, not for the signers.",
"Not a validated FDA 21 CFR Part 11 system as it comes. An administrator can turn on Part 11 mode (signers sign with their own confirmed accounts and password, and each signature shows its meaning), but your organization still has to validate the install, write and follow its own procedures, and certify its electronic signatures to the FDA.",
"Not a HIPAA-covered service. Do not send protected health information unless your organization has its own agreements and controls for every service the install uses.",
"Not a consumer-disclosure system beyond the electronic-records agreement each signer gives. If a law requires you to deliver specific consumer notices electronically, check that its own rules are met.",
diff --git a/src/lib/services/der.ts b/src/lib/services/der.ts
new file mode 100644
index 0000000..35affa1
--- /dev/null
+++ b/src/lib/services/der.ts
@@ -0,0 +1,280 @@
+// A small DER reader and writer, for the parts of certificates, timestamp
+// tokens, OCSP answers and revocation lists that sealing needs to look at.
+//
+// It works on byte offsets into the original buffer, so a certificate or a
+// token can be passed on byte for byte, which keeps its signature intact.
+// Only definite lengths and single-byte tags are read, which is all DER
+// (and every structure handled here) uses.
+
+export const TAG = {
+ bitString: 0x03,
+ boolean: 0x01,
+ enumerated: 0x0a,
+ generalizedTime: 0x18,
+ integer: 0x02,
+ null: 0x05,
+ octetString: 0x04,
+ oid: 0x06,
+ sequence: 0x30,
+ set: 0x31,
+ utcTime: 0x17,
+} as const;
+
+/** The identifier byte of a context-specific tag, [n]. */
+export function contextTag(number: number, constructed = true): number {
+ return 0x80 | (constructed ? 0x20 : 0) | number;
+}
+
+export type Tlv = {
+ /** Where the content starts. */
+ contentStart: number;
+ /** One past the last byte of the whole element. */
+ end: number;
+ /** Where the element, its tag byte, starts. */
+ start: number;
+ /** The identifier byte: class, constructed bit and tag number. */
+ tag: number;
+};
+
+export class DerError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = "DerError";
+ }
+}
+
+export function readTlv(
+ bytes: Uint8Array,
+ offset = 0,
+ limit = bytes.length,
+): Tlv {
+ if (offset + 2 > limit) {
+ throw new DerError("The data ends inside an element.");
+ }
+
+ const tag = bytes[offset]!;
+
+ if ((tag & 0x1f) === 0x1f) {
+ throw new DerError("Multi-byte tags are not supported.");
+ }
+
+ const first = bytes[offset + 1]!;
+ let length: number;
+ let headerLength: number;
+
+ if (first < 0x80) {
+ length = first;
+ headerLength = 2;
+ } else {
+ const count = first & 0x7f;
+
+ if (count === 0 || count > 4) {
+ throw new DerError("Indefinite or oversized lengths are not supported.");
+ }
+
+ if (offset + 2 + count > limit) {
+ throw new DerError("The data ends inside a length.");
+ }
+
+ length = 0;
+
+ for (let index = 0; index < count; index += 1) {
+ length = length * 256 + bytes[offset + 2 + index]!;
+ }
+
+ headerLength = 2 + count;
+ }
+
+ const contentStart = offset + headerLength;
+ const end = contentStart + length;
+
+ if (end > limit) {
+ throw new DerError("An element is longer than the data holding it.");
+ }
+
+ return { contentStart, end, start: offset, tag };
+}
+
+/** The elements directly inside a constructed element. */
+export function children(bytes: Uint8Array, parent: Tlv): Tlv[] {
+ const items: Tlv[] = [];
+ let offset = parent.contentStart;
+
+ while (offset < parent.end) {
+ const item = readTlv(bytes, offset, parent.end);
+
+ items.push(item);
+ offset = item.end;
+ }
+
+ return items;
+}
+
+/** The whole element, tag and length included. */
+export function elementBytes(bytes: Uint8Array, tlv: Tlv): Buffer {
+ return Buffer.from(bytes.subarray(tlv.start, tlv.end));
+}
+
+export function contentBytes(bytes: Uint8Array, tlv: Tlv): Buffer {
+ return Buffer.from(bytes.subarray(tlv.contentStart, tlv.end));
+}
+
+export function expectTag(
+ tlv: Tlv | undefined,
+ tag: number,
+ what: string,
+): Tlv {
+ if (!tlv || tlv.tag !== tag) {
+ throw new DerError(`Expected ${what}.`);
+ }
+
+ return tlv;
+}
+
+export function decodeOid(content: Uint8Array): string {
+ const parts: number[] = [];
+ let value = 0;
+
+ for (const byte of content) {
+ value = value * 128 + (byte & 0x7f);
+
+ if ((byte & 0x80) === 0) {
+ if (parts.length === 0) {
+ const first = value < 80 ? Math.floor(value / 40) : 2;
+
+ parts.push(first, value - first * 40);
+ } else {
+ parts.push(value);
+ }
+
+ value = 0;
+ }
+ }
+
+ return parts.join(".");
+}
+
+export function readOid(bytes: Uint8Array, tlv: Tlv): string {
+ return decodeOid(contentBytes(bytes, expectTag(tlv, TAG.oid, "an OID")));
+}
+
+/** A UTCTime or GeneralizedTime, as a date. */
+export function readTime(bytes: Uint8Array, tlv: Tlv): Date {
+ const text = contentBytes(bytes, tlv).toString("latin1");
+ const match =
+ tlv.tag === TAG.utcTime
+ ? /^(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})?Z$/.exec(text)
+ : tlv.tag === TAG.generalizedTime
+ ? /^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})?(?:\.\d+)?Z$/.exec(text)
+ : null;
+
+ if (!match) {
+ throw new DerError("Expected a time.");
+ }
+
+ let year = Number(match[1]);
+
+ if (tlv.tag === TAG.utcTime) {
+ year += year < 50 ? 2000 : 1900;
+ }
+
+ return new Date(
+ Date.UTC(
+ year,
+ Number(match[2]) - 1,
+ Number(match[3]),
+ Number(match[4]),
+ Number(match[5]),
+ Number(match[6] ?? "0"),
+ ),
+ );
+}
+
+// --- Writing -------------------------------------------------------------
+
+function encodeLength(length: number): Buffer {
+ if (length < 0x80) {
+ return Buffer.from([length]);
+ }
+
+ const bytes: number[] = [];
+ let rest = length;
+
+ while (rest > 0) {
+ bytes.unshift(rest & 0xff);
+ rest = Math.floor(rest / 256);
+ }
+
+ return Buffer.from([0x80 | bytes.length, ...bytes]);
+}
+
+export function encode(tag: number, ...content: Uint8Array[]): Buffer {
+ const body = Buffer.concat(content);
+
+ return Buffer.concat([Buffer.from([tag]), encodeLength(body.length), body]);
+}
+
+export function encodeOid(value: string): Buffer {
+ const parts = value.split(".").map(Number);
+ const numbers = [parts[0]! * 40 + parts[1]!, ...parts.slice(2)];
+ const bytes: number[] = [];
+
+ for (const number of numbers) {
+ const chunk: number[] = [number & 0x7f];
+ let rest = Math.floor(number / 128);
+
+ while (rest > 0) {
+ chunk.unshift((rest & 0x7f) | 0x80);
+ rest = Math.floor(rest / 128);
+ }
+
+ bytes.push(...chunk);
+ }
+
+ return encode(TAG.oid, Buffer.from(bytes));
+}
+
+/** An INTEGER from unsigned big-endian bytes. */
+export function encodeUnsignedInteger(value: Uint8Array): Buffer {
+ let start = 0;
+
+ while (start < value.length - 1 && value[start] === 0) {
+ start += 1;
+ }
+
+ const trimmed = Buffer.from(value.subarray(start));
+
+ return encode(
+ TAG.integer,
+ trimmed[0]! & 0x80 ? Buffer.concat([Buffer.from([0]), trimmed]) : trimmed,
+ );
+}
+
+export function encodeSmallInteger(value: number): Buffer {
+ const bytes: number[] = [];
+ let rest = value;
+
+ do {
+ bytes.unshift(rest & 0xff);
+ rest = Math.floor(rest / 256);
+ } while (rest > 0);
+
+ if (bytes[0]! & 0x80) {
+ bytes.unshift(0);
+ }
+
+ return encode(TAG.integer, Buffer.from(bytes));
+}
+
+export const der = {
+ null: () => Buffer.from([TAG.null, 0]),
+ octets: (value: Uint8Array) => encode(TAG.octetString, value),
+ oid: encodeOid,
+ sequence: (...items: Uint8Array[]) => encode(TAG.sequence, ...items),
+ set: (...items: Uint8Array[]) => encode(TAG.set, ...items),
+};
+
+/** An AlgorithmIdentifier with NULL parameters, as hash algorithms use. */
+export function algorithm(oid: string): Buffer {
+ return der.sequence(der.oid(oid), der.null());
+}
diff --git a/src/lib/services/pdf-incremental.ts b/src/lib/services/pdf-incremental.ts
new file mode 100644
index 0000000..eec8edf
--- /dev/null
+++ b/src/lib/services/pdf-incremental.ts
@@ -0,0 +1,623 @@
+import { createHash } from "node:crypto";
+
+import {
+ PDFArray,
+ PDFDict,
+ PDFDocument,
+ PDFName,
+ PDFNumber,
+ PDFRawStream,
+ PDFRef,
+ PDFString,
+ decodePDFRawStream,
+ type PDFObject,
+} from "pdf-lib";
+
+// Incremental updates: new and changed objects appended after the end of a
+// PDF, with their own cross-reference section, leaving every earlier byte
+// as it was. That is the only way to add to a signed PDF without breaking
+// its signatures, and it is how long-term validation data and archive
+// timestamps go in after the seal.
+//
+// This handles the files SignuDoc itself writes: a classic cross-reference
+// table (pdf-lib saved with object streams off), possibly followed by
+// earlier updates of the same kind. A file whose last section is a
+// cross-reference stream is refused.
+
+export class PdfUpdateError extends Error {
+ constructor(message: string, options?: { cause?: unknown }) {
+ super(message, options);
+ this.name = "PdfUpdateError";
+ }
+}
+
+export type ObjectRef = { generation: number; number: number };
+
+export type UpdatedObject = {
+ /** The object's body: a dictionary, an array, or a stream. */
+ body: Buffer;
+ ref: ObjectRef;
+};
+
+type Trailer = {
+ id: string | null;
+ info: string | null;
+ root: ObjectRef;
+ size: number;
+ startxref: number;
+};
+
+const BYTE_RANGE_PLACEHOLDER =
+ "/ByteRange [0 0000000000 0000000000 0000000000]";
+
+function parseRef(text: string | undefined): ObjectRef | null {
+ const match = text ? /^(\d+)\s+(\d+)\s+R$/.exec(text.trim()) : null;
+
+ return match
+ ? { generation: Number(match[2]), number: Number(match[1]) }
+ : null;
+}
+
+function refText(ref: ObjectRef): string {
+ return `${String(ref.number)} ${String(ref.generation)} R`;
+}
+
+/** The dictionary that starts at `start` ("<<"), nested ones included. */
+function dictionaryAt(text: string, start: number): string {
+ let depth = 0;
+
+ for (let index = start; index < text.length - 1; index += 1) {
+ const pair = text.slice(index, index + 2);
+
+ if (pair === "<<") {
+ depth += 1;
+ index += 1;
+ } else if (pair === ">>") {
+ depth -= 1;
+ index += 1;
+
+ if (depth === 0) {
+ return text.slice(start, index + 1);
+ }
+ }
+ }
+
+ throw new PdfUpdateError("The PDF trailer is not closed.");
+}
+
+function readTrailer(bytes: Uint8Array): Trailer {
+ // Only the end of the file is needed, and a trailer is short.
+ const tailStart = Math.max(0, bytes.length - 4096);
+ const tail = Buffer.from(bytes.subarray(tailStart)).toString("latin1");
+ const marker = tail.lastIndexOf("startxref");
+ const startxref = Number(/startxref\s+(\d+)/.exec(tail.slice(marker))?.[1]);
+
+ if (marker === -1 || !Number.isFinite(startxref)) {
+ throw new PdfUpdateError("The PDF has no cross-reference offset.");
+ }
+
+ const text = Buffer.from(bytes).toString("latin1");
+
+ if (!text.startsWith("xref", startxref)) {
+ throw new PdfUpdateError(
+ "The PDF uses a cross-reference stream, which cannot be updated here.",
+ );
+ }
+
+ const trailerAt = text.indexOf("trailer", startxref);
+ const dictionaryStart = text.indexOf("<<", trailerAt);
+
+ if (trailerAt === -1 || dictionaryStart === -1) {
+ throw new PdfUpdateError("The PDF has no trailer.");
+ }
+
+ const dictionary = dictionaryAt(text, dictionaryStart);
+
+ if (/\/Encrypt\b/.test(dictionary)) {
+ throw new PdfUpdateError("Encrypted PDFs cannot be updated here.");
+ }
+
+ const size = Number(/\/Size\s+(\d+)/.exec(dictionary)?.[1]);
+ const root = parseRef(/\/Root\s+(\d+\s+\d+\s+R)/.exec(dictionary)?.[1]);
+
+ if (!Number.isFinite(size) || !root) {
+ throw new PdfUpdateError("The PDF trailer has no size or root.");
+ }
+
+ return {
+ id: /\/ID\s*(\[[^\]]*\])/.exec(dictionary)?.[1] ?? null,
+ info: /\/Info\s+(\d+\s+\d+\s+R)/.exec(dictionary)?.[1] ?? null,
+ root,
+ size,
+ startxref,
+ };
+}
+
+/**
+ * Appends one update holding `objects`. An object with the number of an
+ * existing one replaces it; any other number must be new, from
+ * `nextObjectNumber` up.
+ */
+export function appendIncrementalUpdate(
+ bytes: Uint8Array,
+ objects: readonly UpdatedObject[],
+): Uint8Array {
+ if (objects.length === 0) {
+ return bytes;
+ }
+
+ const trailer = readTrailer(bytes);
+ const parts: Buffer[] = [Buffer.from(bytes)];
+ let position = bytes.length;
+ const offsets = new Map<number, { generation: number; offset: number }>();
+ const push = (part: Buffer) => {
+ parts.push(part);
+ position += part.length;
+ };
+
+ if (bytes[bytes.length - 1] !== 0x0a) {
+ push(Buffer.from("\n", "latin1"));
+ }
+
+ for (const object of objects) {
+ offsets.set(object.ref.number, {
+ generation: object.ref.generation,
+ offset: position,
+ });
+ push(
+ Buffer.concat([
+ Buffer.from(
+ `${String(object.ref.number)} ${String(object.ref.generation)} obj\n`,
+ "latin1",
+ ),
+ object.body,
+ Buffer.from("\nendobj\n", "latin1"),
+ ]),
+ );
+ }
+
+ const xrefOffset = position;
+ const numbers = [...offsets.keys()].sort((a, b) => a - b);
+ let xref = "xref\n";
+
+ for (let index = 0; index < numbers.length;) {
+ let end = index;
+
+ while (end + 1 < numbers.length && numbers[end + 1] === numbers[end]! + 1) {
+ end += 1;
+ }
+
+ xref += `${String(numbers[index])} ${String(end - index + 1)}\n`;
+
+ for (let entry = index; entry <= end; entry += 1) {
+ const { generation, offset } = offsets.get(numbers[entry]!)!;
+
+ xref += `${String(offset).padStart(10, "0")} ${String(generation).padStart(5, "0")} n\r\n`;
+ }
+
+ index = end + 1;
+ }
+
+ const size = Math.max(trailer.size, numbers[numbers.length - 1]! + 1);
+
+ xref +=
+ "trailer\n<<\n" +
+ `/Size ${String(size)}\n` +
+ `/Root ${refText(trailer.root)}\n` +
+ (trailer.info ? `/Info ${trailer.info}\n` : "") +
+ (trailer.id ? `/ID ${trailer.id}\n` : "") +
+ `/Prev ${String(trailer.startxref)}\n` +
+ ">>\n" +
+ `startxref\n${String(xrefOffset)}\n%%EOF\n`;
+ push(Buffer.from(xref, "latin1"));
+
+ return new Uint8Array(Buffer.concat(parts));
+}
+
+/** A signature dictionary's /ByteRange and /Contents, to fill in later. */
+export function signaturePlaceholder(contentsBytes: number): string {
+ return `${BYTE_RANGE_PLACEHOLDER}\n/Contents <${"0".repeat(contentsBytes * 2)}>`;
+}
+
+/**
+ * Appends an update whose objects include one signature dictionary written
+ * with `signaturePlaceholder`, then fills in its byte range and the value
+ * `sign` makes over the bytes that range covers.
+ */
+export async function appendSignedUpdate(
+ bytes: Uint8Array,
+ objects: readonly UpdatedObject[],
+ sign: (signedContent: Buffer) => Promise<Buffer>,
+): Promise<Uint8Array> {
+ const updated = Buffer.from(appendIncrementalUpdate(bytes, objects));
+ const text = updated.toString("latin1");
+ const rangeAt = text.indexOf(BYTE_RANGE_PLACEHOLDER, bytes.length);
+ const contentsAt = text.indexOf("/Contents <", rangeAt);
+
+ if (rangeAt === -1 || contentsAt === -1) {
+ throw new PdfUpdateError("The update has no signature placeholder.");
+ }
+
+ const open = contentsAt + "/Contents ".length;
+ const close = text.indexOf(">", open);
+ const range = [0, open, close + 1, updated.length - close - 1];
+ const rangeText = `/ByteRange [${range.join(" ")}]`;
+
+ if (rangeText.length > BYTE_RANGE_PLACEHOLDER.length) {
+ throw new PdfUpdateError("The PDF is too large to sign here.");
+ }
+
+ updated.write(
+ rangeText.padEnd(BYTE_RANGE_PLACEHOLDER.length, " "),
+ rangeAt,
+ "latin1",
+ );
+
+ const signature = await sign(
+ Buffer.concat([updated.subarray(0, open), updated.subarray(close + 1)]),
+ );
+ const hex = signature.toString("hex");
+ const room = close - open - 1;
+
+ if (hex.length > room) {
+ throw new PdfUpdateError(
+ `The signature (${String(signature.length)} bytes) does not fit its placeholder.`,
+ );
+ }
+
+ updated.write(hex, open + 1, "latin1");
+
+ return new Uint8Array(updated);
+}
+
+// --- Reading what is already there ---------------------------------------
+
+export type PdfSignature = {
+ byteRange: [number, number, number, number];
+ /** The CMS (or RFC 3161 token), without the zero padding. */
+ contents: Buffer;
+ subFilter: string | null;
+};
+
+/** The DER element at the start of a padded signature slot. */
+function withoutPadding(slot: Buffer): Buffer {
+ if (slot.length < 2) {
+ return slot;
+ }
+
+ const first = slot[1]!;
+ const lengthBytes = first < 0x80 ? 0 : first & 0x7f;
+ const length = lengthBytes === 0 ? first : slot.readUIntBE(2, lengthBytes);
+
+ return slot.subarray(0, 2 + lengthBytes + length);
+}
+
+/** Every signature and document timestamp in the file, oldest first. */
+export function findSignatures(bytes: Uint8Array): PdfSignature[] {
+ const text = Buffer.from(bytes).toString("latin1");
+ const pattern = /\/ByteRange\s*\[\s*(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s*\]/g;
+ const found: PdfSignature[] = [];
+ const seen = new Set<number>();
+
+ for (const match of text.matchAll(pattern)) {
+ const range = match.slice(1, 5).map(Number) as [
+ number,
+ number,
+ number,
+ number,
+ ];
+ const [, length, resume] = range;
+
+ if (seen.has(length) || text[length] !== "<" || text[resume - 1] !== ">") {
+ continue;
+ }
+
+ seen.add(length);
+
+ // The /SubFilter sits in the same dictionary, before or after.
+ const dictionaryStart = text.lastIndexOf("<<", match.index);
+ const around = text.slice(dictionaryStart, resume + 200);
+ const subFilter = /\/SubFilter\s*\/([A-Za-z0-9.#]+)/.exec(around)?.[1];
+
+ found.push({
+ byteRange: range,
+ contents: withoutPadding(
+ Buffer.from(text.slice(length + 1, resume - 1), "hex"),
+ ),
+ subFilter: subFilter ?? null,
+ });
+ }
+
+ return found.sort((a, b) => a.byteRange[1] - b.byteRange[1]);
+}
+
+/**
+ * Loads the file's latest version with pdf-lib, to read the objects an
+ * update changes. Nothing is saved from it: the update is written by hand.
+ */
+async function loadLatest(bytes: Uint8Array) {
+ const document = await PDFDocument.load(bytes, { updateMetadata: false });
+ const trailer = readTrailer(bytes);
+ let next = Math.max(trailer.size, document.context.largestObjectNumber + 1);
+
+ return {
+ allocate(): ObjectRef {
+ const ref = { generation: 0, number: next };
+
+ next += 1;
+ return ref;
+ },
+ document,
+ trailer,
+ };
+}
+
+function objectBody(value: PDFObject): Buffer {
+ return Buffer.from(value.toString(), "latin1");
+}
+
+function streamBody(data: Uint8Array): Buffer {
+ return Buffer.concat([
+ Buffer.from(`<<\n/Length ${String(data.length)}\n>>\nstream\n`, "latin1"),
+ Buffer.from(data),
+ Buffer.from("\nendstream", "latin1"),
+ ]);
+}
+
+function toPdfRef(ref: ObjectRef): PDFRef {
+ return PDFRef.of(ref.number, ref.generation);
+}
+
+function fromPdfRef(ref: PDFRef): ObjectRef {
+ return { generation: ref.generationNumber, number: ref.objectNumber };
+}
+
+export type ValidationEntries = {
+ certificates: readonly Uint8Array[];
+ crls: readonly Uint8Array[];
+ ocsps: readonly Uint8Array[];
+};
+
+function digestOf(data: Uint8Array): string {
+ return createHash("sha256").update(data).digest("hex");
+}
+
+/** The streams an existing /DSS lists, by kind, with their digests. */
+function existingDssEntries(
+ document: PDFDocument,
+ dss: PDFDict | undefined,
+): Record<
+ "CRLs" | "Certs" | "OCSPs",
+ { digests: Set<string>; refs: PDFRef[] }
+> {
+ const result = {
+ CRLs: { digests: new Set<string>(), refs: [] as PDFRef[] },
+ Certs: { digests: new Set<string>(), refs: [] as PDFRef[] },
+ OCSPs: { digests: new Set<string>(), refs: [] as PDFRef[] },
+ };
+
+ if (!dss) {
+ return result;
+ }
+
+ for (const key of ["Certs", "OCSPs", "CRLs"] as const) {
+ const list = dss.lookupMaybe(PDFName.of(key), PDFArray);
+
+ for (let index = 0; index < (list?.size() ?? 0); index += 1) {
+ const entry = list!.get(index);
+
+ if (!(entry instanceof PDFRef)) {
+ continue;
+ }
+
+ const stream = document.context.lookup(entry);
+
+ if (stream instanceof PDFRawStream) {
+ result[key].refs.push(entry);
+ result[key].digests.add(digestOf(decodePDFRawStream(stream).decode()));
+ }
+ }
+ }
+
+ return result;
+}
+
+/**
+ * Adds certificates, OCSP answers and revocation lists to the document
+ * security store (/DSS, ISO 32000-2 12.8.4.3), keeping what it already
+ * holds. Returns the file unchanged when everything is already there.
+ */
+export async function appendDocumentSecurityStore(
+ bytes: Uint8Array,
+ entries: ValidationEntries,
+): Promise<Uint8Array> {
+ const { allocate, document, trailer } = await loadLatest(bytes);
+ const catalog = document.catalog;
+ const existing = existingDssEntries(
+ document,
+ catalog.lookupMaybe(PDFName.of("DSS"), PDFDict),
+ );
+ const objects: UpdatedObject[] = [];
+ const lists = {
+ CRLs: entries.crls,
+ Certs: entries.certificates,
+ OCSPs: entries.ocsps,
+ };
+ let added = 0;
+
+ for (const key of ["Certs", "OCSPs", "CRLs"] as const) {
+ for (const data of lists[key]) {
+ const digest = digestOf(data);
+
+ if (existing[key].digests.has(digest)) {
+ continue;
+ }
+
+ const ref = allocate();
+
+ existing[key].digests.add(digest);
+ existing[key].refs.push(toPdfRef(ref));
+ objects.push({ body: streamBody(data), ref });
+ added += 1;
+ }
+ }
+
+ if (added === 0) {
+ return bytes;
+ }
+
+ const dssRef = allocate();
+ const dss = document.context.obj({ Type: "DSS" });
+
+ for (const key of ["Certs", "OCSPs", "CRLs"] as const) {
+ if (existing[key].refs.length > 0) {
+ dss.set(PDFName.of(key), document.context.obj(existing[key].refs));
+ }
+ }
+
+ objects.push({ body: objectBody(dss), ref: dssRef });
+ catalog.set(PDFName.of("DSS"), toPdfRef(dssRef));
+ declarePadesExtension(document, catalog);
+ objects.push({ body: objectBody(catalog), ref: trailer.root });
+
+ return appendIncrementalUpdate(bytes, objects);
+}
+
+/**
+ * Names the extension that brought /DSS and document timestamps to PDF 1.7
+ * (ESIC level 5), for readers that look for it.
+ */
+function declarePadesExtension(document: PDFDocument, catalog: PDFDict) {
+ const esic = document.context.obj({
+ BaseVersion: PDFName.of("1.7"),
+ ExtensionLevel: 5,
+ });
+ const extensions = catalog.get(PDFName.of("Extensions"));
+
+ if (extensions instanceof PDFDict) {
+ if (!extensions.has(PDFName.of("ESIC"))) {
+ extensions.set(PDFName.of("ESIC"), esic);
+ }
+ } else if (!extensions) {
+ catalog.set(PDFName.of("Extensions"), document.context.obj({ ESIC: esic }));
+ }
+}
+
+/**
+ * Adds a document timestamp (/DocTimeStamp, ETSI.RFC3161) over the whole
+ * file, as PAdES B-LTA puts after the validation data. `timestamp` gets the
+ * SHA-256 of the covered bytes and returns the RFC 3161 token for it.
+ */
+export async function appendDocumentTimestamp(
+ bytes: Uint8Array,
+ timestamp: (digest: Buffer) => Promise<Buffer>,
+ { contentsBytes = 16_384 }: { contentsBytes?: number } = {},
+): Promise<Uint8Array> {
+ const { allocate, document, trailer } = await loadLatest(bytes);
+ const catalog = document.catalog;
+ const page = document.getPage(0);
+ const signatureRef = allocate();
+ const fieldRef = allocate();
+ const objects: UpdatedObject[] = [];
+ // Field names must differ; the object number does.
+ const fieldName = `SignuDoc archive timestamp ${String(fieldRef.number)}`;
+
+ objects.push({
+ body: Buffer.from(
+ "<<\n/Type /DocTimeStamp\n/Filter /Adobe.PPKLite\n/SubFilter /ETSI.RFC3161\n" +
+ `${signaturePlaceholder(contentsBytes)}\n>>`,
+ "latin1",
+ ),
+ ref: signatureRef,
+ });
+
+ const field = document.context.obj({
+ F: 132,
+ FT: "Sig",
+ P: page.ref,
+ Rect: [0, 0, 0, 0],
+ Subtype: "Widget",
+ T: PDFString.of(fieldName),
+ Type: "Annot",
+ V: toPdfRef(signatureRef),
+ });
+
+ objects.push({ body: objectBody(field), ref: fieldRef });
+
+ // The page lists the widget among its annotations.
+ const annots = page.node.get(PDFName.of("Annots"));
+
+ if (annots instanceof PDFRef) {
+ const list = document.context.lookup(annots, PDFArray);
+
+ list.push(toPdfRef(fieldRef));
+ objects.push({ body: objectBody(list), ref: fromPdfRef(annots) });
+ } else {
+ if (annots instanceof PDFArray) {
+ annots.push(toPdfRef(fieldRef));
+ } else {
+ page.node.set(
+ PDFName.of("Annots"),
+ document.context.obj([toPdfRef(fieldRef)]),
+ );
+ }
+
+ objects.push({ body: objectBody(page.node), ref: fromPdfRef(page.ref) });
+ }
+
+ // The form lists the field, and says the file holds signatures.
+ const acroFormValue = catalog.get(PDFName.of("AcroForm"));
+ const acroForm =
+ acroFormValue instanceof PDFRef
+ ? document.context.lookup(acroFormValue, PDFDict)
+ : acroFormValue instanceof PDFDict
+ ? acroFormValue
+ : document.context.obj({ Fields: [] });
+ const fieldsValue = acroForm.get(PDFName.of("Fields"));
+
+ if (fieldsValue instanceof PDFRef) {
+ const list = document.context.lookup(fieldsValue, PDFArray);
+
+ list.push(toPdfRef(fieldRef));
+ objects.push({ body: objectBody(list), ref: fromPdfRef(fieldsValue) });
+ } else if (fieldsValue instanceof PDFArray) {
+ fieldsValue.push(toPdfRef(fieldRef));
+ } else {
+ acroForm.set(
+ PDFName.of("Fields"),
+ document.context.obj([toPdfRef(fieldRef)]),
+ );
+ }
+
+ const flags = acroForm.lookupMaybe(PDFName.of("SigFlags"), PDFNumber);
+
+ acroForm.set(
+ PDFName.of("SigFlags"),
+ PDFNumber.of((flags?.asNumber() ?? 0) | 3),
+ );
+
+ if (acroFormValue instanceof PDFRef) {
+ objects.push({
+ body: objectBody(acroForm),
+ ref: fromPdfRef(acroFormValue),
+ });
+ } else {
+ catalog.set(PDFName.of("AcroForm"), acroForm);
+ }
+
+ declarePadesExtension(document, catalog);
+ objects.push({ body: objectBody(catalog), ref: trailer.root });
+
+ return appendSignedUpdate(bytes, objects, async (content) =>
+ timestamp(createHash("sha256").update(content).digest()),
+ );
+}
+
+/** Whether the latest catalog has a document security store. */
+export async function hasDocumentSecurityStore(
+ bytes: Uint8Array,
+): Promise<boolean> {
+ const document = await PDFDocument.load(bytes, { updateMetadata: false });
+
+ return Boolean(document.catalog.lookupMaybe(PDFName.of("DSS"), PDFDict));
+}
diff --git a/src/lib/services/pdf-ltv.test.ts b/src/lib/services/pdf-ltv.test.ts
new file mode 100644
index 0000000..4a85297
--- /dev/null
+++ b/src/lib/services/pdf-ltv.test.ts
@@ -0,0 +1,408 @@
+import assert from "node:assert/strict";
+import { execFile } from "node:child_process";
+import { createHash } from "node:crypto";
+import { mkdtemp, rm, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import test from "node:test";
+import { promisify } from "node:util";
+
+import {
+ PDFArray,
+ PDFDict,
+ PDFDocument,
+ PDFName,
+ StandardFonts,
+} from "pdf-lib";
+
+import { children, contentBytes, readOid, readTlv } from "./der.ts";
+import { findSignatures, hasDocumentSecurityStore } from "./pdf-incremental.ts";
+import {
+ addLongTermValidation,
+ collectValidationData,
+ createValidationFetch,
+ describePadesLevel,
+ readCms,
+ resetValidationCache,
+} from "./pdf-ltv.ts";
+import {
+ createSelfSignedSealIdentity,
+ requestDocumentTimestamp,
+ saveSealedPdf,
+} from "./pdf-seal.ts";
+import { sealForTheLongTerm } from "./seal-identity.ts";
+import { startTestPki, type TestPki } from "./pki-test-support.ts";
+
+const run = promisify(execFile);
+const localFetch = createValidationFetch({ allowPrivateAddresses: true });
+
+async function makePdf(): Promise<PDFDocument> {
+ const pdf = await PDFDocument.create();
+ const page = pdf.addPage([612, 792]);
+
+ page.drawText("Signed agreement", {
+ font: await pdf.embedFont(StandardFonts.Helvetica),
+ x: 72,
+ y: 700,
+ });
+
+ return pdf;
+}
+
+async function sealedWith(pki: TestPki, { timestamp = true } = {}) {
+ return saveSealedPdf(await makePdf(), pki.seal, {
+ name: "Harbour & Finch",
+ reason: "Signed with SignuDoc",
+ timestampUrl: timestamp ? pki.timestampUrl : null,
+ });
+}
+
+async function withPki(run: (pki: TestPki) => Promise<void>) {
+ resetValidationCache();
+
+ const pki = await startTestPki();
+
+ try {
+ await run(pki);
+ } finally {
+ await pki.close();
+ }
+}
+
+/** The bytes each signature's byte range covers hash to what it signed. */
+function assertSignaturesCoverTheirRanges(bytes: Uint8Array) {
+ for (const signature of findSignatures(bytes)) {
+ const [a, b, c, d] = signature.byteRange;
+ const covered = Buffer.concat([
+ Buffer.from(bytes.subarray(a, a + b)),
+ Buffer.from(bytes.subarray(c, c + d)),
+ ]);
+ const digest = createHash("sha256").update(covered).digest();
+ const contents = signature.contents;
+ // ContentInfo > SignedData > encapContentInfo or signerInfos.
+ const signedData = children(
+ contents,
+ children(contents, readTlv(contents))[1]!,
+ )[0]!;
+ const parts = children(contents, signedData);
+ const encapsulated = parts[2]!;
+ const [type, wrapped] = children(contents, encapsulated);
+
+ if (readOid(contents, type!) === "1.2.840.113549.1.9.16.1.4") {
+ // A document timestamp: TSTInfo's messageImprint is the digest.
+ const octets = children(contents, wrapped!)[0]!;
+ const tstInfo = readTlv(contents, octets.contentStart, octets.end);
+ const imprint = children(contents, tstInfo)[2]!;
+
+ assert.deepEqual(
+ contentBytes(contents, children(contents, imprint)[1]!),
+ digest,
+ );
+ } else {
+ const signerInfo = children(contents, parts[parts.length - 1]!)[0]!;
+ const attributes = children(contents, children(contents, signerInfo)[3]!);
+ const messageDigest = attributes.find(
+ (attribute) =>
+ readOid(contents, children(contents, attribute)[0]!) ===
+ "1.2.840.113549.1.9.4",
+ )!;
+ const value = children(
+ contents,
+ children(contents, messageDigest)[1]!,
+ )[0]!;
+
+ assert.deepEqual(contentBytes(contents, value), digest);
+ }
+
+ // Nothing after a signature's range but later updates' bytes.
+ assert.ok(c + d <= bytes.length);
+ }
+}
+
+async function dssCounts(bytes: Uint8Array) {
+ const document = await PDFDocument.load(bytes, { updateMetadata: false });
+ const dss = document.catalog.lookup(PDFName.of("DSS"), PDFDict);
+ const count = (key: string) =>
+ dss.lookupMaybe(PDFName.of(key), PDFArray)?.size() ?? 0;
+
+ return { certs: count("Certs"), crls: count("CRLs"), ocsps: count("OCSPs") };
+}
+
+test("a CA-issued seal gets its chain, OCSP answers and an archive timestamp (B-LTA)", async (t) => {
+ await withPki(async (pki) => {
+ const sealed = await sealedWith(pki);
+
+ assert.equal(await describePadesLevel(sealed), "B-T");
+
+ const result = await addLongTermValidation(sealed, {
+ fetch: localFetch,
+ timestamp: (digest) => requestDocumentTimestamp(digest, pki.timestampUrl),
+ });
+
+ assert.deepEqual(result.problems, []);
+ assert.deepEqual(result.revoked, []);
+ assert.equal(await describePadesLevel(result.bytes), "B-LTA");
+ // The seal's issuer is not in the seal, but the time-stamping
+ // service sends it with its tokens.
+ assert.equal(pki.state.caFetches, 0);
+ // The seal and the time-stamping certificates each got an answer.
+ assert.equal(pki.state.ocspRequests, 2);
+
+ const counts = await dssCounts(result.bytes);
+
+ // Seal, CA, time-stamping authority.
+ assert.equal(counts.certs, 3);
+ assert.equal(counts.ocsps, 2);
+ assert.equal(counts.crls, 0);
+
+ // The first bytes are the sealed file, unchanged.
+ assert.deepEqual(
+ Buffer.from(result.bytes.subarray(0, sealed.length)),
+ Buffer.from(sealed),
+ );
+ assert.equal(findSignatures(result.bytes).length, 2);
+ assertSignaturesCoverTheirRanges(result.bytes);
+
+ // pdf-lib still reads the file, as later steps do.
+ await PDFDocument.load(result.bytes, { updateMetadata: false });
+
+ try {
+ await run("pdfsig", ["-v"]);
+ } catch {
+ t.diagnostic("pdfsig is not installed; skipped the poppler check");
+ return;
+ }
+
+ const directory = await mkdtemp(path.join(os.tmpdir(), "ltv-"));
+
+ try {
+ const file = path.join(directory, "lta.pdf");
+
+ await writeFile(file, result.bytes);
+
+ const { stdout } = await run("pdfsig", ["-nocert", file]);
+
+ // Poppler checks the seal, and lists the archive timestamp, which it
+ // cannot check itself.
+ assert.equal(
+ stdout.match(/Signature Validation: Signature is Valid\./g)?.length,
+ 1,
+ stdout,
+ );
+ assert.match(stdout, /SignuDoc archive timestamp/);
+
+ // OpenSSL checks the archive timestamp against the bytes it covers
+ // and the test CA.
+ const archive = findSignatures(result.bytes).at(-1)!;
+ const [a, b, c, d] = archive.byteRange;
+ const covered = path.join(directory, "covered.bin");
+ const token = path.join(directory, "token.der");
+ const caFile = path.join(directory, "ca.pem");
+
+ await writeFile(
+ covered,
+ Buffer.concat([
+ Buffer.from(result.bytes.subarray(a, a + b)),
+ Buffer.from(result.bytes.subarray(c, c + d)),
+ ]),
+ );
+ await writeFile(token, archive.contents);
+ await writeFile(
+ caFile,
+ `-----BEGIN CERTIFICATE-----\n${pki.caCertificate.toString("base64")}\n-----END CERTIFICATE-----\n`,
+ );
+
+ const verified = await run("openssl", [
+ "ts",
+ "-verify",
+ "-data",
+ covered,
+ "-in",
+ token,
+ "-token_in",
+ "-CAfile",
+ caFile,
+ ]).catch((error: { stderr?: string; stdout?: string }) => ({
+ stdout: `${error.stdout ?? ""}${error.stderr ?? ""}`,
+ }));
+
+ assert.match(verified.stdout, /Verification: OK/);
+ } finally {
+ await rm(directory, { force: true, recursive: true });
+ }
+ });
+});
+
+test("without OCSP, the revocation list is used", async () => {
+ await withPki(async (pki) => {
+ pki.state.ocspDown = true;
+
+ const result = await addLongTermValidation(
+ await sealedWith(pki, { timestamp: false }),
+ {
+ fetch: localFetch,
+ },
+ );
+ const counts = await dssCounts(result.bytes);
+
+ assert.deepEqual(result.revoked, []);
+ assert.equal(counts.ocsps, 0);
+ assert.equal(counts.crls, 1);
+ assert.equal(pki.state.crlFetches, 1);
+ // With no timestamp token to bring it, the seal's issuer came from the
+ // address the seal certificate names.
+ assert.equal(pki.state.caFetches, 1);
+ assert.match(result.problems.join(" "), /OCSP at .* failed/);
+ // A seal without a timestamp is B-B, whatever validation data it has.
+ assert.equal(await describePadesLevel(result.bytes), "B-B");
+ });
+});
+
+test("a revoked seal certificate is reported", async () => {
+ await withPki(async (pki) => {
+ pki.state.revoked.add("1001");
+
+ const result = await addLongTermValidation(
+ await sealedWith(pki, { timestamp: false }),
+ {
+ fetch: localFetch,
+ },
+ );
+
+ assert.equal(result.revoked.length, 1);
+ assert.match(result.revoked[0]!, /Harbour & Finch document seal/);
+ });
+});
+
+test("adding the same validation data twice changes nothing", async () => {
+ await withPki(async (pki) => {
+ const once = await addLongTermValidation(await sealedWith(pki), {
+ fetch: localFetch,
+ });
+ const twice = await addLongTermValidation(once.bytes, {
+ fetch: localFetch,
+ });
+
+ assert.equal(twice.bytes.length, once.bytes.length);
+ });
+});
+
+test("a time-stamping service that fails leaves the validation data in place", async () => {
+ await withPki(async (pki) => {
+ const result = await addLongTermValidation(await sealedWith(pki), {
+ fetch: localFetch,
+ timestamp: async () => {
+ throw new Error("down");
+ },
+ });
+
+ assert.equal(await describePadesLevel(result.bytes), "B-LT");
+ assert.match(result.problems.join(" "), /archive timestamp failed: down/);
+ });
+});
+
+test("the timestamp tokens and certificates inside a seal are found", async () => {
+ await withPki(async (pki) => {
+ const [signature] = findSignatures(await sealedWith(pki));
+ const contents = readCms(signature!.contents);
+
+ assert.equal(contents.certificates.length, 1);
+ assert.equal(contents.timestampTokens.length, 1);
+ });
+});
+
+test("addresses on this machine or a private network are not fetched", async () => {
+ const guarded = createValidationFetch();
+
+ for (const url of [
+ "http://127.0.0.1/ca.cer",
+ "http://localhost/ca.cer",
+ "http://10.1.2.3/ocsp",
+ "http://192.168.0.4/ocsp",
+ "http://169.254.169.254/latest",
+ "http://[::1]/ocsp",
+ "http://[::ffff:127.0.0.1]/ocsp",
+ "file:///etc/passwd",
+ ]) {
+ await assert.rejects(guarded(url), /Refused/, url);
+ }
+});
+
+test("the install's seal is B-LTA with a CA certificate and a time-stamping service", async () => {
+ await withPki(async (pki) => {
+ const sealed = await sealForTheLongTerm(
+ await makePdf(),
+ pki.seal,
+ {
+ name: "Harbour & Finch",
+ reason: "Signed",
+ timestampUrl: pki.timestampUrl,
+ },
+ { fetch: localFetch },
+ );
+
+ assert.equal(await describePadesLevel(sealed), "B-LTA");
+ });
+});
+
+test("with the time-stamping service down, a CA seal still gets its validation data", async () => {
+ await withPki(async (pki) => {
+ const original = console.error;
+
+ console.error = () => {};
+
+ try {
+ const sealed = await sealForTheLongTerm(
+ await makePdf(),
+ pki.seal,
+ {
+ name: "Harbour & Finch",
+ reason: "Signed",
+ timestampUrl: pki.timestampUrl.replace("/tsa", "/missing"),
+ },
+ { fetch: localFetch },
+ );
+
+ assert.equal(await describePadesLevel(sealed), "B-B");
+ assert.equal(await hasDocumentSecurityStore(sealed), true);
+ } finally {
+ console.error = original;
+ }
+ });
+});
+
+test("a self-made seal without a timestamp is left as it is", async () => {
+ const { generateKeyPairSync } = await import("node:crypto");
+ const { privateKey, publicKey } = generateKeyPairSync("rsa", {
+ modulusLength: 2048,
+ privateKeyEncoding: { format: "pem", type: "pkcs8" },
+ publicKeyEncoding: { format: "pem", type: "spki" },
+ });
+ const identity = createSelfSignedSealIdentity({
+ commonName: "Test seal",
+ privateKeyPem: privateKey,
+ publicKeyPem: publicKey,
+ });
+ const sealed = await sealForTheLongTerm(await makePdf(), identity, {
+ name: "SignuDoc",
+ reason: "Signed",
+ });
+
+ assert.equal(await describePadesLevel(sealed), "B-B");
+ assert.equal(await hasDocumentSecurityStore(sealed), false);
+ assert.equal(findSignatures(sealed).length, 1);
+});
+
+test("a certificate authority that does not answer is given up on in time", async () => {
+ await withPki(async (pki) => {
+ const sealed = await sealedWith(pki, { timestamp: false });
+ const started = Date.now();
+ const data = await collectValidationData(
+ findSignatures(sealed).map((signature) => signature.contents),
+ { budgetMs: 300, fetch: () => new Promise<Buffer>(() => {}) },
+ );
+
+ assert.ok(Date.now() - started < 3_000);
+ assert.match(data.problems.join(" "), /Ran out of time/);
+ });
+});
diff --git a/src/lib/services/pdf-ltv.ts b/src/lib/services/pdf-ltv.ts
new file mode 100644
index 0000000..5e456bd
--- /dev/null
+++ b/src/lib/services/pdf-ltv.ts
@@ -0,0 +1,1015 @@
+import {
+ createHash,
+ verify as verifySignature,
+ X509Certificate,
+} from "node:crypto";
+import { isIP } from "node:net";
+
+import {
+ algorithm,
+ children,
+ contentBytes,
+ contextTag,
+ der,
+ elementBytes,
+ encode,
+ expectTag,
+ readOid,
+ readTime,
+ readTlv,
+ TAG,
+ type Tlv,
+} from "./der.ts";
+import {
+ appendDocumentSecurityStore,
+ appendDocumentTimestamp,
+ findSignatures,
+ hasDocumentSecurityStore,
+} from "./pdf-incremental.ts";
+
+// Long-term validation (PAdES B-LT and B-LTA, ETSI EN 319 142-1).
+//
+// A seal made today verifies today, while its certificates are valid and
+// their issuers still answer revocation checks. Years later they may not.
+// So after sealing, the certificates of the seal and of its timestamp, and
+// a fresh answer that none of them is revoked (an OCSP response, or a
+// revocation list), go into the PDF's document security store (B-LT). Then
+// a document timestamp seals all of that in (B-LTA), so a reader can show
+// the evidence existed at that time, even after the certificates expire.
+//
+// The certificates come from the signatures themselves; a missing issuer is
+// fetched from the address its certificate names (authority information
+// access), and revocation answers from the OCSP responder or revocation list
+// the certificate names. Those are the certificate authority's own services,
+// outside this install.
+
+const OIDS = {
+ caIssuers: "1.3.6.1.5.5.7.48.2",
+ crlDistributionPoints: "2.5.29.31",
+ ecdsaSha256: "1.2.840.10045.4.3.2",
+ ecdsaSha384: "1.2.840.10045.4.3.3",
+ ecdsaSha512: "1.2.840.10045.4.3.4",
+ infoAccess: "1.3.6.1.5.5.7.1.1",
+ ocsp: "1.3.6.1.5.5.7.48.1",
+ ocspBasic: "1.3.6.1.5.5.7.48.1.1",
+ ocspNoCheck: "1.3.6.1.5.5.7.48.1.5",
+ sha1: "1.3.14.3.2.26",
+ sha1WithRsa: "1.2.840.113549.1.1.5",
+ sha256: "2.16.840.1.101.3.4.2.1",
+ sha256WithRsa: "1.2.840.113549.1.1.11",
+ sha384WithRsa: "1.2.840.113549.1.1.12",
+ sha512WithRsa: "1.2.840.113549.1.1.13",
+ signedData: "1.2.840.113549.1.7.2",
+ timeStampToken: "1.2.840.113549.1.9.16.2.14",
+ tstInfo: "1.2.840.113549.1.9.16.1.4",
+} as const;
+
+const SIGNATURE_HASHES: Record<string, string> = {
+ [OIDS.ecdsaSha256]: "sha256",
+ [OIDS.ecdsaSha384]: "sha384",
+ [OIDS.ecdsaSha512]: "sha512",
+ [OIDS.sha1WithRsa]: "sha1",
+ [OIDS.sha256WithRsa]: "sha256",
+ [OIDS.sha384WithRsa]: "sha384",
+ [OIDS.sha512WithRsa]: "sha512",
+};
+
+const MAX_CHAIN_CERTIFICATES = 16;
+const MAX_FETCHES = 24;
+/** All the lookups for one document, together. */
+const LOOKUP_BUDGET_MS = 15_000;
+const MAX_RESPONSE_BYTES = 4 * 1024 * 1024;
+const FETCH_TIMEOUT_MS = 10_000;
+const ISSUER_CACHE_MS = 24 * 60 * 60 * 1000;
+const REVOCATION_CACHE_MS = 10 * 60 * 1000;
+
+export class LongTermValidationError extends Error {
+ constructor(message: string, options?: { cause?: unknown }) {
+ super(message, options);
+ this.name = "LongTermValidationError";
+ }
+}
+
+// --- Certificates --------------------------------------------------------
+
+export type Certificate = {
+ caIssuerUrls: string[];
+ crlUrls: string[];
+ der: Buffer;
+ fingerprint: string;
+ /** The issuer Name, as encoded. */
+ issuerName: Buffer;
+ ocspNoCheck: boolean;
+ ocspUrls: string[];
+ /** The serial number's INTEGER content, as OCSP and CRLs compare it. */
+ serial: Buffer;
+ /** The subject public key, without the BIT STRING's unused-bits byte. */
+ subjectKey: Buffer;
+ /** The subject Name, as encoded. */
+ subjectName: Buffer;
+ x509: X509Certificate;
+};
+
+function uriNames(bytes: Uint8Array, tlv: Tlv, into: string[]) {
+ // GeneralName uniformResourceIdentifier is [6] IA5String.
+ if (tlv.tag === 0x86) {
+ into.push(contentBytes(bytes, tlv).toString("latin1"));
+ return;
+ }
+
+ if (tlv.tag & 0x20) {
+ for (const child of children(bytes, tlv)) {
+ uriNames(bytes, child, into);
+ }
+ }
+}
+
+function httpUrls(urls: string[]): string[] {
+ return urls.filter((url) => /^https?:\/\//i.test(url));
+}
+
+export function parseCertificate(input: Uint8Array): Certificate {
+ const bytes = Buffer.from(input);
+ const certificate = readTlv(bytes);
+ const tbs = expectTag(
+ children(bytes, certificate)[0],
+ TAG.sequence,
+ "a certificate",
+ );
+ const fields = children(bytes, tbs);
+ const offset = fields[0]?.tag === contextTag(0) ? 1 : 0;
+ const serial = expectTag(fields[offset], TAG.integer, "a serial number");
+ const issuerName = expectTag(fields[offset + 2], TAG.sequence, "an issuer");
+ const subject = expectTag(fields[offset + 4], TAG.sequence, "a subject");
+ const spki = expectTag(fields[offset + 5], TAG.sequence, "a public key");
+ const key = expectTag(
+ children(bytes, spki)[1],
+ TAG.bitString,
+ "a public key",
+ );
+ const parsed: Certificate = {
+ caIssuerUrls: [],
+ crlUrls: [],
+ der: elementBytes(bytes, certificate),
+ fingerprint: createHash("sha256")
+ .update(bytes.subarray(certificate.start, certificate.end))
+ .digest("hex"),
+ issuerName: elementBytes(bytes, issuerName),
+ ocspNoCheck: false,
+ ocspUrls: [],
+ serial: contentBytes(bytes, serial),
+ subjectKey: contentBytes(bytes, key).subarray(1),
+ subjectName: elementBytes(bytes, subject),
+ x509: new X509Certificate(elementBytes(bytes, certificate)),
+ };
+ const extensions = fields.find((field) => field.tag === contextTag(3));
+
+ if (extensions) {
+ const list = expectTag(
+ children(bytes, extensions)[0],
+ TAG.sequence,
+ "extensions",
+ );
+
+ for (const extension of children(bytes, list)) {
+ const parts = children(bytes, extension);
+ const id = readOid(bytes, parts[0]!);
+ const value = parts[parts.length - 1]!;
+ const inner = readTlv(bytes, value.contentStart, value.end);
+
+ if (id === OIDS.ocspNoCheck) {
+ parsed.ocspNoCheck = true;
+ } else if (id === OIDS.crlDistributionPoints) {
+ uriNames(bytes, inner, parsed.crlUrls);
+ } else if (id === OIDS.infoAccess) {
+ for (const description of children(bytes, inner)) {
+ const [method, location] = children(bytes, description);
+ const urls: string[] = [];
+
+ uriNames(bytes, location!, urls);
+
+ if (readOid(bytes, method!) === OIDS.ocsp) {
+ parsed.ocspUrls.push(...urls);
+ } else if (readOid(bytes, method!) === OIDS.caIssuers) {
+ parsed.caIssuerUrls.push(...urls);
+ }
+ }
+ }
+ }
+ }
+
+ parsed.caIssuerUrls = httpUrls(parsed.caIssuerUrls);
+ parsed.crlUrls = httpUrls(parsed.crlUrls);
+ parsed.ocspUrls = httpUrls(parsed.ocspUrls);
+
+ return parsed;
+}
+
+/**
+ * Whether `issuer` signed `certificate`: its subject is the certificate's
+ * issuer, and its key verifies the certificate's signature. (OpenSSL's own
+ * issuer check also wants the issuer to be allowed to sign certificates,
+ * which a self-made seal certificate is not.)
+ */
+function isIssuedBy(certificate: Certificate, issuer: Certificate): boolean {
+ try {
+ return (
+ certificate.issuerName.equals(issuer.subjectName) &&
+ certificate.x509.verify(issuer.x509.publicKey)
+ );
+ } catch {
+ return false;
+ }
+}
+
+export function isSelfSigned(certificate: Certificate): boolean {
+ return isIssuedBy(certificate, certificate);
+}
+
+/** Certificates from a DER or PEM certificate, or a certs-only PKCS#7. */
+export function certificatesFromBundle(body: Uint8Array): Certificate[] {
+ const text = Buffer.from(body).toString("latin1");
+
+ if (text.includes("-----BEGIN CERTIFICATE-----")) {
+ return [
+ ...text.matchAll(
+ /-----BEGIN CERTIFICATE-----([\s\S]*?)-----END CERTIFICATE-----/g,
+ ),
+ ].map((match) =>
+ parseCertificate(Buffer.from(match[1]!.replace(/\s+/g, ""), "base64")),
+ );
+ }
+
+ try {
+ return [parseCertificate(body)];
+ } catch {
+ return readCms(body).certificates.map(parseCertificate);
+ }
+}
+
+// --- CMS -----------------------------------------------------------------
+
+type CmsContents = {
+ certificates: Buffer[];
+ /** Timestamp tokens in the signer infos' unsigned attributes. */
+ timestampTokens: Buffer[];
+};
+
+/** The certificates and timestamp tokens of a CMS SignedData. */
+export function readCms(input: Uint8Array): CmsContents {
+ const bytes = Buffer.from(input);
+ const contentInfo = readTlv(bytes);
+ const [type, wrapped] = children(bytes, contentInfo);
+
+ if (readOid(bytes, type!) !== OIDS.signedData) {
+ throw new LongTermValidationError("Not a CMS SignedData.");
+ }
+
+ const signedData = children(bytes, wrapped!)[0]!;
+ const parts = children(bytes, signedData);
+ const result: CmsContents = { certificates: [], timestampTokens: [] };
+
+ for (const part of parts) {
+ if (part.tag === contextTag(0)) {
+ for (const certificate of children(bytes, part)) {
+ if (certificate.tag === TAG.sequence) {
+ result.certificates.push(elementBytes(bytes, certificate));
+ }
+ }
+ }
+ }
+
+ const signerInfos = parts[parts.length - 1]!;
+
+ for (const signerInfo of children(bytes, signerInfos)) {
+ const unsigned = children(bytes, signerInfo).find(
+ (field) => field.tag === contextTag(1),
+ );
+
+ for (const attribute of unsigned ? children(bytes, unsigned) : []) {
+ const [id, values] = children(bytes, attribute);
+
+ if (readOid(bytes, id!) === OIDS.timeStampToken) {
+ for (const token of children(bytes, values!)) {
+ result.timestampTokens.push(elementBytes(bytes, token));
+ }
+ }
+ }
+ }
+
+ return result;
+}
+
+/** Every certificate in a CMS and in the timestamp tokens inside it. */
+function cmsCertificates(cms: Uint8Array, depth = 0): Buffer[] {
+ const contents = readCms(cms);
+
+ return [
+ ...contents.certificates,
+ ...(depth < 3
+ ? contents.timestampTokens.flatMap((token) =>
+ cmsCertificates(token, depth + 1),
+ )
+ : []),
+ ];
+}
+
+// --- Fetching --------------------------------------------------------------
+
+export type ValidationFetch = (
+ url: string,
+ request?: { body: Buffer; contentType: string },
+) => Promise<Buffer>;
+
+function isPrivateAddress(host: string): boolean {
+ const address = host.replace(/^\[|\]$/g, "").toLowerCase();
+
+ if (address === "localhost" || address.endsWith(".localhost")) {
+ return true;
+ }
+
+ const version = isIP(address);
+
+ if (version === 4) {
+ const [a, b] = address.split(".").map(Number) as [number, number];
+
+ return (
+ a === 0 ||
+ a === 10 ||
+ a === 127 ||
+ (a === 100 && b >= 64 && b <= 127) ||
+ (a === 169 && b === 254) ||
+ (a === 172 && b >= 16 && b <= 31) ||
+ (a === 192 && b === 168)
+ );
+ }
+
+ if (version === 6) {
+ // An IPv4 address mapped into IPv6, which URL writes in hex.
+ const hex = /^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/.exec(address);
+ const mapped = hex
+ ? [parseInt(hex[1]!, 16), parseInt(hex[2]!, 16)]
+ .flatMap((word) => [word >> 8, word & 0xff])
+ .join(".")
+ : /^::ffff:(\d+\.\d+\.\d+\.\d+)$/.exec(address)?.[1];
+
+ return (
+ address === "::" ||
+ address === "::1" ||
+ /^f[cd]/.test(address) ||
+ /^fe[89ab]/.test(address) ||
+ (mapped ? isPrivateAddress(mapped) : false)
+ );
+ }
+
+ return false;
+}
+
+/**
+ * Fetches from a certificate authority's service. Only http and https, no
+ * addresses on this machine or a private network (the addresses come from
+ * certificates), a few redirects at most, and a size limit.
+ */
+export function createValidationFetch({
+ allowPrivateAddresses = false,
+ maxBytes = MAX_RESPONSE_BYTES,
+ timeoutMs = FETCH_TIMEOUT_MS,
+}: {
+ allowPrivateAddresses?: boolean;
+ maxBytes?: number;
+ timeoutMs?: number;
+} = {}): ValidationFetch {
+ return async (url, request) => {
+ let target = new URL(url);
+
+ for (let hop = 0; hop < 4; hop += 1) {
+ if (target.protocol !== "http:" && target.protocol !== "https:") {
+ throw new LongTermValidationError(
+ `Refused to fetch ${target.protocol} URL.`,
+ );
+ }
+
+ if (!allowPrivateAddresses && isPrivateAddress(target.hostname)) {
+ throw new LongTermValidationError(
+ `Refused to fetch from a private address (${target.hostname}).`,
+ );
+ }
+
+ const response = await fetch(target, {
+ body: request ? new Uint8Array(request.body) : undefined,
+ headers: request ? { "content-type": request.contentType } : undefined,
+ method: request ? "POST" : "GET",
+ redirect: "manual",
+ signal: AbortSignal.timeout(timeoutMs),
+ });
+ const location = response.headers.get("location");
+
+ if (response.status >= 300 && response.status < 400 && location) {
+ target = new URL(location, target);
+ continue;
+ }
+
+ if (!response.ok || !response.body) {
+ throw new LongTermValidationError(
+ `${target.host} answered ${String(response.status)}.`,
+ );
+ }
+
+ const declared = Number(response.headers.get("content-length") ?? "0");
+
+ if (declared > maxBytes) {
+ throw new LongTermValidationError(`${target.host} sent too much.`);
+ }
+
+ const chunks: Buffer[] = [];
+ const reader = response.body.getReader();
+ let total = 0;
+
+ for (;;) {
+ const { done, value } = await reader.read();
+
+ if (done) {
+ break;
+ }
+
+ total += value.length;
+
+ if (total > maxBytes) {
+ await reader.cancel();
+ throw new LongTermValidationError(`${target.host} sent too much.`);
+ }
+
+ chunks.push(Buffer.from(value));
+ }
+
+ return Buffer.concat(chunks);
+ }
+
+ throw new LongTermValidationError("Too many redirects.");
+ };
+}
+
+type CacheEntry = { expiresAt: number; value: unknown };
+
+declare global {
+ var __signudocValidationCache: Map<string, CacheEntry> | undefined;
+}
+
+function cache(): Map<string, CacheEntry> {
+ globalThis.__signudocValidationCache ??= new Map();
+
+ return globalThis.__signudocValidationCache;
+}
+
+/** Forgets cached issuer certificates and revocation answers, for tests. */
+export function resetValidationCache() {
+ globalThis.__signudocValidationCache = undefined;
+}
+
+async function cached<T>(
+ key: string,
+ lifetimeMs: (value: T) => number,
+ load: () => Promise<T>,
+): Promise<T> {
+ const store = cache();
+ const hit = store.get(key);
+
+ if (hit && hit.expiresAt > Date.now()) {
+ return hit.value as T;
+ }
+
+ const value = await load();
+
+ if (store.size > 500) {
+ store.clear();
+ }
+
+ const lifetime = lifetimeMs(value);
+
+ if (lifetime > 0) {
+ store.set(key, { expiresAt: Date.now() + lifetime, value });
+ }
+
+ return value;
+}
+
+// --- Revocation ------------------------------------------------------------
+
+type RevocationAnswer = {
+ data: Buffer;
+ /** Certificates the answer came with, such as a delegated OCSP responder. */
+ extraCertificates: Buffer[];
+ kind: "crl" | "ocsp";
+ nextUpdate: Date | null;
+ status: "good" | "revoked";
+};
+
+function hashName(oid: string): string | null {
+ return oid === OIDS.sha1 ? "sha1" : oid === OIDS.sha256 ? "sha256" : null;
+}
+
+function verifiesWith(
+ hash: string | undefined,
+ data: Buffer,
+ signer: Certificate,
+ signature: Buffer,
+): boolean {
+ if (!hash) {
+ return false;
+ }
+
+ try {
+ return verifySignature(hash, data, signer.x509.publicKey, signature);
+ } catch {
+ return false;
+ }
+}
+
+/** The OCSP request for one certificate (RFC 6960 4.1.1), with SHA-1 IDs. */
+export function buildOcspRequest(
+ certificate: Certificate,
+ issuer: Certificate,
+): Buffer {
+ const sha1 = (value: Buffer) => createHash("sha1").update(value).digest();
+ const certId = der.sequence(
+ algorithm(OIDS.sha1),
+ der.octets(sha1(issuer.subjectName)),
+ der.octets(sha1(issuer.subjectKey)),
+ encode(TAG.integer, certificate.serial),
+ );
+
+ return der.sequence(der.sequence(der.sequence(der.sequence(certId))));
+}
+
+/** Reads an OCSP response for `certificate`, checking it is the issuer's. */
+export function readOcspResponse(
+ body: Buffer,
+ certificate: Certificate,
+ issuer: Certificate,
+): RevocationAnswer {
+ const response = readTlv(body);
+ const [status, responseBytes] = children(body, response);
+
+ if (
+ contentBytes(body, expectTag(status, TAG.enumerated, "a status"))[0] !== 0
+ ) {
+ throw new LongTermValidationError(
+ "The OCSP responder did not answer successfully.",
+ );
+ }
+
+ const [type, octets] = children(body, children(body, responseBytes!)[0]!);
+
+ if (readOid(body, type!) !== OIDS.ocspBasic) {
+ throw new LongTermValidationError(
+ "The OCSP answer is not a basic response.",
+ );
+ }
+
+ const basicStart = octets!.contentStart;
+ const basic = readTlv(body, basicStart, octets!.end);
+ const [tbs, signatureAlgorithm, signatureValue, certsField] = children(
+ body,
+ basic,
+ );
+ const tbsFields = children(body, tbs!);
+ const responses = tbsFields.find(
+ (field, index) =>
+ index > 0 &&
+ field.tag === TAG.sequence &&
+ tbsFields[index - 1]!.tag === TAG.generalizedTime,
+ );
+ let match: { status: "good" | "revoked"; nextUpdate: Date | null } | null =
+ null;
+
+ for (const single of responses ? children(body, responses) : []) {
+ const [certId, certStatus, , ...rest] = children(body, single);
+ const [hashAlgorithm, nameHash, keyHash, serial] = children(body, certId!);
+ const hash = hashName(readOid(body, children(body, hashAlgorithm!)[0]!));
+
+ if (
+ !hash ||
+ !contentBytes(body, serial!).equals(certificate.serial) ||
+ !contentBytes(body, nameHash!).equals(
+ createHash(hash).update(issuer.subjectName).digest(),
+ ) ||
+ !contentBytes(body, keyHash!).equals(
+ createHash(hash).update(issuer.subjectKey).digest(),
+ )
+ ) {
+ continue;
+ }
+
+ if (certStatus!.tag === 0x82) {
+ throw new LongTermValidationError(
+ "The OCSP responder does not know the certificate.",
+ );
+ }
+
+ const next = rest.find((field) => field.tag === contextTag(0));
+
+ match = {
+ nextUpdate: next ? readTime(body, children(body, next)[0]!) : null,
+ status: certStatus!.tag === 0x80 ? "good" : "revoked",
+ };
+ break;
+ }
+
+ if (!match) {
+ throw new LongTermValidationError(
+ "The OCSP answer is about another certificate.",
+ );
+ }
+
+ const extraCertificates =
+ certsField && certsField.tag === contextTag(0)
+ ? children(body, children(body, certsField)[0]!).map((cert) =>
+ elementBytes(body, cert),
+ )
+ : [];
+ const hash =
+ SIGNATURE_HASHES[readOid(body, children(body, signatureAlgorithm!)[0]!)];
+ const signature = contentBytes(body, signatureValue!).subarray(1);
+ const signed = elementBytes(body, tbs!);
+ // Signed by the issuer itself, or by a responder the issuer certified.
+ const candidates = [
+ issuer,
+ ...extraCertificates
+ .map((cert) => parseCertificate(cert))
+ .filter((responder) => isIssuedBy(responder, issuer)),
+ ];
+
+ if (
+ !candidates.some((signer) => verifiesWith(hash, signed, signer, signature))
+ ) {
+ throw new LongTermValidationError(
+ "The OCSP answer's signature does not verify.",
+ );
+ }
+
+ return {
+ data: elementBytes(body, response),
+ extraCertificates,
+ kind: "ocsp",
+ nextUpdate: match.nextUpdate,
+ status: match.status,
+ };
+}
+
+/** Reads a revocation list from `issuer`, and whether it lists `certificate`. */
+export function readCrl(
+ body: Buffer,
+ certificate: Certificate,
+ issuer: Certificate,
+): RevocationAnswer {
+ const list = readTlv(body);
+ const [tbs, signatureAlgorithm, signatureValue] = children(body, list);
+ const fields = children(body, tbs!);
+ const offset = fields[0]!.tag === TAG.integer ? 1 : 0;
+ const issuerName = fields[offset + 1]!;
+
+ if (!elementBytes(body, issuerName).equals(issuer.subjectName)) {
+ throw new LongTermValidationError(
+ "The revocation list is from another issuer.",
+ );
+ }
+
+ const hash =
+ SIGNATURE_HASHES[readOid(body, children(body, signatureAlgorithm!)[0]!)];
+
+ if (
+ !verifiesWith(
+ hash,
+ elementBytes(body, tbs!),
+ issuer,
+ contentBytes(body, signatureValue!).subarray(1),
+ )
+ ) {
+ throw new LongTermValidationError(
+ "The revocation list's signature does not verify.",
+ );
+ }
+
+ const rest = fields.slice(offset + 3);
+ const nextUpdate =
+ rest[0] &&
+ (rest[0].tag === TAG.utcTime || rest[0].tag === TAG.generalizedTime)
+ ? readTime(body, rest[0])
+ : null;
+ const revoked = rest.find((field) => field.tag === TAG.sequence);
+ const listed = (revoked ? children(body, revoked) : []).some((entry) =>
+ contentBytes(body, children(body, entry)[0]!).equals(certificate.serial),
+ );
+
+ return {
+ data: elementBytes(body, list),
+ extraCertificates: [],
+ kind: "crl",
+ nextUpdate,
+ status: listed ? "revoked" : "good",
+ };
+}
+
+// --- Collecting --------------------------------------------------------------
+
+export type ValidationData = {
+ certificates: Buffer[];
+ crls: Buffer[];
+ ocsps: Buffer[];
+ /** What could not be found or checked, for the log. */
+ problems: string[];
+ /** Subjects of certificates their issuer says are revoked. */
+ revoked: string[];
+};
+
+function revocationLifetime(answer: RevocationAnswer | null): number {
+ // No answer is not kept: the next document asks again.
+ if (!answer) {
+ return 0;
+ }
+
+ if (!answer.nextUpdate) {
+ return REVOCATION_CACHE_MS;
+ }
+
+ return Math.max(
+ 0,
+ Math.min(REVOCATION_CACHE_MS, answer.nextUpdate.getTime() - Date.now()),
+ );
+}
+
+/**
+ * Gathers the certificate chains of every signature given (CMS or RFC 3161
+ * tokens) up to their roots, with a revocation answer for each certificate
+ * that needs one.
+ */
+export async function collectValidationData(
+ signatures: readonly Uint8Array[],
+ {
+ budgetMs = LOOKUP_BUDGET_MS,
+ fetch: fetchFrom = createValidationFetch(),
+ }: { budgetMs?: number; fetch?: ValidationFetch } = {},
+): Promise<ValidationData> {
+ const deadline = Date.now() + budgetMs;
+ const pool = new Map<string, Certificate>();
+ const result: ValidationData = {
+ certificates: [],
+ crls: [],
+ ocsps: [],
+ problems: [],
+ revoked: [],
+ };
+ let fetches = 0;
+ // A slow certificate authority must not hold up a signing for long.
+ const limitedFetch: ValidationFetch = async (url, request) => {
+ fetches += 1;
+
+ const remaining = deadline - Date.now();
+
+ if (fetches > MAX_FETCHES) {
+ throw new LongTermValidationError("Too many lookups for one document.");
+ }
+
+ if (remaining <= 0) {
+ throw new LongTermValidationError("Ran out of time for lookups.");
+ }
+
+ let timer: NodeJS.Timeout | undefined;
+
+ try {
+ return await Promise.race([
+ fetchFrom(url, request),
+ new Promise<never>((_, reject) => {
+ timer = setTimeout(
+ () =>
+ reject(
+ new LongTermValidationError("Ran out of time for lookups."),
+ ),
+ remaining,
+ );
+ }),
+ ]);
+ } finally {
+ clearTimeout(timer);
+ }
+ };
+ const addToPool = (certificate: Certificate) => {
+ if (!pool.has(certificate.fingerprint)) {
+ pool.set(certificate.fingerprint, certificate);
+ }
+
+ return pool.get(certificate.fingerprint)!;
+ };
+ const queue: Certificate[] = [];
+
+ for (const signature of signatures) {
+ for (const certificate of cmsCertificates(signature)) {
+ queue.push(addToPool(parseCertificate(certificate)));
+ }
+ }
+
+ const done = new Set<string>();
+
+ while (queue.length > 0 && done.size < MAX_CHAIN_CERTIFICATES) {
+ const certificate = queue.shift()!;
+
+ if (done.has(certificate.fingerprint)) {
+ continue;
+ }
+
+ done.add(certificate.fingerprint);
+ result.certificates.push(certificate.der);
+
+ if (isSelfSigned(certificate)) {
+ continue;
+ }
+
+ const name = certificate.x509.subject.replace(/\n/g, ", ");
+ let issuer = [...pool.values()].find((candidate) =>
+ isIssuedBy(certificate, candidate),
+ );
+
+ for (const url of issuer ? [] : certificate.caIssuerUrls) {
+ try {
+ const found = await cached(
+ `issuer:${url}`,
+ () => ISSUER_CACHE_MS,
+ async () => certificatesFromBundle(await limitedFetch(url)),
+ );
+
+ found.forEach(addToPool);
+ issuer = found.find((candidate) => isIssuedBy(certificate, candidate));
+ } catch (error) {
+ result.problems.push(
+ `Could not fetch the issuer of ${name}: ${describe(error)}`,
+ );
+ }
+
+ if (issuer) {
+ break;
+ }
+ }
+
+ if (!issuer) {
+ result.problems.push(`The issuer of ${name} was not found.`);
+ continue;
+ }
+
+ queue.push(issuer);
+
+ if (certificate.ocspNoCheck) {
+ continue;
+ }
+
+ const answer = await cached<RevocationAnswer | null>(
+ `revocation:${certificate.fingerprint}`,
+ revocationLifetime,
+ () => fetchRevocation(certificate, issuer, limitedFetch, result.problems),
+ );
+
+ if (!answer) {
+ result.problems.push(`No revocation information was found for ${name}.`);
+ continue;
+ }
+
+ (answer.kind === "ocsp" ? result.ocsps : result.crls).push(answer.data);
+
+ for (const extra of answer.extraCertificates) {
+ queue.push(addToPool(parseCertificate(extra)));
+ }
+
+ if (answer.status === "revoked") {
+ result.revoked.push(name);
+ }
+ }
+
+ return result;
+}
+
+function describe(error: unknown): string {
+ return error instanceof Error ? error.message : String(error);
+}
+
+async function fetchRevocation(
+ certificate: Certificate,
+ issuer: Certificate,
+ fetchFrom: ValidationFetch,
+ problems: string[],
+): Promise<RevocationAnswer | null> {
+ for (const url of certificate.ocspUrls) {
+ try {
+ return readOcspResponse(
+ await fetchFrom(url, {
+ body: buildOcspRequest(certificate, issuer),
+ contentType: "application/ocsp-request",
+ }),
+ certificate,
+ issuer,
+ );
+ } catch (error) {
+ problems.push(`OCSP at ${url} failed: ${describe(error)}`);
+ }
+ }
+
+ for (const url of certificate.crlUrls) {
+ try {
+ return readCrl(await fetchFrom(url), certificate, issuer);
+ } catch (error) {
+ problems.push(`The revocation list at ${url} failed: ${describe(error)}`);
+ }
+ }
+
+ return null;
+}
+
+// --- The document ------------------------------------------------------------
+
+export type PadesLevel = "B-B" | "B-T" | "B-LT" | "B-LTA";
+
+/**
+ * The PAdES baseline level of the file's first signature: B-T when it has a
+ * signature timestamp, B-LT when validation data was added after it, B-LTA
+ * when a document timestamp follows that. Null when the file is unsigned.
+ */
+export async function describePadesLevel(
+ bytes: Uint8Array,
+): Promise<PadesLevel | null> {
+ const signatures = findSignatures(bytes);
+ const first = signatures.find(
+ (signature) => signature.subFilter !== "ETSI.RFC3161",
+ );
+
+ if (!first) {
+ return null;
+ }
+
+ if (readCms(first.contents).timestampTokens.length === 0) {
+ return "B-B";
+ }
+
+ if (!(await hasDocumentSecurityStore(bytes))) {
+ return "B-T";
+ }
+
+ const firstEnd = first.byteRange[2] + first.byteRange[3];
+ const archived = signatures.some(
+ (signature) =>
+ signature.subFilter === "ETSI.RFC3161" &&
+ signature.byteRange[2] + signature.byteRange[3] > firstEnd,
+ );
+
+ return archived ? "B-LTA" : "B-LT";
+}
+
+export type LongTermValidationResult = {
+ bytes: Uint8Array;
+ problems: string[];
+ revoked: string[];
+};
+
+/**
+ * Adds validation data for every signature in the file and, given a
+ * time-stamping function, a document timestamp after it with the timestamp's
+ * own validation data. Returns the file as far as it got: a failure in the
+ * document timestamp keeps the validation data.
+ */
+export async function addLongTermValidation(
+ bytes: Uint8Array,
+ {
+ fetch: fetchFrom = createValidationFetch(),
+ timestamp,
+ }: {
+ fetch?: ValidationFetch;
+ /** Returns an RFC 3161 token for a SHA-256 digest. */
+ timestamp?: ((digest: Buffer) => Promise<Buffer>) | null;
+ } = {},
+): Promise<LongTermValidationResult> {
+ const data = await collectValidationData(
+ findSignatures(bytes).map((signature) => signature.contents),
+ { fetch: fetchFrom },
+ );
+ const problems = [...data.problems];
+ const revoked = [...data.revoked];
+ let current = await appendDocumentSecurityStore(bytes, data);
+
+ if (!timestamp) {
+ return { bytes: current, problems, revoked };
+ }
+
+ try {
+ current = await appendDocumentTimestamp(current, timestamp);
+
+ const archive = findSignatures(current).at(-1)!;
+ const more = await collectValidationData([archive.contents], {
+ fetch: fetchFrom,
+ });
+
+ problems.push(...more.problems);
+ revoked.push(...more.revoked);
+ current = await appendDocumentSecurityStore(current, more);
+ } catch (error) {
+ problems.push(`The archive timestamp failed: ${describe(error)}`);
+ }
+
+ return { bytes: current, problems, revoked };
+}
diff --git a/src/lib/services/pdf-seal.ts b/src/lib/services/pdf-seal.ts
index f146774..4509f5b 100644
--- a/src/lib/services/pdf-seal.ts
+++ b/src/lib/services/pdf-seal.ts
@@ -6,6 +6,8 @@ import { Signer, SUBFILTER_ETSI_CADES_DETACHED } from "@signpdf/utils";
import forge from "node-forge";
import type { PDFDocument } from "pdf-lib";
+import { children, elementBytes, readTlv } from "./der.ts";
+
// A PAdES baseline (B-B, or B-T with a timestamp) seal on a finished PDF.
//
// The seal is a CMS signature over the whole file, made with this install's
@@ -265,6 +267,25 @@ async function requestTimestampToken(
timestampUrl: string,
): Promise<forge.asn1.Asn1> {
const imprint = createHash("sha256").update(signatureValue).digest();
+
+ return (await fetchTimestampToken(imprint, timestampUrl)).asn1;
+}
+
+/**
+ * An RFC 3161 token for a SHA-256 digest, byte for byte as the service sent
+ * it, for a document timestamp.
+ */
+export async function requestDocumentTimestamp(
+ digest: Buffer,
+ timestampUrl: string,
+): Promise<Buffer> {
+ return (await fetchTimestampToken(digest, timestampUrl)).der;
+}
+
+async function fetchTimestampToken(
+ imprint: Buffer,
+ timestampUrl: string,
+): Promise<{ asn1: forge.asn1.Asn1; der: Buffer }> {
const nonce = randomBytes(8);
nonce[0] = nonce[0]! & 0x7f;
@@ -306,9 +327,14 @@ async function requestTimestampToken(
const body = Buffer.from(await response.arrayBuffer());
let parsed: forge.asn1.Asn1;
+ let tokenDer: Buffer | null = null;
try {
parsed = asn1.fromDer(body.toString("binary"));
+
+ const [, token] = children(body, readTlv(body));
+
+ tokenDer = token ? elementBytes(body, token) : null;
} catch (error) {
throw new PdfSealError(
"The time-stamping service sent an unreadable answer.",
@@ -328,13 +354,13 @@ async function requestTimestampToken(
: -1;
// 0 = granted, 1 = granted with modifications.
- if ((status !== 0 && status !== 1) || !parts[1]) {
+ if ((status !== 0 && status !== 1) || !parts[1] || !tokenDer) {
throw new PdfSealError("The time-stamping service refused the request.");
}
assertTokenMatchesRequest(parts[1], imprint, nonce);
- return parts[1];
+ return { asn1: parts[1], der: tokenDer };
}
class CadesSigner extends Signer {
diff --git a/src/lib/services/pki-test-support.ts b/src/lib/services/pki-test-support.ts
new file mode 100644
index 0000000..10a6b49
--- /dev/null
+++ b/src/lib/services/pki-test-support.ts
@@ -0,0 +1,430 @@
+import {
+ createHash,
+ createPrivateKey,
+ generateKeyPairSync,
+ sign,
+} from "node:crypto";
+import {
+ createServer,
+ type IncomingMessage,
+ type ServerResponse,
+} from "node:http";
+
+import forge from "node-forge";
+
+import {
+ algorithm,
+ children,
+ contentBytes,
+ der,
+ elementBytes,
+ encode,
+ encodeSmallInteger,
+ readTlv,
+ TAG,
+} from "./der.ts";
+import { parseCertificate } from "./pdf-ltv.ts";
+import type { SealIdentity } from "./pdf-seal.ts";
+
+// A certificate authority for tests, served over HTTP on this machine: its
+// own certificate (for authority information access), an OCSP responder, a
+// revocation list and an RFC 3161 time-stamping service whose tokens are
+// signed for real, so a PDF reader can check every signature it makes.
+//
+// Only for tests. Nothing here is careful about anything but shape.
+
+const OID = {
+ caIssuers: "1.3.6.1.5.5.7.48.2",
+ contentType: "1.2.840.113549.1.9.3",
+ messageDigest: "1.2.840.113549.1.9.4",
+ ocsp: "1.3.6.1.5.5.7.48.1",
+ ocspBasic: "1.3.6.1.5.5.7.48.1.1",
+ sha256: "2.16.840.1.101.3.4.2.1",
+ sha256WithRsa: "1.2.840.113549.1.1.11",
+ signedData: "1.2.840.113549.1.7.2",
+ signingCertificateV2: "1.2.840.113549.1.9.16.2.47",
+ tstInfo: "1.2.840.113549.1.9.16.1.4",
+} as const;
+
+type KeyPair = { privateKeyPem: string; publicKeyPem: string };
+
+function makeKeys(): KeyPair {
+ const { privateKey, publicKey } = generateKeyPairSync("rsa", {
+ modulusLength: 2048,
+ privateKeyEncoding: { format: "pem", type: "pkcs8" },
+ publicKeyEncoding: { format: "pem", type: "spki" },
+ });
+
+ return { privateKeyPem: privateKey, publicKeyPem: publicKey };
+}
+
+function uri(url: string): Buffer {
+ return encode(0x86, Buffer.from(url, "latin1"));
+}
+
+function binary(value: Buffer): string {
+ return value.toString("binary");
+}
+
+function generalizedTime(date: Date): Buffer {
+ const text = date
+ .toISOString()
+ .replace(/[-:T]/g, "")
+ .replace(/\.\d+Z$/, "Z");
+
+ return encode(TAG.generalizedTime, Buffer.from(text, "latin1"));
+}
+
+function utcTime(date: Date): Buffer {
+ const text = date
+ .toISOString()
+ .slice(2)
+ .replace(/[-:T]/g, "")
+ .replace(/\.\d+Z$/, "Z");
+
+ return encode(TAG.utcTime, Buffer.from(text, "latin1"));
+}
+
+function signSha256(data: Buffer, keys: KeyPair): Buffer {
+ return sign("sha256", data, createPrivateKey(keys.privateKeyPem));
+}
+
+function bitString(value: Buffer): Buffer {
+ return encode(TAG.bitString, Buffer.from([0]), value);
+}
+
+/** DER SET OF: the elements sorted by their encoding. */
+function sortedSet(items: Buffer[]): Buffer {
+ return der.set(...[...items].sort(Buffer.compare));
+}
+
+function issueCertificate({
+ ca = false,
+ commonName,
+ extensions = [],
+ issuer,
+ keys,
+ serial,
+}: {
+ ca?: boolean;
+ commonName: string;
+ extensions?: object[];
+ issuer: { certificate: forge.pki.Certificate | null; keys: KeyPair };
+ keys: KeyPair;
+ serial: string;
+}): forge.pki.Certificate {
+ const certificate = forge.pki.createCertificate();
+ const notBefore = new Date(Date.now() - 24 * 60 * 60 * 1000);
+ const notAfter = new Date(Date.now() + 365 * 24 * 60 * 60 * 1000);
+ const subject = [
+ { name: "commonName", value: commonName },
+ { name: "organizationName", value: "Harbour & Finch Test CA" },
+ ];
+
+ certificate.serialNumber = serial;
+ certificate.publicKey = forge.pki.publicKeyFromPem(keys.publicKeyPem);
+ certificate.validity.notBefore = notBefore;
+ certificate.validity.notAfter = notAfter;
+ certificate.setSubject(subject);
+ certificate.setIssuer(
+ issuer.certificate ? issuer.certificate.subject.attributes : subject,
+ );
+ certificate.setExtensions([
+ { cA: ca, critical: true, name: "basicConstraints" },
+ ca
+ ? { critical: true, cRLSign: true, keyCertSign: true, name: "keyUsage" }
+ : {
+ critical: true,
+ digitalSignature: true,
+ name: "keyUsage",
+ nonRepudiation: true,
+ },
+ { name: "subjectKeyIdentifier" },
+ ...extensions,
+ ]);
+ certificate.sign(
+ forge.pki.privateKeyFromPem(issuer.keys.privateKeyPem),
+ forge.md.sha256.create(),
+ );
+
+ return certificate;
+}
+
+function certificateDer(certificate: forge.pki.Certificate): Buffer {
+ return Buffer.from(
+ forge.asn1.toDer(forge.pki.certificateToAsn1(certificate)).getBytes(),
+ "binary",
+ );
+}
+
+export type TestPki = {
+ close: () => Promise<void>;
+ /** The CA certificate, DER. */
+ caCertificate: Buffer;
+ /** A seal identity issued by the CA, its chain holding only itself. */
+ seal: SealIdentity;
+ sealCertificate: Buffer;
+ /** Switches and counters for the services. */
+ state: {
+ caFetches: number;
+ crlFetches: number;
+ ocspDown: boolean;
+ ocspRequests: number;
+ /** Serial numbers (hex, lowercase) the CA says are revoked. */
+ revoked: Set<string>;
+ timestampRequests: number;
+ };
+ timestampUrl: string;
+};
+
+async function readBody(request: IncomingMessage): Promise<Buffer> {
+ const chunks: Buffer[] = [];
+
+ for await (const chunk of request) {
+ chunks.push(chunk as Buffer);
+ }
+
+ return Buffer.concat(chunks);
+}
+
+export async function startTestPki(): Promise<TestPki> {
+ let handler: (
+ request: IncomingMessage,
+ response: ServerResponse,
+ ) => Promise<void> = async (_request, response) => {
+ response.writeHead(503).end();
+ };
+ const server = createServer((request, response) => {
+ handler(request, response).catch(() => {
+ response.writeHead(500).end();
+ });
+ });
+
+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
+
+ const address = server.address();
+ const base = `http://127.0.0.1:${String(typeof address === "object" && address ? address.port : 0)}`;
+ const caKeys = makeKeys();
+ const ca = issueCertificate({
+ ca: true,
+ commonName: "Test Root CA",
+ issuer: { certificate: null, keys: caKeys },
+ keys: caKeys,
+ serial: "01",
+ });
+ const caDer = certificateDer(ca);
+ const caParsed = parseCertificate(caDer);
+ const infoAccess = {
+ id: "1.3.6.1.5.5.7.1.1",
+ value: binary(
+ der.sequence(
+ der.sequence(der.oid(OID.ocsp), uri(`${base}/ocsp`)),
+ der.sequence(der.oid(OID.caIssuers), uri(`${base}/ca.cer`)),
+ ),
+ ),
+ };
+ const crlPoints = {
+ id: "2.5.29.31",
+ value: binary(
+ der.sequence(
+ der.sequence(encode(0xa0, encode(0xa0, uri(`${base}/ca.crl`)))),
+ ),
+ ),
+ };
+ const sealKeys = makeKeys();
+ const sealCertificate = issueCertificate({
+ commonName: "Harbour & Finch document seal",
+ extensions: [infoAccess, crlPoints],
+ issuer: { certificate: ca, keys: caKeys },
+ keys: sealKeys,
+ serial: "1001",
+ });
+ const sealDer = certificateDer(sealCertificate);
+ const tsaKeys = makeKeys();
+ const tsaCertificate = issueCertificate({
+ commonName: "Test Time-Stamping Authority",
+ extensions: [
+ { critical: true, name: "extKeyUsage", timeStamping: true },
+ infoAccess,
+ crlPoints,
+ ],
+ issuer: { certificate: ca, keys: caKeys },
+ keys: tsaKeys,
+ serial: "2001",
+ });
+ const tsaDer = certificateDer(tsaCertificate);
+ const tsaParsed = parseCertificate(tsaDer);
+ const state: TestPki["state"] = {
+ caFetches: 0,
+ crlFetches: 0,
+ ocspDown: false,
+ ocspRequests: 0,
+ revoked: new Set(),
+ timestampRequests: 0,
+ };
+ let tokenSerial = 1;
+
+ function ocspAnswer(requestBody: Buffer): Buffer {
+ // OCSPRequest > TBSRequest > requestList > Request > CertID
+ let node = readTlv(requestBody);
+
+ for (let depth = 0; depth < 4; depth += 1) {
+ node = children(requestBody, node)[0]!;
+ }
+
+ const certId = elementBytes(requestBody, node);
+ const serial = contentBytes(requestBody, children(requestBody, node)[3]!);
+ const now = new Date();
+ const revoked = state.revoked.has(
+ serial.toString("hex").replace(/^0+/, ""),
+ );
+ const single = der.sequence(
+ certId,
+ revoked ? encode(0xa1, generalizedTime(now)) : encode(0x80),
+ generalizedTime(now),
+ encode(0xa0, generalizedTime(new Date(now.getTime() + 60 * 60 * 1000))),
+ );
+ const responseData = der.sequence(
+ encode(0xa1, caParsed.subjectName),
+ generalizedTime(now),
+ der.sequence(single),
+ );
+ const basic = der.sequence(
+ responseData,
+ algorithm(OID.sha256WithRsa),
+ bitString(signSha256(responseData, caKeys)),
+ );
+
+ return der.sequence(
+ encode(TAG.enumerated, Buffer.from([0])),
+ encode(0xa0, der.sequence(der.oid(OID.ocspBasic), der.octets(basic))),
+ );
+ }
+
+ function revocationList(): Buffer {
+ const now = new Date();
+ const entries = [...state.revoked].map((serial) =>
+ der.sequence(
+ encode(
+ TAG.integer,
+ Buffer.from(serial.length % 2 ? `0${serial}` : serial, "hex"),
+ ),
+ utcTime(now),
+ ),
+ );
+ const tbs = der.sequence(
+ encodeSmallInteger(1),
+ algorithm(OID.sha256WithRsa),
+ caParsed.subjectName,
+ utcTime(now),
+ utcTime(new Date(now.getTime() + 24 * 60 * 60 * 1000)),
+ ...(entries.length > 0 ? [der.sequence(...entries)] : []),
+ );
+
+ return der.sequence(
+ tbs,
+ algorithm(OID.sha256WithRsa),
+ bitString(signSha256(tbs, caKeys)),
+ );
+ }
+
+ function timestampAnswer(requestBody: Buffer): Buffer {
+ // TimeStampReq { version, messageImprint, nonce, certReq }
+ const fields = children(requestBody, readTlv(requestBody));
+ const messageImprint = elementBytes(requestBody, fields[1]!);
+ const nonce = fields.slice(2).find((field) => field.tag === TAG.integer);
+ const tstInfo = der.sequence(
+ encodeSmallInteger(1),
+ der.oid("1.2.3.4.1"),
+ messageImprint,
+ encodeSmallInteger(tokenSerial++),
+ generalizedTime(new Date()),
+ ...(nonce ? [elementBytes(requestBody, nonce)] : []),
+ );
+ const attributes = [
+ der.sequence(der.oid(OID.contentType), der.set(der.oid(OID.tstInfo))),
+ der.sequence(
+ der.oid(OID.messageDigest),
+ der.set(der.octets(createHash("sha256").update(tstInfo).digest())),
+ ),
+ der.sequence(
+ der.oid(OID.signingCertificateV2),
+ der.set(
+ der.sequence(
+ der.sequence(
+ der.sequence(
+ der.octets(createHash("sha256").update(tsaDer).digest()),
+ ),
+ ),
+ ),
+ ),
+ ),
+ ].sort(Buffer.compare);
+ const signerInfo = der.sequence(
+ encodeSmallInteger(1),
+ der.sequence(tsaParsed.issuerName, encode(TAG.integer, tsaParsed.serial)),
+ algorithm(OID.sha256),
+ encode(0xa0, ...attributes),
+ algorithm(OID.sha256WithRsa),
+ der.octets(signSha256(sortedSet(attributes), tsaKeys)),
+ );
+ const signedData = der.sequence(
+ encodeSmallInteger(3),
+ der.set(algorithm(OID.sha256)),
+ der.sequence(der.oid(OID.tstInfo), encode(0xa0, der.octets(tstInfo))),
+ encode(0xa0, tsaDer, caDer),
+ der.set(signerInfo),
+ );
+ const token = der.sequence(
+ der.oid(OID.signedData),
+ encode(0xa0, signedData),
+ );
+
+ return der.sequence(der.sequence(encodeSmallInteger(0)), token);
+ }
+
+ handler = async (request, response) => {
+ const body = await readBody(request);
+
+ if (request.url === "/ca.cer") {
+ state.caFetches += 1;
+ response
+ .writeHead(200, { "content-type": "application/pkix-cert" })
+ .end(caDer);
+ } else if (request.url === "/ca.crl") {
+ state.crlFetches += 1;
+ response
+ .writeHead(200, { "content-type": "application/pkix-crl" })
+ .end(revocationList());
+ } else if (request.url === "/ocsp") {
+ state.ocspRequests += 1;
+
+ if (state.ocspDown) {
+ response.writeHead(503).end();
+ } else {
+ response
+ .writeHead(200, { "content-type": "application/ocsp-response" })
+ .end(ocspAnswer(body));
+ }
+ } else if (request.url === "/tsa") {
+ state.timestampRequests += 1;
+ response
+ .writeHead(200, { "content-type": "application/timestamp-reply" })
+ .end(timestampAnswer(body));
+ } else {
+ response.writeHead(404).end();
+ }
+ };
+
+ return {
+ caCertificate: caDer,
+ close: () => new Promise<void>((resolve) => server.close(() => resolve())),
+ seal: {
+ certificateChainPem: [forge.pki.certificateToPem(sealCertificate)],
+ privateKeyPem: sealKeys.privateKeyPem,
+ },
+ sealCertificate: sealDer,
+ state,
+ timestampUrl: `${base}/tsa`,
+ };
+}
diff --git a/src/lib/services/seal-identity.ts b/src/lib/services/seal-identity.ts
index bd0b6f0..91a188f 100644
--- a/src/lib/services/seal-identity.ts
+++ b/src/lib/services/seal-identity.ts
@@ -1,4 +1,5 @@
import {
+ X509Certificate,
createCipheriv,
createDecipheriv,
generateKeyPairSync,
@@ -17,8 +18,15 @@ import {
resolveAuthSecret,
type EnvSource,
} from "../utils/env.ts";
+import {
+ addLongTermValidation,
+ isSelfSigned,
+ parseCertificate,
+ type ValidationFetch,
+} from "./pdf-ltv.ts";
import {
createSelfSignedSealIdentity,
+ requestDocumentTimestamp,
saveSealedPdf,
sealIdentityFromPkcs12,
type SealIdentity,
@@ -248,24 +256,107 @@ export async function saveInstallSealedPdf(
timestampUrl,
};
+ return sealForTheLongTerm(pdfDocument, sealIdentity, options);
+}
+
+/**
+ * Seals the document (PAdES B-B, or B-T with a time-stamping service), then
+ * adds what keeps the seal checkable for years: the certificates and
+ * revocation answers (B-LT) and an archive timestamp over them (B-LTA).
+ * Each step after the first only adds to the file, and is skipped with a
+ * logged reason when a service it needs cannot be reached.
+ */
+export async function sealForTheLongTerm(
+ pdfDocument: PDFDocument,
+ identity: SealIdentity,
+ options: SealOptions,
+ { fetch }: { fetch?: ValidationFetch } = {},
+): Promise<Uint8Array> {
+ const timestampUrl = options.timestampUrl ?? null;
+ // A self-made certificate has no issuer to ask about, so without a
+ // timestamp there is nothing to add for it.
+ const fromAuthority = isCertificateAuthoritySeal(identity);
+
if (!timestampUrl) {
- return saveSealedPdf(pdfDocument, sealIdentity, options);
+ const sealed = await saveSealedPdf(pdfDocument, identity, options);
+
+ return fromAuthority ? withLongTermValidation(sealed, null, fetch) : sealed;
}
+ let sealed: Uint8Array;
+
try {
- return await saveSealedPdf(
+ sealed = await saveSealedPdf(
await clonePdf(pdfDocument),
- sealIdentity,
+ identity,
options,
);
} catch (error) {
// A time-stamping service that is down must not stop a signing. The
// document is still sealed, only without the independent time.
console.error("[seal] Timestamping failed; sealing without it.", error);
- return saveSealedPdf(pdfDocument, sealIdentity, {
+ sealed = await saveSealedPdf(pdfDocument, identity, {
...options,
timestampUrl: null,
});
+
+ return fromAuthority ? withLongTermValidation(sealed, null, fetch) : sealed;
+ }
+
+ return withLongTermValidation(sealed, timestampUrl, fetch);
+}
+
+/** Whether the seal certificate was issued by someone else. */
+function isCertificateAuthoritySeal(identity: SealIdentity): boolean {
+ try {
+ return !isSelfSigned(
+ parseCertificate(
+ new X509Certificate(identity.certificateChainPem[0]!).raw,
+ ),
+ );
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * Adds long-term validation (PAdES B-LT) and, with a time-stamping service,
+ * an archive timestamp (B-LTA). It only adds to a seal already made, so
+ * when a certificate authority or the time-stamping service cannot be
+ * reached the document keeps the seal it has, and the reason is logged.
+ */
+async function withLongTermValidation(
+ sealed: Uint8Array,
+ timestampUrl: string | null,
+ fetch: ValidationFetch | undefined,
+): Promise<Uint8Array> {
+ try {
+ const result = await addLongTermValidation(sealed, {
+ fetch,
+ timestamp: timestampUrl
+ ? (digest) => requestDocumentTimestamp(digest, timestampUrl)
+ : null,
+ });
+
+ if (result.revoked.length > 0) {
+ console.error(
+ `[seal] A certificate authority says these certificates are revoked: ${result.revoked.join("; ")}. Readers will not accept the seal. Replace SEAL_P12_BASE64.`,
+ );
+ }
+
+ if (result.problems.length > 0) {
+ console.warn(
+ `[seal] Long-term validation is incomplete: ${result.problems.join(" ")}`,
+ );
+ }
+
+ return result.bytes;
+ } catch (error) {
+ console.error(
+ "[seal] Adding long-term validation failed; keeping the seal without it.",
+ error,
+ );
+ return sealed;
}
}